id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,536,030
consteval.cpp
CoffeeBeforeArch_cpp_20_samples/consteval/consteval.cpp
// This program shows off the basics of consteval in C++20 // By: Nick from CoffeeBeforeArch #include <cstdlib> #include <iostream> // A consteval function // This MUST be evaluated at compile time consteval int fibonacci(int N) { if (N <= 1) return N; return fibonacci(N - 1) + fibonacci(N - 2); } int main() { // This works with our consteval function int val = fibonacci(22); // This does not! // val = fibonacci(rand() % 20); // Print the result std::cout << "The fibonacci number is: " << val << '\n'; return 0; }
543
C++
.cpp
19
26.315789
58
0.677606
CoffeeBeforeArch/cpp_20_samples
34
5
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,032
to_array.cpp
CoffeeBeforeArch_cpp_20_samples/to_array/to_array.cpp
// This program shows off the basics of std::to_array in C++20 // By: Nick from CoffeeBeforeArch #include <array> #include <iostream> int main() { // What happens when we create an array like so? // We get an array with a single const char*! auto a1 = std::array{"foo"}; for (auto e : a1) std::cout << e << ' '; std::cout << '\n'; // If we want to separate the characters, we can use std::to_array auto a2 = std::to_array("foo"); for (auto e : a2) std::cout << e << ' '; std::cout << '\n'; return 0; }
526
C++
.cpp
16
30.375
68
0.626482
CoffeeBeforeArch/cpp_20_samples
34
5
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,035
hello.cpp
CoffeeBeforeArch_cpp_20_samples/modules/hello.cpp
module; #include <iostream> #include <string_view> export module hello; export void greeter(const std::string_view &name) { std::cout << "Hello, " << name << "!\n"; }
172
C++
.cpp
7
22.857143
51
0.685185
CoffeeBeforeArch/cpp_20_samples
34
5
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,037
stop_token.cpp
CoffeeBeforeArch_cpp_20_samples/concepts/stop_token.cpp
// This program shows off the basics of stop tokens in C++20 // By: Nick from CoffeeBeforeArch #include <chrono> #include <concepts> #include <iostream> #include <thread> using namespace std::chrono; // Here, we constrain the type to those that are signed and integral // This helps avoid long, and non-intuitive template error messages // Instead, we get a simple one that says the constraint that failed! template <std::signed_integral T> void sleepFunc(T num) { std::this_thread::sleep_for(seconds(num)); } int main() { // Let's create a jthread an pass it a stop token std::jthread jt0([](std::stop_token tk) { // Print in a loop for (int i = 0; i < 10; i++) { std::cout << "Printing value: " << i << '\n'; // Stop, if that has been requested if (tk.stop_requested()) { return; } // Sleep so this doesn't finish too quickly // This should be a long int, not a double! sleepFunc(1.5); } }); // Pause the main thread before cancelling the jthread sleepFunc(5); // Request for our jthread to stop jt0.request_stop(); std::cout << "Stopped the jthread!\n"; return 0; }
1,160
C++
.cpp
36
28.694444
69
0.671749
CoffeeBeforeArch/cpp_20_samples
34
5
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,039
background.cpp
CoffeeBeforeArch_cpp_20_samples/jthreads/background.cpp
// This program shows off the basics of jthreads in C++ // By: Nick from CoffeeBeforeArch #include <iostream> #include <thread> int main() { // What happens when we spawn a thread, and we don't join it? // If it's join-able, std::terminate gets called (usually calls abort) std::thread t0([]() { std::cout << "Printing from the new thread!\n"; }); // If we call join, we wait for the thread to finish // t0.join(); // If we call detach, the thread is no longer join-able (terminate isn't // called) // However, if main exits, our string may not print! t0.detach(); return 0; }
604
C++
.cpp
16
35.0625
75
0.685026
CoffeeBeforeArch/cpp_20_samples
34
5
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,041
fast_mod.cpp
CoffeeBeforeArch_cpp_20_samples/condition_attributes/fast_mod.cpp
// This program shows off the likely and unlikely C++20 attributes // By: Nick from CoffeeBeforeArch #include <benchmark/benchmark.h> #include <random> #include <vector> // Function for generating argument pairs static void custom_args(benchmark::internal::Benchmark *b) { for (int i = 1 << 4; i <= 1 << 10; i <<= 2) { // Collect stats at 1/8, 1/2, and 7/8 for (int j : {32, 128, 224}) { b = b->ArgPair(i, j); } } } // Baseline for intuitive modulo operation static void baseMod(benchmark::State &s) { // Number of elements int N = s.range(0); // Max for mod operator int ceil = s.range(1); // Vector for input and output of modulo std::vector<int> input; std::vector<int> output; input.resize(N); output.resize(N); // Generate random inputs std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<int> dist(0, 255); for (int &i : input) { i = dist(rng); } while (s.KeepRunning()) { // Compute the modulo for each element for (int i = 0; i < N; i++) { output[i] = input[i] % ceil; } } } // Register the benchmark BENCHMARK(baseMod)->Apply(custom_args); // Baseline for intuitive modulo operation static void fastMod(benchmark::State &s) { // Number of elements int N = s.range(0); // Max for mod operator int ceil = s.range(1); // Vector for input and output of modulo std::vector<int> input; std::vector<int> output; input.resize(N); output.resize(N); // Generate random inputs std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<int> dist(0, 255); for (int &i : input) { i = dist(rng); } while (s.KeepRunning()) { // DON'T compute the mod for each element // Skip the expensive operation using a simple compare for (int i = 0; i < N; i++) { if (input[i] >= ceil) [[unlikely]] { output[i] = input[i] % ceil; } else { output[i] = input[i]; } } } } // Register the benchmark BENCHMARK(fastMod)->Apply(custom_args); // Benchmark main function BENCHMARK_MAIN();
2,094
C++
.cpp
75
24.533333
66
0.64656
CoffeeBeforeArch/cpp_20_samples
34
5
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,044
proto_utils_test.cc
google_eidos-audition/eidos/utils/proto_utils_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <unistd.h> #include <filesystem> #include <cstdio> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "eidos/port/status-matchers.h" #include "eidos/utils/proto_utils.h" #include "eidos/utils/test.pb.h" #include "google/protobuf/util/message_differencer.h" #include "gtest/gtest.h" using google::protobuf::util::MessageDifferencer; namespace eidos { namespace utils { namespace { const char *const kTestDir = "eidos/utils/testdata"; const char *const kProtoName = "123"; const char *const kInvalidPath = "invalid"; constexpr int kProtoId = 456; void SetupProto(TestProto *proto) { proto->set_name(kProtoName); proto->set_id(kProtoId); } } // namespace TEST(ProtoUtilsTest, ReadingTextFormat) { TestProto proto; SetupProto(&proto); const std::string proto_path = absl::StrCat(kTestDir, "/test.textproto"); TestProto new_proto; EXPECT_FALSE(ReadTextProto(kInvalidPath, &new_proto).ok()); ASSERT_OK(ReadTextProto(proto_path, &new_proto)); EXPECT_EQ(new_proto.name(), proto.name()); EXPECT_EQ(new_proto.id(), proto.id()); } TEST(ProtoUtilsTest, WriteBinaryFormat) { TestProto proto; SetupProto(&proto); const std::string temp_path = std::tmpnam(nullptr); ASSERT_OK(WriteBinaryProto(proto, temp_path)); TestProto new_proto; EXPECT_OK(ReadBinaryProto(temp_path, &new_proto)); EXPECT_TRUE(MessageDifferencer::Equals(new_proto, proto)); EXPECT_TRUE(std::filesystem::remove(temp_path)); } TEST(ProtoUtilsTest, WriteTextFormat) { TestProto proto; SetupProto(&proto); const std::string temp_path = std::tmpnam(nullptr); ASSERT_OK(WriteTextProto(proto, temp_path)); TestProto new_proto; EXPECT_OK(ReadTextProto(temp_path, &new_proto)); EXPECT_TRUE(MessageDifferencer::Equals(new_proto, proto)); EXPECT_TRUE(std::filesystem::remove(temp_path)); } } // namespace utils } // namespace eidos // Local Variables: // mode: c++ // End:
2,509
C++
.cc
72
32.958333
75
0.755876
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,045
proto_utils.cc
google_eidos-audition/eidos/utils/proto_utils.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/utils/proto_utils.h" #include <fstream> #include <sstream> #include "absl/strings/str_cat.h" namespace eidos { namespace utils { absl::Status ReadFileContents(absl::string_view filepath, bool binary_mode, std::string *contents) { const std::string filepath_str(filepath); std::ios_base::openmode mode = std::ios_base::in; if (binary_mode) mode |= std::ios::binary; std::ifstream input_stream(filepath_str, mode); if (!input_stream) { return absl::NotFoundError(absl::StrCat( "Failed to open \"", filepath_str, "\"")); } std::ostringstream string_buffer; string_buffer << input_stream.rdbuf(); *contents = string_buffer.str(); return absl::OkStatus(); } absl::Status WriteFileContents(const std::string &contents, bool binary_mode, absl::string_view filepath) { const std::string filepath_str(filepath); std::ios_base::openmode mode = std::ios_base::out; if (binary_mode) mode |= std::ios::binary; std::ofstream output_stream(filepath_str, mode); if (!output_stream) { return absl::InternalError(absl::StrCat( "Failed to open \"", filepath_str, "\"")); } output_stream.write(contents.c_str(), contents.size()); if (!output_stream) { return absl::InternalError(absl::StrCat( "Failed to write to \"", filepath_str, "\"")); } return absl::OkStatus(); } } // namespace utils } // namespace eidos
2,040
C++
.cc
53
34.773585
77
0.693939
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,046
auditory_pipeline.cc
google_eidos-audition/eidos/audition/auditory_pipeline.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/auditory_pipeline.h" #include <algorithm> #include <cstdint> #include <functional> #include <map> #include <set> #include <string> #include "absl/memory/memory.h" #include "eidos/audition/carfac_config.pb.h" #include "eidos/audition/carfac_model.h" #include "eidos/audition/gammatone_filterbank_config.pb.h" #include "eidos/audition/mock_basilar_membrane_model.h" #include "eidos/audition/sumner2002_hair_cell_synapse_config.pb.h" #include "eidos/audition/zhang2001_spike_generator_config.pb.h" #include "eidos/port/logging.h" #include "third_party/audition/models/amt/meddis1986_hair_cell_synapse_model.h" #include "third_party/audition/models/baumgarte/baumgarte_model.h" #include "third_party/audition/models/bruce_carney/bruce2018_hair_cell_synapse_model.h" #include "third_party/audition/models/bruce_carney/bruce2018_spike_generator.h" #include "third_party/audition/models/bruce_carney/jackson_spike_generator.h" #include "third_party/audition/models/bruce_carney/zhang2001_spike_generator.h" #include "third_party/audition/models/bruce_carney/zilany2014_ihc_model.h" #include "third_party/audition/models/dsam/sumner2002_hair_cell_synapse_model.h" #include "third_party/audition/models/gammatone/gammatone_filterbank_model.h" namespace eidos { namespace audition { namespace { // Extracts model-specific configuration from the generic configuration message. // If no configuration is present, the defaults will be passed to the model. template <typename ModelConfigType> ModelConfigType GetModelConfig(const AuditoryModelConfig &config) { ModelConfigType model_config; if (config.has_config() && config.config().Is<ModelConfigType>()) { const std::string model_name = AuditoryModelType_Name(config.model_type()); GOOGLE_CHECK(config.config().UnpackTo(&model_config)) << model_name << ": Failed to extract configuration"; GOOGLE_LOG(INFO) << "Configuration [" << model_name << "]: " << model_config.DebugString(); } return model_config; } // Given the model configuration generates instance of the model. std::unique_ptr<AuditoryModel> MakeModel(const AuditoryModelConfig &config) { const AuditoryModelType model_type = config.model_type(); switch (model_type) { case MODEL_MOCK_BASILAR_MEMBRANE: return absl::make_unique<MockBasilarMembraneModel>(); case MODEL_CARFAC: return absl::make_unique<CarfacModel>( GetModelConfig<CarfacConfig>(config)); case MODEL_BAUMGARTE: return absl::make_unique<BaumgarteModel>(); case MODEL_GAMMATONE_SLANEY: return absl::make_unique<GammatoneFilterbankModel>( GetModelConfig<GammatoneFilterbankConfig>(config)); case MODEL_ZILANY_IHC_2014: return absl::make_unique<Zilany2014IhcModel>(); case MODEL_MEDDIS_SYNAPSE_1986: return absl::make_unique<Meddis1986HairCellSynapseModel>(); case MODEL_BRUCE_SYNAPSE_2018: return absl::make_unique<Bruce2018HairCellSynapseModel>(); case MODEL_SUMNER_SYNAPSE_2002: return absl::make_unique<Sumner2002HairCellSynapseModel>( GetModelConfig<Sumner2002HairCellSynapseConfig>(config)); case MODEL_BRUCE_SPIKES_2018: return absl::make_unique<Bruce2018SpikeGeneratorModel>(); case MODEL_JACKSON_SPIKES: return absl::make_unique<JacksonSpikeGeneratorModel>(); case MODEL_ZHANG_SPIKES_2001: return absl::make_unique<Zhang2001SpikeGeneratorModel>( GetModelConfig<Zhang2001SpikeGeneratorConfig>(config)); default: { GOOGLE_LOG(FATAL) << "Unknown model type"; return std::unique_ptr<AuditoryModel>(nullptr); } } } } // namespace bool AuditoryPipeline::Init(const AuditoryPipelineConfig &config) { if (config.models().empty()) { GOOGLE_LOG(ERROR) << "No models were supplied"; return false; } models_.reserve(config.models().size()); int model_counter = 0; std::set<AuditoryModelType> models_set; for (const auto &model_config : config.models()) { const AuditoryModelType model_type = model_config.model_type(); if (model_type == MODEL_UNKNOWN) { GOOGLE_LOG(ERROR) << "Model " << model_counter << ": Unknown model type!"; return false; } const std::string &model_name = AuditoryModelType_Name(model_type); if (models_set.find(model_type) != models_set.end()) { GOOGLE_LOG(ERROR) << "Model " << model_counter << ": Model " << model_name << " is already in the pipeline"; return false; } models_set.insert(model_type); std::unique_ptr<AuditoryModel> model = MakeModel(model_config); GOOGLE_LOG(INFO) << "Creating " << model_name << " ..."; models_.emplace_back(std::move(model)); model_counter++; } // Create the links between the models. for (uint32_t i = 0; i < models_.size(); ++i) { if (i > 0) models_[i]->set_previous_model(models_[i - 1].get()); } return Verify(); } bool AuditoryPipeline::Init(const std::vector<AuditoryModelType> &model_types) { if (model_types.empty()) { GOOGLE_LOG(ERROR) << "No models were supplied"; return false; } AuditoryPipelineConfig config; config.mutable_models()->Reserve(model_types.size()); for (const auto model_type : model_types) { // Following will generate model with an empty config. AuditoryModelConfig *model_config = config.add_models(); model_config->set_model_type(model_type); } return Init(config); } bool AuditoryPipeline::Verify() const { if (!models_[0]->waveform_input()) { GOOGLE_LOG(ERROR) << "The head model " << models_[0]->ModelTypeAsString() << " does not take waveform as input"; return false; } // A very basic check that the models can connect to each other provided by // the mapping between current auditory stage and a set of outputs that can // feed into it. This mechanism is not perfect, but will do for now. static const std::map<AuditoryStageType, std::set<AuditoryOutputType>> kStageValidLinks = { { STAGE_HAIR_CELLS, { OUTPUT_BASILAR_MEMBRANE_DISPLACEMENT } }, { STAGE_AUDITORY_NERVE_SYNAPSE, { OUTPUT_BASILAR_MEMBRANE_DISPLACEMENT, OUTPUT_IHC_TRANSMEMBRANE_POTENTIAL, OUTPUT_SYNAPSE_FIRING_RATES} } }; for (uint32_t i = 1; i < models_.size(); ++i) { const AuditoryStageType stage_type = models_[i]->stage_type(); const auto allowed_inputs_pos = kStageValidLinks.find(stage_type); if (allowed_inputs_pos == kStageValidLinks.end()) { GOOGLE_LOG(ERROR) << "Model " << models_[0]->ModelTypeAsString() << ": No link constraints found for stage " << AuditoryStageType_Name(stage_type); return false; } const AuditoryOutputType input_type = models_[i - 1]->output_type(); const auto &allowed_inputs = allowed_inputs_pos->second; if (allowed_inputs.find(input_type) == allowed_inputs.end()) { GOOGLE_LOG(ERROR) << "Model " << models_[0]->ModelTypeAsString() << ": Can't have " << AuditoryOutputType_Name(input_type) << " as input"; return false; } } GOOGLE_LOG(INFO) << "Loaded pipeline with " << models_.size() << " models."; return true; } void AuditoryPipeline::Process(const StimulusConfig &stimulus_config, const Eigen::Ref<const Eigen::ArrayXXd> &input, AuditoryResponse *response) { GOOGLE_CHECK(!models_.empty()) << "Pipeline is empty!"; GOOGLE_CHECK(response != nullptr); auto &outputs = *response->mutable_outputs(); outputs.clear(); if (stimulus_config.store_intermediate_outputs()) { outputs.reserve(models_.size()); } else { outputs.reserve(1); } Eigen::ArrayXXd model_input = input, model_output; const int num_models = models_.size(); for (int i = 0; i < num_models; ++i) { AuditoryModel *model = models_[i].get(); model->Init(stimulus_config); GOOGLE_LOG(INFO) << "Running " << model->ModelTypeAsString() << " ..."; model->ProcessSegment(model_input, &model_output); if (stimulus_config.store_intermediate_outputs() || i == num_models - 1) { outputs.emplace_back(model->output_type(), model_output); } model_input.swap(model_output); } // Check if the channel frequencies sorted in descending order and always // present them in ascending order which may require rearranging the outputs. ChannelProperties channel_properties = models_.back()->GetChannelProperties(); auto &center_frequencies = channel_properties.center_frequencies; if (std::is_sorted(center_frequencies.begin(), center_frequencies.end(), std::greater<double>())) { // Weak descending order. GOOGLE_LOG(INFO) << "Re-arranging CFs into ascending order ..."; std::sort(center_frequencies.begin(), center_frequencies.end()); const int num_channels = center_frequencies.size(); int num_rearranged = 0; for (auto &model_output_info : outputs) { Eigen::ArrayXXd &model_outputs = model_output_info.second; if (model_outputs.rows() == num_channels) { // Re-arrange the output rows according to the order of CFs. model_outputs.colwise().reverseInPlace(); num_rearranged++; } } GOOGLE_LOG(INFO) << num_rearranged << " outputs rearranged."; } else { GOOGLE_CHECK(std::is_sorted(center_frequencies.begin(), center_frequencies.end())) << "The center frequencies are unordered!"; } *response->mutable_channel_properties() = channel_properties; } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
10,317
C++
.cc
228
40.004386
87
0.694392
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,047
zilany2014_ihc_model_test.cc
google_eidos-audition/eidos/audition/zilany2014_ihc_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test that the IHC model from Zilany, et. al. (2014) behaves. #include <algorithm> #include "Eigen/Core" #include "eidos/audition/stimulus_config.pb.h" #include "eidos/port/logging.h" #include "gtest/gtest.h" #include "third_party/audition/models/bruce_carney/zilany2014_ihc_model.h" namespace eidos { namespace audition { namespace { // Checks the model over the random monaural waveform. void CheckRandomStimulus(int requested_num_channels, int expected_num_channels, int min_output_level) { StimulusConfig stimulus_config; stimulus_config.set_sample_rate(100000 /* 100 kHz */); stimulus_config.set_num_channels(requested_num_channels); const int kNumEars = 1; const int kNumSamples = 5000; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); Zilany2014IhcModel model; model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); EXPECT_EQ(output.rows(), expected_num_channels); EXPECT_EQ(output.cols(), kNumSamples); const ChannelProperties &channel_properties = model.GetChannelProperties(); EXPECT_EQ(output.rows(), channel_properties.NumChannels()); EXPECT_EQ(output.size(), channel_properties.NumChannels() * kNumSamples); const auto &center_frequencies = channel_properties.center_frequencies; EXPECT_TRUE(std::is_sorted(center_frequencies.begin(), center_frequencies.end())); const float output_level = output.matrix().squaredNorm(); GOOGLE_LOG(INFO) << "Output level: " << output_level; EXPECT_LT(min_output_level, output_level); EXPECT_LT(-1.5, output.minCoeff()); // Minimal potential. EXPECT_GT(2.0, output.maxCoeff()); // Maximal potential. } } // namespace TEST(Zilany2014IhcModelTest, RandomizedWaveformWithDefaultsTest) { // Mimimal permissable value for the amplification in the output. constexpr double kMinOutputLevel = 910.0; CheckRandomStimulus(0 /* requested channels */, 251 /* actual channels */, kMinOutputLevel); } TEST(Zilany2014IhcModelTest, RandomizedWaveformTest) { constexpr int kNumChannels = 100; constexpr double kMinOutputLevel = 350.0; CheckRandomStimulus(kNumChannels /* requested channels */, kNumChannels /* actual channels */, kMinOutputLevel); } } // namespace audition } // namespace eidos
3,003
C++
.cc
67
40.656716
79
0.732308
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,048
auditory_response_test.cc
google_eidos-audition/eidos/audition/auditory_response_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple check that the auditory output wrapper behaves. #include "eidos/audition/auditory_response.h" #include <filesystem> #include <cstdio> #include <string> #include "Eigen/Core" #include "absl/strings/str_cat.h" #include "eidos/audition/auditory_model_config.pb.h" #include "gtest/gtest.h" namespace eidos { namespace audition { constexpr int kNumChannels = 200; constexpr int kNumSamples = 10000; TEST(AuditoryResponseTest, CheckWriteNpy) { AuditoryResponse response; response.mutable_outputs()->emplace_back( OUTPUT_SYNAPSE_SPIKE_TIMES, Eigen::ArrayXXd::Random(kNumChannels, kNumSamples)); const std::string temp_path = std::tmpnam(nullptr); response.WriteNpy(temp_path); EXPECT_TRUE(std::filesystem::remove(temp_path)); } TEST(AuditoryResponseTest, CheckWriteNpz) { AuditoryResponse response; const Eigen::ArrayXXd &data = Eigen::ArrayXXd::Random( kNumChannels, kNumSamples); response.mutable_outputs()->emplace_back( OUTPUT_BASILAR_MEMBRANE_DISPLACEMENT, data); response.mutable_outputs()->emplace_back( OUTPUT_IHC_TRANSMEMBRANE_POTENTIAL, data); response.mutable_outputs()->emplace_back( OUTPUT_SYNAPSE_FIRING_RATES, data); response.mutable_outputs()->emplace_back( OUTPUT_SYNAPSE_SPIKE_TIMES, data); response.mutable_channel_properties()->center_frequencies. emplace_back(0.0); const std::string temp_path = std::tmpnam(nullptr); response.WriteNpz(temp_path); EXPECT_TRUE(std::filesystem::remove(temp_path)); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,186
C++
.cc
58
35.172414
75
0.759207
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,049
auditory_pipeline_test.cc
google_eidos-audition/eidos/audition/auditory_pipeline_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Check that the auditory pipeline interface behaves. #include <algorithm> #include <functional> #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/audition/auditory_pipeline.h" #include "eidos/audition/auditory_response.h" #include "eidos/audition/stimulus_config.pb.h" #include "gtest/gtest.h" namespace eidos { namespace audition { TEST(AuditoryPipelineTest, CheckEmpty) { AuditoryPipeline pipeline; std::vector<AuditoryModelType> empty_models; EXPECT_FALSE(pipeline.Init(empty_models)); AuditoryPipelineConfig empty_config; EXPECT_FALSE(pipeline.Init(empty_config)); empty_config.add_models(); // Add empty model. EXPECT_FALSE(pipeline.Init(empty_config)); } // Duplicates are not allowed. TEST(AuditoryPipelineTest, CheckDuplicate) { AuditoryPipeline pipeline; const std::vector<AuditoryModelType> models = { MODEL_GAMMATONE_SLANEY, MODEL_GAMMATONE_SLANEY}; EXPECT_FALSE(pipeline.Init(models)); } // Checks that all head models take audio as an input. TEST(AuditoryPipelineTest, CheckNoWaveformInputs) { const std::vector<AuditoryModelType> non_waveform_models = { MODEL_MEDDIS_SYNAPSE_1986, MODEL_JACKSON_SPIKES}; for (const auto model_type : non_waveform_models) { std::vector<AuditoryModelType> models = { model_type }; AuditoryPipeline pipeline; EXPECT_FALSE(pipeline.Init(models)); } } TEST(AuditoryPipelineTest, CheckInitFromList) { AuditoryPipeline pipeline; const std::vector<AuditoryModelType> models = { MODEL_GAMMATONE_SLANEY, MODEL_MEDDIS_SYNAPSE_1986, MODEL_JACKSON_SPIKES }; EXPECT_TRUE(pipeline.Init(models)); EXPECT_EQ(models.size(), pipeline.Size()); } TEST(AuditoryPipelineTest, CheckInitFromConfig) { AuditoryPipeline pipeline; AuditoryPipelineConfig config; config.add_models()->set_model_type(MODEL_GAMMATONE_SLANEY); config.add_models()->set_model_type(MODEL_MEDDIS_SYNAPSE_1986); config.add_models()->set_model_type(MODEL_JACKSON_SPIKES); EXPECT_TRUE(pipeline.Init(config)); EXPECT_EQ(config.models().size(), pipeline.Size()); } TEST(AuditoryPipelineTest, CheckStimulusFeed) { // Create pipeline config. AuditoryPipelineConfig config; config.add_models()->set_model_type(MODEL_GAMMATONE_SLANEY); config.add_models()->set_model_type(MODEL_MEDDIS_SYNAPSE_1986); // Initialize pipeline. AuditoryPipeline pipeline; EXPECT_TRUE(pipeline.Init(config)); // Prepare stimulus. StimulusConfig stimulus_config; stimulus_config.set_sample_rate(16000 /* Hz */); constexpr int kNumEars = 1; constexpr int kNumSamples = 20000; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); // Run the stimulus through the pipeline. The output corresponds to the // synaptic firing rates. AuditoryResponse response; pipeline.Process(stimulus_config, input, &response); EXPECT_EQ(1, response.outputs().size()); const auto &last_output = response.outputs()[0]; EXPECT_EQ(OUTPUT_SYNAPSE_FIRING_RATES, last_output.first); const Eigen::ArrayXXd &output = last_output.second; EXPECT_EQ(kNumSamples, output.cols()); EXPECT_LT(10, output.rows()); // Frequency channels. EXPECT_LT(5.0, output.minCoeff()); // Min firing rate. EXPECT_LT(50.0, output.maxCoeff()); // Max firing rate. const ChannelProperties &channel_properties = response.channel_properties(); const auto &center_frequencies = channel_properties.center_frequencies; EXPECT_LT(0, center_frequencies.size()); EXPECT_TRUE(std::is_sorted(center_frequencies.begin(), center_frequencies.end())); // Run the same stimulus again, but this time store the intermediate outputs. stimulus_config.set_store_intermediate_outputs(true); pipeline.Process(stimulus_config, input, &response); const auto &outputs = response.outputs(); EXPECT_EQ(2, outputs.size()); EXPECT_EQ(OUTPUT_BASILAR_MEMBRANE_DISPLACEMENT, outputs[0].first); EXPECT_LT(0, outputs[0].second.rows()); EXPECT_LT(0, outputs[0].second.cols()); EXPECT_EQ(OUTPUT_SYNAPSE_FIRING_RATES, outputs[1].first); EXPECT_LT(0, outputs[1].second.rows()); EXPECT_LT(0, outputs[1].second.cols()); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
4,877
C++
.cc
115
39.695652
79
0.758323
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,050
auditory_model.cc
google_eidos-audition/eidos/audition/auditory_model.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/auditory_model.h" namespace eidos { namespace audition { AuditoryStageType OutputType2Stage(AuditoryOutputType output_type) { if (output_type == OUTPUT_BASILAR_MEMBRANE_DISPLACEMENT) { return STAGE_BASILAR_MEMBRANE; } else if (output_type == OUTPUT_IHC_TRANSMEMBRANE_POTENTIAL) { return STAGE_HAIR_CELLS; } else { return STAGE_AUDITORY_NERVE_SYNAPSE; } } AuditoryModel::AuditoryModel(AuditoryModelType model_type, AuditoryStageType stage_type, AuditoryOutputType output_type, bool waveform_input) : model_type_(model_type), stage_type_(stage_type), output_type_(output_type), waveform_input_(waveform_input), previous_model_(nullptr) { } void AuditoryModel::Init(const StimulusConfig &stimulus_config) { stimulus_config_ = stimulus_config; } std::string AuditoryModel::ModelTypeAsString() const { return AuditoryModelType_Name(model_type_); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
1,670
C++
.cc
43
34.883721
80
0.72761
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,051
bruce2018_spike_generator_test.cc
google_eidos-audition/eidos/audition/bruce2018_spike_generator_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple check that the spike generator behaves. #include <algorithm> #include <random> #include <vector> #include "Eigen/Core" #include "eidos/audition/gammatone_filterbank_config.pb.h" #include "eidos/audition/stimulus_config.pb.h" #include "eidos/audition/utils.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "third_party/audition/models/amt/meddis1986_hair_cell_synapse_model.h" #include "third_party/audition/models/bruce_carney/bruce2018_spike_generator.h" #include "third_party/audition/models/gammatone/gammatone_filterbank_model.h" using testing::AllOf; using testing::Each; using testing::Gt; using testing::Le; namespace eidos { namespace audition { namespace { constexpr double kSpontRate = 60.0; // Spontaneous firing rate (spikes/sec). constexpr double kAbsoluteRefractoryPeriod = 0.7E-3; // sec constexpr double kRelativeRefractoryPeriod = 0.6E-3; // sec } // namespace TEST(Bruce2018SpikeGeneratorTest, SingleFiberRandomStimulus) { constexpr double kNumSamples = 100000; // Number of samples to test. constexpr double kSampleRate = 100000; // 100 kHz constexpr double kMinRate = 11.0; // Minimal firing rate. constexpr double kMaxRate = 153.0; // Maximum firing rate. constexpr double kMaxRepeats = 6; // Increase the initial stimulii buffer // size by (maximum) this factor. for (int n = 1; n <= kMaxRepeats; ++n) { const std::vector<double> &rates = GetRandomUniformVector(kNumSamples * n, kMinRate, kMaxRate); const std::vector<double> &spike_times = Bruce2018SpikeGenerator( rates, 1.0 / kSampleRate /* sample_period */, kSpontRate, kAbsoluteRefractoryPeriod, kRelativeRefractoryPeriod); EXPECT_LT(2, spike_times.size()); // At least two spikes. EXPECT_TRUE(std::is_sorted(spike_times.begin(), spike_times.end())); // Check that all the spike times are sane. Please note, we don't expect a // spike at time 0. const double stimulus_length = rates.size() / kSampleRate; ASSERT_THAT(spike_times, Each(AllOf(Gt(0.0), Le(stimulus_length)))); } } TEST(Bruce2018SpikeGeneratorTest, InputsFromMeddis1986HairCell) { // Generate firing rates using Meddis' hair cell model given the random // stimulus. constexpr int kNumChannels = 251; constexpr int kNumSamples = 10000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumChannels, kNumSamples); constexpr int kSampleRate = 16000; // Hz. Eigen::ArrayXXd rates; Meddis1986HairCellSynapse(input, kSampleRate, false /* subtract spontaneous firing rate */, &rates); EXPECT_EQ(kNumChannels, rates.rows()); EXPECT_EQ(kNumSamples, rates.cols()); // Run through the spike generator. Eigen::ArrayXXd spikes; Bruce2018SpikeGenerator(rates, 1.0 / kSampleRate /* sample_period */, kSpontRate, kAbsoluteRefractoryPeriod, kRelativeRefractoryPeriod, &spikes); EXPECT_EQ(kNumChannels, spikes.rows()); EXPECT_EQ(kNumSamples, spikes.cols()); EXPECT_FALSE(spikes.isZero()); EXPECT_EQ(0.0, spikes.minCoeff()); EXPECT_EQ(1.0, spikes.maxCoeff()); // Expect these lower bounds on the number of spikes. EXPECT_LT(7000, (spikes.array() != 0).count()); } TEST(Bruce2018SpikeGeneratorTest, InputsFromMaGammatoneAndMeddis1986HairCell) { // Given the random stimulus, approximate basilar membrane displacements using // gammatone filters followed by the Meddis' model producing the firing rates. constexpr int kNumChannels = 251; constexpr double kSampleRate = 16000.0; // Hz. constexpr int kNumSamples = 20000; // Long enough so we get a good average. constexpr int kNumEars = 1; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); // Estimate basilar membrane displacements. StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); GammatoneFilterbankConfig gammatone_config; gammatone_config.set_filter_type(GAMMATONE_FILTERBANK_COOKE_AND_MA); GammatoneFilterbankModel model(gammatone_config); model.Init(stimulus_config); Eigen::ArrayXXd bm_output; model.ProcessSegment(input, &bm_output); const ChannelProperties &channel_properties = model.GetChannelProperties(); EXPECT_EQ(channel_properties.NumChannels(), bm_output.rows()); EXPECT_EQ(kNumSamples, bm_output.cols()); // Estimate firing rates. Eigen::ArrayXXd rates; Meddis1986HairCellSynapse(bm_output, kSampleRate, false /* subtract spontaneous firing rate */, &rates); EXPECT_EQ(kNumChannels, rates.rows()); EXPECT_EQ(kNumSamples, rates.cols()); // Run through the spike generator. Eigen::ArrayXXd spikes; Bruce2018SpikeGenerator(rates, 1.0 / kSampleRate /* sample_period */, kSpontRate, kAbsoluteRefractoryPeriod, kRelativeRefractoryPeriod, &spikes); EXPECT_EQ(kNumChannels, spikes.rows()); EXPECT_EQ(kNumSamples, spikes.cols()); EXPECT_FALSE(spikes.isZero()); EXPECT_EQ(0.0, spikes.minCoeff()); EXPECT_EQ(1.0, spikes.maxCoeff()); // Expect these lower bounds on the number of spikes. EXPECT_LT(2400, (spikes.array() != 0).count()); } TEST(Bruce2018SpikeGeneratorTest, SimpleModelInterfaceRandomInputs) { // Generate random firing rate inputs in the range (kMinRate, kMaxRate). constexpr double kNumChannels = 50; constexpr double kNumSamples = 200000; // Number of samples to test. constexpr double kMinRate = 11.0; // Minimal firing rate. constexpr double kMaxRate = 153.0; // Maximum firing rate. const Eigen::ArrayXXd input = kMinRate + (Eigen::ArrayXXd::Random( kNumChannels, kNumSamples) * 0.5 + 0.5) + (kMaxRate - kMinRate); // Run the model. constexpr double kSampleRate = 100000; // 100 kHz StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); Bruce2018SpikeGeneratorModel model; Eigen::ArrayXXd spikes; model.Init(stimulus_config); model.ProcessSegment(input, &spikes); EXPECT_EQ(kNumChannels, spikes.rows()); EXPECT_EQ(kNumSamples, spikes.cols()); EXPECT_FALSE(spikes.isZero()); EXPECT_EQ(0.0, spikes.minCoeff()); EXPECT_EQ(1.0, spikes.maxCoeff()); // Expect these lower bounds on the number of spikes. constexpr int kMinNumSpikes = 8000; EXPECT_LT(kMinNumSpikes, (spikes.array() != 0).count()); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
7,170
C++
.cc
156
41.621795
80
0.72475
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,052
windowing_test.cc
google_eidos-audition/eidos/audition/windowing_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/windowing.h" #include <cmath> #include <vector> #include "Eigen/Core" #include "eidos/audition/stimulus_config.pb.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::Each; using testing::Eq; namespace eidos { namespace audition { constexpr int kNumChannels = 251; constexpr int kNumSamples = 4000; constexpr int kSampleRate = 16000; // 16 kHz. constexpr double kFrameShift = 1E-2; // 10 ms. constexpr double kWindowWidth = 25E-3; // 25 ms. constexpr int kNumExtraSamples = 3000; constexpr int kNumExtraStep = 33; TEST(WindowingTest, BasicCheckForFrames) { StimulusConfig config; config.set_sample_rate(kSampleRate); config.set_window_duration_sec(kWindowWidth); config.set_frame_shift_sec(kFrameShift); for (int i = 0; i < kNumExtraSamples; i += kNumExtraStep) { const int num_samples = kNumSamples + i; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random( kNumChannels, num_samples); const FrameInfo &info = GetFrameInfo(input, config); EXPECT_GT(info.num_frames, 0); EXPECT_GT(info.frame_size, 0); EXPECT_GT(info.frame_shift, 0); const std::vector<Eigen::ArrayXXd> frames = Window(input, config); EXPECT_EQ(frames.size(), info.num_frames); for (int j = 0; j < info.num_frames; ++j) { EXPECT_EQ(frames[j].rows(), kNumChannels); EXPECT_EQ(frames[j].cols(), info.frame_size); } } } TEST(WindowingTest, BasicTimeIntegration) { const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random( kNumChannels, kNumSamples); StimulusConfig config; config.set_sample_rate(kSampleRate); config.set_window_duration_sec(kWindowWidth); config.set_frame_shift_sec(kFrameShift); const FrameInfo &info = GetFrameInfo(input, config); EXPECT_GT(info.num_frames, 0); const Eigen::ArrayXXd frames = WindowAndIntegrateTime(input, config); EXPECT_EQ(frames.cols(), info.num_frames); EXPECT_EQ(frames.rows(), input.rows()); } TEST(WindowingTest, BasicWindowFunction) { constexpr int kFrameSize = 101; // No-op window function. Eigen::ArrayXXd window = ComputeWindowFunction( WINDOW_FUNCTION_NONE, kFrameSize, kNumChannels); EXPECT_EQ(window.rows(), kNumChannels); EXPECT_EQ(window.cols(), kFrameSize); const std::vector<double> window_vec(window.data(), window.data() + window.size()); EXPECT_THAT(window_vec, Each(Eq(1.0))); // Hann window. window = ComputeWindowFunction( WINDOW_FUNCTION_HANN, kFrameSize, kNumChannels); EXPECT_EQ(window.rows(), kNumChannels); EXPECT_EQ(window.cols(), kFrameSize); EXPECT_EQ(1.0, window(0, std::ceil(kFrameSize / 2))); // Hamming window. window = ComputeWindowFunction( WINDOW_FUNCTION_HAMMING, kFrameSize, kNumChannels); EXPECT_EQ(window.rows(), kNumChannels); EXPECT_EQ(window.cols(), kFrameSize); EXPECT_EQ(1.0, window(0, std::ceil(kFrameSize / 2))); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
3,588
C++
.cc
93
35.408602
75
0.725445
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,053
psychoacoustic_scale_utils_test.cc
google_eidos-audition/eidos/audition/psychoacoustic_scale_utils_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Check that various psychoacoustic scale conversions are sane. #include "eidos/audition/psychoacoustic_scale_utils.h" #include <algorithm> #include <cstdlib> #include <vector> #include "gtest/gtest.h" namespace eidos { namespace audition { TEST(PsychoacousticScaleUtilsTest, CheckErb) { // Checks unit conversions. constexpr double kSourceHz = 2000; // 2 kHz constexpr double kTargetErb = 240.578; constexpr double kEpsilon = 1E-5; EXPECT_NEAR(kTargetErb, erb::HzToErb(kSourceHz), kEpsilon); EXPECT_NEAR(kSourceHz, erb::ErbToHz(kTargetErb), kEpsilon); } TEST(PsychoacousticScaleUtilsTest, CheckErbRates) { // Checks rate conversions. Note that the epsilon for this test is higher // because of the use of logarithmic and exponential functions during the // conversions. constexpr double kSourceHz = 2000; // 2 kHz constexpr double kTargetErbRate = 21.1552; constexpr double kEpsilon = 1E-2; EXPECT_NEAR(kTargetErbRate, erb::HzToErbRate(kSourceHz), kEpsilon); EXPECT_NEAR(kSourceHz, erb::ErbRateToHz(kTargetErbRate), kEpsilon); } TEST(PsychoacousticScaleUtilsTest, CheckErbRange) { constexpr double kMinFrequency = 50; // Hz constexpr double kMaxFrequency = 10000; // Hz constexpr int kNumChannels = 500; const std::vector<double> freqs = erb::GetFrequenciesHz( kNumChannels, kMinFrequency, kMaxFrequency); // Following checks for weak ordering. EXPECT_TRUE(std::is_sorted(freqs.begin(), freqs.end())); // Following checks for strict ordering. for (std::size_t i = 0; i < freqs.size(); ++i) { if (i) { EXPECT_LT(freqs[i - 1], freqs[i]); } } EXPECT_LT(kMinFrequency, freqs[0]); EXPECT_GT(kMaxFrequency, freqs.back()); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,379
C++
.cc
61
36.688525
75
0.749567
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,054
psychoacoustic_scale_utils.cc
google_eidos-audition/eidos/audition/psychoacoustic_scale_utils.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/psychoacoustic_scale_utils.h" #include <cmath> namespace eidos { namespace audition { namespace erb { // This equation is an approximation for the moderate sound levels, normally // between 10 Hz and 10 kHz. This equation is approximation of an earlier // proposed square polynomial model ERB(f) = a * f^2 + b * f + c, originally // proposed by Moore and Glasberg (1983). double HzToErb(double hz) { return 24.7f * (0.00437 * hz + 1.0); } double ErbToHz(double erb) { return (erb / 24.7 - 1.0) / 0.00437; } double HzToErbRate(double hz) { return (21.4 * std::log10(hz * 0.00437 + 1.0)); } double ErbRateToHz(double erb_rate) { return ((std::pow(10.0, erb_rate / 21.4) - 1.0) / 0.00437); } std::vector<double> GetFrequenciesHz(int num_channels, double min_frequency, double max_frequency) { const double min_erb_rate = erb::HzToErbRate(min_frequency); const double max_erb_rate = erb::HzToErbRate(max_frequency); const double step = (max_erb_rate - min_erb_rate) / num_channels; double erb_rate = min_erb_rate + step / 2.0; std::vector<double> center_frequencies(num_channels); for (int i = 0; i < num_channels; ++i) { center_frequencies[i] = erb::ErbRateToHz(erb_rate); erb_rate += step; } return center_frequencies; } } // namespace erb } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,055
C++
.cc
54
34.907407
76
0.696635
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,055
auditory_feature_extractor_main.cc
google_eidos-audition/eidos/audition/auditory_feature_extractor_main.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple utility for extracting cochlear features. // // Example usage: // -------------- // - Using the model names: // bazel-bin/eidos/audition/auditory_feature_extractor \ // --models GAMMATONE_SLANEY,SUMNER_SYNAPSE_2002 \ // --waveform_file input.wav --output_file output.npy // - Using pipeline configuration contents: // bazel-bin/eidos/audition/auditory_feature_extractor \ // --config_proto_contents "pipeline { models { model_type: MODEL_BAUMGARTE } }" \ // --waveform_file input.wav --output_file output.npy // - Using pipeline configuration file: // bazel-bin/eidos/audition/auditory_feature_extractor \ // --config_proto_file pipeline.textproto \ // --waveform_file input.wav \ // --output_file_format npz --output_file output.npz // - Processing multiple audio files: // bazel-bin/eidos/audition/auditory_feature_extractor \ // --models BAUMGARTE,SUMNER_SYNAPSE_2002 \ // --waveform_file_list file_list.txt --output_dir /tmp \ // --output_file_format npz #include <algorithm> #include <cstddef> #include <filesystem> #include <string> #include <thread> #include <utility> #include <vector> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "eidos/audition/auditory_feature_extractor.h" #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/audition/auditory_pipeline_config.pb.h" #include "eidos/audition/auditory_response.h" #include "eidos/audition/waveform.pb.h" #include "eidos/audition/waveform_utils.h" #include "eidos/port/logging.h" #include "eidos/utils/proto_utils.h" #include "google/protobuf/text_format.h" ABSL_FLAG(std::string, waveform_file, "", "Audio file in WAVE format which is a subset of RIFF specification. " "Multiple sampling rates are supported but some models may require " "higher sampling rates, so the input must be upsampled. Number of " "bits per sample is not restricted to 16 bits. Only single channel " "audio is supported at the moment."); ABSL_FLAG(std::string, waveform_file_list, "", "A text file containing newline-separated list of full paths to " "individual audio files. Mutually exclusive with --waveform_file " "flag."); ABSL_FLAG(int, downsample_step, -1, "Simple temporal downsampling: Output every N-th sample. Please " "note, this flag is mutually exclusive with the proper resampling " "flags --output_resample_up_factor and " "--output_resample_down_factor."); ABSL_FLAG(std::string, models, "", "Comma-separated list of model types. Supported types:\n" "\"MOCK_BASILAR_MEMBRANE\", \"CARFAC\", \"BAUMGARTE\", " "\"ZILANY_IHC_2014\", \"GAMMATONE_SLANEY\", " "\"MEDDIS_SYNAPSE_1986\", \"BRUCE_SYNAPSE_2018\", " "\"SUMNER_SYNAPSE_2002\", \"BRUCE_SPIKES_2018\", " "\"JACKSON_SPIKES\", \"ZHANG_SPIKES_2001\"."); ABSL_FLAG(std::string, config_proto_file, "", "Feature extractor configuration file in textual proto format."); ABSL_FLAG(std::string, config_proto_contents, "", "Feature extractor configuration string as textual proto."); ABSL_FLAG(double, audio_scaling_gain, 0.07, "Gain factor for audio scaling. Range: [0.01,0.1]."); ABSL_FLAG(std::string, output_file_format, "npy", "Format of the output file containing the model's response to " "stimulus. Supported values:\n" "\"npy\": Numpy .npy format: Single matrix with single-precision " "floats),\n" "\"npz\": Numpy .npz format: Multiple matrices with single-precision " "floats. Each matrix corresponds to the output of a particular " "auditory stage."); ABSL_FLAG(std::string, output_file, "", "File path containing the output from the model in response to the " "individual stimulus. The format of the file is specified using " "--output_file_format option."); ABSL_FLAG(std::string, output_dir, "", "Path to the directory where the model responses to individual " "stimulii provided by --waveform_file_list flag will be stored. " "Mutually exclusive with --output_file flag."); ABSL_FLAG(int, num_channels, 251, "Number of channels (frequency bands) for analysis corresponding " "to <n> equidistant locations along the cochlea."); ABSL_FLAG(double, min_cf_hz, 0.0, "Lowest characteristic frequency (CF) for analysis (in Hz). If " "unset, model-specific defaults will be used."); ABSL_FLAG(double, max_cf_hz, 0.0, "Highest characteristic frequency (CF) for analysis (in Hz). If " "unset, model-specific defaults will be used."); ABSL_FLAG(std::string, stimulus_config_proto_file, "", ("Text proto file specifying stimulus configuration. Can be used " "as an alternative to command-line flags.")); ABSL_FLAG(int, num_tasks, -1, "Number of tasks to run in parallel when processing a list of audio " "files. The value of -1 means that parallel processing is " "disabled. Set this flag to a non-negative number to enable the " "parallelism. A value of 0 will use the default hardware concurrency " "settings, positive number will force the precise number of tasks. " "Please note: Not all the models are thread-safe yet!"); ABSL_FLAG(bool, apply_window_to_outputs, false, "If enabled, applies windowing function to the response."); ABSL_FLAG(double, window_duration_sec, 25E-3, "Window (also frame) duration (width) in seconds. Default is 25 ms."); ABSL_FLAG(double, frame_shift_sec, 1E-2, "Frame shift (in seconds). After computing each frame, advance " "to the next by this amount. Default is 10 ms."); ABSL_FLAG(std::string, window_function, "NONE", "Window function type specified as string. By default, no windowing " "function is applied. Supported values: \"NONE\", \"HANN\", " "\"HAMMING\"."); ABSL_FLAG(int, output_resample_up_factor, 0, "Resample the response: Upsampling factor <p>. The signal is " "resampled by <p/q>, where <q> is the downsampling factor."); ABSL_FLAG(int, output_resample_down_factor, 0, "Resample the response: Downsampling factor <q>. The signal is " "resampled by <p/q>, where <p> is the upsampling factor."); namespace eidos { namespace audition { namespace { // Converts model type option string to the actual model types. std::vector<AuditoryModelType> GetModelTypes() { const std::vector<std::string> model_strings = absl::StrSplit( absl::GetFlag(FLAGS_models), ',', absl::SkipEmpty()); GOOGLE_CHECK(!model_strings.empty()) << "No models were supplied!"; std::vector<AuditoryModelType> model_types; model_types.reserve(model_strings.size()); AuditoryModelType model_type; for (const auto &model_string : model_strings) { GOOGLE_CHECK(AuditoryModelType_Parse(absl::StrCat( "MODEL_", model_string), &model_type)) << "Failed to parse model type: " << model_string; model_types.emplace_back(model_type); } return model_types; } // Gets window function type from string. WindowFunction GetWindowFunctionFromString() { const std::string function_name = absl::GetFlag(FLAGS_window_function); WindowFunction window = WINDOW_FUNCTION_NONE; GOOGLE_CHECK(WindowFunction_Parse(absl::StrCat( "WINDOW_FUNCTION_", function_name), &window)) << "Failed to parse window function: " << function_name; return window; } // Initializes stimulus configuration from the command-line flags. void InitStimulusConfig(StimulusConfig *stimulus_config) { const std::string stimulus_config_proto_file = absl::GetFlag( FLAGS_stimulus_config_proto_file); if (stimulus_config_proto_file.empty()) { stimulus_config->set_num_channels(absl::GetFlag(FLAGS_num_channels)); stimulus_config->set_lowest_cf_hz(absl::GetFlag(FLAGS_min_cf_hz)); stimulus_config->set_highest_cf_hz(absl::GetFlag(FLAGS_max_cf_hz)); stimulus_config->set_audio_scaling_gain(absl::GetFlag( FLAGS_audio_scaling_gain)); stimulus_config->set_downsample_step(absl::GetFlag(FLAGS_downsample_step)); stimulus_config->set_apply_window_to_outputs( absl::GetFlag(FLAGS_apply_window_to_outputs)); stimulus_config->set_window_duration_sec( absl::GetFlag(FLAGS_window_duration_sec)); stimulus_config->set_frame_shift_sec(absl::GetFlag(FLAGS_frame_shift_sec)); stimulus_config->set_window_function(GetWindowFunctionFromString()); stimulus_config->set_output_resample_up_factor( absl::GetFlag(FLAGS_output_resample_up_factor)); stimulus_config->set_output_resample_down_factor( absl::GetFlag(FLAGS_output_resample_down_factor)); } else { GOOGLE_LOG(INFO) << "Reading stimulus configuration from " << stimulus_config_proto_file; GOOGLE_CHECK_OK(utils::ReadTextProto(stimulus_config_proto_file, stimulus_config)) << "Failed to read stimulus configuration from: " << stimulus_config_proto_file; } } // Returns a fully qualified output path for the waveform input path given the // output directory and a file format. std::string OutputPathForInputWaveform(const std::string &input_wave_path, const std::string &output_file_format, const std::string &output_dir) { const std::filesystem::path path(input_wave_path); GOOGLE_CHECK(path.is_absolute()) << "Path should be absolute: " << input_wave_path; std::string output_path = absl::StrCat(output_dir, "/", path.stem().string()); if (path.has_extension()) { output_path = absl::StrCat(output_path, ".", output_file_format); } return output_path; } } // namespace // Processes the input audio stimulus storing the result in the output file. The // format of the output file is given by "output_file_format". void ProcessFile(const std::string &waveform_file, const std::string &output_file_format, const std::string &output_file) { // Read the stimuli, denormalize the audio. GOOGLE_LOG(INFO) << "Reading " << waveform_file << " ..."; Waveform waveform; GOOGLE_CHECK(ReadWaveform(waveform_file, &waveform)) << "Failed to read waveform from \"" << waveform_file << "\""; DenormalizeWaveform(&waveform); // Fetch some of the options. const int num_channels = absl::GetFlag(FLAGS_num_channels); const std::string config_proto_file = absl::GetFlag(FLAGS_config_proto_file); const std::string config_proto_contents = absl::GetFlag( FLAGS_config_proto_contents); const bool npz_output_format = (output_file_format == "npz"); // Prepare configuration. AuditoryFeatureExtractorConfig config; GOOGLE_CHECK_LT(0, num_channels) << "Invalid number of channels: " << num_channels; StimulusConfig *stimulus_config = config.mutable_config(); InitStimulusConfig(stimulus_config); if (!absl::GetFlag(FLAGS_models).empty()) { // Configuration is specified via list of models. const std::vector<AuditoryModelType> &model_types = GetModelTypes(); bool store_intermediate_outputs = false; if (model_types.size() > 1 && npz_output_format) { store_intermediate_outputs = true; } AuditoryPipelineConfig *pipeline_config = config.mutable_pipeline(); pipeline_config->mutable_models()->Reserve(model_types.size()); for (const auto model_type : model_types) { AuditoryModelConfig *model_config = pipeline_config->add_models(); model_config->set_model_type(model_type); } stimulus_config->set_store_intermediate_outputs(store_intermediate_outputs); } else if (!config_proto_file.empty() || !config_proto_contents.empty()) { // Please note, the proto may override some of the stimulus configuration // options provided through the flags. Therefore we simply merge the // contents of the default config with the proto loaded through the pipeline // configuration flag. AuditoryFeatureExtractorConfig pipeline_config; if (!config_proto_file.empty()) { GOOGLE_LOG(INFO) << "Reading configuration from " << config_proto_file; GOOGLE_CHECK_OK(utils::ReadTextProto(config_proto_file, &pipeline_config)) << "Failed to read configuration from: " << config_proto_file; } else { // Read from string. using google::protobuf::TextFormat; GOOGLE_CHECK(TextFormat::ParseFromString(config_proto_contents, &pipeline_config)) << "Failed to parse config contents"; } config.MergeFrom(pipeline_config); if (config.pipeline().models().size() > 1 && npz_output_format) { stimulus_config->set_store_intermediate_outputs(true); } } else { GOOGLE_LOG(FATAL) << "Specify --models, --config_proto_file or " << "--config_proto_contents"; } // Generate cochlear features. GOOGLE_LOG(INFO) << "Extracting features ..."; AuditoryFeatureExtractor extractor; AuditoryResponse response; GOOGLE_CHECK(extractor.ComputeFeatures(waveform, config, &response)) << "Failed to extract features from " << waveform_file; GOOGLE_CHECK_LE(1, response.outputs().size()) << "Expected at least one output from the auditory pipeline"; // Write the results. const std::string output_format_msg = (npz_output_format ? "(npz)" : "(npy)"); GOOGLE_LOG(INFO) << "Saving " << output_format_msg << " output to " << output_file << " ..."; if (!npz_output_format) { response.WriteNpy(output_file); } else { // Assume .npz output format. response.WriteNpz(output_file); } } void Run() { // Figure out the output file format. const std::string output_file_format = absl::GetFlag( FLAGS_output_file_format); GOOGLE_CHECK(output_file_format == "npy" || output_file_format == "npz") << "Unsupported output file format: " << output_file_format; // Process individual file or a list of files. const std::string waveform_file = absl::GetFlag(FLAGS_waveform_file); const std::string output_file = absl::GetFlag(FLAGS_output_file); const std::string waveform_file_list = absl::GetFlag( FLAGS_waveform_file_list); const std::string output_dir = absl::GetFlag(FLAGS_output_dir); if (!waveform_file.empty() && !output_file.empty()) { ProcessFile(waveform_file, output_file_format, output_file); } else if (!waveform_file_list.empty() && !output_dir.empty()) { // Check that output directory is valid. const std::filesystem::path output_dir_path(output_dir); GOOGLE_CHECK(std::filesystem::is_directory(output_dir_path)) << "Output directory does not exist or is not a directory: " << output_dir; // Read the file list. std::string contents; GOOGLE_CHECK_OK(utils::ReadFileContents( waveform_file_list, /* binary_mode= */false, &contents)) << "Failed to read " << waveform_file_list; std::vector<std::string> waveform_files = absl::StrSplit( contents, '\n', absl::SkipEmpty()); GOOGLE_CHECK(!waveform_files.empty()) << "No waveforms were supplied!"; for (auto &wav_file : waveform_files) { absl::StripAsciiWhitespace(&wav_file); } std::sort(waveform_files.begin(), waveform_files.end()); std::unique(waveform_files.begin(), waveform_files.end()); // Process individual files. int num_parallel_tasks = absl::GetFlag(FLAGS_num_tasks); if (num_parallel_tasks < 0) { // Sequential mode. for (const auto &wav_file : waveform_files) { ProcessFile(wav_file, output_file_format, OutputPathForInputWaveform( wav_file, output_file_format, output_dir)); } } else { // Parallel mode of operation. GOOGLE_LOG(WARNING) << "NOTE: Not all the models are thread-safe yet. " << "Please check the code to see whether parallel " << "mode is suitable for a particular model."; const int hardware_concurrency = std::thread::hardware_concurrency(); if (num_parallel_tasks == 0 || num_parallel_tasks > hardware_concurrency) { num_parallel_tasks = hardware_concurrency; } const int num_waveforms = waveform_files.size(); int num_batches = num_waveforms / num_parallel_tasks; if (num_batches == 0) num_batches = 1; GOOGLE_LOG(INFO) << "Number of tasks: " << num_parallel_tasks << ", batches: " << num_batches; // Process the waveforms in parallel using the minimal threading interface // of C++11. Ideally a thread pool will fit here, but dragging in // additional dependencies was ruled out. for (int i = 0; i < num_waveforms; ) { const int num_remaining = num_waveforms - i; if (num_remaining == 0) { break; } else if (num_parallel_tasks > num_remaining) { num_parallel_tasks = num_remaining; } std::vector<std::thread> workers(num_parallel_tasks); for (int j = 0; j < num_parallel_tasks; ++j) { const std::string &wav_file = waveform_files[i + j]; const std::string &output_path = OutputPathForInputWaveform( wav_file, output_file_format, output_dir); workers[j] = std::thread(ProcessFile, wav_file, output_file_format, output_path); } for (auto &worker : workers) { if (worker.joinable()) worker.join(); } i += num_parallel_tasks; } } } else { GOOGLE_LOG(FATAL) << "Wrong combination of input/output flags!"; } } } // namespace audition } // namespace eidos int main(int argc, char *argv[]) { absl::ParseCommandLine(argc, argv); GOOGLE_CHECK(!absl::GetFlag(FLAGS_waveform_file).empty() || !absl::GetFlag(FLAGS_waveform_file_list).empty()) << "--waveform_file or --waveform_file_list are required"; GOOGLE_CHECK(!absl::GetFlag(FLAGS_output_file).empty() || !absl::GetFlag(FLAGS_output_dir).empty()) << "Specify --output_file or --output_dir"; eidos::audition::Run(); return 0; } // Local Variables: // mode: c++ // End:
19,201
C++
.cc
388
43.213918
90
0.669259
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,056
auditory_response.cc
google_eidos-audition/eidos/audition/auditory_response.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/auditory_response.h" #include <cstdint> #include "cnpy.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // Name of the array containing the center frequencies. constexpr char kCenterFrequenciesName[] = "CENTER_FREQUENCIES"; } // namespace void AuditoryResponse::WriteNpy(const std::string &filename) const { GOOGLE_CHECK_LT(0, outputs_.size()); const auto &response = outputs_.back().second; const uint32_t num_rows = response.rows(); const uint32_t num_cols = response.cols(); const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_mat = response.cast<float>(); const std::vector<std::size_t> shape = {static_cast<std::size_t>(num_rows), static_cast<std::size_t>(num_cols)}; const float *data = row_mat.data(); cnpy::npy_save(filename, data, shape, "w"); } void AuditoryResponse::WriteNpz(const std::string &filename) const { std::string write_mode = "w"; GOOGLE_LOG(INFO) << "Writing " << outputs_.size() << " outputs to " << filename; for (uint32_t i = 0; i < outputs_.size(); ++i) { const Eigen::ArrayXXd &response = outputs_[i].second; const std::size_t num_rows = response.rows(); const std::size_t num_cols = response.cols(); const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_mat = response.cast<float>(); const std::vector<std::size_t> shape = { num_rows, num_cols }; const float *data = row_mat.data(); const std::string output_name = AuditoryOutputType_Name(outputs_[i].first); GOOGLE_LOG(INFO) << "Writing " << output_name; cnpy::npz_save(filename, output_name, data, shape, write_mode); write_mode = "a"; } // Save center frequencies as a separate vector. const auto &center_frequencies = channel_properties_.center_frequencies; const std::size_t num_channels = center_frequencies.size(); GOOGLE_CHECK_LT(0, num_channels); cnpy::npz_save(filename, kCenterFrequenciesName, center_frequencies.data(), { num_channels }, write_mode); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,814
C++
.cc
64
40.203125
79
0.695144
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,057
jackson_spike_generator_test.cc
google_eidos-audition/eidos/audition/jackson_spike_generator_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple check that Jackson's spike generator behaves. #include <algorithm> #include <random> #include <vector> #include "Eigen/Core" #include "eidos/audition/gammatone_filterbank_config.pb.h" #include "eidos/audition/stimulus_config.pb.h" #include "eidos/audition/utils.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "third_party/audition/models/amt/meddis1986_hair_cell_synapse_model.h" #include "third_party/audition/models/bruce_carney/jackson_spike_generator.h" #include "third_party/audition/models/gammatone/gammatone_filterbank_model.h" using testing::AllOf; using testing::Each; using testing::Gt; using testing::Le; namespace eidos { namespace audition { TEST(JacksonSpikeGeneratorTest, SingleFiberRandomStimulus) { constexpr double kNumSamples = 100000; // Number of samples to test. constexpr double kSampleRate = 100000; // 100 kHz constexpr double kMinRate = 11.0; // Minimal firing rate. constexpr double kMaxRate = 153.0; // Maximum firing rate. constexpr double kMaxRepeats = 30; const std::vector<double> &rates = GetRandomUniformVector(kNumSamples, kMinRate, kMaxRate); for (int i = 1; i <= kMaxRepeats; ++i) { const std::vector<double> &spike_times = JacksonSpikeGenerator(rates, 1.0 / kSampleRate, i /* num_repeats */); EXPECT_LE(45, spike_times.size()); // Minimum number of spikes. EXPECT_TRUE(std::is_sorted(spike_times.begin(), spike_times.end())); // Check that all the spike times are sane. We expect the last possible // spike to be around one second which corresponds to stimulus duration. ASSERT_THAT(spike_times, Each(AllOf(Gt(0.0), Le(1.0)))); } } TEST(JacksonSpikeGeneratorTest, InputsFromMeddis1986HairCell) { // Generate firing rates using Meddis' hair cell model given the random // stimulus. constexpr int kNumChannels = 251; constexpr int kNumSamples = 10000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumChannels, kNumSamples); constexpr int kSampleRate = 16000; // Hz. Eigen::ArrayXXd rates; Meddis1986HairCellSynapse(input, kSampleRate, false /* subtract spontaneous firing rate */, &rates); EXPECT_EQ(kNumChannels, rates.rows()); EXPECT_EQ(kNumSamples, rates.cols()); // Run through Jackson's spike generator. Eigen::ArrayXXd spikes; JacksonSpikeGenerator(rates, 1.0 / kSampleRate /* sampling period */, 1 /* number of repetitions */, &spikes); EXPECT_EQ(kNumChannels, spikes.rows()); EXPECT_EQ(kNumSamples, spikes.cols()); EXPECT_FALSE(spikes.isZero()); EXPECT_EQ(0.0, spikes.minCoeff()); EXPECT_EQ(1.0, spikes.maxCoeff()); // Expect these lower bounds on the number of spikes. EXPECT_LT(7000, (spikes.array() != 0).count()); } TEST(JacksonSpikeGeneratorTest, InputsFromSlaneyGammatoneAndMeddis1986HairCell) { // Given the random stimulus, approximate basilar membrane displacements using // gammatone filters followed by the Meddis' model producing the firing rates. constexpr int kNumChannels = 251; constexpr double kSampleRate = 16000.0; // Hz. constexpr int kNumSamples = 20000; // Long enough so we get a good average. constexpr int kNumEars = 1; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); // Estimate basilar membrane displacements. StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); GammatoneFilterbankConfig gammatone_config; gammatone_config.set_filter_type(GAMMATONE_FILTERBANK_SLANEY); GammatoneFilterbankModel model(gammatone_config); model.Init(stimulus_config); Eigen::ArrayXXd bm_output; model.ProcessSegment(input, &bm_output); const ChannelProperties &channel_properties = model.GetChannelProperties(); EXPECT_EQ(channel_properties.NumChannels(), bm_output.rows()); EXPECT_EQ(kNumSamples, bm_output.cols()); // Estimate firing rate probabilities. Eigen::ArrayXXd rates; Meddis1986HairCellSynapse(bm_output, kSampleRate, false /* subtract spontaneous firing rate */, &rates); EXPECT_EQ(kNumChannels, rates.rows()); EXPECT_EQ(kNumSamples, rates.cols()); // Run through Jackson's spike generator. Eigen::ArrayXXd spikes; JacksonSpikeGenerator(rates, 1.0 / kSampleRate /* sampling period */, 1 /* number of repetitions */, &spikes); EXPECT_EQ(kNumChannels, spikes.rows()); EXPECT_EQ(kNumSamples, spikes.cols()); EXPECT_FALSE(spikes.isZero()); EXPECT_EQ(0.0, spikes.minCoeff()); EXPECT_EQ(1.0, spikes.maxCoeff()); // Expect these lower bounds on the number of spikes. EXPECT_LT(2000, (spikes.array() != 0).count()); } TEST(JacksonSpikeGeneratorTest, SimpleModelInterfaceRandomInputs) { // Generate random firing rate inputs in the range (kMinRate, kMaxRate). constexpr double kNumChannels = 50; constexpr double kNumSamples = 200000; // Number of samples to test. constexpr double kMinRate = 11.0; // Minimal firing rate. constexpr double kMaxRate = 153.0; // Maximum firing rate. const Eigen::ArrayXXd input = kMinRate + (Eigen::ArrayXXd::Random( kNumChannels, kNumSamples) * 0.5 + 0.5) + (kMaxRate - kMinRate); // Run the model. constexpr double kSampleRate = 100000; // 100 kHz StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); JacksonSpikeGeneratorModel model; Eigen::ArrayXXd spikes; model.Init(stimulus_config); model.ProcessSegment(input, &spikes); EXPECT_EQ(kNumChannels, spikes.rows()); EXPECT_EQ(kNumSamples, spikes.cols()); EXPECT_FALSE(spikes.isZero()); EXPECT_EQ(0.0, spikes.minCoeff()); EXPECT_EQ(1.0, spikes.maxCoeff()); // Expect these lower bounds on the number of spikes. constexpr int kMinNumSpikes = 9000; EXPECT_LT(kMinNumSpikes, (spikes.array() != 0).count()); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
6,622
C++
.cc
147
41.22449
80
0.729583
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,058
mock_basilar_membrane_model.cc
google_eidos-audition/eidos/audition/mock_basilar_membrane_model.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/mock_basilar_membrane_model.h" #include "eidos/audition/psychoacoustic_scale_utils.h" namespace eidos { namespace audition { namespace { // Minimum characteristic frequency in Hz (human). constexpr double kMinFrequency = 25.0; // Maximum characteristic frequency in Hz (human). constexpr double kMaxFrequency = 10E+3; // Mock transmembrane voltages. constexpr double kMinVoltage = -0.018051; // ~18 mV constexpr double kMaxVoltage = 0.038092; // ~38 mV // Creates mock properties for the model. ChannelProperties CreateProperties(int num_channels) { ChannelProperties properties; properties.center_frequencies = erb::GetFrequenciesHz( num_channels, kMinFrequency, kMaxFrequency); return properties; } } // namespace constexpr int MockBasilarMembraneModel::kDefaultNumChannelsForWaveformInput; MockBasilarMembraneModel::MockBasilarMembraneModel() : AuditoryModel(MODEL_MOCK_BASILAR_MEMBRANE, STAGE_BASILAR_MEMBRANE, OUTPUT_BASILAR_MEMBRANE_DISPLACEMENT, true /* waveform input */) {} void MockBasilarMembraneModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); } ChannelProperties MockBasilarMembraneModel::GetChannelProperties() const { return channel_properties_; } void MockBasilarMembraneModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { const int num_samples = input.cols(); if (input.rows() == 1) { int num_channels = stimulus_config().num_channels(); if (num_channels <= 0) { num_channels = kDefaultNumChannelsForWaveformInput; } channel_properties_ = CreateProperties(num_channels); // Simulate transmembrane voltages in [kMinVoltage, kMaxVoltage] V. *output = kMinVoltage + (Eigen::ArrayXXd::Random( num_channels, num_samples) * 0.5 + 0.5) * (kMaxVoltage - kMinVoltage); } else { channel_properties_ = CreateProperties(input.rows()); *output = input; } } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,689
C++
.cc
67
37.089552
78
0.751822
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,059
auditory_feature_extractor.cc
google_eidos-audition/eidos/audition/auditory_feature_extractor.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/auditory_feature_extractor.h" #include <vector> #include "eidos/audition/auditory_pipeline.h" #include "eidos/audition/resampler.h" #include "eidos/audition/stimulus_config.pb.h" #include "eidos/audition/waveform_utils.h" #include "eidos/audition/windowing.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // Only accept monaural input for now. constexpr int kNumEars = 1; } // namespace bool AuditoryFeatureExtractor::ComputeFeatures( const Waveform &waveform, const AuditoryFeatureExtractorConfig &config, AuditoryResponse *response) const { // Fetch the audio sampling rate from the waveform. StimulusConfig stimulus_config = config.config(); stimulus_config.set_sample_rate(waveform.sample_rate()); // Scales the input waveform to [-1, 1] range. std::vector<float> samples; ScaleToUnitWaveform(waveform, stimulus_config.audio_scaling_gain(), &samples); const int num_samples = samples.size(); Eigen::ArrayXXd input(kNumEars, num_samples); for (int i = 0; i < num_samples; ++i) { input(0, i) = samples[i]; } // Initialize the pipeline. AuditoryPipeline pipeline; if (!pipeline.Init(config.pipeline())) { GOOGLE_LOG(ERROR) << "Failed to initialize auditory pipeline"; return false; } // Feed the stimulus to the pipeline. pipeline.Process(stimulus_config, input, response); const auto &last_output = response->outputs().back().second; if (last_output.matrix().squaredNorm() <= 0) { GOOGLE_LOG(ERROR) << "Invalid filterbank output!"; return false; } GOOGLE_LOG(INFO) << "Generated " << last_output.size() << " values " << "[sample_rate: " << stimulus_config.sample_rate() << ", frequency channels: " << last_output.rows() << ", samples: " << last_output.cols() << "]."; // Resample the output, if required, and adjust the sampling rate. const int downsample_step = stimulus_config.downsample_step(); if (ShouldResampleOutputs(stimulus_config) || downsample_step > 1) { for (auto &output : *response->mutable_outputs()) { Eigen::ArrayXXd output_frames; if (downsample_step > 1) { output_frames = DownstepResample(output.second, stimulus_config); } else { output_frames = Resample(output.second, stimulus_config); } output.second.swap(output_frames); } // Update sampling rate. int output_sample_rate; if (downsample_step > 1) { output_sample_rate = stimulus_config.sample_rate() / downsample_step; } else { output_sample_rate = stimulus_config.sample_rate() * stimulus_config.output_resample_up_factor() / stimulus_config.output_resample_down_factor(); } stimulus_config.set_sample_rate(output_sample_rate); GOOGLE_LOG(INFO) << "Resampler: Generated " << last_output.cols() << " samples. Sample rate: " << stimulus_config.sample_rate(); } // Apply windowing if necessary. if (stimulus_config.apply_window_to_outputs()) { for (auto &output : *response->mutable_outputs()) { Eigen::ArrayXXd output_frames = WindowAndIntegrateTime( output.second, stimulus_config); output.second.swap(output_frames); } GOOGLE_LOG(INFO) << "Windowing: Generated " << last_output.cols() << " frames."; } return true; } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
4,102
C++
.cc
101
35.980198
80
0.688159
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,060
carfac_model.cc
google_eidos-audition/eidos/audition/carfac_model.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/carfac_model.h" #include "cpp/agc.h" #include "cpp/car.h" #include "cpp/carfac.h" #include "cpp/ihc.h" #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // We only support monaural inputs. constexpr int kNumEars = 1; // Manufactures CARFAC output configuration given the corresponding // configuration proto. CARFACOutput *NewOutput(const CarfacConfig::OutputTypes &output_types) { return new CARFACOutput( output_types.store_nap(), // Store Neural Activity Patterns (NAP). output_types.store_bm(), // Store Basilar Membrane (BM) displacements. output_types.store_ohc(), // Store Outer Hair Cells (OHCs). output_types.store_agc()); // Store Adaptive Gain Control (AGC). } // Default initialization for the Cascade of Asymmetric Resonators (CAR) // filter parameters. These defaults have been copied from CAR implementation. void InitDefaults(CarfacConfig::CarParams *car) { CARParams def_car; // Constructed with defaults. if (car->velocity_scale() == 0.0) { car->set_velocity_scale(def_car.velocity_scale); } if (car->v_offset() == 0.0) car->set_v_offset(def_car.v_offset); if (car->min_zeta() == 0.0) car->set_min_zeta(def_car.min_zeta); if (car->max_zeta() == 0.0) car->set_max_zeta(def_car.max_zeta); if (car->first_pole_theta() == 0.0) { car->set_first_pole_theta(def_car.first_pole_theta); } if (car->zero_ratio() == 0.0) car->set_zero_ratio(def_car.zero_ratio); if (car->high_f_damping_compression() == 0.0) { car->set_high_f_damping_compression(def_car.high_f_damping_compression); } if (car->erb_per_step() == 0.0) car->set_erb_per_step(def_car.erb_per_step); if (car->min_pole_hz() == 0.0) car->set_min_pole_hz(def_car.min_pole_hz); // The Greenwood map's break frequency in Hertz. if (car->erb_break_freq() == 0.0) { car->set_erb_break_freq(def_car.erb_break_freq); } // Glassberg and Moore's high-cf ratio. if (car->erb_q() == 0.0) car->set_erb_q(def_car.erb_q); } // Default initialization for the IHC filter parameters. These defaults have // been copied from CAR implementation. void InitDefaults(CarfacConfig::IhcParams *ihc) { IHCParams def_ihc; // Constructed with default values. ihc->set_just_half_wave_rectify(def_ihc.just_half_wave_rectify); // Force. ihc->set_one_capacitor(def_ihc.one_capacitor); // Force. if (ihc->tau_lpf() == 0.0) ihc->set_tau_lpf(def_ihc.tau_lpf); if (ihc->tau1_out() == 0.0) ihc->set_tau1_out(def_ihc.tau1_out); if (ihc->tau1_in() == 0.0) ihc->set_tau1_in(def_ihc.tau1_in); if (ihc->tau2_out() == 0.0) ihc->set_tau2_out(def_ihc.tau2_out); if (ihc->tau2_in() == 0.0) ihc->set_tau2_in(def_ihc.tau2_in); if (ihc->ac_corner_hz() == 0.0) ihc->set_ac_corner_hz(def_ihc.ac_corner_hz); } // Default initialization for the Adaptive Gain Control (AGC) filter parameters. // These defaults have been copied from CAR implementation. void InitDefaults(CarfacConfig::AgcParams *agc) { AGCParams def_agc; // Constructed with default values. if (agc->num_stages() == 0) agc->set_num_stages(def_agc.num_stages); if (agc->agc_stage_gain() == 0.0) { agc->set_agc_stage_gain(def_agc.agc_stage_gain); } if (agc->agc1_scales().empty()) { *agc->mutable_agc1_scales() = { def_agc.agc1_scales.begin(), def_agc.agc1_scales.end()}; } if (agc->agc2_scales().empty()) { *agc->mutable_agc2_scales() = { def_agc.agc2_scales.begin(), def_agc.agc2_scales.end()}; } GOOGLE_CHECK_LT(0, agc->agc1_scales().size()); GOOGLE_CHECK_EQ(agc->agc1_scales().size(), agc->agc2_scales().size()); if (agc->time_constants().empty()) { *agc->mutable_time_constants() = { def_agc.time_constants.begin(), def_agc.time_constants.end()}; } GOOGLE_CHECK_EQ(agc->time_constants().size(), agc->agc1_scales().size()); if (agc->decimation().empty()) { *agc->mutable_decimation() = { def_agc.decimation.begin(), def_agc.decimation.end()}; } if (agc->agc_mix_coeff() == 0.0) { agc->set_agc_mix_coeff(def_agc.agc_mix_coeff); } } // Default initialization for the configuration. void InitDefaults(CarfacConfig *config) { InitDefaults(config->mutable_car()); InitDefaults(config->mutable_ihc()); InitDefaults(config->mutable_agc()); // If no output signal types were configured, only store neural activity // pattern (NAP). CarfacConfig::OutputTypes *output_types = config->mutable_output_types(); if (!output_types->store_nap() && !output_types->store_bm() && !output_types->store_ohc() && !output_types->store_agc()) { output_types->set_store_nap(true); output_types->set_store_bm(false); output_types->set_store_ohc(false); output_types->set_store_agc(false); } } // Initializes CAR parameters from the configuration proto. void InitFromProto(const CarfacConfig::CarParams &proto, CARParams *car) { car->velocity_scale = proto.velocity_scale(); car->v_offset = proto.v_offset(); car->min_zeta = proto.min_zeta(); car->max_zeta = proto.max_zeta(); car->first_pole_theta = proto.first_pole_theta(); car->zero_ratio = proto.zero_ratio(); car->high_f_damping_compression = proto.high_f_damping_compression(); car->erb_per_step = proto.erb_per_step(); car->min_pole_hz = proto.min_pole_hz(); car->erb_break_freq = proto.erb_break_freq(); car->erb_q = proto.erb_q(); } // Initializes IHC parameters from the configuration proto. void InitFromProto(const CarfacConfig::IhcParams &proto, IHCParams *ihc) { ihc->just_half_wave_rectify = proto.just_half_wave_rectify(); ihc->one_capacitor = proto.one_capacitor(); ihc->tau_lpf = proto.tau_lpf(); ihc->tau1_out = proto.tau1_out(); ihc->tau1_in = proto.tau1_in(); ihc->tau2_out = proto.tau2_out(); ihc->tau2_in = proto.tau2_in(); ihc->ac_corner_hz = proto.ac_corner_hz(); } // Initializes AGC parameters from the configuration proto. void InitFromProto(const CarfacConfig::AgcParams &proto, AGCParams *agc) { agc->num_stages = proto.num_stages(); agc->agc_stage_gain = proto.agc_stage_gain(); agc->agc1_scales = { proto.agc1_scales().begin(), proto.agc1_scales().end()}; agc->agc2_scales = { proto.agc2_scales().begin(), proto.agc2_scales().end()}; agc->time_constants = { proto.time_constants().begin(), proto.time_constants().end()}; agc->decimation = { proto.decimation().begin(), proto.decimation().end()}; agc->agc_mix_coeff = proto.agc_mix_coeff(); } } // namespace struct CarfacHandle { CarfacHandle(FPType sample_rate, const CARParams &car_params, const IHCParams &ihc_params, const AGCParams &agc_params) : carfac_(kNumEars, sample_rate, car_params, ihc_params, agc_params) {} CarfacHandle() = delete; CARFAC carfac_; }; // Note: The output of the last stage of CARFAC, the neural activity pattern // (NAP) represents, at least conceptually, the instantaneous firing rates of // the groups of primary auditory neurons attached to each inner hair cell // (IHC). // // TODO(agutkin): Double-check if NAP can represent firing rates. CarfacModel::CarfacModel(const CarfacConfig &config) : AuditoryModel( MODEL_CARFAC, STAGE_AUDITORY_NERVE_SYNAPSE, OUTPUT_SYNAPSE_FIRING_RATES, true /* waveform input */) { config_ = config; InitDefaults(&config_); } CarfacModel::~CarfacModel() = default; void CarfacModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); // Initialize the values for CARFAC filter parameters. CARParams car_params; // Will use the defaults. InitFromProto(config_.car(), &car_params); IHCParams ihc_params; // Will use the defaults. InitFromProto(config_.ihc(), &ihc_params); AGCParams agc_params; // Will use the defaults. InitFromProto(config_.agc(), &agc_params); // Create the filter handle. const int sample_rate = stimulus_config.sample_rate(); GOOGLE_CHECK_LT(0, sample_rate) << "Invalid sampling rate: " << sample_rate; impl_.reset(new CarfacHandle(sample_rate, car_params, ihc_params, agc_params)); // CARFAC configures its own number of filters based on the sampling rate. if (stimulus_config.num_channels() > 0) { GOOGLE_LOG(WARNING) << "Ignoring override of number of channels"; } // Compute channel properties. auto &center_frequencies = channel_properties_.center_frequencies; const int num_channels = impl_->carfac_.num_channels(); const Eigen::ArrayXf &pole_frequencies = impl_->carfac_.pole_frequencies(); GOOGLE_CHECK_EQ(num_channels, pole_frequencies.size()); center_frequencies.resize(num_channels); Eigen::VectorXd::Map(&center_frequencies[0], num_channels) = pole_frequencies.cast<double>(); } ChannelProperties CarfacModel::GetChannelProperties() const { return channel_properties_; } void CarfacModel::Reset() { GOOGLE_CHECK(impl_ != nullptr); impl_->carfac_.Reset(); } void CarfacModel::ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { GOOGLE_CHECK(impl_ != nullptr); std::unique_ptr<CARFACOutput> output_buffer(NewOutput( config_.output_types())); impl_->carfac_.RunSegment(input.cast<float>(), config_.agc_open_loop(), // AGC open loop. output_buffer.get()); const std::vector<ArrayXX> *output_signal = nullptr; const CarfacConfig::OutputTypes &output_types = config_.output_types(); if (output_types.store_nap()) { output_signal = &output_buffer->nap(); } else if (output_types.store_bm()) { output_signal = &output_buffer->bm(); } else if (output_types.store_ohc()) { output_signal = &output_buffer->ohc(); } else { output_signal = &output_buffer->agc(); } GOOGLE_CHECK_EQ(1, output_signal->size()); // Single ear. *output = (*output_signal)[0].cast<double>(); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
10,595
C++
.cc
241
40.572614
80
0.6942
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,061
mock_basilar_membrane_model_test.cc
google_eidos-audition/eidos/audition/mock_basilar_membrane_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test for the mock basilar membrane model. #include "Eigen/Core" #include "eidos/audition/mock_basilar_membrane_model.h" #include "eidos/audition/stimulus_config.pb.h" #include "gtest/gtest.h" namespace eidos { namespace audition { namespace { TEST(MockBasilarMembraneModelTest, CheckTwoDimensionalStimulus) { StimulusConfig stimulus_config; stimulus_config.set_sample_rate(100000 /* Hz */); stimulus_config.set_audio_scaling_gain(1.0); constexpr int kNumChannels = 100; constexpr int kNumSamples = 10000; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random( kNumChannels, kNumSamples); MockBasilarMembraneModel model; model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); EXPECT_EQ(kNumChannels, output.rows()); EXPECT_EQ(kNumSamples, output.cols()); } // Checks the case when the input is assumed to be monaural input. void CheckWaveformWithSimulatedChannels(int input_num_channels, int expected_num_channels) { StimulusConfig stimulus_config; stimulus_config.set_sample_rate(100000 /* Hz */); stimulus_config.set_audio_scaling_gain(1.0); stimulus_config.set_num_channels(input_num_channels); constexpr int kNumSamples = 10000; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random( 1, kNumSamples); MockBasilarMembraneModel model; model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); EXPECT_EQ(expected_num_channels, output.rows()); EXPECT_EQ(kNumSamples, output.cols()); } TEST(MockBasilarMembraneModelTest, CheckMockWaveformWithDefaultNumChannels) { CheckWaveformWithSimulatedChannels( 0, MockBasilarMembraneModel::kDefaultNumChannelsForWaveformInput); } TEST(MockBasilarMembraneModelTest, CheckMockWaveformWithConfiguredNumChannels) { constexpr int kNumChannels = 50; CheckWaveformWithSimulatedChannels(kNumChannels, kNumChannels); } } // namespace } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,638
C++
.cc
67
36.567164
80
0.772053
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,062
fractional_gaussian_noise_test.cc
google_eidos-audition/eidos/audition/fractional_gaussian_noise_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Checks that fractional Gaussian and Brownian motion APIs behave. #include <algorithm> #include <cmath> #include <numeric> #include "Eigen/Core" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "third_party/audition/models/bruce_carney/fractional_gaussian_noise.h" using testing::Each; using testing::Ne; namespace eidos { namespace audition { TEST(FractionalGaussianNoiseTest, JacksonWhiteGaussianNoise) { // Check a case of pure white Gaussian noise. constexpr int kOutputLength = 100000; constexpr double kEpsilon = 2E-1; Eigen::VectorXd output = JacksonFractionalGaussianNoise( kOutputLength, 0.5 /* Hurst index */, 0.0 /* mean */, 1.0 /* standard deviation */); EXPECT_EQ(kOutputLength, output.size()); std::vector<double> vec(output.data(), output.data() + output.size()); EXPECT_THAT(vec, Each(Ne(0.0))); double mean = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size(); EXPECT_NEAR(0.0, mean, kEpsilon); // Same as above, but Brownian motion corresponding to white Gaussian // noise. Compute cumulative subtraction to get at the white noise. output = JacksonFractionalGaussianNoise( kOutputLength, 1.5 /* Hurst index */, 0.0 /* mean */, 1.0 /* standard deviation */); EXPECT_EQ(kOutputLength, output.size()); double cum_sum = 0.0; for (int i = 0; i < kOutputLength; ++i) { vec[i] = output[i] - cum_sum; cum_sum += vec[i]; } mean = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size(); EXPECT_NEAR(0.0, mean, kEpsilon); } TEST(FractionalGaussianNoiseTest, JacksonFractionalGaussianNoiseOrBrownian) { // Generate fractional Gaussian noise. constexpr int kOutputLength = 30000; constexpr double kEpsilon = 1.5; for (double hurst = 0.01; hurst <= 2.0; hurst += 0.05) { const Eigen::VectorXd output = JacksonFractionalGaussianNoise( kOutputLength, hurst /* Hurst index */, 0.0 /* mean */, 1.0 /* standard deviation */); EXPECT_EQ(kOutputLength, output.size()); const std::vector<double> vec(output.data(), output.data() + output.size()); if (hurst < 1.0) { // Fractional Gaussian noise. The mean should be roughly around zero and // the standard deviation around unity, which, given the small sample // size, is going to just about hold true given a large epsilon. const double mean = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size(); EXPECT_NEAR(0.0, std::fabs(mean), kEpsilon); const double sum_squares = std::inner_product( vec.begin(), vec.end(), vec.begin(), 0.0, [](double x, double y) { return x + y; }, [mean](double x, double y) { return (x - mean) * (y - mean); }); const double stddev = sum_squares / (vec.size() - 1); EXPECT_NEAR(1.0, std::fabs(stddev), kEpsilon); } } } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
3,540
C++
.cc
83
38.686747
79
0.682913
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,063
resampler_test.cc
google_eidos-audition/eidos/audition/resampler_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/resampler.h" #include <vector> #include "Eigen/Core" #include "eidos/audition/stimulus_config.pb.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::AllOf; using testing::Each; using testing::Gt; using testing::Le; namespace eidos { namespace audition { constexpr int kNumChannels = 50; constexpr int kNumSamples = 200000; constexpr int kSampleRate = 96000; // 96 kHz. constexpr int kUpsamplingFactor = 1; constexpr int kDownsamplingFactor = 6; // 16 kHz = kSampleRate / 6. TEST(WindowingTest, BasicCheckDownsampleStep) { // Check no-op. StimulusConfig config; config.set_downsample_step(1); const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random( kNumChannels, kNumSamples); Eigen::ArrayXXd output = DownstepResample(input, config); EXPECT_EQ(input.cols(), output.cols()); EXPECT_EQ(input.rows(), output.rows()); config.set_downsample_step(3); output = DownstepResample(input, config); EXPECT_EQ(input.cols() / 3, output.cols()); EXPECT_EQ(input.rows(), output.rows()); } TEST(WindowingTest, BasicCheckNormalDownsample) { // Prepare configuration. StimulusConfig config; config.set_sample_rate(kSampleRate); config.set_output_resample_up_factor(kUpsamplingFactor); config.set_output_resample_down_factor(kDownsamplingFactor); EXPECT_TRUE(ShouldResampleOutputs(config)); // Call the downsampler. constexpr double kOriginalVal = 1.0; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Constant( kNumChannels, kNumSamples, kOriginalVal); const Eigen::ArrayXXd output = Resample(input, config); EXPECT_EQ(kNumChannels, output.rows()); const int num_output_samples = output.cols(); EXPECT_EQ(num_output_samples, kNumSamples / kDownsamplingFactor + 1); // Check resampled values, these should not be 1.0 because of the filtering. const std::vector<double> resampled(output.data(), output.data() + output.size()); EXPECT_THAT(resampled, Each(AllOf(Gt(kOriginalVal / 2), Le(kOriginalVal * 2)))); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,761
C++
.cc
70
36.257143
78
0.734877
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,064
sumner2002_hair_cell_synapse_model_test.cc
google_eidos-audition/eidos/audition/sumner2002_hair_cell_synapse_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test for synaptic model by Sumner, et. al. (2002). #include "Eigen/Core" #include "eidos/audition/gammatone_filterbank_config.pb.h" #include "eidos/audition/sumner2002_hair_cell_synapse_config.pb.h" #include "gtest/gtest.h" #include "third_party/audition/models/dsam/sumner2002_hair_cell_synapse_model.h" #include "third_party/audition/models/gammatone/gammatone_filterbank_model.h" namespace eidos { namespace audition { namespace { // Fills in and returns model configuration. Sumner2002HairCellSynapseConfig GetConfig(bool output_spikes) { Sumner2002HairCellSynapseConfig config; config.set_ca_cond_mode(SUMNER2002_CA_COND_MODE_ORIGINAL); config.set_cleft_replenish_mode(SUMNER2002_CLEFT_REPLENISH_MODE_ORIGINAL); config.set_output_spikes(output_spikes); return config; } } // namespace TEST(Sumner2002HairCellSynapseModelTest, CheckRandomOriginalPaperProbs) { // This model is extremely sensitive to the input stimulus levels. Supplying // "wrong" stimulus intensity will result in numeric overflows and/or invalid // probability estimates. constexpr int kNumChannels = 10; constexpr int kNumSamples = 200000; constexpr int kSampleRate = 100000; // Hz. constexpr double kInputScaleFactor = 100.0; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumChannels, kNumSamples) / kInputScaleFactor; Eigen::ArrayXXd output; const Sumner2002HairCellSynapseConfig config = GetConfig( /* output_spikes */false); Sumner2002HairCellSynapse(config, input, kSampleRate, &output); EXPECT_EQ(kNumChannels, output.rows()); EXPECT_EQ(kNumSamples, output.cols()); EXPECT_LE(0.0, output.minCoeff()); EXPECT_GE(1.0, output.maxCoeff()); } TEST(Sumner2002HairCellSynapseModelTest, CheckRandomOriginalPaperSpikes) { constexpr int kNumChannels = 10; constexpr int kNumSamples = 200000; constexpr int kSampleRate = 100000; // Hz. constexpr double kInputScaleFactor = 5.0; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumChannels, kNumSamples) / kInputScaleFactor; Eigen::ArrayXXd output; const Sumner2002HairCellSynapseConfig config = GetConfig( /* output_spikes */true); Sumner2002HairCellSynapse(config, input, kSampleRate, &output); EXPECT_EQ(kNumChannels, output.rows()); EXPECT_EQ(kNumSamples, output.cols()); EXPECT_LE(0.0, output.minCoeff()); EXPECT_GE(5.0, output.maxCoeff()); } TEST(Sumner2002HairCellSynapseTest, GammatoneOverRandomStimulus) { constexpr int kNumChannels = 251; constexpr int kNumSamples = 10000; // Long enough so we get a good average. constexpr double kInputScaleFactor = 5.0; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumChannels, kNumSamples) / kInputScaleFactor; constexpr int kSampleRate = 48000; // Hz. // Estimate basilar membrane displacements. StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate /* Hz */); GammatoneFilterbankConfig gammatone_config; gammatone_config.set_filter_type(GAMMATONE_FILTERBANK_SLANEY); GammatoneFilterbankModel model(gammatone_config); model.Init(stimulus_config); Eigen::ArrayXXd bm_output; model.ProcessSegment(input, &bm_output); const ChannelProperties &channel_properties = model.GetChannelProperties(); EXPECT_EQ(channel_properties.NumChannels(), bm_output.rows()); EXPECT_EQ(kNumSamples, bm_output.cols()); // Run Sumner's model. Eigen::ArrayXXd output; const Sumner2002HairCellSynapseConfig config = GetConfig( /* output_spikes */false); Sumner2002HairCellSynapse(config, bm_output, kSampleRate, &output); EXPECT_EQ(kNumChannels, output.rows()); EXPECT_EQ(kNumSamples, output.cols()); EXPECT_LE(0.0, output.minCoeff()); EXPECT_GE(1.0, output.maxCoeff()); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
4,413
C++
.cc
101
41.089109
80
0.773488
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,065
meddis1986_hair_cell_synapse_model_test.cc
google_eidos-audition/eidos/audition/meddis1986_hair_cell_synapse_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test for Ray Meddis' model of inner hair cell synapse. #include "Eigen/Core" #include "eidos/audition/gammatone_filterbank_config.pb.h" #include "eidos/audition/stimulus_config.pb.h" #include "gtest/gtest.h" #include "third_party/audition/models/amt/meddis1986_hair_cell_synapse_model.h" #include "third_party/audition/models/baumgarte/baumgarte_model.h" #include "third_party/audition/models/gammatone/gammatone_filterbank_model.h" namespace eidos { namespace audition { // Computes IHC synapse response and performs various checks depending on // whether the steady-state response is removed from the response or not. void RandomStimulus(bool subtract_spontaneous_rate) { constexpr int kNumChannels = 251; constexpr int kNumSamples = 10000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumChannels, kNumSamples); constexpr int kSampleRate = 16000; // Hz. Eigen::ArrayXXd output; Meddis1986HairCellSynapse(input, kSampleRate, subtract_spontaneous_rate, &output); EXPECT_EQ(kNumChannels, output.rows()); EXPECT_EQ(kNumSamples, output.cols()); // Check the bounds on steady-state spontaneous firing rate and the maximum // firing rate. Spontaneous rate is so small that it doesn't make a huge // effect on the firing rate limits. EXPECT_LT(10.0, output.minCoeff()); EXPECT_GT(80.0, output.maxCoeff()); } TEST(Meddis1986HairCellSynapseTest, RandomizedStimulusWithSpontaneousRateTest) { RandomStimulus(false /* subtract_spontaneous_rate */); } TEST(Meddis1986HairCellSynapseTest, RandomizedStimulusWithNoSpontaneousRateTest) { RandomStimulus(true /* subtract_spontaneous_rate */); } TEST(Meddis1986HairCellSynapseTest, GammatoneOverRandomStimulus) { constexpr int kNumChannels = 251; constexpr int kNumSamples = 10000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumChannels, kNumSamples); constexpr int kSampleRate = 16000; // Hz. // Estimate basilar membrane displacements. StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate /* Hz */); GammatoneFilterbankConfig config; config.set_filter_type(GAMMATONE_FILTERBANK_SLANEY); GammatoneFilterbankModel model(config); model.Init(stimulus_config); Eigen::ArrayXXd bm_output; model.ProcessSegment(input, &bm_output); const ChannelProperties &channel_properties = model.GetChannelProperties(); EXPECT_EQ(channel_properties.NumChannels(), bm_output.rows()); EXPECT_EQ(kNumSamples, bm_output.cols()); // Run Meddis' model. Eigen::ArrayXXd output; Meddis1986HairCellSynapse(bm_output, kSampleRate, false /* subtract_spontaneous_rate */, &output); EXPECT_EQ(kNumChannels, output.rows()); EXPECT_EQ(kNumSamples, output.cols()); EXPECT_LT(60.0, output.minCoeff()); EXPECT_GT(70.0, output.maxCoeff()); } TEST(Meddis1986HairCellSynapseTest, BaumgarteOverRandomStimulus) { // Random input pressure wave. const int kNumEars = 1; const int kNumSamples = 20000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); // Estimate IHC voltages. For the Meddis model, we ideally need the // BM displacements instead. const int kSampleRate = 100000; // Hz const int kNumChannels = 251; StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); stimulus_config.set_downsample_step(1); // No downsampling. BaumgarteModel model; model.Init(stimulus_config); Eigen::ArrayXXd voltages; model.ProcessSegment(input, &voltages); EXPECT_EQ(kNumChannels, voltages.rows()); EXPECT_EQ(kNumSamples, voltages.cols()); EXPECT_LT(-1.0, voltages.minCoeff()); EXPECT_GT(2.0, voltages.maxCoeff()); // Run the synapse model. Perform fake voltage -> BM displacement scaling. Meddis1986HairCellSynapseModel synapse_model; synapse_model.Init(stimulus_config); Eigen::ArrayXXd rates; // firing rates. constexpr double kVoltageToDisplacement = 2000.0; const Eigen::ArrayXXd bm_displacements = voltages * kVoltageToDisplacement; synapse_model.ProcessSegment(bm_displacements, &rates); const ChannelProperties &channel_properties = model.GetChannelProperties(); EXPECT_EQ(kNumChannels, channel_properties.NumChannels()); EXPECT_EQ(kNumChannels, rates.rows()); EXPECT_EQ(kNumSamples, rates.cols()); EXPECT_LT(1.0, rates.minCoeff()); // Hz. EXPECT_GT(210.0, rates.maxCoeff()); // Hz. } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
5,213
C++
.cc
115
42.382609
80
0.762345
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,066
auditory_feature_extractor_test.cc
google_eidos-audition/eidos/audition/auditory_feature_extractor_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Sanity check for the feature extractor. #include "Eigen/Core" #include "eidos/audition/auditory_feature_extractor.h" #include "eidos/audition/auditory_feature_extractor_config.pb.h" #include "eidos/audition/auditory_response.h" #include "eidos/audition/waveform_utils.h" #include "gtest/gtest.h" namespace eidos { namespace audition { namespace { // Source waveform in original sample rate (24 kHz). const char kWaveFilePath[] = "eidos/audition/testdata/ne_np/nep_letter_ma.wav"; // Source waveform in 100kHz. const char k100kHzWaveFilePath[] = "eidos/audition/testdata/ne_np/nep_letter_ma_100kHz.wav"; // CARFAC filterbank produces 72 tonotopic channels for 24 kHz input. const int kNumChannelsAt24Carfac = 72; // Number of channels for Baumgarte's model. const int kNumChannelsBaumgarte = 251; } // namespace class AuditoryFeatureExtractorTest : public ::testing::Test { protected: // Some filterbanks (like Baumgarte's and Zilany's) require the stimulus // to be 100kHz or more. void Init(bool high_sample_rate) { if (high_sample_rate) { ASSERT_TRUE(ReadWaveform(k100kHzWaveFilePath, &wave_)); EXPECT_EQ(100000, wave_.sample_rate()); } else { ASSERT_TRUE(ReadWaveform(kWaveFilePath, &wave_)); EXPECT_EQ(24000, wave_.sample_rate()); } EXPECT_EQ(1, wave_.num_channels()); // Mono. } void CheckModel(AuditoryModelType model_type, int expected_num_channels) { StimulusConfig *stimulus_config = config_.mutable_config(); stimulus_config->set_audio_scaling_gain(0.07); config_.mutable_pipeline()->add_models()->set_model_type(model_type); AuditoryResponse response; AuditoryFeatureExtractor extractor; EXPECT_TRUE(extractor.ComputeFeatures(wave_, config_, &response)) << "Failed to extract " << AuditoryModelType_Name(model_type) << " features!"; EXPECT_EQ(1, response.outputs().size()); const Eigen::ArrayXXd &output = response.outputs().back().second; EXPECT_EQ(wave_.samples().size(), output.cols()); EXPECT_EQ(expected_num_channels, output.rows()); // Check that output is not all zeros. EXPECT_GT(output.matrix().squaredNorm(), 0.0); } // Configuration for the cochlear extractor. AuditoryFeatureExtractorConfig config_; // Actual waveform for testing. Waveform wave_; }; // Runs the input waveform through the filterbank only without any downsampling // or audio image stabilization. The output is sample-based. TEST_F(AuditoryFeatureExtractorTest, CarfacCheckOriginalWaveform) { Init(false /* use native sample rate */); CheckModel(MODEL_CARFAC, kNumChannelsAt24Carfac); } TEST_F(AuditoryFeatureExtractorTest, BaumgarteCheckOriginalWaveform) { Init(true /* use 100kHz audio */); config_.mutable_config()->set_downsample_step(1 /* no downsampling */); CheckModel(MODEL_BAUMGARTE, kNumChannelsBaumgarte); } TEST_F(AuditoryFeatureExtractorTest, Zilany2014CheckOriginalWaveform) { Init(true /* use 100kHz audio */); config_.mutable_config()->set_downsample_step(1 /* no downsampling */); CheckModel( MODEL_ZILANY_IHC_2014, kNumChannelsBaumgarte /* same number of channels as Baumgarte's */); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
3,870
C++
.cc
93
38.505376
79
0.741489
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,067
baumgarte_model_test.cc
google_eidos-audition/eidos/audition/baumgarte_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test for Baumgarte's model of auditory periphery. #include <algorithm> #include <cstddef> #include <fstream> #include <functional> #include <string> #include "Eigen/Core" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "eidos/audition/stimulus_config.pb.h" #include "eidos/audition/waveform.pb.h" #include "eidos/audition/waveform_utils.h" #include "eidos/port/logging.h" #include "gtest/gtest.h" #include "third_party/audition/models/baumgarte/baumgarte_model.h" namespace eidos { namespace audition { namespace { // Test mock. class BaumgarteModelMock : public BaumgarteModel { public: using BaumgarteModel::set_native_downsample_step; }; // Checks computed channel properties. The Slaney's implementation places center // frequencies in decreasing order, while Ma's implementation uses increasing // order. template <typename Comparator> void CheckChannelProperties(const ChannelProperties &channel_properties, int expected_num_channels, Comparator comparator) { const auto &center_frequencies = channel_properties.center_frequencies; EXPECT_EQ(center_frequencies.size(), expected_num_channels); EXPECT_TRUE(std::is_sorted(center_frequencies.begin(), center_frequencies.end(), comparator)); } } // namespace TEST(BaumgarteModelTest, SimpleTest) { StimulusConfig stimulus_config; stimulus_config.set_sample_rate(100000 /* Hz */); stimulus_config.set_audio_scaling_gain(1.0); constexpr int kDownsampleStep = 5; constexpr int kNumEars = 1; constexpr int kNumSamples = 10000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); BaumgarteModelMock model; model.set_native_downsample_step(kDownsampleStep); model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); EXPECT_EQ(output.cols(), kNumSamples / kDownsampleStep); const ChannelProperties &channel_properties = model.GetChannelProperties(); CheckChannelProperties(channel_properties, output.rows(), std::less<double>()); EXPECT_EQ(output.size(), channel_properties.NumChannels() * kNumSamples / kDownsampleStep); const float output_level = output.matrix().squaredNorm(); GOOGLE_LOG(INFO) << "Output level: " << output_level; constexpr double kMinOutputAmplificationLevel = 2.0; EXPECT_LT(kMinOutputAmplificationLevel, output_level); EXPECT_LT(-1.0, output.minCoeff()); // Minimal potential. EXPECT_GT(2.0, output.maxCoeff()); // Maximal potential. } // Checks various values for downsampling count parameter. TEST(BaumgarteModelTest, DownsampleTest) { constexpr int kNumEars = 1; constexpr int kNumSamples = 10000; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); constexpr int kMaxDownsample = 20; constexpr int kDownsampleStep = 4; StimulusConfig stimulus_config; stimulus_config.set_sample_rate(100000 /* Hz */); stimulus_config.set_audio_scaling_gain(1.0); for (int i = 1; i < kMaxDownsample; i += kDownsampleStep) { BaumgarteModelMock model; model.set_native_downsample_step(i); model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); const int expected_num_samples = std::ceil( static_cast<double>(kNumSamples) / i); EXPECT_EQ(output.cols(), expected_num_samples); } } // Checks various values for the number of analysis channels. TEST(BaumgarteModelTest, NumberOfChannelsTest) { constexpr int kNumEars = 1; constexpr int kNumSamples = 10000; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); constexpr int kMaxNumChannels = 280; constexpr int kMinNumChannels = 100; constexpr int kStep = 5; StimulusConfig stimulus_config; stimulus_config.set_sample_rate(100000 /* Hz */); stimulus_config.set_audio_scaling_gain(1.0); for (int i = kMinNumChannels; i <= kMaxNumChannels; i += kStep) { stimulus_config.set_num_channels(i); BaumgarteModelMock model; model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); EXPECT_EQ(output.rows(), i); } } namespace { // Path the test data for auditory filters. const char kAuditoryTestDataPath[] = "eidos/audition/testdata/auditory"; // Number of reference Basilar Membrane (BM) sections. constexpr int kRefNumBmSections = 251; // Number of reference time steps. constexpr int kRefNumTimeSteps = 1000; // Returns full path pointing to the auditory test file. std::string AuditoryTestFile(absl::string_view filename) { return absl::StrCat(kAuditoryTestDataPath, "/", filename); } // Utility function to read a vector of specified POD types from a headerless // binary file. template <typename T> void ReadFromFile(const std::string &path, std::vector<T> *vec) { std::ifstream ifs(path, std::ios::binary); ASSERT_TRUE(ifs.good()) << "Failed to open " << path; ifs.seekg(0, std::ios::end); const std::size_t file_size = ifs.tellg(); ifs.seekg(0, std::ios::beg); const int num_values = file_size / sizeof(T); EXPECT_EQ(kRefNumBmSections * kRefNumTimeSteps, num_values); vec->resize(num_values); ifs.read(reinterpret_cast<char *>(vec->data()), file_size); EXPECT_TRUE(ifs.good()) << "Failed to read " << num_values << " float values from " << path; } // Runs the stimulus waveform through the filterbank and compares the resulting // excitation against the golden data from a file. void CheckExcitationImpl(const std::string &waveform_path, const std::string &ref_excitation_path) { // Read the waveform. Waveform waveform; ASSERT_TRUE(ReadWaveform(waveform_path, &waveform)) << "Failed to open " << waveform_path; DenormalizeWaveform(&waveform); const int kNumEars = 1; // Mono. const int num_input_samples = waveform.samples().size(); Eigen::ArrayXXd input(kNumEars, num_input_samples); for (int i = 0; i < num_input_samples; ++i) { input(0, i) = waveform.samples(i); } // Generate excitation. Use downsample step of 10. StimulusConfig stimulus_config; stimulus_config.set_audio_scaling_gain(1.0); stimulus_config.set_sample_rate(waveform.sample_rate()); BaumgarteModelMock model; model.set_native_downsample_step(10); model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); const ChannelProperties &channel_properties = model.GetChannelProperties(); CheckChannelProperties(channel_properties, output.rows(), std::less<double>()); EXPECT_EQ(kRefNumTimeSteps, output.cols()); const Eigen::ArrayXXd &exc = output; EXPECT_EQ(kRefNumBmSections, exc.rows()); EXPECT_EQ(kRefNumTimeSteps, exc.cols()); // Read the reference excitation. These are stored in an N-by-M matrix, where // the N corresponds to BM sections and M corresponds to time. std::vector<float> ref_exc_vals; ReadFromFile(ref_excitation_path, &ref_exc_vals); const Eigen::Map<Eigen::Matrix<float, kRefNumBmSections, kRefNumTimeSteps>> ref_exc_map(ref_exc_vals.data()); const Eigen::ArrayXXd ref_exc = ref_exc_map.cast<double>(); EXPECT_EQ(kRefNumBmSections, ref_exc.rows()); EXPECT_EQ(kRefNumTimeSteps, ref_exc.cols()); // We almost match the reference implementation. const float kEpsilon = 7.9E-3; EXPECT_TRUE(ref_exc.isApprox(exc, kEpsilon)); } // Runs the stimulus waveform through the filterbank and compares the resulting // excitation against the golden data from a file. void CheckExcitation(const std::string &stimulus_filename, const std::string &ref_excitation_filename) { CheckExcitationImpl(AuditoryTestFile(stimulus_filename), AuditoryTestFile(ref_excitation_filename)); } } // namespace // Checks response to pure 1kHz tone at sound pressure level (SPL) of 60 dB. TEST(BaumgarteModelTest, Check_1kHz60dB_SPL_Tone) { CheckExcitation("1kHz_60dB_SPL_tone.wav", "1kHz_60dB_SPL_tone_baumgarte.exc"); } // Checks response to two pure 1kHz impulses at 0s and 50ms. TEST(BaumgarteModelTest, Check_PureImpulse) { CheckExcitation("impulse_1000at0s_and_-1000at0.05s.wav", "impulse_1000at0s_and_-1000at0.05s_baumgarte.exc"); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
8,974
C++
.cc
207
39.898551
81
0.740758
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,068
waveform_utils.cc
google_eidos-audition/eidos/audition/waveform_utils.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/waveform_utils.h" #include <cstdint> #include <limits> #include <vector> #include "eidos/port/logging.h" #include "google/protobuf/repeated_field.h" #include "wave/error.h" #include "wave/file.h" namespace eidos { namespace audition { namespace { // Scaling factor. const float kInt16ToFloatDivisor = -static_cast<float>(std::numeric_limits<int16_t>::min()); // Converts wave I/O error codes to readable strings. std::string ErrorToString(wave::Error status) { switch (status) { case wave::kFailedToOpen: return "Open failed"; case wave::kNotOpen: return "File not open"; case wave::kInvalidFormat: return "Invalid format"; case wave::kWriteError: return "Write error"; case wave::kReadError: return "Read error"; case wave::kInvalidSeek: return "Invalid seek"; default: return "Unknown"; } } } // namespace bool ReadWaveform(const std::string &filepath, Waveform *proto) { wave::File file; wave::Error status = file.Open(filepath, wave::OpenMode::kIn); if (status != wave::kNoError) { GOOGLE_LOG(ERROR) << "Failed to open waveform from \"" << filepath << "\": " << ErrorToString(status); return false; } proto->Clear(); proto->set_num_channels(file.channel_number()); if (proto->num_channels() != 1) { GOOGLE_LOG(ERROR) << "Multi-channel audio is not supported yet"; return false; } proto->set_sample_rate(file.sample_rate()); proto->set_bits_per_sample(file.bits_per_sample()); std::vector<float> contents; status = file.Read(&contents); if (status != wave::kNoError) { GOOGLE_LOG(ERROR) << "Failed to read waveform from \"" << filepath << "\": " << ErrorToString(status); } *proto->mutable_samples() = {contents.begin(), contents.end()}; if (proto->samples().size() == 0) { GOOGLE_LOG(ERROR) << "Waveform is empty: " << filepath; return false; } GOOGLE_LOG(INFO) << "Waveform info: Sample rate: " << proto->sample_rate() << " Hz, samples: " << proto->samples().size() << ", channels: " << proto->num_channels() << ", bits per sample: " << proto->bits_per_sample(); return true; } bool WriteWaveform(const Waveform &proto, const std::string &filepath) { wave::File file; wave::Error status = file.Open(filepath, wave::OpenMode::kOut); if (status != wave::kNoError) { GOOGLE_LOG(ERROR) << "Failed to open waveform in " << filepath << ": " << ErrorToString(status); return false; } file.set_channel_number(proto.num_channels()); file.set_sample_rate(proto.sample_rate()); file.set_bits_per_sample(proto.bits_per_sample()); status = file.Write({proto.samples().begin(), proto.samples().end()}); if (status != wave::kNoError) { GOOGLE_LOG(ERROR) << "Failed to write waveform to " << filepath << ": " << ErrorToString(status); } return true; } void ScaleToUnitWaveform(const Waveform &waveform, float scaling_gain, std::vector<float> *samples) { const int num_samples = waveform.samples().size(); samples->clear(); samples->resize(num_samples); for (int i = 0; i < num_samples; ++i) { (*samples)[i] = (waveform.samples(i) / kInt16ToFloatDivisor) * scaling_gain; } } namespace { template <typename T> void DenormalizeWaveformImpl(Waveform *waveform) { std::transform( waveform->mutable_samples()->begin(), waveform->mutable_samples()->end(), waveform->mutable_samples()->begin(), [](float sample) -> float { return sample * std::numeric_limits<T>::max(); }); } } // namespace void DenormalizeWaveform(Waveform *waveform) { GOOGLE_CHECK(waveform != nullptr); switch (waveform->bits_per_sample()) { case 8: DenormalizeWaveformImpl<int8_t>(waveform); break; case 16: DenormalizeWaveformImpl<int16_t>(waveform); break; case 32: DenormalizeWaveformImpl<int32_t>(waveform); break; default: { GOOGLE_LOG(FATAL) << "Unsupported sample width: " << waveform->bits_per_sample(); } } } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
4,871
C++
.cc
140
30.228571
80
0.656343
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,069
windowing.cc
google_eidos-audition/eidos/audition/windowing.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/windowing.h" #include <cmath> #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // Estimates number of frames in waveform. All quantities are supplied in // sample units. int NumFramesInWave(int total_num_samples, int frame_size, int frame_shift) { const int estimated_num_frames = (total_num_samples - frame_size) / frame_shift + 1; int i, frame_offset = 0; for (i = 0; i < estimated_num_frames; ++i) { if (frame_offset + frame_size > total_num_samples) { break; } frame_offset += frame_shift; } return i; } // Computes Hann window with dimension (num_channels, frame_size). Eigen::ArrayXXd ComputeWindowHann(int frame_size, int num_channels) { const double factor = 2.0 * M_PI / (frame_size - 1); Eigen::VectorXd vec(frame_size); for (int i = 0; i < frame_size; ++i) { vec(i) = 0.5 - 0.5 * std::cos(factor * i); } return vec.replicate(/* row factor */1, num_channels).transpose(); } // Computes Hamming window with dimension (num_channels, frame_size). Eigen::ArrayXXd ComputeWindowHamming(int frame_size, int num_channels) { const double factor = 2.0 * M_PI / (frame_size - 1); Eigen::VectorXd vec(frame_size); for (int i = 0; i < frame_size; ++i) { vec(i) = 0.54 - 0.46 * std::cos(factor * i); } return vec.replicate(/* row factor */1, num_channels).transpose(); } } // namespace Eigen::ArrayXXd ComputeWindowFunction(WindowFunction window_function, int frame_size, int num_channels) { switch (window_function) { case WINDOW_FUNCTION_HANN: return ComputeWindowHann(frame_size, num_channels); case WINDOW_FUNCTION_HAMMING: return ComputeWindowHamming(frame_size, num_channels); case WINDOW_FUNCTION_NONE: default: return Eigen::ArrayXXd::Constant(num_channels, frame_size, 1.0); } } FrameInfo GetFrameInfo(const Eigen::ArrayXXd &input, const StimulusConfig &config) { const int sample_rate = config.sample_rate(); const double window_duration_sec = config.window_duration_sec(); const double frame_shift_sec = config.frame_shift_sec(); FrameInfo info; info.frame_size = std::round(window_duration_sec * sample_rate); info.frame_shift = std::round(frame_shift_sec * sample_rate); info.num_frames = NumFramesInWave(input.cols(), info.frame_size, info.frame_shift); return info; } std::vector<Eigen::ArrayXXd> Window(const Eigen::ArrayXXd &input, const StimulusConfig &config) { const FrameInfo &info = GetFrameInfo(input, config); GOOGLE_CHECK_GT(info.num_frames, 0) << "Invalid number of frames: " << info.num_frames; const int num_channels = input.rows(); const Eigen::ArrayXXd &window_function = ComputeWindowFunction( config.window_function(), info.frame_size, num_channels); std::vector<Eigen::ArrayXXd> output; output.resize(info.num_frames); int cur_offset = 0, cur_frame_size = info.frame_size; const int num_samples = input.cols(); for (int i = 0; i < info.num_frames; ++i) { if (cur_offset + info.frame_size > num_samples) { // Copy the remaining buffer and pad with zeros. cur_frame_size = num_samples - cur_offset; output[i] = Eigen::ArrayXXd::Zero(num_channels, info.frame_size); output[i].block(0, 0, num_channels, cur_frame_size) = input.block(0, cur_offset, num_channels, cur_frame_size); } else { output[i] = input.block(0, cur_offset, num_channels, cur_frame_size); } output[i] *= window_function; cur_offset += info.frame_shift; } return output; } Eigen::ArrayXXd WindowAndIntegrateTime(const Eigen::ArrayXXd &input, const StimulusConfig &config) { const std::vector<Eigen::ArrayXXd> &frames = Window(input, config); const int num_frames = frames.size(); GOOGLE_CHECK_GT(num_frames, 0) << "Invalid number of frames: " << num_frames; const int frame_size = frames[0].cols(); GOOGLE_CHECK_GT(frame_size, 0) << "Invalid frame size: " << frame_size; const int num_channels = frames[0].rows(); Eigen::ArrayXXd output = Eigen::ArrayXXd(num_channels, num_frames); // TODO(agutkin): Row-wise norm (frames[i].rowwise().norm()) does not seem to // compile at the moment. Resorting to brute-force logic. for (int i = 0; i < num_frames; ++i) { const Eigen::ArrayXXd &frame = frames[i]; for (int j = 0; j < num_channels; ++j) { double sum = 0.0; for (int k = 0; k < frame_size; ++k) { sum += (frame(j, k) * frame(j, k)); } output(j, i) = std::sqrt(sum / frame_size); } } return output; } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
5,388
C++
.cc
130
36.915385
86
0.673088
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,070
utils.cc
google_eidos-audition/eidos/audition/utils.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/utils.h" #include <algorithm> #include <random> namespace eidos { namespace audition { std::vector<double> GetRandomUniformVector(int n, double min_val, double max_val) { std::random_device rnd_seed; // Obtain a seed for the random number engine. std::mt19937 rnd_gen(rnd_seed()); // Standard Mersenne Twister engine. std::uniform_real_distribution<double> dist(min_val, max_val); std::vector<double> vec(n); std::generate(vec.begin(), vec.end(), [&dist, &rnd_gen]() { return dist(rnd_gen); }); return vec; } std::vector<double> GetRandomNormalVector(int n, double mu, double sigma) { std::random_device rnd_seed; // Obtain a seed for the random number engine. std::mt19937 rnd_gen(rnd_seed()); // Standard Mersenne Twister engine. std::normal_distribution<double> dist(mu, sigma); std::vector<double> vec(n); std::generate(vec.begin(), vec.end(), [&dist, &rnd_gen]() { return dist(rnd_gen); }); return vec; } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
1,720
C++
.cc
42
37.428571
78
0.696589
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,071
resampler.cc
google_eidos-audition/eidos/audition/resampler.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "eidos/audition/resampler.h" #include <vector> #include "eidos/port/logging.h" #include "resample.h" // @com_github_resample namespace eidos { namespace audition { bool ShouldResampleOutputs(const StimulusConfig &config) { return ( (config.output_resample_up_factor() > 0) && (config.output_resample_down_factor() > 0) && (config.output_resample_up_factor() != config.output_resample_down_factor()) && (config.downsample_step() <= 1)); } Eigen::ArrayXXd DownstepResample(const Eigen::ArrayXXd &input, const StimulusConfig &config) { const int downsample_step = config.downsample_step(); if (downsample_step <= 1) { return input; } const int num_channels = input.rows(); const int num_output_samples = input.cols() / downsample_step; Eigen::ArrayXXd output = Eigen::ArrayXXd(num_channels, num_output_samples); for (int i = 0; i < num_channels; ++i) { int n = 0; for (int j = 0; j < num_output_samples; ++j) { output(i, j) = input(i, n); n += downsample_step; } } return output; } Eigen::ArrayXXd Resample(const Eigen::ArrayXXd &input, const StimulusConfig &config) { const int sample_rate = config.sample_rate(); GOOGLE_CHECK_LT(0.0, sample_rate); const int up_factor = config.output_resample_up_factor(); GOOGLE_CHECK_LT(0.0, up_factor) << "Invalid upsampling factor: " << up_factor; const int down_factor = config.output_resample_down_factor(); GOOGLE_CHECK_LT(0.0, down_factor) << "Invalid downsampling factor: " << down_factor; if (up_factor == down_factor) { // No-op. return input; } // Figure out the number of output samples by resampling the first channel. const int num_samples = input.cols(); auto channel = std::vector<double>(input.row(0).data(), input.row(0).data() + num_samples); std::vector<double> output_channel; ::resample(up_factor, down_factor, channel, output_channel); const int num_output_samples = output_channel.size(); GOOGLE_CHECK_LT(0, num_output_samples) << "Invalid number of output samples: " << num_output_samples; // Resample the signal starting from the second channel. const int num_channels = input.rows(); Eigen::ArrayXXd output = Eigen::ArrayXXd(num_channels, num_output_samples); output.row(0) = Eigen::Map<Eigen::ArrayXd>(output_channel.data(), num_output_samples); for (int i = 1; i < num_channels; ++i) { auto channel = std::vector<double>(input.row(i).data(), input.row(i).data() + num_samples); ::resample(up_factor, down_factor, channel, output_channel); GOOGLE_CHECK_EQ(output_channel.size(), num_output_samples); output.row(i) = Eigen::Map<Eigen::ArrayXd>(output_channel.data(), num_output_samples); } return output; } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
3,645
C++
.cc
86
36.825581
80
0.660936
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,072
auditory_model_test.cc
google_eidos-audition/eidos/audition/auditory_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Sanity checks for the auditory model interface. #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/audition/stimulus_config.pb.h" #include "gtest/gtest.h" namespace eidos { namespace audition { namespace { // Model type (ID). constexpr AuditoryModelType kModelType = MODEL_CARFAC; // Auditory stage. constexpr AuditoryStageType kStageType = STAGE_AUDITORY_NERVE_SYNAPSE; // Model output. constexpr AuditoryOutputType kOutputType = OUTPUT_SYNAPSE_FIRING_RATES; // Mock a no-op synapse model. class MockSynapseModel : public AuditoryModel { public: MockSynapseModel() : AuditoryModel(kModelType, kStageType, kOutputType, true /* waveform input */) {} ChannelProperties GetChannelProperties() const override { return {}; } void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override {} }; } // namespace TEST(AuditoryModelTest, CheckMockModel) { MockSynapseModel model; EXPECT_EQ(kStageType, model.stage_type()); EXPECT_EQ(kOutputType, model.output_type()); EXPECT_EQ(kStageType, OutputType2Stage(kOutputType)); EXPECT_TRUE(model.previous_model() == nullptr); EXPECT_EQ("MODEL_CARFAC", model.ModelTypeAsString()); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,008
C++
.cc
51
36.588235
75
0.749486
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,073
waveform_utils_test.cc
google_eidos-audition/eidos/audition/waveform_utils_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Sanity check for waveform utilities. #include <algorithm> #include <filesystem> #include <cstdio> #include <cmath> #include <numeric> #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "eidos/audition/waveform_utils.h" #include "google/protobuf/util/message_differencer.h" #include "gtest/gtest.h" using google::protobuf::util::MessageDifferencer; namespace eidos { namespace audition { namespace { // Source waveform. const char kWaveFilePath[] = "eidos/audition/testdata/ne_np/nep_0258_0119737288.wav"; } // namespace TEST(WaveformUtilsTest, Reading) { Waveform wave; ASSERT_TRUE(ReadWaveform(kWaveFilePath, &wave)); EXPECT_EQ(1, wave.num_channels()); // Mono. EXPECT_EQ(48000, wave.sample_rate()); EXPECT_EQ(16, wave.bits_per_sample()); EXPECT_EQ(192912, wave.samples().size()); } TEST(WaveformUtilsTest, ReadingAndWriting) { Waveform wave; ASSERT_TRUE(ReadWaveform(kWaveFilePath, &wave)); const std::string &temp_path = std::tmpnam(nullptr); ASSERT_TRUE(WriteWaveform(wave, temp_path)); Waveform new_wave; ASSERT_TRUE(ReadWaveform(temp_path, &new_wave)); EXPECT_TRUE(MessageDifferencer::Equals(new_wave, wave)); EXPECT_TRUE(std::filesystem::remove(temp_path)); } TEST(WaveformUtilsTest, UnitScaling) { Waveform wave; ASSERT_TRUE(ReadWaveform(kWaveFilePath, &wave)); std::vector<float> samples; ScaleToUnitWaveform(wave, 0.5, &samples); EXPECT_LT(0, samples.size()); for (auto sample : samples) { EXPECT_GT(1.0, sample); EXPECT_LT(-1.0, sample); } } TEST(WaveformUtilsTest, CheckDenormalize) { Waveform wave; ASSERT_TRUE(ReadWaveform(kWaveFilePath, &wave)); for (auto sample : wave.samples()) { EXPECT_GT(1.0, std::fabs(sample)); } DenormalizeWaveform(&wave); const float mean = std::accumulate(wave.samples().begin(), wave.samples().end(), 0.0) / wave.samples().size(); EXPECT_LT(2.0, std::fabs(mean)); // Samples are not within [-1, 1] range. } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,657
C++
.cc
79
31.392405
76
0.735569
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,074
auditory_feature_extractor_config_tester.cc
google_eidos-audition/eidos/audition/auditory_feature_extractor_config_tester.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple command-line utility for testing the supplied auditory feature // extractor configuration. #include <string> #include "Eigen/Core" #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "eidos/audition/auditory_feature_extractor.h" #include "eidos/audition/auditory_feature_extractor_config.pb.h" #include "eidos/audition/auditory_response.h" #include "eidos/audition/waveform.pb.h" #include "eidos/port/status-matchers.h" #include "eidos/utils/proto_utils.h" #include "gtest/gtest.h" ABSL_FLAG(std::string, config_proto_file, "", "Configuration protocol buffer file in text format."); namespace eidos { namespace audition { TEST(AuditoryFeatureExtractorConfigTest, CheckRunConfig) { // Read configuration. const std::string config_proto_file = absl::GetFlag(FLAGS_config_proto_file); ASSERT_TRUE(!config_proto_file.empty()) << "Specify --config_proto_file"; AuditoryFeatureExtractorConfig config; ASSERT_OK(utils::ReadTextProto(config_proto_file, &config)) << "Failed to read configuration from: " << config_proto_file; config.mutable_config()->set_downsample_step(1); // No downsampling. // Prepare the stimulus. All of the stimulus parameters are hardcoded at // present. The amplitude of random stimulus is unit normalized. Waveform input; input.set_num_channels(1); input.set_sample_rate(100000); // 100 kHz. input.set_bits_per_sample(16); // PCM. constexpr int kNumSamples = 50000; const Eigen::VectorXd vec = Eigen::VectorXd::Random(kNumSamples); input.mutable_samples()->Reserve(kNumSamples); for (int i = 0; i < kNumSamples; ++i) { input.add_samples(vec(i)); } // Process the stimulus and perform some basic checks. AuditoryFeatureExtractor processor; AuditoryResponse response; EXPECT_TRUE(processor.ComputeFeatures(input, config, &response)) << "Failed to compute features"; const auto &outputs = response.outputs(); EXPECT_EQ(1, outputs.size()); EXPECT_EQ(kNumSamples, outputs[0].second.cols()); } } // namespace audition } // namespace eidos int main(int argc, char *argv[]) { absl::ParseCommandLine(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } // Local Variables: // mode: c++ // End:
2,845
C++
.cc
70
38.257143
79
0.748191
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,075
bruce2018_hair_cell_synapse_model_test.cc
google_eidos-audition/eidos/audition/bruce2018_hair_cell_synapse_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test that the synaptic model from Bruce, et. al. (2018) behaves. #include "Eigen/Core" #include "eidos/audition/mock_basilar_membrane_model.h" #include "eidos/audition/stimulus_config.pb.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "third_party/audition/models/baumgarte/baumgarte_model.h" #include "third_party/audition/models/bruce_carney/bruce2018_hair_cell_synapse_model.h" namespace eidos { namespace audition { // Transmembrane voltages. constexpr double kMinVoltage = -0.018051; // ~18 mV constexpr double kMaxVoltage = 0.038092; // ~38 mV // Sanity checks for a single fiber given a random voltages stimulus using // either exact or approximate Power-Law implementation. void CheckSingleFiberOnRandomVoltages(bool exact_power_law, Eigen::RowArrayXd *rates) { constexpr int kNumSamples = 200000; // Long enough so we get a good average. constexpr int kSampleRate = 100000; // Hz. constexpr double kSpontRate = 60.0; // Spontaneous firing rate (spikes/sec). constexpr double kCenterFreq = 1000.0; // CF in Hz. // Simulate transmembrane voltages in the range [kMinVoltage, kMaxVoltage] V. const Eigen::RowArrayXd ihc_voltages = kMinVoltage + (Eigen::RowArrayXd::Random(kNumSamples) * 0.5 + 0.5) * (kMaxVoltage - kMinVoltage); Bruce2018HairCellSynapse(ihc_voltages, 1.0 / kSampleRate, kCenterFreq, kSpontRate, exact_power_law, rates); EXPECT_EQ(kNumSamples, rates->size()); } TEST(Bruce2018HairCellSynapseModelTest, RandomSingleFiberExactPowerLaw) { Eigen::RowArrayXd rates; CheckSingleFiberOnRandomVoltages(true /* exact Power-Law */, &rates); EXPECT_LE(0.0, rates.minCoeff()); EXPECT_GT(5300.0, rates.maxCoeff()); // Hz. } TEST(Bruce2018HairCellSynapseModelTest, RandomSingleFiberApproxPowerLaw) { Eigen::RowArrayXd rates; CheckSingleFiberOnRandomVoltages(false /* exact Power-Law */, &rates); EXPECT_LE(0.0, rates.minCoeff()); EXPECT_GT(5300.0, rates.maxCoeff()); // Hz. } TEST(Bruce2018HairCellSynapseModelTest, RandomAllFibers) { // Simulate transmembrane voltages and pass them unmodified using the mock // basilar membrane model. constexpr int kNumChannels = 40; constexpr int kNumSamples = 100000; const Eigen::ArrayXXd stimulus = kMinVoltage + (Eigen::ArrayXXd::Random(kNumChannels, kNumSamples) * 0.5 + 0.5) * (kMaxVoltage - kMinVoltage); constexpr int kSampleRate = 100000; // Hz. StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); MockBasilarMembraneModel bm_model; bm_model.Init(stimulus_config); Eigen::ArrayXXd ihc_voltages; // IHC voltages mocked above. bm_model.ProcessSegment(stimulus, &ihc_voltages); // Run the model. Bruce2018HairCellSynapseModel model; model.set_previous_model(&bm_model); model.Init(stimulus_config); Eigen::ArrayXXd rates; // firing rates. model.ProcessSegment(ihc_voltages, &rates); const ChannelProperties &channel_properties = model.GetChannelProperties(); EXPECT_EQ(kNumChannels, channel_properties.NumChannels()); EXPECT_EQ(kNumChannels, rates.rows()); EXPECT_EQ(kNumSamples, rates.cols()); EXPECT_LE(0.0, rates.minCoeff()); EXPECT_GT(70000.0, rates.maxCoeff()); // Hz. } // Simulate the transmembrane voltages using Baumgarte model. TEST(Bruce2018HairCellSynapseModelTest, BaumgarteOverRandomInputs) { // Random input pressure wave. const int kNumEars = 1; const int kNumSamples = 20000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); // Estimate IHC voltages. const int kSampleRate = 100000; // Hz const int kNumChannels = 251; StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); stimulus_config.set_downsample_step(1); // No downsampling. BaumgarteModel bm_model; bm_model.Init(stimulus_config); Eigen::ArrayXXd voltages; bm_model.ProcessSegment(input, &voltages); EXPECT_EQ(kNumChannels, voltages.rows()); EXPECT_EQ(kNumSamples, voltages.cols()); EXPECT_LT(-1.0, voltages.minCoeff()); EXPECT_GT(2.0, voltages.maxCoeff()); // Run the synapse model. Bruce2018HairCellSynapseModel synapse_model; synapse_model.set_previous_model(&bm_model); synapse_model.Init(stimulus_config); Eigen::ArrayXXd rates; // firing rates. synapse_model.ProcessSegment(voltages, &rates); const ChannelProperties &channel_properties = synapse_model.GetChannelProperties(); EXPECT_EQ(kNumChannels, channel_properties.NumChannels()); EXPECT_EQ(kNumChannels, rates.rows()); EXPECT_EQ(kNumSamples, rates.cols()); EXPECT_LE(0.0, rates.minCoeff()); EXPECT_GT(7000.0, rates.maxCoeff()); // Hz. } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
5,429
C++
.cc
121
41.652893
87
0.747826
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,076
utils_test.cc
google_eidos-audition/eidos/audition/utils_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Sanity checks for utils library. #include <algorithm> #include <cmath> #include <numeric> #include <vector> #include "eidos/audition/utils.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::AllOf; using testing::Each; using testing::Ge; using testing::Le; namespace eidos { namespace audition { TEST(UtilsTest, CheckRandomUniformVector) { constexpr int kMaxLengthTrials = 10; constexpr int kMaxNumRanges = 100; for (int l = 1; l <= kMaxLengthTrials; ++l) { const int n = l * 100; for (int i = 1; i <= kMaxNumRanges; ++i) { const std::vector<double> vec = GetRandomUniformVector( n, -i, i); EXPECT_EQ(n, vec.size()); EXPECT_THAT(vec, Each(AllOf(Ge(-i), Le(i)))); } } } TEST(UtilsTest, CheckRandomNormalVector) { constexpr int kVecLen = 100000; constexpr double kEpsilon = 2E-2; const std::vector<double> vec = GetRandomNormalVector( kVecLen, 0.0 /* zero mean */, 1.0 /* unit standard deviation */); EXPECT_EQ(kVecLen, vec.size()); const double mean = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size(); EXPECT_NEAR(0.0, std::fabs(mean), kEpsilon); const double sum_squares = std::inner_product( vec.begin(), vec.end(), vec.begin(), 0.0, [](double x, double y) { return x + y; }, [mean](double x, double y) { return (x - mean) * (y - mean); }); const double stddev = sum_squares / (vec.size() - 1); EXPECT_NEAR(1.0, stddev, kEpsilon); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
2,136
C++
.cc
60
32.95
80
0.69134
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,077
zhang2001_spike_generator_test.cc
google_eidos-audition/eidos/audition/zhang2001_spike_generator_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // A very simple test for the Zhang and Carney's spike generator. #include <vector> #include "Eigen/Core" #include "gtest/gtest.h" #include "third_party/audition/models/bruce_carney/zhang2001_spike_generator.h" namespace eidos { namespace audition { TEST(Zhang2001SpikeGeneratorTest, MultiFiberRandomStimulus) { constexpr int kNumChannels = 100; constexpr int kNumSamples = 5000; // Number of samples to test. constexpr double kSampleRate = 16000; // 16 kHz constexpr double kMaxRepeats = 5; // Maximum number of trials. const std::vector<int> kMinNumSpikes = { 500, 1000, 1500, 2000, 3000 }; const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumChannels, kNumSamples) * 100.0; for (int n = 1; n <= kMaxRepeats; ++n) { Eigen::ArrayXXd spikes; Zhang2001SpikeGenerator(input, 1.0 / kSampleRate, // Sample period (sec). n, &spikes); EXPECT_EQ(kNumChannels, spikes.rows()); EXPECT_EQ(kNumSamples, spikes.cols()); EXPECT_FALSE(spikes.isZero()); EXPECT_EQ(0.0, spikes.minCoeff()); EXPECT_EQ(1.0, spikes.maxCoeff()); // Expect these lower bounds on the number of spikes. EXPECT_LT(kMinNumSpikes[n - 1], (spikes.array() != 0).count()); } } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
1,943
C++
.cc
48
36.833333
79
0.706257
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,078
gammatone_filterbank_model_test.cc
google_eidos-audition/eidos/audition/gammatone_filterbank_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test for gammatone filterbanks. #include <algorithm> #include <functional> #include "Eigen/Core" #include "eidos/audition/stimulus_config.pb.h" #include "gtest/gtest.h" #include "third_party/audition/models/gammatone/gammatone_filterbank_model.h" namespace eidos { namespace audition { namespace { // A small amplitude value. constexpr float kSmallAmplitude = 1E-6; // Checks computed channel properties. The Slaney's implementation places center // frequencies in decreasing order, while Ma's implementation uses increasing // order. template <typename Comparator> void CheckChannelProperties(const ChannelProperties &channel_properties, int expected_num_channels, Comparator comparator) { const auto &center_frequencies = channel_properties.center_frequencies; EXPECT_EQ(center_frequencies.size(), expected_num_channels); EXPECT_TRUE(std::is_sorted(center_frequencies.begin(), center_frequencies.end(), comparator)); } // Checks random unit impulse response of Slaney's filterbank. void CheckUnitImpulseResponseSlaney(int num_channels, int num_expected_channels, float min_cf_hz, float expected_min_cf_hz, float max_cf_hz, float expected_max_cf_hz) { constexpr int kNumEars = 1; constexpr int kNumSamples = 20000; // Long enough so we get a good average. Eigen::ArrayXXd input = Eigen::ArrayXXd::Zero(kNumEars, kNumSamples); input(0, 1) = 1.0; // Unit impulse. // Set up stimulus configuration. constexpr int kSampleRate = 16000; // Hz. StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); stimulus_config.set_num_channels(num_channels); stimulus_config.set_lowest_cf_hz(min_cf_hz); stimulus_config.set_highest_cf_hz(max_cf_hz); // Initialize the model and process random stimulus. GammatoneFilterbankConfig config; config.set_filter_type(GAMMATONE_FILTERBANK_SLANEY); GammatoneFilterbankModel model(config); model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); // Check channel properties. Note: The frequencies extend in descending order. // The lowest and highest CFs of the filters don't exactly correspond to the // requested values due to specific ERB computations in Slaney's filter. const ChannelProperties &channel_properties = model.GetChannelProperties(); const auto &cfs = channel_properties.center_frequencies; CheckChannelProperties(channel_properties, output.rows(), std::greater<double>()); EXPECT_NEAR(expected_min_cf_hz, cfs.back(), 1E-6); EXPECT_LT(2, cfs.size()); const double cf_delta = cfs[cfs.size() - 2] - cfs.back(); EXPECT_LT(0.0, cf_delta); EXPECT_LT(cfs[0] + cf_delta / 2.0, expected_max_cf_hz); // Check response properties. EXPECT_EQ(num_expected_channels, output.rows()); EXPECT_EQ(kNumSamples, output.cols()); const int total_samples = channel_properties.NumChannels() * kNumSamples; EXPECT_EQ(output.size(), total_samples); EXPECT_LT(-1.0, output.minCoeff()); EXPECT_GT(0.5, output.maxCoeff()); const float output_amplification_level = output.matrix().squaredNorm(); EXPECT_LT(0.8, output_amplification_level); // Compute percentage of the amplitudes we can safely neglect. int negligible_samples = 0; for (int i = 0; i < output.rows(); ++i) { // channels for (int j = 0; j < kNumSamples; ++j) { if (output(i, j) < kSmallAmplitude) negligible_samples++; } } const float negligible_samples_ratio = negligible_samples / static_cast<float>(total_samples); EXPECT_LT(0.95, negligible_samples_ratio); } } // namespace TEST(GammatoneFilterbankModelTest, UnitImpulseResponseSlaneyDefNumChannels) { CheckUnitImpulseResponseSlaney( 0, GammatoneFilterbankModel::kDefaultNumChannels, // Number of channels. 0, GammatoneFilterbankModel::kLowestCFrequency, // Lowest CF. // Expect maximum CF to be around half the sample rate. 0, 8000.0); // Highest CF. } TEST(GammatoneFilterbankModelTest, CheckUnitImpulseResponseSlaney) { constexpr int kRequestedChannels = 155; constexpr double kMinCfHz = 100.0; constexpr double kMaxCfHz = 5000.0; CheckUnitImpulseResponseSlaney( kRequestedChannels, kRequestedChannels, kMinCfHz, kMinCfHz, kMaxCfHz, kMaxCfHz); } namespace { // Checks gammatone response given the implementation on a random stimulus. template <typename Comparator> void CheckRandomResponse(GammatoneFilterbankType filter_type, float min_displacement, float max_displacement, Comparator comparator) { constexpr double kSampleRate = 44000; // Hz. StimulusConfig stimulus_config; stimulus_config.set_sample_rate(kSampleRate); constexpr int kNumEars = 1; constexpr int kNumSamples = 50000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); GammatoneFilterbankConfig config; config.set_filter_type(filter_type); GammatoneFilterbankModel model(config); model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); const ChannelProperties &channel_properties = model.GetChannelProperties(); CheckChannelProperties(channel_properties, output.rows(), comparator); EXPECT_EQ(kNumSamples, output.cols()); const int total_samples = channel_properties.NumChannels() * kNumSamples; EXPECT_EQ(output.size(), total_samples); EXPECT_LT(min_displacement, output.minCoeff()); EXPECT_GT(max_displacement, output.maxCoeff()); const float output_amplification_level = output.matrix().squaredNorm(); EXPECT_LT(0.8, output_amplification_level); } } // namespace TEST(GammatoneFilterbankModelTest, CheckRandomResponseSlaney) { CheckRandomResponse(GAMMATONE_FILTERBANK_SLANEY, -1.0, // min_displacement 0.8, // max_displacement std::greater<double>()); } TEST(GammatoneFilterbankModelTest, CheckRandomResponseCookeAndMa) { CheckRandomResponse(GAMMATONE_FILTERBANK_COOKE_AND_MA, -520.0, // min_displacement 520.0, // max displacement std::less<double>()); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
7,045
C++
.cc
155
40.419355
80
0.725167
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,079
carfac_model_test.cc
google_eidos-audition/eidos/audition/carfac_model_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test for CARFAC model. #include <algorithm> #include <cstddef> #include <functional> #include "Eigen/Core" #include "eidos/audition/carfac_config.pb.h" #include "eidos/audition/carfac_model.h" #include "eidos/audition/stimulus_config.pb.h" #include "eidos/port/logging.h" #include "gtest/gtest.h" namespace eidos { namespace audition { namespace { // Given the model configuration runs the filterbank over the simple stimulus // and checks the resulting signal. The expected level of the output signal is // provided by <min_aplification_level>. void BasicFilterbankCheck(const CarfacConfig &model_config, int min_amplification_level) { // Generate simple random stimulus. StimulusConfig stimulus_config; stimulus_config.set_audio_scaling_gain(1.0); stimulus_config.set_sample_rate(16000 /* 16 kHz */); const int kNumEars = 1; const int kNumSamples = 10000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); // Filter the stimulus. CarfacModel model(model_config); model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); // Perform basic sanity checks. const ChannelProperties &channel_properties = model.GetChannelProperties(); EXPECT_EQ(kNumSamples, output.cols()); EXPECT_LT(0, channel_properties.NumChannels()); EXPECT_EQ(output.rows(), channel_properties.NumChannels()); const auto &center_frequencies = channel_properties.center_frequencies; // Note: center frequencies are sorted in descending order. EXPECT_TRUE(std::is_sorted(center_frequencies.begin(), center_frequencies.end(), std::greater<double>())); const float output_level = output.matrix().squaredNorm(); GOOGLE_LOG(INFO) << "Output level: " << output_level; EXPECT_LT(min_amplification_level, output_level); } } // namespace // Performs generation of neural activity pattern (NAP) triggered by default // configuration, accompanied by some basic checks. TEST(CarfacModelTest, SimpleNapTest) { CarfacConfig config; constexpr double kMinAmplificationLevel = 1E+5; BasicFilterbankCheck(config, kMinAmplificationLevel); } // Obtains estimates of basilar membrane (BM) displacements and performs simple // checks. TEST(CarfacModelTest, SimpleBmTest) { CarfacConfig config; config.mutable_output_types()->set_store_nap(false); config.mutable_output_types()->set_store_bm(true); constexpr double kMinAmplificationLevel = 1E+5; BasicFilterbankCheck(config, kMinAmplificationLevel); } // Obtains outer hair cell (OHC) signal and performs simple checks. TEST(CarfacModelTest, SimpleOhcTest) { CarfacConfig config; config.mutable_output_types()->set_store_nap(false); config.mutable_output_types()->set_store_ohc(true); constexpr double kMinAmplificationLevel = 1E+5; BasicFilterbankCheck(config, kMinAmplificationLevel); } // Obtains adaptive gain control (AGC) signal and performs simple checks. TEST(CarfacModelTest, SimpleAgcTest) { CarfacConfig config; config.mutable_output_types()->set_store_nap(false); config.mutable_output_types()->set_store_agc(true); constexpr double kMinAmplificationLevel = 2E+3; BasicFilterbankCheck(config, kMinAmplificationLevel); } // Disables AGC through the coniguration. TEST(CarfacModelTest, SimpleNapNoAgcTest) { CarfacConfig config; config.mutable_agc()->set_num_stages(0); // Disable AGC. constexpr double kMinAmplificationLevel = 1E+5; BasicFilterbankCheck(config, kMinAmplificationLevel); } // Tweaks some of the Cascade of Asymmetric Resonators (CAR) filter parameters // and checks that the model is still sane. TEST(CarfacModelTest, SimpleTweakCarTest) { CarfacConfig config; constexpr double kMinAmplificationLevel = 1E+5; config.mutable_car()->set_min_pole_hz(20.0); // Hz. for (int i = 1; i <= 10; ++i) { config.mutable_car()->set_erb_per_step(0.1); BasicFilterbankCheck(config, kMinAmplificationLevel); } } // CARFAC's number of analysis channels depends on the sampling rate. TEST(CarfacModelTest, SamplingRatesTest) { const int kNumEars = 1; const int kNumSamples = 10000; // Long enough so we get a good average. const Eigen::ArrayXXd input = Eigen::ArrayXXd::Random(kNumEars, kNumSamples); const std::vector<float> sampling_rates_hz = { 8000, 16000, 22040, 44100, 80000, 100000}; const std::vector<int> num_channels = { 53, 65, 71, 83, 94, 98 }; for (std::size_t i = 0; i < sampling_rates_hz.size(); ++i) { StimulusConfig stimulus_config; const int sample_rate = sampling_rates_hz[i]; stimulus_config.set_sample_rate(sample_rate); CarfacConfig model_config; CarfacModel model(model_config); model.Init(stimulus_config); Eigen::ArrayXXd output; model.ProcessSegment(input, &output); EXPECT_EQ(output.rows(), num_channels[i]); } } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
5,572
C++
.cc
132
39.424242
80
0.755765
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,080
hair_cell_synapse_test.cc
google_eidos-audition/eidos/audition/dsam/hair_cell_synapse_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple DSAM-based test driver for hair cell models. // // The parameter files are copied from either DSAM examples or SAMS tutorials. #include <DSAM.h> #include <iostream> int main() { // Initialize modules. EarObjectPtr stimulus = Init_EarObject(wxT("DataFile_In")); EarObjectPtr bm_filter = Init_EarObject(wxT("BM_gammaT")); EarObjectPtr hair_cell = Init_EarObject(wxT("IHC_Meddis86")); // Setup connections between modules. ConnectOutSignalToIn_EarObject(stimulus, bm_filter); ConnectOutSignalToIn_EarObject(bm_filter, hair_cell); // Read module configurations. ReadPars_ModuleMgr(stimulus, wxT("input_data_file.params")); PrintPars_ModuleMgr(stimulus); ReadPars_ModuleMgr(bm_filter, wxT("bm_gammatone.params")); PrintPars_ModuleMgr(bm_filter); ReadPars_ModuleMgr(hair_cell, wxT("ihc_meddis_86.params")); PrintPars_ModuleMgr(hair_cell); // Run the simulation. RunProcess_ModuleMgr(stimulus); RunProcess_ModuleMgr(bm_filter); RunProcess_ModuleMgr(hair_cell); WriteOutSignal_DataFile(wxT("output.dat"), hair_cell); FreeAll_EarObject(); return 0; } // Local Variables: // mode: c++ // End:
1,730
C++
.cc
44
37.181818
78
0.759833
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,081
auditory_nerve_test.cc
google_eidos-audition/eidos/audition/dsam/auditory_nerve_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple DSAM-based test driver for hair cell models. // // The parameter files are copied from either DSAM examples or SAMS tutorials. #include <DSAM.h> #include <iostream> int main() { // Initialize modules. EarObjectPtr stimulus = Init_EarObject(wxT("DataFile_In")); EarObjectPtr bm_filter = Init_EarObject(wxT("BM_gammaT")); EarObjectPtr hair_cell = Init_EarObject(wxT("IHC_Meddis86")); EarObjectPtr anf_spikes = Init_EarObject(wxT("An_SG_Binomial")); // Setup connections between modules. ConnectOutSignalToIn_EarObject(stimulus, bm_filter); ConnectOutSignalToIn_EarObject(bm_filter, hair_cell); ConnectOutSignalToIn_EarObject(hair_cell, anf_spikes); // Read module configurations. ReadPars_ModuleMgr(stimulus, wxT("input_data_file.params")); PrintPars_ModuleMgr(stimulus); ReadPars_ModuleMgr(bm_filter, wxT("bm_gammatone.params")); PrintPars_ModuleMgr(bm_filter); ReadPars_ModuleMgr(hair_cell, wxT("ihc_meddis_86.params")); PrintPars_ModuleMgr(hair_cell); ReadPars_ModuleMgr(anf_spikes, wxT("anf_spikes_binomial.params")); PrintPars_ModuleMgr(anf_spikes); // Run the simulation. RunProcess_ModuleMgr(stimulus); RunProcess_ModuleMgr(bm_filter); RunProcess_ModuleMgr(hair_cell); RunProcess_ModuleMgr(anf_spikes); WriteOutSignal_DataFile(wxT("output.dat"), anf_spikes); FreeAll_EarObject(); return 0; } // Local Variables: // mode: c++ // End:
1,995
C++
.cc
49
38.489796
78
0.762642
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,082
zhang2001_spike_generator.cc
google_eidos-audition/third_party/audition/models/bruce_carney/zhang2001_spike_generator.cc
// Copyright 2001 Xuedong Zhang // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. #include "third_party/audition/models/bruce_carney/zhang2001_spike_generator.h" #include <cstdlib> #include <cmath> #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // Dead time or absolute refractory period (sec). constexpr double kDeadTime = 0.75E-3; // Relative refractory parameters: // // According to Zhang and Carney (2001), following spike history parameters for // two exponents fit // - Westerman and Smith (1989): "A diffusion model of the transient response // of the cochlear inner hair cell synapse."., JASA, vol. 83, no. 6. // - Gaumond and Kim (1983): "Response of cochlear nerve fibers to brief // acoustic stimuli: Role of dischargeâ€history effects.", JASA, // vol. 74, no. 5. constexpr double kC0 = 0.5; // Dimensionless. constexpr double kS0 = 0.001; // sec constexpr double kC1 = 0.5; // Dimensionless. constexpr double kS1 = 0.0125; // sec // This is the spike generator including refractoriness, the spikes // are generated by nonhemogeneous process. The average rate is // modified by the synapse output simutaneously. The probability of // the spike generating is also affected by the synapse history as // absolute and relative refractoriness. class SpikeGenerator { public: SpikeGenerator(double sample_period, double dead_time) { time_t seed; seed = std::time(NULL); std::srand(seed); dead_time_ = dead_time; sample_period_ = sample_period; cur_time_ = 0.0; spike_time_ = 0.0; } // Resets the spike generator, simulates the situation that the // fiber has spontaneous rate. void Init(double spont) { if (spont > 0.0) { spike_time_ = cur_time_ - std::rand() / static_cast<double>(RAND_MAX) * 1.0 / spont; } else { spike_time_ = spike_time_ - cur_time_; cur_time_ = 0; } } // Gets the time of spike generator. double GetCurrentTime() const { return cur_time_; } // This function generate the spikes according synapse // output(x=sout), also including the refractoriness. bool Run(double x) { bool spike = false; cur_time_ += sample_period_; // running time // Interval from last spike, including 'wrap around' between trials. const double since_last_spike = cur_time_ - spike_time_; if (since_last_spike > dead_time_) { const double prob = x * (1.0 - ( kC0 * std::exp( -(since_last_spike - dead_time_) / kS0) + kC1 * std::exp( -(since_last_spike - dead_time_) / kS1))) * sample_period_; if (prob > drand48()) { spike_time_ = cur_time_; spike = true; } } return spike; } private: double sample_period_; // Time resolution (in seconds). double cur_time_; // Current running time (in seconds). double spike_time_; // Time when the last spike happened (In seconds). double dead_time_; // In seconds. }; } // namespace // The logic should probably be reworked, where the number of trials becomes the // number of fibers converging on a particular cell along the BM partition. void Zhang2001SpikeGenerator(const Eigen::Ref<const Eigen::ArrayXXd> &input, double sample_period, // Seconds. int num_repeats, // Number of trials. Eigen::ArrayXXd *output) { const int num_channels = input.rows(); const int num_samples = input.cols(); *output = Eigen::ArrayXXd::Zero(num_channels, num_samples); for (int i = 0; i < num_channels; ++i) { SpikeGenerator spike_gen(sample_period, kDeadTime); for (int n = 0; n < num_repeats; ++n) { spike_gen.Init(input(i, 0)); for (int j = 0; j < num_samples; ++j) { if (spike_gen.Run(input(i, j))) { const double running_spike_time = spike_gen.GetCurrentTime(); const double running_spike_sample = running_spike_time / sample_period; // The spike times are relative to the beginning of the trial. // Need to offset the spike by the overall elapsed time. const int current_sample = static_cast<int>(std::fmod( running_spike_sample, num_samples)); (*output)(i, current_sample) = 1.0; } } } } } Zhang2001SpikeGeneratorModel::Zhang2001SpikeGeneratorModel( const Zhang2001SpikeGeneratorConfig &config) : AuditoryModel(MODEL_ZHANG_SPIKES_2001, STAGE_AUDITORY_NERVE_SYNAPSE, OUTPUT_SYNAPSE_SPIKE_TIMES, false /* waveform input */), config_(config) { if (config_.num_fibers() <= 0) { config_.set_num_fibers(1); } } void Zhang2001SpikeGeneratorModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); } ChannelProperties Zhang2001SpikeGeneratorModel::GetChannelProperties() const { const AuditoryModel *model = previous_model(); GOOGLE_CHECK(model != nullptr); return model->GetChannelProperties(); } void Zhang2001SpikeGeneratorModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, // Rates. Eigen::ArrayXXd *output) { const int sample_rate = stimulus_config().sample_rate(); GOOGLE_CHECK_LT(0, sample_rate); const double sample_period = 1.0 / sample_rate; Zhang2001SpikeGenerator(input, sample_period, config_.num_fibers(), output); } } // namespace audition } // namespace eidos
5,856
C++
.cc
142
36.626761
80
0.682002
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,083
fractional_gaussian_noise.cc
google_eidos-audition/third_party/audition/models/bruce_carney/fractional_gaussian_noise.cc
// Copyright 2003-2005 Scott Jackson // Copyright 2008-2012 Muhammad S. A. Zilany // Copyright 2019 Google LLC // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "third_party/audition/models/bruce_carney/fractional_gaussian_noise.h" #include <cmath> #include <complex> #include <vector> #include "eidos/audition/utils.h" #include "eidos/port/logging.h" #include "unsupported/Eigen/FFT" namespace eidos { namespace audition { namespace { // Computes cumulative sum of the <input> mimicking Matlab cumsum API. Eigen::VectorXd CumulativeSum(const Eigen::VectorXd &input) { const int num_elements = input.size(); Eigen::VectorXd output(num_elements); double cum_sum = 0.0; for (int i = 0; i < num_elements; ++i) { cum_sum += input[i]; output[i] = cum_sum; } return output; } // Computes random vectors drawn from normal distribution. Eigen::VectorXd RandomNormalVector(int length) { const std::vector<double> vec = GetRandomNormalVector( length, 0.0 /* mean */, 1.0 /* standard deviation */); return Eigen::VectorXd::Map(vec.data(), vec.size()); } } // namespace Eigen::VectorXd JacksonFractionalGaussianNoise(int output_length, double hurst_index, double mu, double sigma) { if (hurst_index <= 0.0 || hurst_index > 2.0) { GOOGLE_LOG(FATAL) << "The Hurst index must be in the interval (0, 2]"; } if (sigma <= 0.0) { GOOGLE_LOG(FATAL) << "Standard deviation must be greater than zero"; } // Determine whether Gaussian noise or Brownian motion should be produced. bool brownian_motion = false; if (hurst_index > 1.0) { brownian_motion = true; hurst_index -= 1.0; } // Generate the outputs. Eigen::VectorXd output; if (hurst_index == 0.5) { // Gaussian noise is equivalent to white Gaussian noise. output = RandomNormalVector(output_length); } else { const double n_fft = std::pow(2.0, std::ceil( std::log2(2.0 * (output_length - 1)))); const int n_fft_half = std::round(n_fft / 2.0); Eigen::ArrayXd k(2 * n_fft_half); for (int i = 0; i <= n_fft_half; ++i) { k[i] = i; } for (int i = 1; i < n_fft_half; ++i) { k[n_fft_half + i] = n_fft_half - i; } // Zmag = 0.5 .* ((k+1).^(2.*H) - 2.*k.^(2.*H) + (abs(k-1)).^(2.*H)). const double double_hurst = 2.0 * hurst_index; Eigen::ArrayXd z_mag = 0.5 * ((k + 1.0).pow(double_hurst) - 2.0 * k.pow(double_hurst) + (k - 1.0).abs().pow(double_hurst)); // Zmag = real(fft(Zmag)). Eigen::FFT<double> fft; Eigen::VectorXcd fft_out; fft.fwd(fft_out, z_mag.matrix()); z_mag = fft_out.real(); if (z_mag.minCoeff() < 0.0) { GOOGLE_LOG(FATAL) << "The fast Fourier transform of the circulant " << "covariance had negative values."; } z_mag = z_mag.sqrt(); // Z = Zmag.*(randn(1,Nfft) + i.*randn(1,Nfft)). const Eigen::VectorXd rand_r = RandomNormalVector(n_fft); const Eigen::VectorXd rand_i = RandomNormalVector(n_fft); Eigen::ArrayXcd Z(rand_r.size());; Z.real() = rand_r; Z.imag() = rand_i; Z *= z_mag; // y = real(ifft(Z)) .* sqrt(Nfft). Eigen::VectorXcd Z_inv; fft.inv(Z_inv, Z.matrix()); output = (Z_inv.real() * std::sqrt(n_fft)).head(output_length); } // Convert to Brownian motion, if necessary. if (brownian_motion) { output = CumulativeSum(output); } // Translate by the mean and scale by standard deviation. return (output.array() + mu) * sigma; } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
3,883
C++
.cc
106
31.056604
79
0.612337
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,084
jackson_spike_generator.cc
google_eidos-audition/third_party/audition/models/bruce_carney/jackson_spike_generator.cc
// Copyright 2003 B. Scott Jackson // Copyright 2011 Muhammad S. A. Zilany // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. #include "third_party/audition/models/bruce_carney/jackson_spike_generator.h" #include <algorithm> #include <cstdint> #include <cmath> #include <cstddef> #include <numeric> #include <random> #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // Dead time or absolute refractory period (sec). constexpr double kDeadTime = 0.75E-3; // Relative refractory parameters: // // According to Zhang and Carney (2001), following spike history parameters for // two exponents fit // - Westerman and Smith (1989): "A diffusion model of the transient response // of the cochlear inner hair cell synapse."., JASA, vol. 83, no. 6. // - Gaumond and Kim (1983): "Response of cochlear nerve fibers to brief // acoustic stimuli: Role of discharge‚Äêhistory effects.", JASA, // vol. 74, no. 5. constexpr double kC0 = 0.5; // Dimensionless. constexpr double kS0 = 0.001; // sec constexpr double kC1 = 0.5; // Dimensionless. constexpr double kS1 = 0.0125; // sec } // namespace std::vector<double> JacksonSpikeGenerator(const std::vector<double> &rates, double sample_period, int num_repeats) { // Determine the mean of the rate vector. Ignore the negative or zero rates // effectively half-rectifying the input signal. const uint64_t num_samples = rates.size(); const double mean_rate = std::accumulate( rates.begin(), rates.end(), 0.0, [](double current, double rate) { if (rate > 0.0) { return current + rate; } else { return current; } }) / num_samples; const double dt = sample_period; const double T = num_samples * dt; // Total duration of the input (sec). uint64_t spike_buffer_size = static_cast<uint64_t>( mean_rate * T * num_repeats); std::vector<double> spike_times; spike_times.reserve(spike_buffer_size); // Get a vector of pseudo-random numbers. std::random_device rnd_seed; // Obtain a seed for the random number engine. std::mt19937 rnd_gen(rnd_seed()); // Standard Mersenne Twister engine. std::uniform_real_distribution<double> dist(0.0, 1.0); std::vector<double> rnd_inputs(spike_buffer_size + 1); std::generate(rnd_inputs.begin(), rnd_inputs.end(), [&dist, &rnd_gen]() { return dist(rnd_gen); }); // Integer number of discrete time bins within deadtime. const uint64_t dead_time_index = std::floor(kDeadTime / dt); // Deadtime rounded down to length of an integer number of discrete time bins. const double dead_time_rounded = dead_time_index * dt; // If y0(t) = kC0 * exp(-t / kS0), then y0(t + dt) = y0(t) * refrac_mult0, the // <kC1, kS1> pair is similar. const double refrac_mult0 = 1.0 - dt / kS0; const double refrac_mult1 = 1.0 - dt / kS1; // Calculate effects of a random spike before t=0 on refractoriness and the // time-warping sum at t=0. uint64_t rnd_buf_index = 0; const double end_of_last_dead_time = std::max( 0.0, std::log(rnd_inputs[rnd_buf_index++]) / rates[0] + kDeadTime); // Values of first and second exponenentials in the refractory function. double refrac_value0 = kC0 * std::exp(end_of_last_dead_time / kS0); double refrac_value1 = kC1 * std::exp(end_of_last_dead_time / kS1); // Value of time-warping sum. This is the "integral" of the refractory // function normalized by 'dt'. double x_sum = rates[0] * (-end_of_last_dead_time + kC0 * kS0 * (std::exp(end_of_last_dead_time / kS0) - 1.0) + kC1 * kS1 * (std::exp(end_of_last_dead_time / kS1) - 1.0)); // Calculate first interspike interval in a homogeneous, unit-rate Poisson // process (normalized by 'dt'). double unit_rate_interval = -std::log(rnd_inputs[rnd_buf_index++]) / dt; // NOTE: Both 'unit_rate_interval' and 'x_sum' are divided (or normalized) by // 'dt' in order to reduce calculation time. This way we only need to divide // by 'dt' once per spike (when calculating 'unit_rate_interval'), instead of // multiplying by 'dt' once per time bin (when calculating the new value of // 'x_sum'). double time = dt; uint64_t k = 0; for (int j = 0; j < num_repeats; ++j) { for (; (k < num_samples) && (time < T); ++k, time += dt, refrac_value0 *= refrac_mult0, refrac_value1 *= refrac_mult1) { if (rates[k] <= 0.0) { continue; // Ignore non-positive rates. } // Update time-warping sum. x_sum += (rates[k] * (1.0 - refrac_value0 - refrac_value1)); // A spike occurs when time-warping sum exceeds interspike "time" in // unit-rate process. if (x_sum >= unit_rate_interval) { spike_times.emplace_back(time); // Check if we've reached the capacity for the spike buffer. If so, // readjust the buffer and also get more random numbers since these have // been used up. if (spike_times.size() >= spike_buffer_size) { spike_buffer_size += static_cast<uint64_t>( std::ceil(mean_rate * ((T - time) + (num_repeats - j - 1) * T))); rnd_inputs.resize(spike_buffer_size); std::generate(rnd_inputs.begin(), rnd_inputs.end(), [&dist, &rnd_gen]() { return dist(rnd_gen); }); rnd_buf_index = 0; } // Next interspike "time" in unit-rate process. unit_rate_interval = -std::log(rnd_inputs[rnd_buf_index++]) / dt; x_sum = 0.0; // Increase index and time to the last time bin in the deadtime, and // reset (relative) refractory function. k += dead_time_index; time += dead_time_rounded; refrac_value0 = kC0; refrac_value1 = kC1; } } // Reset index and time to begin a new repetion. Don't just set to zero, // since new repetition may start within the deadtime following the last // spike in the previous repetition. time -= T; k -= num_samples; } // Delete spike(s) that occur after the last repetition of the rate function // ends. while (!spike_times.empty() && (spike_times.back() > T)) { spike_times.pop_back(); } std::sort(spike_times.begin(), spike_times.end()); return spike_times; } void JacksonSpikeGenerator(const Eigen::Ref<const Eigen::ArrayXXd> &rates, double sample_period, int num_repeats, Eigen::ArrayXXd *output) { const int num_channels = rates.rows(); const int num_samples = rates.cols(); *output = Eigen::ArrayXXd::Zero(num_channels, num_samples); for (int i = 0; i < num_channels; i++) { const auto &channel_vec = rates.row(i); const std::vector<double> channel_rates(channel_vec.data(), channel_vec.data() + num_samples); const std::vector<double> &spike_times = JacksonSpikeGenerator(channel_rates, sample_period, num_repeats); for (const auto spike_time : spike_times) { const double spike_sample = spike_time / sample_period; (*output)(i, spike_sample) = 1.0; } } } JacksonSpikeGeneratorModel::JacksonSpikeGeneratorModel() : AuditoryModel(MODEL_JACKSON_SPIKES, STAGE_AUDITORY_NERVE_SYNAPSE, OUTPUT_SYNAPSE_SPIKE_TIMES, false /* waveform input */) {} void JacksonSpikeGeneratorModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); } ChannelProperties JacksonSpikeGeneratorModel::GetChannelProperties() const { const AuditoryModel *prev_model = previous_model(); GOOGLE_CHECK(prev_model != nullptr); return prev_model->GetChannelProperties();; } void JacksonSpikeGeneratorModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { const int sample_rate = stimulus_config().sample_rate(); GOOGLE_CHECK_LT(0, sample_rate); JacksonSpikeGenerator(input, 1.0 / sample_rate /* sample period */, 1 /* number of repetitions */, output); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
8,732
C++
.cc
191
40.036649
80
0.65668
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,085
bruce2018_spike_generator.cc
google_eidos-audition/third_party/audition/models/bruce_carney/bruce2018_spike_generator.cc
// Copyright 2007 Ian C. Bruce, Yousof Erfani, Muhammad S. A. Zilany // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. #include "third_party/audition/models/bruce_carney/bruce2018_spike_generator.h" #include <algorithm> #include <cstdint> #include <cmath> #include <random> #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/audition/utils.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { constexpr int64_t kZero = static_cast<int64_t>(0); // ----------------------------------------------- // Synaptic release / spike generation parameters. // ----------------------------------------------- // Number of synaptic release sites. constexpr int kNumSites = 4; // Resting value of the mean redocking time. constexpr double kTimeRedockingRest = 14.0E-3; // Size of jump in mean redocking time when a redocking event occurs. constexpr double kTimeRedockingJump = 0.4E-3; // Time constant for short-term adaptation (in mean redocking time). constexpr double kTau = 60.0e-3; // Minimum spontaneous firing rate (spikes/sec). constexpr double kMinSpontaneousRate = 1E-4; // Maximum spontaneous firing rate (spikes/sec). constexpr double kMaxSpontaneousRate = 180; // Minimum refractory period (sec). constexpr double kMinRefractoryPeriod = 0.0; // Maximum refractory period (sec). constexpr double kMaxRefractoryPeriod = 20E-3; // Passes the output of the synapse model through the spike generator. // The rate probabilities in <rates> correspond to the output of the synapse // model. int SpikeGenerator(const std::vector<double> &rates, double sample_period, double t_rd_init, double tabs, double trel, double total_mean_rate, int64_t max_num_spikes, std::vector<double> *spike_times, std::vector<double> *trd_vector) { const int64_t num_rates = rates.size(); // Estimating max number of spikes and events (including before zero // elements). const double mean_inter_events = 1.0 / total_mean_rate + t_rd_init / kNumSites; // The sufficient array size (more than 99.7% of cases) to register event // times after zero. const int64_t max_num_events = std::ceil(static_cast<int64_t>( num_rates * sample_period / mean_inter_events + 3 * std::sqrt(num_rates * sample_period / mean_inter_events))) + kNumSites; // Max random array size: <kNumSites> elements for <one_site_redock> // initialization, <kNumSites> elements for <pre_release_time_bins> // initialization, 1 element for <t_ref> initialization, // <max_num_spikes> elements for <t_ref> in the loop, // <max_num_events> elements one time for redocking, another time for // rate intervals. Also, for before zero elements, average add 2 <kNumSites> // events (redock and unit_rate) and add <kNumSites> (max) for <t_ref>s: 3 // <kNumSites> spikes in total. const int64_t rand_buf_len = 2 * kNumSites + 1 + max_num_spikes + 2 * max_num_events + max_num_spikes + 3 * kNumSites; const std::vector<double> rand_nums = GetRandomUniformVector( rand_buf_len, 0.0, 1.0); int64_t rand_buf_index = 0; // Initial < redocking time associated with <kNumSites> release sites. std::vector<double> one_site_redock(kNumSites); // Initial values associated with nsites release sites. std::vector<double> pre_release_time_bins(kNumSites); for (int i = 0; i < kNumSites; ++i) { one_site_redock[i] = -t_rd_init * std::log(rand_nums[rand_buf_index++]); pre_release_time_bins[i] = std::max( -static_cast<double>(num_rates), std::ceil((kNumSites / std::max(rates[0], 0.1) + t_rd_init) * std::log(rand_nums[rand_buf_index++]) / sample_period)); } // Sort the <kNumSites> initial pre-release times and associate the farthest // from zero as the site which has also generated a spike. std::sort(pre_release_time_bins.begin(), pre_release_time_bins.end()); std::vector<double> previous_release_times(kNumSites); for (int i = 0; i < kNumSites; ++i) { previous_release_times[i] = pre_release_time_bins[i] * sample_period; } // Position of the first spike (this is often a *negative* value). int k_init = static_cast<int>(pre_release_time_bins[0]); double current_refractory_period = k_init * sample_period; // Refractory regions. // Current refractory time. double t_ref = tabs - trel * std::log(rand_nums[rand_buf_index++]); int64_t k = k_init; // Can be negative. // Set dynamic mean redocking time to initial mean redocking time. double previous_redocking_period = t_rd_init; double current_redocking_period = previous_redocking_period; // Whether to decay the value of current_redocking_period at the end of the // time step. bool t_rd_decay = true; bool rd_first = false; // Whether a first redocking event has occurred. // Find the spike times for all the num_rates. int one_site_redock_rounded, elapsed_time_rounded; std::vector<double> elapsed_time(kNumSites, 0.0), x_sum(kNumSites, 0.0); std::vector<int> unit_rate_interval(kNumSites, 0); std::vector<double> current_release_times(kNumSites, 0.0); while (k < num_rates) { for (int site_no = 0; site_no < kNumSites; ++site_no) { if (k > pre_release_time_bins[site_no]) { // Redocking times do not necessarily occur exactly at time step value // - calculate the number of integer steps for the elapsed time and // redocking time. one_site_redock_rounded = static_cast<int>( std::floor(one_site_redock[site_no] / sample_period)); elapsed_time_rounded = static_cast<int>(std::floor(elapsed_time[site_no] / sample_period)); // Check if redocking event has occurred. if (one_site_redock_rounded == elapsed_time_rounded) { current_redocking_period = previous_redocking_period + kTimeRedockingJump; previous_redocking_period = current_redocking_period; t_rd_decay = false; // Dont' decay the value of redocking period. rd_first = true; // Redocking has occurred. } // For each site, the code starts from its associated previous release // time. elapsed_time[site_no] += sample_period; } // The elapsed time passes the one time redock (the redocking is // finished). In this case the synaptic vesicle starts sensing the input // for each site, integration starts after the redockinging is finished // for the corresponding site. if (elapsed_time[site_no] >= one_site_redock[site_no]) { // There are <kNumSites> integrals each vesicle senses 1 / <kNumSites> // of the whole rate. x_sum[site_no] += (rates[std::max(kZero, k)] / kNumSites); } // Check if release event happened at <site_no>. if ((x_sum[site_no] >= unit_rate_interval[site_no]) && (k >= pre_release_time_bins[site_no])) { one_site_redock[site_no] = -current_redocking_period * std::log(rand_nums[rand_buf_index++]); current_release_times[site_no] = previous_release_times[site_no] + elapsed_time[site_no]; elapsed_time[site_no] = 0.0; // Check if a spike occured for the current event - release. if (current_release_times[site_no] >= current_refractory_period) { // Register only non-negative spike times. if (current_release_times[site_no] >= 0) { spike_times->push_back(current_release_times[site_no]); } const double trel_k = std::min(trel * 100.0 / rates[std::max(kZero, k)], trel); t_ref = tabs - trel_k * std::log(rand_nums[rand_buf_index++]); current_refractory_period = current_release_times[site_no] + t_ref; } previous_release_times[site_no] = current_release_times[site_no]; x_sum[site_no] = 0.0; unit_rate_interval[site_no] = static_cast<int>( -std::log(rand_nums[rand_buf_index++]) / sample_period); } // Error handling in case the random buffer is not large enough. if ((rand_buf_index + 1) > rand_buf_len) { k = num_rates; site_no = kNumSites; } } // Decay the adaptive mean redocking time towards the resting value if no // redocking events occurred in this time step. if (t_rd_decay && rd_first) { current_redocking_period = previous_redocking_period - (sample_period / kTau) * (previous_redocking_period - kTimeRedockingRest); previous_redocking_period = current_redocking_period; } else { t_rd_decay = true; } // Store the value of the adaptive mean redocking time if it is within the // simulation output period. if ((k >= 0) && (k < num_rates)) { trd_vector->push_back(current_redocking_period); } k++; } return spike_times->size(); } } // namespace std::vector<double> Bruce2018SpikeGenerator(const std::vector<double> &rates, double sample_period, double spont_rate, double absolute_refractory_period, double relative_refractory_period) { // Sanity checks. CheckWithinRange(spont_rate, kMinSpontaneousRate, kMaxSpontaneousRate, "Spontaneous rate"); CheckWithinRange(absolute_refractory_period, kMinRefractoryPeriod, kMaxRefractoryPeriod, "Absolute refractory period"); CheckWithinRange(relative_refractory_period, kMinRefractoryPeriod, kMaxRefractoryPeriod, "Relative refractory period"); // Initial value of the mean redocking time. const double time_redocking_init = kTimeRedockingRest + 0.02E-3 * spont_rate - kTimeRedockingJump; // Compute the overall mean synaptic rate. double total_mean_rate = 0.0; const int64_t num_rates = rates.size(); for (int64_t i = 0; i < num_rates; ++i) { total_mean_rate += rates[i] / num_rates; } // Compute mean interspike interval (ISI) and estimate the number of spikes. const double mean_isi = 1.0 / total_mean_rate + time_redocking_init / kNumSites + absolute_refractory_period + relative_refractory_period; const double signal_length = num_rates * sample_period; // In seconds. const int64_t max_num_spikes = std::ceil( signal_length / mean_isi + 3 * std::sqrt(signal_length / mean_isi)); // Compute the spikes. std::vector<double> spike_times, redocking_times; spike_times.reserve(max_num_spikes); const int num_spikes = SpikeGenerator( rates, sample_period, time_redocking_init, absolute_refractory_period, relative_refractory_period, total_mean_rate, max_num_spikes, &spike_times, &redocking_times); GOOGLE_CHECK_LT(0, num_spikes); return spike_times; } void Bruce2018SpikeGenerator(const Eigen::Ref<const Eigen::ArrayXXd> &rates, double sample_period, double spont_rate, double absolute_refractory_period, double relative_refractory_period, Eigen::ArrayXXd *output) { const int num_channels = rates.rows(); const int num_samples = rates.cols(); *output = Eigen::ArrayXXd::Zero(num_channels, num_samples); for (int i = 0; i < num_channels; i++) { const auto &channel_vec = rates.row(i); const std::vector<double> channel_rates(channel_vec.data(), channel_vec.data() + num_samples); const std::vector<double> &spike_times = Bruce2018SpikeGenerator( channel_rates, sample_period, spont_rate, absolute_refractory_period, relative_refractory_period); for (const auto spike_time : spike_times) { const double spike_sample = spike_time / sample_period; (*output)(i, spike_sample) = 1.0; } } } Bruce2018SpikeGeneratorModel::Bruce2018SpikeGeneratorModel() : AuditoryModel(MODEL_BRUCE_SPIKES_2018, STAGE_AUDITORY_NERVE_SYNAPSE, OUTPUT_SYNAPSE_SPIKE_TIMES, false /* waveform input */) {} void Bruce2018SpikeGeneratorModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); } ChannelProperties Bruce2018SpikeGeneratorModel::GetChannelProperties() const { const AuditoryModel *model = previous_model(); GOOGLE_CHECK(model != nullptr); return model->GetChannelProperties(); } namespace { // TODO(agutkin): Hard-coded fiber parameters that should be channel-specific. constexpr double kSpontRate = 60.0; // Spontaneous firing rate (spikes/sec). constexpr double kAbsoluteRefractoryPeriod = 0.7E-3; // sec constexpr double kRelativeRefractoryPeriod = 0.6E-3; // sec } // namespace void Bruce2018SpikeGeneratorModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { const int sample_rate = stimulus_config().sample_rate(); GOOGLE_CHECK_LT(0, sample_rate); Bruce2018SpikeGenerator(input, 1.0 / sample_rate /* sample period */, kSpontRate, kAbsoluteRefractoryPeriod, kRelativeRefractoryPeriod, output); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
13,875
C++
.cc
286
41.762238
80
0.665091
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,086
bruce2018_hair_cell_synapse_model.cc
google_eidos-audition/third_party/audition/models/bruce_carney/bruce2018_hair_cell_synapse_model.cc
// Copyright 2007 Ian C. Bruce, Yousof Erfani, Muhammad S. A. Zilany // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. #include "third_party/audition/models/bruce_carney/bruce2018_hair_cell_synapse_model.h" #include <cstdint> #include <cmath> #include <vector> #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/port/logging.h" #include "resample.h" // See @com_github_resample. #include "third_party/audition/models/bruce_carney/fractional_gaussian_noise.h" namespace eidos { namespace audition { namespace { // Sampling frequency used for the synapse model for analysis. constexpr double kAnalysisSampleRate = 10E3; // 10 kHz // Sample period (aka bin width) for the model used in the analysis. constexpr double kAnalysisSamplePeriod = 1.0 / kAnalysisSampleRate; // Power-Law function parameters. constexpr double kAlpha1 = 1.5E-6 * 100E3; constexpr double kBeta1 = 5E-4; constexpr double kAlpha2 = 1E-2 * 100E3; constexpr double kBeta2 = 1E-1; } // namespace // For Power-Law adaptation please see: // // - Drew, P.J. and Abbott, L.F. (2006): "Models and properties of power-law // adaptation in neural systems.", Journal of neurophysiology, no. 96, // pp. 826-833. // // TODO(agutkin): Please note, the implementation below is highly likely to be // buggy (in terms of container manipulation). void Bruce2018HairCellSynapse(const Eigen::RowArrayXd &ihc_out, double sample_period, double center_freq, double spont_rate, bool exact_power_law, Eigen::RowArrayXd *rates) { const uint32_t num_samples = ihc_out.size(); const uint32_t delay_point = std::floor(7500.0 / (center_freq / 1E3)); const uint32_t num_output_samples = std::ceil( (num_samples + 2 * delay_point) * sample_period * kAnalysisSampleRate); // Generate random numbers. Please note, the mean and variance roughly // correspond to the particular implementation of fractional Gaussian noise // in the original paper ("ffGn.m"). double sigma = 0.0; if (spont_rate < 0.2) { sigma = 1.0; } else if (spont_rate < 20.0) { sigma = 10.0; } else { sigma = spont_rate / 2.0; } const Eigen::VectorXd rand_nums = JacksonFractionalGaussianNoise( num_output_samples, 0.9 /* Hurst index */, 0.0 /* mean */, sigma /* standard deviation */); // ================================================================ // Mapping from the IHC output to the input to Power-Law adapation. // ================================================================ const double cf_slope = std::pow(spont_rate, 0.19) * std::pow(10.0, -0.87); const double cf_const = 0.1 * std::pow(std::log10(spont_rate), 2) + 0.56 * std::log10(spont_rate) - 0.84; const double cf_sat = std::pow(10.0, (cf_slope * 8965.5 / 1E3 + cf_const)); const double cf_factor = std::min(cf_sat, std::pow( 10.0, cf_slope * center_freq / 1E3 + cf_const)) * 2.0; const double mult_factor = std::max(2.95 * std::max( 1.0, 1.5 - spont_rate / 100), 4.3 - 0.2 * center_freq / 1E3); std::vector<double> mapping_out(num_samples); for (uint32_t i = 0; i < num_samples; ++i) { mapping_out[i] = std::pow(10.0, (0.9 * std::log10(std::fabs( ihc_out[i]) * cf_factor)) + mult_factor); if (ihc_out[i] < 0.0) mapping_out[i] = -mapping_out[i]; } std::vector<double> power_law_input(num_samples + 3 * delay_point); const double spont_rate_3 = 3.0 * spont_rate; for (uint32_t i = 0; i < delay_point; ++i) { power_law_input[i] = mapping_out[0] + spont_rate_3; } for (uint32_t i = delay_point; i < num_samples + delay_point; ++i) { power_law_input[i] = mapping_out[i - delay_point] + spont_rate_3; } for (uint32_t i = num_samples + delay_point; i < num_samples + 3 * delay_point; ++i) { power_law_input[i] = power_law_input[i - 1] + spont_rate_3; } mapping_out.clear(); // =============================================================== // Downsample to low frequency <kAnalysisSampleRate> for analysis. // =============================================================== const uint32_t downsample_factor = static_cast<uint32_t>(std::ceil(1.0 / ( sample_period * kAnalysisSampleRate))); std::vector<double> resampled_ihc; ::resample(1 /* upsample factor */, downsample_factor, power_law_input, resampled_ihc); GOOGLE_CHECK_LE(resampled_ihc.size(), power_law_input.size()) << "Downsampling factor of " << downsample_factor << " does not result in smaller output"; // Pad to <num_output_samples> if necessary. if (resampled_ihc.size() < num_output_samples) { resampled_ihc.insert(resampled_ihc.end(), power_law_input.begin() + resampled_ihc.size(), power_law_input.begin() + num_output_samples); } power_law_input.clear(); // =============================================================== // Run Power-Law adaptation. // =============================================================== uint32_t k = 0; double I1 = 0.0, I2 = 0.0; std::vector<double> sout1(num_output_samples, 0.0); std::vector<double> sout2(num_output_samples, 0.0); std::vector<double> n1(num_output_samples, 0.0); std::vector<double> n2(num_output_samples, 0.0); std::vector<double> n3(num_output_samples, 0.0); std::vector<double> m1(num_output_samples, 0.0); std::vector<double> m2(num_output_samples, 0.0); std::vector<double> m3(num_output_samples, 0.0); std::vector<double> m4(num_output_samples, 0.0); std::vector<double> m5(num_output_samples, 0.0); std::vector<double> resampled_rates(num_output_samples, 0.0); for (uint32_t i = 0; i < num_output_samples; ++i, ++k) { sout1[k] = std::max(0.0, resampled_ihc[i] + rand_nums[i] - kAlpha1 * I1); sout2[k] = std::max(0.0, resampled_ihc[i] - kAlpha2 * I2); if (exact_power_law) { // Exact implementation of the Power-Law. I1 = 0; I2 = 0; for (uint32_t j = 0; j <= k; ++j) { I1 += (sout1[j] * kAnalysisSamplePeriod / ((k - j) * kAnalysisSamplePeriod + kBeta1)); I2 += (sout2[j] * kAnalysisSamplePeriod / ((k - j) * kAnalysisSamplePeriod + kBeta2)); } } else { // Approximate implementation of the Power-Law. if (k == 0) { n1[0] = 1.0E-3 * sout2[0]; n2[0] = n1[0]; n3[0] = n2[0]; } else if (k == 1) { n1[1] = 1.992127932802320 * n1[0] + 1.0E-3 * ( sout2[1] - 0.994466986569624 * sout2[0]); n2[1] = 1.999195329360981 * n2[0] + n1[1] - 1.997855276593802 * n1[0]; n3[1] = -0.798261718183851 * n3[0] + n2[1] + 0.798261718184977 * n2[0]; } else { n1[k] = 1.992127932802320 * n1[k - 1] - 0.992140616993846 * n1[k - 2] + 1.0E-3 * (sout2[k] - 0.994466986569624 * sout2[k - 1] + 0.000000000002347 * sout2[k - 2]); n2[k] = 1.999195329360981 * n2[k - 1] - 0.999195402928777 * n2[k - 2] + n1[k] - 1.997855276593802 * n1[k - 1] + 0.997855827934345 * n1[k - 2]; n3[k] = -0.798261718183851 * n3[k - 1] - 0.199131619873480 * n3[k - 2] + n2[k] + 0.798261718184977 * n2[k - 1] + 0.199131619874064 * n2[k - 2]; } I2 = n3[k]; if (k == 0) { m1[0] = 0.2 * sout1[0]; m2[0] = m1[0]; m3[0] = m2[0]; m4[0] = m3[0]; m5[0] = m4[0]; } else if (k == 1) { m1[1] = 0.491115852967412 * m1[0] + 0.2 * ( sout1[1] - 0.173492003319319 * sout1[0]); m2[1] = 1.084520302502860 * m2[0] + m1[1] - 0.803462163297112 * m1[0]; m3[1] = 1.588427084535629 * m3[0] + m2[1] - 1.416084732997016 * m2[0]; m4[1] = 1.886287488516458 * m4[0] + m3[1] - 1.830362725074550 * m3[0]; m5[1] = 1.989549282714008 * m5[0] + m4[1] - 1.983165053215032 * m4[0]; } else { m1[k] = 0.491115852967412 * m1[k - 1] - 0.055050209956838 * m1[k - 2] + 0.2 * (sout1[k] - 0.173492003319319 * sout1[k - 1] + 0.000000172983796 * sout1[k - 2]); m2[k] = 1.084520302502860 * m2[k - 1] - 0.288760329320566 * m2[k - 2] + m1[k] - 0.803462163297112 * m1[k - 1] + 0.154962026341513 * m1[k - 2]; m3[k] = 1.588427084535629 * m3[k - 1] - 0.628138993662508 * m3[k - 2] + m2[k] - 1.416084732997016 * m2[k - 1] + 0.496615555008723 * m2[k - 2]; m4[k] = 1.886287488516458 * m4[k - 1] - 0.888972875389923 * m4[k - 2] + m3[k] - 1.830362725074550 * m3[k - 1] + 0.836399964176882 * m3[k - 2]; m5[k] = 1.989549282714008 * m5[k - 1] - 0.989558985673023 * m5[k - 2] + m4[k] - 1.983165053215032 * m4[k - 1] + 0.983193027347456 * m4[k - 2]; } I1 = m5[k]; } resampled_rates[k] = sout1[k] + sout2[k]; } GOOGLE_CHECK(k != 0); sout1.clear(); sout2.clear(); resampled_ihc.clear(); // =============================================================== // Upsample to the original sampling rate. // =============================================================== std::vector<double> tmp_rates((k - 1) * downsample_factor, 0.0); for (uint32_t i = 0; i < k - 1; ++i) { const double incr = (resampled_rates[i + 1] - resampled_rates[i]) / downsample_factor; for (uint32_t j = 0; j < downsample_factor; ++j) { tmp_rates[i * downsample_factor + j] = resampled_rates[i] + j * incr; } } rates->resize(num_samples); for (uint32_t i = 0; i < num_samples; ++i) { (*rates)[i] = tmp_rates[i + delay_point]; } } Bruce2018HairCellSynapseModel::Bruce2018HairCellSynapseModel() : AuditoryModel(MODEL_BRUCE_SYNAPSE_2018, STAGE_AUDITORY_NERVE_SYNAPSE, OUTPUT_SYNAPSE_FIRING_RATES, false /* waveform input */) {} void Bruce2018HairCellSynapseModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); } ChannelProperties Bruce2018HairCellSynapseModel::GetChannelProperties() const { const AuditoryModel *model = previous_model(); GOOGLE_CHECK(model != nullptr); return model->GetChannelProperties(); } namespace { // TODO(agutkin): Hard-coded fiber parameters that should be channel-specific. constexpr double kSpontRate = 60.0; // Spontaneous firing rate (spikes/sec). } // namespace void Bruce2018HairCellSynapseModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { const int sample_rate = stimulus_config().sample_rate(); GOOGLE_CHECK_LT(0, sample_rate); const ChannelProperties &channel_properties = GetChannelProperties(); const auto &center_frequencies = channel_properties.center_frequencies; const int num_channels = center_frequencies.size(); GOOGLE_CHECK_LT(0, num_channels); *output = Eigen::ArrayXXd::Zero(num_channels, input.cols()); Eigen::RowArrayXd fiber_output; for (int i = 0; i < num_channels; ++i) { Bruce2018HairCellSynapse(input.row(i), 1.0 / sample_rate, center_frequencies[i], kSpontRate, false /* approximate Power-Law */, &fiber_output); output->row(i).swap(fiber_output.row(0)); } } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
11,806
C++
.cc
255
40.490196
87
0.594775
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,087
zilany2014_ihc_model.cc
google_eidos-audition/third_party/audition/models/bruce_carney/zilany2014_ihc_model.cc
// Copyright 2013 Muhammad S. A. Zilany, Ian C. Bruce, Rasha A. Ibrahim, // Paul C. Nelson and Laurel H. Carney // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. #include "third_party/audition/models/bruce_carney/zilany2014_ihc_model.h" #include <cstdint> #include <cmath> #include <complex> #include <vector> #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/audition/psychoacoustic_scale_utils.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // Type of the species. enum Species { SPECIES_CAT = 0, SPECIES_HUMAN_SHERA = 1, // Shera et al. (PNAS 2002). SPECIES_HUMAN_GLASBERG = 2 // Glasberg & Moore (Hear. Res. 1990). }; // \pi * 2 constexpr double kTwoPi = 6.283185307179586; // Returns a complex number equal to exp(i * theta). This computes // (0, theta) -> exp^0 * (sin(theta) + i * cos(theta)). std::complex<double> CompExp(double theta) { return std::exp(std::complex<double>(0, theta)); } // Gets TauMax, TauMin for the tuning filter. The TauMax is determined by the // bandwidth / Q10 of the tuning filter at low level. The TauMin is determined // by the gain change between high and low level. double GetTauWb(double cf, int species, int order, double *taumax, double *taumin) { // NOTE(agutkin): The gain should be species-dependent, but it's not. double gain, Q10 = 0.0; gain = 52.0 / 2.0 * (std::tanh(2.2 * std::log10(cf / 0.6e3) + 0.15) + 1.0); if (gain > 60.0) gain = 60.0; if (gain < 15.0) gain = 15.0; // ratio of TauMin/TauMax according to the gain, order. const double ratio = std::pow(10, (-gain / (20.0 * order))); if (species == Species::SPECIES_CAT) { Q10 = std::pow(10, 0.4708 * std::log10(cf / 1E3) + 0.4664); } else if (species == Species::SPECIES_HUMAN_SHERA) { Q10 = std::pow((cf / 1000), 0.3) * 12.7 * 0.505 + 0.2085; } else if (species == Species::SPECIES_HUMAN_GLASBERG) { Q10 = cf / 24.7 / (4.37 * (cf / 1000) + 1) * 0.505 + 0.2085; } else { GOOGLE_LOG(FATAL) << "Unknown species: " << species; } const double bw = cf / Q10; taumax[0] = 2.0 / (kTwoPi * bw); taumin[0] = taumax[0] * ratio; return 0; } double GetTauBm(double cf, double taumax, double *bmTaumax, double *bmTaumin, double *ratio) { // NOTE(agutkin): The gain should be species-dependent, but it's not. double gain = 52.0 / 2.0 * (std::tanh(2.2 * std::log10(cf / 0.6E3) + 0.15) + 1.0); if (gain > 60.0) gain = 60.0; if (gain < 15.0) gain = 15.0; constexpr double bwfactor = 0.7; constexpr double factor = 2.5; ratio[0] = std::pow(10, (-gain / (20.0 * factor))); bmTaumax[0] = taumax / bwfactor; bmTaumin[0] = bmTaumax[0] * ratio[0]; return 0.0; } // Passes the signal through the signal-path C1 Tenth Order Nonlinear // Chirp-Gammatone Filter. // // NOTE: This function is thread unsafe. double C1ChirpFilt(double x, double tdres, double cf, int n, double taumax, double rsigma) { static double C1gain_norm, C1initphase; static double C1input[12][4], C1output[12][4]; // ======== setup the locations of poles and zeros ======= const double sigma0 = 1 / taumax; const double ipw = 1.01 * cf * kTwoPi - 50; const double ipb = 0.2343 * kTwoPi * cf - 1104; const double rpa = std::pow(10, std::log10(cf) * 0.9 + 0.55) + 2000; const double pzero = std::pow(10, std::log10(cf) * 0.7 + 1.6) + 500; double rzero = -pzero; // ====================================================== const int order_of_pole = 10; const int half_order_pole = order_of_pole / 2; const int order_of_zero = half_order_pole; const double fs_bilinear = kTwoPi * cf / std::tan(kTwoPi * cf * tdres / 2); const double CF = kTwoPi * cf; std::complex<double> p[11]; double preal, pimg; if (n == 0) { p[1].real(-sigma0); p[1].imag(ipw); p[5].real(p[1].real() - rpa); p[5].imag(p[1].imag() - ipb); p[3].real((p[1].real() + p[5].real()) * 0.5); p[3].imag((p[1].imag() + p[5].imag()) * 0.5); p[2] = std::conj(p[1]); p[4] = std::conj(p[3]); p[6] = std::conj(p[5]); p[7] = p[1]; p[8] = p[2]; p[9] = p[5]; p[10] = p[6]; C1initphase = 0.0; for (int i = 1; i <= half_order_pole; i++) { preal = p[i * 2 - 1].real(); pimg = p[i * 2 - 1].imag(); C1initphase = C1initphase + std::atan(CF / (-rzero)) - std::atan((CF - pimg) / (-preal)) - std::atan((CF + pimg) / (-preal)); } // ===================== Initialize C1input & C1output ===================== for (int i = 1; i <= (half_order_pole + 1); i++) { C1input[i][3] = 0; C1input[i][2] = 0; C1input[i][1] = 0; C1output[i][3] = 0; C1output[i][2] = 0; C1output[i][1] = 0; } // ===================== normalize the gain ===================== C1gain_norm = 1.0; for (int r = 1; r <= order_of_pole; r++) { C1gain_norm = C1gain_norm * (std::pow((CF - p[r].imag()), 2) + p[r].real() * p[r].real()); } } const double norm_gain = std::sqrt(C1gain_norm) / std::pow(std::sqrt(CF * CF + rzero * rzero), order_of_zero); p[1].real(-sigma0 - rsigma); if (p[1].real() > 0.0) { GOOGLE_LOG(FATAL) << "The system becomes unstable!"; } p[1].imag(ipw); p[5].real(p[1].real() - rpa); p[5].imag(p[1].imag() - ipb); p[3].real((p[1].real() + p[5].real()) * 0.5); p[3].imag((p[1].imag() + p[5].imag()) * 0.5); p[2] = std::conj(p[1]); p[4] = std::conj(p[3]); p[6] = std::conj(p[5]); p[7] = p[1]; p[8] = p[2]; p[9] = p[5]; p[10] = p[6]; double phase = 0.0; for (int i = 1; i <= half_order_pole; i++) { preal = p[i * 2 - 1].real(); pimg = p[i * 2 - 1].imag(); phase = phase - std::atan((CF - pimg) / (-preal)) - std::atan((CF + pimg) / (-preal)); } rzero = -CF / std::tan((C1initphase - phase) / order_of_zero); if (rzero > 0.0) { GOOGLE_LOG(FATAL) << "The zeros are in the right-hand plane!"; } // =================================================================== // Each iteration of a loop below is for a pair of poles and one zero. // =================================================================== C1input[1][3] = C1input[1][2]; C1input[1][2] = C1input[1][1]; C1input[1][1] = x; double dy; for (int i = 1; i <= half_order_pole; i++) { preal = p[i * 2 - 1].real(); pimg = p[i * 2 - 1].imag(); const double temp = std::pow((fs_bilinear - preal), 2) + std::pow(pimg, 2); dy = C1input[i][1] * (fs_bilinear - rzero) - 2 * rzero * C1input[i][2] - (fs_bilinear + rzero) * C1input[i][3] + 2 * C1output[i][1] * (fs_bilinear * fs_bilinear - preal * preal - pimg * pimg) - C1output[i][2] * ((fs_bilinear + preal) * (fs_bilinear + preal) + pimg * pimg); dy = dy / temp; C1input[i + 1][3] = C1output[i][2]; C1input[i + 1][2] = C1output[i][1]; C1input[i + 1][1] = dy; C1output[i][2] = C1output[i][1]; C1output[i][1] = dy; } dy = C1output[half_order_pole][1] * norm_gain; // Signal path output is divided by 4 to give correct C1 filter gain. const double c1filterout = dy / 4.0; return c1filterout; } // Parallel path C2 filter: same as the signal-path C1 filter with the OHC // completely impaired. // // NOTE: This function is thread unsafe. double C2ChirpFilt(double xx, double tdres, double cf, int n, double taumax, double fcohc) { static double C2gain_norm, C2initphase; static double C2input[12][4], C2output[12][4]; double preal, pimg; // ================ setup the locations of poles and zeros ======= const double sigma0 = 1 / taumax; const double ipw = 1.01 * cf * kTwoPi - 50; const double ipb = 0.2343 * kTwoPi * cf - 1104; const double rpa = std::pow(10, std::log10(cf) * 0.9 + 0.55) + 2000; const double pzero = std::pow(10, std::log10(cf) * 0.7 + 1.6) + 500; double rzero = -pzero; // =============================================================== const int order_of_pole = 10; const int half_order_pole = order_of_pole / 2; const int order_of_zero = half_order_pole; const double fs_bilinear = kTwoPi * cf / std::tan(kTwoPi * cf * tdres / 2); const double CF = kTwoPi * cf; std::complex<double> p[11]; if (n == 0) { p[1].real(-sigma0); p[1].imag(ipw); p[5].real(p[1].real() - rpa); p[5].imag(p[1].imag() - ipb); p[3].real((p[1].real() + p[5].real()) * 0.5); p[3].imag((p[1].imag() + p[5].imag()) * 0.5); p[2] = std::conj(p[1]); p[4] = std::conj(p[3]); p[6] = std::conj(p[5]); p[7] = p[1]; p[8] = p[2]; p[9] = p[5]; p[10] = p[6]; C2initphase = 0.0; for (int i = 1; i <= half_order_pole; i++) { preal = p[i * 2 - 1].real(); pimg = p[i * 2 - 1].imag(); C2initphase = C2initphase + std::atan(CF / (-rzero)) - std::atan((CF - pimg) / (-preal)) - std::atan((CF + pimg) / (-preal)); } // ===================== Initialize C2input & C2output ===================== for (int i = 1; i <= (half_order_pole + 1); i++) { C2input[i][3] = 0; C2input[i][2] = 0; C2input[i][1] = 0; C2output[i][3] = 0; C2output[i][2] = 0; C2output[i][1] = 0; } // ===================== normalize the gain ===================== C2gain_norm = 1.0; for (int r = 1; r <= order_of_pole; r++) { C2gain_norm = C2gain_norm * (std::pow((CF - p[r].imag()), 2) + p[r].real() * p[r].real()); } } const double norm_gain = std::sqrt(C2gain_norm) / std::pow(std::sqrt(CF * CF + rzero * rzero), order_of_zero); p[1].real(-sigma0 * fcohc); if (p[1].real() > 0.0) { GOOGLE_LOG(FATAL) << "The system becomes unstable!"; } p[1].imag(ipw); p[5].real(p[1].real() - rpa); p[5].imag(p[1].imag() - ipb); p[3].real((p[1].real() + p[5].real()) * 0.5); p[3].imag((p[1].imag() + p[5].imag()) * 0.5); p[2] = std::conj(p[1]); p[4] = std::conj(p[3]); p[6] = std::conj(p[5]); p[7] = p[1]; p[8] = p[2]; p[9] = p[5]; p[10] = p[6]; double phase = 0.0; for (int i = 1; i <= half_order_pole; i++) { preal = p[i * 2 - 1].real(); pimg = p[i * 2 - 1].imag(); phase = phase - std::atan((CF - pimg) / (-preal)) - std::atan((CF + pimg) / (-preal)); } rzero = -CF / std::tan((C2initphase - phase) / order_of_zero); if (rzero > 0.0) { GOOGLE_LOG(FATAL) << "The zeros are in the right-hand plane!"; } // ================================================== // time loop begins here // ================================================== C2input[1][3] = C2input[1][2]; C2input[1][2] = C2input[1][1]; C2input[1][1] = xx; double dy; for (int i = 1; i <= half_order_pole; i++) { preal = p[i * 2 - 1].real(); pimg = p[i * 2 - 1].imag(); const double temp = std::pow((fs_bilinear - preal), 2) + std::pow(pimg, 2); dy = C2input[i][1] * (fs_bilinear - rzero) - 2 * rzero * C2input[i][2] - (fs_bilinear + rzero) * C2input[i][3] + 2 * C2output[i][1] * (fs_bilinear * fs_bilinear - preal * preal - pimg * pimg) - C2output[i][2] * ((fs_bilinear + preal) * (fs_bilinear + preal) + pimg * pimg); dy = dy / temp; C2input[i + 1][3] = C2output[i][2]; C2input[i + 1][2] = C2output[i][1]; C2input[i + 1][1] = dy; C2output[i][2] = C2output[i][1]; C2output[i][1] = dy; } dy = C2output[half_order_pole][1] * norm_gain; const double c2filterout = dy / 4.0; return c2filterout; } // Passes the signal through the Control path Third Order Nonlinear Gammatone // Filter. // // NOTE: This function is thread unsafe. double WbGammaTone(double x, double tdres, double centerfreq, int n, double tau, double gain, int order) { static double wbphase; static std::complex<double> wbgtf[4], wbgtfl[4]; if (n == 0) { wbphase = 0; for (int i = 0; i <= order; i++) { wbgtfl[i] = CompExp(0) * 0.0; wbgtf[i] = CompExp(0) * 0.0; } } const double delta_phase = -kTwoPi * centerfreq * tdres; wbphase += delta_phase; const double dtmp = tau * 2.0 / tdres; const double c1LP = (dtmp - 1) / (dtmp + 1); const double c2LP = 1.0 / (dtmp + 1); wbgtf[0] = x * CompExp(wbphase); // frequency shift. for (int j = 1; j <= order; j++) { // IIR Bilinear transformation LPF. wbgtf[j] = c2LP * gain * (wbgtf[j - 1] + wbgtfl[j - 1]) + c1LP * wbgtfl[j]; } // frequency shift back up. const double out = std::real(CompExp(-wbphase) * wbgtf[order]); for (int i = 0; i <= order; i++) { wbgtfl[i] = wbgtf[i]; } return out; } // Calculates the gain and group delay for the Control path Filter. double GainGroupDelay(double tdres, double centerfreq, double cf, double tau, int *grdelay) { const double tmpcos = std::cos(kTwoPi * (centerfreq - cf) * tdres); const double dtmp2 = tau * 2.0 / tdres; const double c1LP = (dtmp2 - 1) / (dtmp2 + 1); const double c2LP = 1.0 / (dtmp2 + 1); const double tmp1 = 1 + c1LP * c1LP - 2 * c1LP * tmpcos; const double tmp2 = 2 * c2LP * c2LP * (1 + tmpcos); const double wb_gain = std::pow(tmp1 / tmp2, 1.0 / 2.0); grdelay[0] = static_cast<int>( std::floor((0.5 - (c1LP * c1LP - c1LP * tmpcos) / (1 + c1LP * c1LP - 2 * c1LP * tmpcos)))); return wb_gain; } // Calculates the delay (basilar membrane, synapse, etc. for cat). double DelayCat(double cf) { constexpr double A0 = 3.0; constexpr double A1 = 12.5; const double x = 11.9 * std::log10(0.80 + cf / 456.0); // cat mapping. const double delay = A0 * std::exp(-x / A1) * 1E-3; return delay; } // Calculates the delay (basilar membrane, synapse, etc.) for human, based // on Harte et al. (JASA 2009). #if 0 // Unused in this version of the model. double DelayHuman(double cf) { constexpr double A = -0.37; constexpr double B = 11.09 / 2; const double delay = B * std::pow(cf * 1E-3, A) * 1E-3; return delay; } #endif // 0 // Gets the output of the OHC Nonlinear Function (Boltzman Function). // // The output is normalized to maximum value of 1. The "asym" is the ratio of // positive Max to negative Max. double Boltzman(double x, double asym, double s0, double s1, double x1) { const double shift = 1.0 / (1.0 + asym); const double x0 = s0 * std::log((1.0 / shift - 1) / (1 + std::exp(x1 / s1))); const double out1 = 1.0 / (1.0 + std::exp(-(x - x0) / s0) * (1.0 + std::exp(-(x - x1) / s1))) - shift; const double out = out1 / (1 - shift); return out; } // Gets the output of the OHC Low Pass Filter in the Control path. // // NOTE: This function is thread unsafe. double OhcLowPass(double x, double tdres, double Fc, int n, double gain, int order) { static double ohc[4], ohcl[4]; if (n == 0) { for (int i = 0; i < (order + 1); i++) { ohc[i] = 0; ohcl[i] = 0; } } const double c = 2.0 / tdres; const double c1LP = (c - kTwoPi * Fc) / (c + kTwoPi * Fc); const double c2LP = kTwoPi * Fc / (kTwoPi * Fc + c); ohc[0] = x * gain; for (int i = 0; i < order; i++) { ohc[i + 1] = c1LP * ohcl[i + 1] + c2LP * (ohc[i] + ohcl[i]); } for (int j = 0; j <= order; j++) ohcl[j] = ohc[j]; return ohc[order]; } // Gets the output of the IHC Low Pass Filter. // // NOTE: This function is thread unsafe. double IhcLowPass(double x, double tdres, double Fc, int n, double gain, int order) { static double ihc[8], ihcl[8]; if (n == 0) { for (int i = 0; i < (order + 1); i++) { ihc[i] = 0; ihcl[i] = 0; } } const double C = 2.0 / tdres; const double c1LP = (C - kTwoPi * Fc) / (C + kTwoPi * Fc); const double c2LP = kTwoPi * Fc / (kTwoPi * Fc + C); ihc[0] = x * gain; for (int i = 0; i < order; i++) { ihc[i + 1] = c1LP * ihcl[i + 1] + c2LP * (ihc[i] + ihcl[i]); } for (int j = 0; j <= order; j++) { ihcl[j] = ihc[j]; } return ihc[order]; } // Gets the output of the Control path using Nonlinear Function after OHC. double NLAfterOhc(double x, double taumin, double taumax, double asym) { double minR = 0.05; const double R = taumin / taumax; if (R < minR) minR = 0.5 * R; const double dc = (asym - 1) / (asym + 1.0) / 2.0 - minR; const double R1 = R - minR; /* This is for new nonlinearity */ const double s0 = -dc / std::log(R1 / (1 - minR)); const double x1 = std::fabs(x); double out = taumax * (minR + (1.0 - minR) * std::exp(-x1 / s0)); if (out < taumin) out = taumin; if (out > taumax) out = taumax; return out; } // Gets the output of the IHC Nonlinear Function (Logarithmic Transduction // Functions). double NLogarithm(double x, double slope, double asym, double cf) { constexpr double corner = 80; const double strength = 20.0E6 / std::pow(10, corner / 20); double xx = std::log(1.0 + strength * std::fabs(x)) * slope; if (x < 0) { const double splx = 20 * std::log10(-x / 20E-6); const double asym_t = asym - (asym - 1) / (1 + std::exp(splx / 5.0)); xx = -1 / asym_t * xx; } return xx; } void IhcModel(const Eigen::ArrayXd &px, double cf, int nrep, double tdres, int totalstim, double cohc, double cihc, Species species, Eigen::RowArrayXd *ihcout) { // Allocate dynamic memory for the temporary variables. std::vector<double> ihcouttmp(totalstim * nrep, 0.0), mey1(totalstim, 0.0), // middle ear mey2(totalstim, 0.0), // middle ear mey3(totalstim, 0.0), // middle ear tmpgain(totalstim, 0.0); // Calculate the center frequency for the control-path wideband filter from // the location on basilar membrane, based on Greenwood (JASA 1990). double bmplace, centerfreq; if (species == SPECIES_CAT) { // Cat frequency shift corresponding to 1.2 mm. // Compute location on basilar membrane using CF. bmplace = 11.9 * std::log10(0.80 + cf / 456.0); // Shift the center frequency. centerfreq = 456.0 * (std::pow(10, (bmplace + 1.2) / 11.9) - 0.80); } else { // Human. // Human frequency shift corresponding to 1.2 mm. // Compute location on basilar membrane using CF. bmplace = (35 / 2.1) * std::log10(1.0 + cf / 165.4); // Shift the center frequency. centerfreq = 165.4 * (std::pow(10, (bmplace + 1.2) / (35 / 2.1)) - 1.0); } // ====== Parameters for the gain ===========. double gain = 52.0 / 2.0 * (std::tanh(2.2 * std::log10(cf / 0.6e3) + 0.15) + 1.0); if (gain > 60.0) gain = 60.0; if (gain < 15.0) gain = 15.0; // ====== Parameters for the control-path wideband filter ======= constexpr int bmorder = 3; double Taumin[1], Taumax[1]; GetTauWb(cf, species, bmorder, Taumax, Taumin); // ====== Parameters for the signal-path C1 filter ====== double bmTaumin[1], bmTaumax[1], ratiobm[1]; GetTauBm(cf, Taumax[0], bmTaumax, bmTaumin, ratiobm); const double bmTaubm = cohc * (bmTaumax[0] - bmTaumin[0]) + bmTaumin[0]; // ====== Parameters for the control-path wideband filter ======= constexpr int wborder = 3; const double TauWBMax = Taumin[0] + 0.2 * (Taumax[0] - Taumin[0]); const double TauWBMin = TauWBMax / Taumax[0] * Taumin[0]; double tauwb = TauWBMax + (bmTaubm - bmTaumax[0]) * (TauWBMax - TauWBMin) / (bmTaumax[0] - bmTaumin[0]); int grdelay[1]; double wbgain = GainGroupDelay(tdres, centerfreq, cf, tauwb, grdelay); tmpgain[0] = wbgain; double lasttmpgain = wbgain; // Nonlinear asymmetry of OHC function and IHC C1 transduction function. constexpr double ohcasym = 7.0; constexpr double ihcasym = 3.0; // Prewarping and related constants for the middle ear. constexpr double fp = 1E3; // Prewarping frequency 1 kHz. const double C = kTwoPi * fp / std::tan(kTwoPi / 2 * fp * tdres); double m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36; double megainmax; // max middle-ear gain. if (species == SPECIES_CAT) { // Cat middle-ear filter - simplified version from Bruce et al. (JASA 2003). m11 = C / (C + 693.48); m12 = (693.48 - C) / C; m13 = 0.0; m14 = 1.0; m15 = -1.0; m16 = 0.0; m21 = 1 / (std::pow(C, 2) + 11053 * C + 1.163e8); m22 = -2 * std::pow(C, 2) + 2.326e8; m23 = std::pow(C, 2) - 11053 * C + 1.163e8; m24 = std::pow(C, 2) + 1356.3 * C + 7.4417e8; m25 = -2 * std::pow(C, 2) + 14.8834e8; m26 = std::pow(C, 2) - 1356.3 * C + 7.4417e8; m31 = 1 / (std::pow(C, 2) + 4620 * C + 909059944); m32 = -2 * std::pow(C, 2) + 2 * 909059944; m33 = std::pow(C, 2) - 4620 * C + 909059944; m34 = 5.7585e5 * C + 7.1665e7; m35 = 14.333e7; m36 = 7.1665e7 - 5.7585e5 * C; megainmax = 41.1405; } else { // Human. // Human middle-ear filter - based on Pascal et al. (JASA 1998). m11 = 1 / (std::pow(C, 2) + 5.9761e3 * C + 2.5255e7); m12 = (-2 * std::pow(C, 2) + 2 * 2.5255e7); m13 = (std::pow(C, 2) - 5.9761e3 * C + 2.5255e7); m14 = (std::pow(C, 2) + 5.6665e3 * C); m15 = -2 * std::pow(C, 2); m16 = (std::pow(C, 2) - 5.6665e3 * C); m21 = 1 / (std::pow(C, 2) + 6.4255e3 * C + 1.3975e8); m22 = (-2 * std::pow(C, 2) + 2 * 1.3975e8); m23 = (std::pow(C, 2) - 6.4255e3 * C + 1.3975e8); m24 = (std::pow(C, 2) + 5.8934e3 * C + 1.7926e8); m25 = (-2 * std::pow(C, 2) + 2 * 1.7926e8); m26 = (std::pow(C, 2) - 5.8934e3 * C + 1.7926e8); m31 = 1 / (std::pow(C, 2) + 2.4891e4 * C + 1.2700e9); m32 = (-2 * std::pow(C, 2) + 2 * 1.2700e9); m33 = (std::pow(C, 2) - 2.4891e4 * C + 1.2700e9); m34 = (3.1137e3 * C + 6.9768e8); m35 = 2 * 6.9768e8; m36 = (-3.1137e3 * C + 6.9768e8); megainmax = 2; } double meout; for (int n = 0; n < totalstim; n++) { if (n == 0) { // Start of the middle-ear filtering section. mey1[0] = m11 * px[0]; if (species != SPECIES_CAT) mey1[0] = m11 * m14 * px[0]; mey2[0] = mey1[0] * m24 * m21; mey3[0] = mey2[0] * m34 * m31; meout = mey3[0] / megainmax; } else if (n == 1) { mey1[1] = m11 * (-m12 * mey1[0] + px[1] - px[0]); if (species != SPECIES_CAT) { mey1[1] = m11 * (-m12 * mey1[0] + m14 * px[1] + m15 * px[0]); } mey2[1] = m21 * (-m22 * mey2[0] + m24 * mey1[1] + m25 * mey1[0]); mey3[1] = m31 * (-m32 * mey3[0] + m34 * mey2[1] + m35 * mey2[0]); meout = mey3[1] / megainmax; } else { mey1[n] = m11 * (-m12 * mey1[n - 1] + px[n] - px[n - 1]); if (species != SPECIES_CAT) { mey1[n] = m11 * (-m12 * mey1[n - 1] - m13 * mey1[n - 2] + m14 * px[n] + m15 * px[n - 1] + m16 * px[n - 2]); } mey2[n] = m21 * (-m22 * mey2[n - 1] - m23 * mey2[n - 2] + m24 * mey1[n] + m25 * mey1[n - 1] + m26 * mey1[n - 2]); mey3[n] = m31 * (-m32 * mey3[n - 1] - m33 * mey3[n - 2] + m34 * mey2[n] + m35 * mey2[n - 1] + m36 * mey2[n - 2]); meout = mey3[n] / megainmax; } // ==================== // Control-path filter. // ==================== const double wbout1 = WbGammaTone(meout, tdres, centerfreq, n, tauwb, wbgain, wborder); const double wbout = std::pow((tauwb / TauWBMax), wborder) * wbout1 * 10e3 * std::max(1.0, cf / 5e3); // Pass the control signal through OHC Nonlinear Function. const double ohcnonlinout = Boltzman(wbout, ohcasym, 12.0, 5.0, 5.0); // Lowpass filtering after the OHC nonlinearity. const double ohcout = OhcLowPass(ohcnonlinout, tdres, 600, n, 1.0, 2); // Nonlinear function after OHC low-pass filter. const double tmptauc1 = NLAfterOhc(ohcout, bmTaumin[0], bmTaumax[0], ohcasym); // Time-constant for the signal-path C1 filter. const double tauc1 = cohc * (tmptauc1 - bmTaumin[0]) + bmTaumin[0]; // Shift of the location of poles of the C1 filter from the initial // positions. const double rsigma = 1.0 / tauc1 - 1.0 / bmTaumax[0]; if (1.0 / tauc1 < 0.0) { GOOGLE_LOG(FATAL) << "The poles are in the right-half plane; " << "system is unstable."; } tauwb = TauWBMax + (tauc1 - bmTaumax[0]) * (TauWBMax - TauWBMin) / (bmTaumax[0] - bmTaumin[0]); const double wb_gain = GainGroupDelay(tdres, centerfreq, cf, tauwb, grdelay); const int grd = grdelay[0]; if ((grd + n) < totalstim) tmpgain[grd + n] = wb_gain; if (tmpgain[n] == 0) tmpgain[n] = lasttmpgain; wbgain = tmpgain[n]; lasttmpgain = wbgain; // ====== Signal-path C1 filter ======. const double c1filterouttmp = C1ChirpFilt(meout, tdres, cf, n, bmTaumax[0], rsigma); // ====== Parallel-path C2 filter ======. const double c2filterouttmp = C2ChirpFilt(meout, tdres, cf, n, bmTaumax[0], 1.0 / ratiobm[0]); // === Run the inner hair cell (IHC) section: NL function and then // perform lowpass filtering === const double c1vihctmp = NLogarithm(cihc * c1filterouttmp, 0.1, ihcasym, cf); const double c2vihctmp = -NLogarithm( c2filterouttmp * std::fabs(c2filterouttmp) * cf / 10.0 * cf / 2e3, 0.2, 1.0, cf); // C2 transduction output. ihcouttmp[n] = IhcLowPass(c1vihctmp + c2vihctmp, tdres, 3000, n, 1.0, 7); } // Stretch out the IHC output according to nrep (number of repetitions). for (int i = 0; i < totalstim * nrep; i++) { ihcouttmp[i] = ihcouttmp[static_cast<int>(std::fmod(i, totalstim))]; } // Adjust total path delay to IHC output signal. const double delay = DelayCat(cf); // Human parameters not used in v5.2. const int delaypoint = std::max(0, static_cast<int>(std::ceil(delay / tdres))); for (int i = delaypoint; i < totalstim * nrep; i++) { (*ihcout)(i) = ihcouttmp[i - delaypoint]; } } } // namespace Zilany2014IhcModel::Zilany2014IhcModel() : AuditoryModel(MODEL_ZILANY_IHC_2014, STAGE_HAIR_CELLS, OUTPUT_IHC_TRANSMEMBRANE_POTENTIAL, true /* waveform input */) {} namespace { // Default number of cochlear channels. constexpr int kDefaultNumChannels = 251; // Outer Hair Cell (OHC) impairment coefficient. Should be between 0 // (degenerate) and 1 (normal). constexpr double kOhcImpairment = 1.0; // Normal. // Inner Hair Cell (IHC) impairment coefficient. Should be between 0 // (degenerate) and 1 (normal). constexpr double kIhcImpairment = 1.0; // Normal. // Minimum characteristic frequency in Hz (human). constexpr double kCharFrequencyMin = 25.0; // Maximum characteristic frequency in Hz (human). constexpr double kCharFrequencyMax = 20E+3; } // namespace void Zilany2014IhcModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); int num_channels = stimulus_config.num_channels(); if (num_channels <= 0) { // Use defaults. num_channels = kDefaultNumChannels; } mutable_stimulus_config()->set_num_channels(num_channels); // Compute linearly spaced characteristic frequencies. auto &cf_channels = channel_properties_.center_frequencies; cf_channels = erb::GetFrequenciesHz( num_channels, kCharFrequencyMin, kCharFrequencyMax); } ChannelProperties Zilany2014IhcModel::GetChannelProperties() const { return channel_properties_; } void Zilany2014IhcModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { // Estimate the IHC transmembrane voltages (aka membrane potentials). const auto &cf_channels = channel_properties_.center_frequencies; const int sample_rate = stimulus_config().sample_rate(); GOOGLE_CHECK_LE(100E3, sample_rate) << "Sample rate lower than lower bound: " << sample_rate; GOOGLE_CHECK_GE(500E3, sample_rate) << "Sample rate higher than upper bound: " << sample_rate; const Eigen::ArrayXd &signal = input.row(0); const int64_t num_samples = input.cols(); const int num_channels = stimulus_config().num_channels(); *output = Eigen::ArrayXXd::Zero(num_channels, num_samples); Eigen::RowArrayXd ihc_voltages(num_samples); for (int i = 0; i < num_channels; ++i) { IhcModel(signal, cf_channels[i], // characteristic frequency 1, // number of repetitions 1.0 / sample_rate, signal.size(), kOhcImpairment, kIhcImpairment, SPECIES_HUMAN_SHERA, &ihc_voltages); output->row(i).swap(ihc_voltages); } } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
29,118
C++
.cc
715
35.953846
80
0.576714
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,088
meddis1986_hair_cell_synapse_model.cc
google_eidos-audition/third_party/audition/models/amt/meddis1986_hair_cell_synapse_model.cc
// Copyright 1998 Malcolm Slaney (Interval Research Corporation) // Copyright 2016 Piotr Majdak // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. #include "third_party/audition/models/amt/meddis1986_hair_cell_synapse_model.h" #include <cmath> #include <vector> #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { // TODO(agutkin): Can be implemented more efficiently using Eigen matrix // operations. void Meddis1986HairCellSynapse(const Eigen::Ref<const Eigen::ArrayXXd> &input, int sample_rate, bool subtract_spontaneous_rate, Eigen::ArrayXXd *output) { GOOGLE_CHECK_LT(0, sample_rate); // Parameters from the original Meddis' papers (see the list references in the // header file). Some are rescaled by the sample rate. constexpr double A = 5.0; // Permeability equation. constexpr double B = 300.0; // Permeability equation. constexpr double M = 1.0; // Maximum number of free packets in transmitter // pool. const double g = 2000.0; // Release rate. const double y = 5.05; // Replenishment rate. const double l = 2500.0; // Rate of loss from the cleft. const double r = 6580.0; // Rate of return from the cleft. const double x = 66.31; // Rate of release from reprocessing // to free transmitter. // This parameter scales the discharge rate. Adjust as necessary. // In combination with the gammatone filterbank (ERBFilterBank), // h=50000 will produce a steady-state average discharge // probability of about 135 spikes/s within the 1kHz channel, // for an input consisting of a 1 kHz sinewave at 60 dB SPL // (0 dB SPL corresponds to an RMS level of 1.0 at the // input of the gammatone filter). constexpr double h = 50000.0; // Variable parameters: // - The hair cell contains a quantity of the "free transmitter", q(t), which // leaks through a permeable membrane into a synaptic cleft. // - The permeability, k(t), fluctuates as a function of the instantaneous // amplitude of the acoustic stimulation s(t). // - The synaptic cleft contains a fluctuating amount of transmitter // substance c(t). An amount rc(t)dt is continuously returned to the hair // cell and another amount lc(t)dt is continuously being lost. // // Compute initial estimates corresponding to spantaneous rate state. The // spontaneous firing rate is determined from the equilbrium state of the // system with no input: the reservoir contents do not change in time. const int num_channels = input.rows(); const double spont_kt = g * A / (A + B); // spont. k(t) const double spont_cleft = M * y * spont_kt / (l * spont_kt + y * (l + r)); const double spont_free_pool = spont_cleft * (l + r) / spont_kt; const double spont_reprocess = spont_cleft * r / x; std::vector<double> ct(num_channels), qt(num_channels), wt(num_channels); for (int i = 0; i < num_channels; ++i) { ct[i] = spont_cleft; qt[i] = spont_free_pool; wt[i] = spont_reprocess; } // Process the input signal. const int num_samples = input.cols(); *output = Eigen::ArrayXXd::Zero(num_channels, num_samples); const double dt = 1.0 / sample_rate; const double gdt = g * dt; const double ydt = y * dt; const double ldt = l * dt; const double rdt = r * dt; const double xdt = x * dt; for (int i = 0; i < num_channels; ++i) { for (int j = 0; j < num_samples; ++j) { const double st = std::max(input(i, j) + A, 0.0); // s(t) const double kdt = gdt * st / (st + B); const double replenish = std::max(ydt * (M - qt[i]), 0.0); const double eject = kdt * qt[i]; const double loss = ldt * ct[i]; const double reuptake = rdt * ct[i]; const double reprocess = xdt * wt[i]; qt[i] = std::max(qt[i] + replenish - eject + reprocess, 0.0); ct[i] = std::max(ct[i] + eject - loss - reuptake, 0.0); wt[i] = std::max(wt[i] + reuptake - reprocess, 0.0); // Note: The DSAM implementation produces "probability estimate" by using // "h * dt" instead of plain "h" here. (*output)(i, j) = ct[i] * h; if (subtract_spontaneous_rate) { (*output)(i, j) = std::max((*output)(i, j) - spont_cleft, 0.0); } } } } Meddis1986HairCellSynapseModel::Meddis1986HairCellSynapseModel() : AuditoryModel(MODEL_MEDDIS_SYNAPSE_1986, STAGE_AUDITORY_NERVE_SYNAPSE, OUTPUT_SYNAPSE_FIRING_RATES, false /* waveform input */) {} void Meddis1986HairCellSynapseModel::Init( const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); } ChannelProperties Meddis1986HairCellSynapseModel::GetChannelProperties() const { const AuditoryModel *prev_model = previous_model(); GOOGLE_CHECK(prev_model != nullptr); return prev_model->GetChannelProperties();; } void Meddis1986HairCellSynapseModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { const int sample_rate = stimulus_config().sample_rate(); GOOGLE_CHECK_LT(0, sample_rate); Meddis1986HairCellSynapse(input, sample_rate, false /* subtract_spontaneous_rate */, output); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
5,858
C++
.cc
124
42.508065
80
0.675354
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,089
baumgarte_model.cc
google_eidos-audition/third_party/audition/models/baumgarte/baumgarte_model.cc
// Copyright 1999,2000 Frank Baumgarte // Copyright 2019 Google LLC // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. #include "third_party/audition/models/baumgarte/baumgarte_model.h" #include <cstdint> #include <cmath> #include <utility> #include <vector> #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // Minimum allowed sample rate in Hz. constexpr int kMinSampleRate = 100000; // Maximum allowed number of model sections. constexpr int kDefaultMaxSections = 252; // Number of laterally coupled sections in one direction. constexpr int kMaxLatCoupledSections = 8; // Highest critical band rate covered by model. constexpr double kMaxBark = 25.0; // Model resolution in critical bands. constexpr double kDeltaZ = 0.1; // Write every kDownsample value to the output. Should be a positive // number. By default no downsampling is performed. constexpr int kDownsample = 1; // \pi constexpr double kPi = 3.14159265358979323846; // \pi * 2 constexpr double kPi2 = 6.283185307179586; // \pi / 2 constexpr double kHalfPi = 1.5707963267948966; // Global impedance scaling (for matching to the cochlea input impedance). constexpr double kRScale = 0.0635; // Default reference frequency for WDFs [Hz]. constexpr double kDefRefWdfFreq = 1000.0; // Default reference resistance for WDFs [Ohm]. constexpr double kDefRefWdfRes = 1000.0; // Amplification used in the linear model. constexpr double kVV = 100.0; // Reference voltage: 0.1 mV. constexpr double kVoltageAmplNorm = 0.0001; // Audio signal is input at the outer ear or at the oval window. enum InputSelection { kOvalWindow, kOuterEar }; // Characteristics of non-linearity. enum NonLinearityCharacteristics { kLinear, // No compression. kNonLinear1 // Nonlinear compression of OHC feedback. }; struct InputEarParameters { explicit InputEarParameters(int max_sections) : f_res(max_sections) {} InputEarParameters() = delete; std::vector<double> f_res; int n_sect = -1; bool feedback = false; NonLinearityCharacteristics nonlin = kNonLinear1; bool coupling = false; int channel = 0; InputSelection inp_sel = kOvalWindow; int down_sample = kDownsample; }; // Structures for hardware model element values. struct HardwareModelValues { explicit HardwareModelValues(int max_sections) : c(max_sections), l(max_sections), g(max_sections), q(max_sections), ce(max_sections), le(max_sections), ge(max_sections) {} HardwareModelValues() = delete; double c_q_nu = 0.0, r_q_nu = 0.0; double r_hel = 0.0, c_hel = 0.0; double r_i = 0.0, z = 0.0; // g = 1/r, ce - second amplification stage. std::vector<double> c, l, g, q, ce, le, ge; }; // Structures for WDF resistances of ear model. struct MiddleEarResistances { double gv1, gv2, gv3, gv4, rv5, rv6, rv7, rv8, gv9, gv10, gc2; }; struct InnerEarResistances { explicit InnerEarResistances(int max_sections) : rzt(max_sections), g2(max_sections), g4(max_sections), g5(max_sections), rL(max_sections), rc(max_sections), r8(max_sections), r9(max_sections), r1(max_sections), re2(max_sections), re3(max_sections), re1(max_sections) {} InnerEarResistances() = delete; std::vector<double> rzt, g2, g4, g5, rL, rc, r8, r9, r1; double rh1 = 0.0, gh2 = 0.0, gh3 = 0.0; std::vector<double> re2, re3, re1; }; struct WdfResistances { explicit WdfResistances(int max_sections) : iear(max_sections) {} WdfResistances() = delete; MiddleEarResistances mear = {}; // Initialize to defaults. InnerEarResistances iear; }; // Whole hardware model. struct HardwareModel { explicit HardwareModel(int max_sections) : values(max_sections), wdf_res(max_sections) {} HardwareModel() = delete; // Can be reset after computing WDF coefficients. HardwareModelValues values; WdfResistances wdf_res; }; // Lateral coupling values. // // Notes: // - "g" is same as in HardwareModelValues. // - "rzt" is the same as in InnerEarResistances. struct CouplingValues { explicit CouplingValues(int max_sections) : g_l(max_sections), g_k(max_sections), g(max_sections), r(max_sections), rzt(max_sections), r_grp(max_sections), g_par(max_sections) { for (auto &coupling : g_l) { coupling.resize(kMaxLatCoupledSections); } } CouplingValues() = delete; std::vector<std::vector<double>> g_l; std::vector<double> g_k, g, r, rzt, r_grp, g_par; }; struct MiddleEarCoefficients { double yv2, yv4, yv5, yv6, yv9, yv10; }; struct InnerEarCoefficients { explicit InnerEarCoefficients(int max_sections) : y1(max_sections), y4(max_sections), y7(max_sections), y8(max_sections), ye1(max_sections), ye2(max_sections) {} InnerEarCoefficients() = delete; std::vector<double> y1, y4, y7, y8, ye1, ye2; double yh1 = 0.0, yh3 = 0.0; }; struct WdfCoefficients { WdfCoefficients(int max_sections) : iear(max_sections) {} WdfCoefficients() = delete; MiddleEarCoefficients mear = {}; // Initialize to defaults. InnerEarCoefficients iear; }; // Structure for the whole model and analysis containing all coefficients for // the signal computation. struct Model { explicit Model(int max_sections) : coupl_val(max_sections), wdf_coef(max_sections) {} Model() = delete; CouplingValues coupl_val; WdfCoefficients wdf_coef; }; // WDF model signals. struct Waves { explicit Waves(int max_sections) : b6(max_sections), a5(max_sections), a7(max_sections), b9(max_sections), b2(max_sections), a6(max_sections), b7(max_sections), u(max_sections), ae1(max_sections), be3(max_sections), be2(max_sections), u_ihc(max_sections), a8(max_sections) {} Waves() = delete; std::vector<double> b6, a5, a7, b9, b2; std::vector<double> a6, b7, u, ae1, be3, be2, u_ihc, a8; double bh2 = 0.0, bh1 = 0.0, av1 = 0.0, bv1 = 0.0, bv2 = 0.0, av3 = 0.0, bv3 = 0.0, bv5 = 0.0, bv6 = 0.0, av8 = 0.0, bv8 = 0.0, av10 = 0.0, bv10 = 0.0; }; struct VoltagesAndCurrents { VoltagesAndCurrents(int max_sections) : u_bm(max_sections), u_ihc(max_sections) {} VoltagesAndCurrents() = delete; std::vector<double> u_bm, u_ihc; double u_of = 0.0, i_of = 0.0; double u_tr = 0.0, i_tr = 0.0; }; struct InputSignalParameters { double sample_freq = 0.0; }; // Master structure holding all the parameters and state. struct EarConfigAndState { explicit EarConfigAndState(int max_sections) : hwm(max_sections), model(max_sections), inp_ear_par(max_sections) {} EarConfigAndState() = delete; HardwareModel hwm; Model model; InputSignalParameters inp_sig_par = {}; // Initialize to defaults. InputEarParameters inp_ear_par; }; void InitDefaults(const StimulusConfig &stimulus_config, int native_downsample_step, EarConfigAndState *model) { auto *ear_param = &model->inp_ear_par; // Signal input at outer ear. ear_param->inp_sel = kOuterEar; // Number of cochlear model sections. // The original implementation sets this to <kMaxBark / kDeltaZ + 1>. const int max_recommended_channels = static_cast<int>(kMaxBark / kDeltaZ + 1); const int num_channels = stimulus_config.num_channels(); if (num_channels > max_recommended_channels) { GOOGLE_LOG(WARNING) << "Number of requested channels (" << num_channels << ") exceeds number of recommended channels (" << max_recommended_channels << ")"; } ear_param->n_sect = num_channels; // Active model with OHC gain. ear_param->feedback = true; // Nonlinear compression of OHC feedback. ear_param->nonlin = kNonLinear1; // Coupling of neighbouring sections. ear_param->coupling = true; // Number of input audio channel (0: 1st channel). ear_param->channel = 0; // Temporal downsampling factor applied before writing output samples // (refers to input sample rate). ear_param->down_sample = native_downsample_step; // Input sample rate. const int sample_rate = stimulus_config.sample_rate(); if (sample_rate < kMinSampleRate) { GOOGLE_LOG(WARNING) << "Sample rate of " << sample_rate << " Hz is too low. Upsample to " << kMinSampleRate << " for sane results"; } model->inp_sig_par.sample_freq = stimulus_config.sample_rate(); } // Computes values of Zwicker's analog model (inner ear). void InitHardwareModelValues(InputEarParameters *params, HardwareModelValues *values) { const int n_sect = params->n_sect; auto &f_res = params->f_res; GOOGLE_CHECK_LT(n_sect, f_res.size()) << "Maximum number of sections exceeded!"; f_res[1] = 5.0 * kDeltaZ / 0.1; f_res[2] = 10.0 * kDeltaZ / 0.1; for (int nu = 3; nu <= n_sect; ++nu) { f_res[nu] = f_res[nu - 1] + kDeltaZ * (25.0 + 75.0 * std::pow(1.0 + 1.4E-6 * (f_res[nu - 1] * f_res[nu - 1]), 0.69)); } values->c_q_nu = 12.5E-9 * kDeltaZ / 0.1; values->r_q_nu = 1.0E6 * kDeltaZ / 0.1; auto &c = values->c; auto &l = values->l; auto &q = values->q; auto &g = values->g; auto &ce = values->ce; auto &le = values->le; auto &ge = values->ge; for (int nu = 1; nu <= n_sect; ++nu) { const double z = nu * kDeltaZ; c[nu] = (255.0E-9 + 335.0E-9 * z / 24.0) * kDeltaZ / 0.1; l[nu] = 1.0 / (c[nu] * kPi2 * kPi2 * f_res[nu] * f_res[nu]); if (z <= 4.0) { q[nu] = 1.0 + 0.5 * z; } if ((z > 4.0) && (z <= 8.0)) { q[nu] = 2.0 + 0.25 * z; } if ((z > 8.0) && (z <= 16.0)) { q[nu] = 3.0 + 0.125 * z; } if (z > 16) { q[nu] = 5.0; } g[nu] = 1.0 / (q[nu] * std::sqrt(l[nu] / c[nu])); ce[nu] = c[nu]; // IHC - filter. le[nu] = 1.0 / (ce[nu] * kPi2 * kPi2 * 0.9 * 0.9 * f_res[nu] * f_res[nu]); ge[nu] = 1.0 / (q[nu] * std::sqrt(le[nu] / ce[nu])); } values->r_hel = 281.1E3; values->c_hel = 56.6E-9; values->r_i = 274.0; } // Computes resistors for the lateral coupling of sections (inner ear). void InitResistorsForLateral(HardwareModelValues *values, InputEarParameters *params, CouplingValues *c_val) { auto &g_k = c_val->g_k; auto &g_l = c_val->g_l; auto &r_grp = c_val->r_grp; auto &g_par = c_val->g_par; auto &rzt = c_val->rzt; auto &g = c_val->g; auto &r = c_val->r; const int n_sect = params->n_sect; const double f_coupl = 1.0 / (1.55 * 148.5); for (int nu = 1; nu <= n_sect; ++nu) { r[nu] = 1.0 / g[nu]; g_k[nu] = f_coupl * g[nu]; g_k[nu] *= 0.97; const double z = nu * kDeltaZ; if (z < 4.5) { g_k[nu] *= (1.0 + (4.5 - z) * 0.16); } if ((z > 10.0) && (z < 17)) { g_k[nu] *= (1.0 + (z - 10.0) * 0.023); } if ((z >= 17.0) && (z < 20)) { g_k[nu] *= (1.0 + (z - 10.0) * 0.023 + (z - 17.0) * 0.04); } if (z >= 20) { g_k[nu] *= (1.0 + (z - 10.0) * 0.023 + (z - 17.0) * 0.04 + (z - 20.0) * 0.06); } for (int mu = 1; mu <= kMaxLatCoupledSections; mu++) { g_l[nu][mu - 1] = g_k[nu] * std::exp(-kHalfPi * mu * mu * kDeltaZ * kDeltaZ * 6.25); } double tmp = 0.0; for (int mu = std::min(kMaxLatCoupledSections, nu - 1); mu > 0; mu--) { tmp += g_l[nu][mu - 1]; } for (int mu = std::min(params->n_sect - nu, kMaxLatCoupledSections); mu > 0; mu--) { tmp += g_l[nu][mu - 1]; } r_grp[nu] = 1.0 / (1.0 + rzt[nu] * (g[nu] + g_k[nu] + tmp)); g_par[nu] = g_k[nu] + tmp; } } // Computes WDF resistances for outer/middle ear model. void InitWdfResistancesMiddleEar(double s_freq, WdfResistances *wdf_resist) { const double omega_tmp = kPi * kDefRefWdfFreq / s_freq; const double tmp = -kPi2 * kDefRefWdfFreq * std::tan(omega_tmp - kHalfPi); auto &mear = wdf_resist->mear; mear.gv1 = kDefRefWdfRes / (100000.0 * kRScale); // Source resistance mear.gv2 = kDefRefWdfRes / (tmp * 0.05 * kRScale); // L1 mear.gv4 = kDefRefWdfRes / (200.0 * kRScale); // R1 mear.gv3 = mear.gv1 + mear.gv2 + mear.gv4; mear.rv5 = kRScale / (tmp * 100E-9 * kDefRefWdfRes); // C2 mear.rv6 = (tmp * 0.02815 * kRScale) / kDefRefWdfRes; // L2 mear.rv7 = (100.0 * kRScale) / kDefRefWdfRes; // R2 mear.rv8 = mear.rv5 + mear.rv6 + mear.rv7; mear.gv9 = kDefRefWdfRes / (500.0 * kRScale); // R3 mear.gv10 = 1.0 / mear.rv8 + mear.gv9; mear.gc2 = 1.0 / (1.0 / mear.gv3 + 1.0 / mear.gv10); } // Computes WDF resistances for cochlear model (inner ear). // // The cot(x) below refers to cotangent of x: // cot(x) = 1 / tan(x) = cos(x) / sin(x). // Since // cos(x) = sin(pi/2 - x), sin(x) = cos(pi/2 - x) and tan(-x) = -tan(x), // the above equation can be rewritten as // cot(x) = sin(pi/2 - x) / cos(pi/2 - x) = tan(pi/2 - x) = -tan(x - pi/2). void InitWdfResistancesInnerEar(double s_freq, HardwareModelValues *values, InputEarParameters *params, WdfResistances *wdf_resist) { const auto &f_res = params->f_res; const auto &l = values->l; const auto &c = values->c; const auto &ce = values->ce; const auto &le = values->le; const auto &ge = values->ge; const auto &c_q_nu = values->c_q_nu; const auto &r_q_nu = values->r_q_nu; const double omega_tmp = kPi / s_freq; const int n_sect = params->n_sect; auto &i_e = wdf_resist->iear; i_e.r1[n_sect] = 1.0 / wdf_resist->mear.gc2; for (int nu = n_sect; nu > 0; nu--) { const double tmp1 = -kPi2 * f_res[nu] * std::tan(omega_tmp * f_res[nu] - kHalfPi); // cot(x)=-tan(x-pi/2) i_e.g2[nu] = tmp1 * c_q_nu * kDefRefWdfRes; i_e.g4[nu] = kDefRefWdfRes / r_q_nu; i_e.g5[nu] = 1.0 / i_e.r1[nu] + i_e.g2[nu] + i_e.g4[nu]; i_e.rL[nu] = tmp1 * l[nu] / kDefRefWdfRes; i_e.rc[nu] = 1.0 / (tmp1 * c[nu] * kDefRefWdfRes); i_e.r8[nu] = i_e.rL[nu] * i_e.rc[nu] / (i_e.rL[nu] + i_e.rc[nu]); i_e.r9[nu] = i_e.r8[nu] * i_e.rL[nu] / i_e.rc[nu]; i_e.r1[nu - 1] = 1.0 / i_e.g5[nu] + i_e.r8[nu]; i_e.rzt[nu] = kDefRefWdfRes * i_e.r8[nu]; i_e.re2[nu] = 1.0 / (tmp1 * ce[nu] * kDefRefWdfRes); i_e.re3[nu] = tmp1 * le[nu] / kDefRefWdfRes; i_e.re1[nu] = 1.0 / (ge[nu] * kDefRefWdfRes); } const double tmp1 = -kPi2 * f_res[1] * std::tan(omega_tmp * f_res[1] - kHalfPi); // cot(x)=-tan(x-pi/2) wdf_resist->iear.rh1 = i_e.r1[0]; wdf_resist->iear.gh2 = tmp1 * values->c_hel * kDefRefWdfRes; wdf_resist->iear.gh3 = kDefRefWdfRes / values->r_hel; } // Computes WDF coefficients. void InitWdfCoefficients(InputEarParameters *params, WdfResistances *wdf_resist, WdfCoefficients *wdf_coef) { const auto &m_e = wdf_resist->mear; auto &m_c = wdf_coef->mear; m_c.yv2 = m_e.gv2 / m_e.gv3; m_c.yv4 = m_e.gv4 / m_e.gv3; m_c.yv5 = m_e.rv5 / m_e.rv8; m_c.yv6 = m_e.rv6 / m_e.rv8; m_c.yv9 = m_e.gv9 / m_e.gv10; m_c.yv10 = m_e.gc2 / m_e.gv10; auto &i_c = wdf_coef->iear; const auto &i_e = wdf_resist->iear; const int n_sect = params->n_sect; for (int nu = 1; nu <= n_sect; ++nu) { i_c.y1[nu] = 1.0 / (i_e.r1[nu] * i_e.g5[nu]); i_c.y4[nu] = i_e.g4[nu] / i_e.g5[nu]; i_c.y7[nu] = i_e.r8[nu] / i_e.r1[nu - 1]; i_c.y8[nu] = (i_e.r8[nu] - i_e.r9[nu]) / (i_e.r8[nu] + i_e.r9[nu]); const double g_tmp = 1.0 / i_e.re2[nu] + 1.0 / i_e.re3[nu] + 1.0 / i_e.re1[nu]; i_c.ye1[nu] = 2.0 / (g_tmp * i_e.re1[nu]); i_c.ye2[nu] = 2.0 / (g_tmp * i_e.re2[nu]); } i_c.yh1 = 2.0 / (i_e.rh1 * (1.0 / i_e.rh1 + i_e.gh2 + i_e.gh3)); i_c.yh3 = 2.0 * i_e.gh3 / (1.0 / i_e.rh1 + i_e.gh2 + i_e.gh3); } // Initializes all the model coefficients. void InitModel(EarConfigAndState *ear_model) { auto &inp_sig_par = ear_model->inp_sig_par; auto &params = ear_model->inp_ear_par; auto &model = ear_model->model; const double s_freq = inp_sig_par.sample_freq; auto &hwm = ear_model->hwm; auto &hwm_val = hwm.values; auto &wdf_res = hwm.wdf_res; InitHardwareModelValues(&params, &hwm_val); InitWdfResistancesMiddleEar(s_freq, &wdf_res); InitWdfResistancesInnerEar(s_freq, &hwm_val, &params, &wdf_res); auto &coupl_val = model.coupl_val; coupl_val.rzt = wdf_res.iear.rzt; coupl_val.g = hwm_val.g; auto &wdf_coef = model.wdf_coef; InitResistorsForLateral(&hwm_val, &params, &coupl_val); InitWdfCoefficients(&params, &wdf_res, &wdf_coef); } // Implements the WDF algorithm which processes an input audio signal and // calculates the excitation signals for the inner hair cells along the basilar // membrane. void ComputeIHCExcitationWaves(const InputEarParameters &params, const WdfCoefficients &wdf_coef, const CouplingValues &coupl_val, double u_ms, Waves *wn, Waves *wo) { // ======================================================= // Compute nonlinear function (for lateral coupling only): // ======================================================= const int n_sect = params.n_sect; std::vector<double> u_nl_vec(n_sect + 1); int nu; if (params.feedback) { switch (params.nonlin) { case kLinear: { // no nonlinearity for (nu = 1; nu <= n_sect; ++nu) { u_nl_vec[nu] = kVV * wo->u[nu]; } break; } case kNonLinear1: { // nonlinearity of middle ear if (u_ms < 0) { u_ms *= 0.99; } for (nu = 1; nu <= n_sect; ++nu) { // nonlinearity of OHC const double tmp = wo->u[nu]; u_nl_vec[nu] = 100 * (tmp / std::sqrt(1.0 + 20.0 * std::fabs(tmp) + 10.0 * tmp * tmp)); } break; } default: { GOOGLE_LOG(FATAL) << "ERROR: unknown nonlinear characteristic"; } } } // Forward propagating waves. const auto &mc = wdf_coef.mear; if (params.inp_sel != kOvalWindow) { // outer ear input wn->av1 = u_ms * 600.0; wn->av3 = wn->av1 - mc.yv4 * wn->av1 - mc.yv2 * (wn->av1 + wo->bv2); wn->av8 = wo->bv6 - wo->bv5; wn->av10 = wn->av8 - mc.yv9 * wn->av8; wn->b6[n_sect] = -wn->av10 - wn->av3; } else { wn->b6[n_sect] = u_ms; // input at oval window } const auto &ic = wdf_coef.iear; for (nu = n_sect; nu > 0; nu--) { wn->a5[nu] = -(1.0 - ic.y1[nu] - ic.y4[nu]) * wo->b2[nu] - ic.y1[nu] * wn->b6[nu]; wn->a7[nu] = -wo->b9[nu] - ic.y8[nu] * (wo->a8[nu] + wo->b9[nu]); wn->b9[nu] = wn->a7[nu] + wo->a8[nu] + wo->b9[nu]; wn->b6[nu - 1] = -wn->a5[nu] - wn->a7[nu]; } wn->bh2 = (1.0 - ic.yh3) * wo->bh2 - ic.yh1 * (wo->bh2 - wn->b6[0]); // Backward propagating waves. wn->a6[0] = wn->bh1 = wn->bh2 + wo->bh2 - wn->b6[0]; const auto &le = coupl_val; const auto &g = coupl_val.g; const auto &g_par = coupl_val.g_par; const auto &r_grp = coupl_val.r_grp; if (!params.feedback) { // ============== // Passive model: // ============== for (nu = 1; nu <= n_sect; ++nu) { wn->b7[nu] = wn->a7[nu] - ic.y7[nu] * (wn->a6[nu - 1] - wn->b6[nu - 1]); wn->u[nu] = wn->b7[nu] / (1.0 + le.rzt[nu] * g[nu]); wn->u_ihc[nu] = wn->u[nu]; wn->a8[nu] = wn->u[nu] + wn->u[nu] - wn->b7[nu]; wn->b2[nu] = wn->a6[nu - 1] + wn->b7[nu] - wn->a5[nu] - wo->b2[nu]; wn->a6[nu] = wn->b2[nu] + wo->b2[nu] - wn->b6[nu]; } } else { if (!params.coupling) { // ========================================= // Nonlinear model without lateral coupling: // ========================================= for (nu = 1; nu <= n_sect; ++nu) { wn->b7[nu] = wn->a7[nu] - ic.y7[nu] * (wn->a6[nu - 1] - wn->b6[nu - 1]); wn->u[nu] = (wn->b7[nu] + le.rzt[nu] * le.g_k[nu] * u_nl_vec[nu]) / (1.0 + le.rzt[nu] * (g[nu] + le.g_k[nu])); wn->u_ihc[nu] = wn->u[nu]; wn->a8[nu] = wn->u[nu] + wn->u[nu] - wn->b7[nu]; wn->b2[nu] = wn->a6[nu - 1] + wn->b7[nu] - wn->a5[nu] - wo->b2[nu]; wn->a6[nu] = wn->b2[nu] + wo->b2[nu] - wn->b6[nu]; } } else { // ====================================== // Nonlinear model with lateral coupling: // ====================================== for (nu = 1; nu <= n_sect; ++nu) { wn->b7[nu] = wn->a7[nu] - ic.y7[nu] * (wn->a6[nu - 1] - wn->b6[nu - 1]); double sum_1 = u_nl_vec[nu] * le.g_k[nu]; for (int mu = std::min(kMaxLatCoupledSections, nu - 1); mu > 0; mu--) { sum_1 += u_nl_vec[nu - mu] * le.g_l[nu][mu - 1]; } for (int mu = std::min(params.n_sect - nu, kMaxLatCoupledSections); mu > 0; mu--) { sum_1 += u_nl_vec[nu + mu] * le.g_l[nu][mu - 1]; } double tmp = sum_1; sum_1 *= le.rzt[nu]; sum_1 += wn->b7[nu]; wn->u[nu] = sum_1 * r_grp[nu]; // Second amplification stage. wn->ae1[nu] = 20 * (tmp - wn->u[nu] * g_par[nu]) * le.r[nu]; tmp = wo->be3[nu] + wo->be2[nu]; wn->be3[nu] = ic.ye1[nu] * (wo->be3[nu] + wn->ae1[nu]) + ic.ye2[nu] * tmp - wo->be3[nu]; wn->be2[nu] = wn->be3[nu] - tmp; wn->u_ihc[nu] = wn->u[nu] + 0.5 * (wn->be2[nu] + wo->be2[nu]); wn->a8[nu] = wn->u[nu] + wn->u[nu] - wn->b7[nu]; wn->b2[nu] = wn->a6[nu - 1] + wn->b7[nu] - wn->a5[nu] - wo->b2[nu]; wn->a6[nu] = wn->b2[nu] + wo->b2[nu] - wn->b6[nu]; } } } if (params.inp_sel != kOvalWindow) { wn->bv10 = wn->av10 - mc.yv10 * (wn->a6[n_sect] - wn->b6[n_sect]); wn->bv3 = -wn->bv10 - wn->a6[n_sect]; wn->bv8 = wn->bv10 - mc.yv9 * wn->av8; wn->bv5 = wo->bv5 - mc.yv5 * (wn->bv8 - wn->av8); wn->bv6 = -wo->bv6 - mc.yv6 * (wn->bv8 - wn->av8); wn->bv1 = wn->bv3 - mc.yv4 * wn->av1 - mc.yv2 * (wn->av1 + wo->bv2); wn->bv2 = wn->bv1 + wn->av1 + wo->bv2; } } // Transforms wave quantities of the WDF into electrical voltages or currents // of the electrical prototype filter. void TransformWavesToVoltagesAndCurrents(const InputEarParameters &params, const Waves &wn, const Waves &wo, VoltagesAndCurrents *ui) { const int n_sect = params.n_sect; for (int nu = 1; nu <= n_sect; ++nu) { ui->u_bm[nu] = 0.5 * (wn.a7[nu] + wn.b7[nu]); ui->u_ihc[nu] = wn.u_ihc[nu]; } } } // namespace // This class hides the gory details involving nested structs that need to be // parametrized by the number of cochlear sections. struct BaumgarteHandle { BaumgarteHandle(int max_sections) : model(max_sections) {} BaumgarteHandle() = delete; EarConfigAndState model; }; BaumgarteModel::BaumgarteModel() : AuditoryModel(MODEL_BAUMGARTE, STAGE_HAIR_CELLS, OUTPUT_IHC_TRANSMEMBRANE_POTENTIAL, true /* waveform input */) {} BaumgarteModel::~BaumgarteModel() = default; void BaumgarteModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); // Figure out the number of cochlear partitions. int max_sections = stimulus_config.num_channels(); if (max_sections == 0) { // Use defaults. max_sections = kDefaultMaxSections; } else { max_sections++; } impl_.reset(new BaumgarteHandle(max_sections)); mutable_stimulus_config()->set_num_channels(max_sections - 1); // Initialize the model. InitDefaults(this->stimulus_config(), native_downsample_step_, &impl_->model); InitModel(&impl_->model); // Compute CF information. auto &center_frequencies = channel_properties_.center_frequencies; const int num_channels = impl_->model.inp_ear_par.n_sect; center_frequencies.reserve(num_channels); for (int i = 1; i <= num_channels; ++i) { center_frequencies.emplace_back(impl_->model.inp_ear_par.f_res[i]); } } ChannelProperties BaumgarteModel::GetChannelProperties() const { return channel_properties_; } void BaumgarteModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { GOOGLE_CHECK(impl_ != nullptr); auto &impl = impl_->model; const auto &params = impl.inp_ear_par; const auto &model = impl.model; const auto &wdf_coef = model.wdf_coef; const auto &coupl_val = model.coupl_val; const int num_channels = stimulus_config().num_channels(); const int max_sections = num_channels + 1; VoltagesAndCurrents ui(max_sections); Waves w_new(max_sections), w_old(max_sections); const int down_sample = params.down_sample; int down_sample_count = down_sample - 1; const int64_t num_samples = input.cols(); const int64_t num_output_samples = std::ceil(static_cast<double>(num_samples) / down_sample); *output = Eigen::ArrayXXd::Zero(num_channels, num_output_samples); for (int64_t i = 0, n = 0; i < num_samples; ++i) { const double u_inp = kVoltageAmplNorm * input(0, i); ComputeIHCExcitationWaves(params, wdf_coef, coupl_val, u_inp, &w_new, &w_old); down_sample_count++; if (down_sample_count == down_sample) { TransformWavesToVoltagesAndCurrents(params, w_new, w_old, &ui); for (int j = 1; j <= params.n_sect; ++j) { (*output)(j - 1, n) = ui.u_ihc[j]; } down_sample_count = 0; n++; } std::swap(w_old, w_new); } } } // namespace audition } // namespace eidos
25,605
C++
.cc
643
34.695179
80
0.592986
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,090
sumner2002_hair_cell_synapse_model.cc
google_eidos-audition/third_party/audition/models/dsam/sumner2002_hair_cell_synapse_model.cc
// Copyright 2000, 2010 Lowel P. O'Mard // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. #include "third_party/audition/models/dsam/sumner2002_hair_cell_synapse_model.h" #include <float.h> #include <cmath> #include <random> #include <vector> #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { struct ChannelVars { double act_ca; // Activation of calcium channels. double conc_ca; // Concentration of calcium at the synapse. double reservoir_Q; // Quantity of transmitter in the free pool. double cleft_C; // Quantity of transmitter in the cleft. double reprocessed_W; // Quantity of transm. in the reproc. store. }; struct UniformRandom { UniformRandom() : rnd_gen(rnd_seed()), dist() {} std::random_device rnd_seed{}; // Random number seed. std::mt19937 rnd_gen; // Standard Mersenne Twister engine. std::uniform_real_distribution<double> dist{}; }; // Following parameters correspond to the HSR population of the fibres // as published in Table II of the Sumner, et. al. (2002) paper (p. 2183). // Maximum sample period (sampling interval) the model can hendle (sec). constexpr double kMaxSamplePeriod = 0.00005; // Calcium reversal potential, E_Ca (Volts). constexpr double kCaVRev = 0.066; // Calcium channel Boltzmann function parameter, beta. constexpr double kBetaCa = 400.0; // Calcium channel Boltzmann function parameter, gamma. constexpr double kGammaCa = 130.0; // Calcium channel transmitter release exponent (power). constexpr double kPCa = 3.0; // Transmitter release permeability, Z (unitless gain). constexpr double kPerm_z = 2e+32; // Calcium current time constant (sec). constexpr double kTauCaChan = 1e-4; // Calcium ion diffusion (accumulation) time constant (sec). constexpr double kTauConcCa = 1e-4; // Replenishment rate (units per second). constexpr double kReplenishRate_y = 10.0; // Loss rate (units per second). constexpr double kLossRate_l = 2580.0; // Reprocessing rate (units per second). constexpr double kReprocessRate_x = 66.31; // Recovery rate (units per second). constexpr double kRecoveryRate_r = 6580.0; // HSR population-specific parameters. namespace hsr { // Maximum calcium conductance (Siemens). constexpr double kGCaMax = 8e-09; // Calcium threshold concentration. constexpr double kPermCa0 = 4.48e-11; // Max. no. of transmitter packets in free pool. constexpr int kMaxFreePool_M = 10; } // namespace hsr // Checks whether the sample period <dt> is good enough for the model. void CheckSamplePeriod(double dt) { GOOGLE_CHECK_LE(dt, kMaxSamplePeriod) << "Maximum sample period exceeded"; GOOGLE_CHECK_GT(1.0, kReplenishRate_y * dt) << "Replenishment rate is too high for the sampling interval"; GOOGLE_CHECK_GT(1.0, kLossRate_l * dt) << "Loss rate is too high for the sampling interval"; GOOGLE_CHECK_GT(1.0, kReprocessRate_x * dt) << "Reprocessing rate is too high for the sampling interval"; GOOGLE_CHECK_GT(1.0, kRecoveryRate_r * dt) << "Recovery rate is too high for the sampling interval"; GOOGLE_CHECK_GT(1.0, dt / kTauCaChan) << "Calcium current time is too high for the sampling interval"; GOOGLE_CHECK_GT(1.0, dt / kTauConcCa) << "Calcium ion diffusion is too high for the sampling interval"; } // Lifted from DSAM. Note: This is different from std:: implementation which // counts the number of *failures* before the first success. // // This routine calculates the number of times that an event occurs with a set // probability <prob> and number of trials <num_trials>. It uses the geometric // distribution method, but the probability must be small. int GeomDistRandom(double prob, int num_trials, UniformRandom *u_random) { if ((num_trials <= 0) || (prob < DBL_EPSILON)) { return 0; } const double log_failure = std::log(1.0 - prob); int i; double sum; for (i = 0, sum = 0.0; ; ++i) { const double u_val = u_random->dist(u_random->rnd_gen); sum += (std::log(u_val) / log_failure); if (sum >= num_trials) break; } if (i > num_trials) i = num_trials; return i; } // Checks the configurations and sets the default model parameters if required. void CheckAndInitDefaults(Sumner2002HairCellSynapseConfig *config) { if (config->g_ca_max() <= 0.0) { config->set_g_ca_max(hsr::kGCaMax); } if (config->perm_ca_0() <= 0.0) { config->set_perm_ca_0(hsr::kPermCa0); } if (config->max_free_pool_m() <= 0.0) { config->set_max_free_pool_m(hsr::kMaxFreePool_M); } } } // namespace void Sumner2002HairCellSynapse( const Sumner2002HairCellSynapseConfig &config, const Eigen::Ref<const Eigen::ArrayXXd> &input, int sample_rate, Eigen::ArrayXXd *output) { // Sanity checks. GOOGLE_CHECK_LT(0.0, sample_rate); const double dt = 1.0 / sample_rate; CheckSamplePeriod(dt); // Fetch configurable parameters. const double ca_cond_mode = config.ca_cond_mode(); const double cleft_replenish_mode = config.cleft_replenish_mode(); const bool output_spikes = config.output_spikes(); const double g_ca_max = config.g_ca_max(); const double perm_ca0 = config.perm_ca_0(); const int max_free_pool_m = config.max_free_pool_m(); // --------------------------------------------------------------------------- // Initialization. // --------------------------------------------------------------------------- // Steady state calcium activation. double ssact_ca = 1.0 / (1.0 + std::exp(-kGammaCa * input(0, 0)) / kBetaCa); // Calcium conductance (*not* current). double i_ca = g_ca_max * std::pow(ssact_ca, 3) * (input(0, 0) - kCaVRev); if (ca_cond_mode == SUMNER2002_CA_COND_MODE_REVISED) i_ca *= kTauConcCa; double spont_perm_k0 = 0.0; if (-i_ca > perm_ca0) { spont_perm_k0 = kPerm_z * (std::pow(-i_ca, kPCa) - std::pow(perm_ca0, kPCa)); } double spont_cleft_c0 = kReplenishRate_y / kLossRate_l; if (cleft_replenish_mode == SUMNER2002_CLEFT_REPLENISH_MODE_ORIGINAL) { spont_cleft_c0 = max_free_pool_m * kReplenishRate_y * spont_perm_k0 / (kReplenishRate_y * (kLossRate_l + kRecoveryRate_r) + spont_perm_k0 * kLossRate_l); } double spont_free_pool_q0; if (spont_cleft_c0 > 0.0) { if (!output_spikes) { // Probabilities. spont_free_pool_q0 = spont_cleft_c0 * (kLossRate_l + kRecoveryRate_r) / spont_perm_k0; } else { // Spikes. spont_free_pool_q0 = std::floor((spont_cleft_c0 * ( kLossRate_l + kRecoveryRate_r) / spont_perm_k0) + 0.5); } } else { spont_free_pool_q0 = max_free_pool_m; } const double spont_reprocess_w0 = spont_cleft_c0 * kRecoveryRate_r / kReprocessRate_x; const int num_channels = input.rows(); std::vector<ChannelVars> channel_vars(num_channels); for (int i = 0; i < num_channels; ++i) { channel_vars[i].act_ca = ssact_ca; channel_vars[i].conc_ca = -i_ca; channel_vars[i].reservoir_Q = spont_free_pool_q0; channel_vars[i].cleft_C = spont_cleft_c0; channel_vars[i].reprocessed_W = spont_reprocess_w0; } // --------------------------------------------------------------------------- // Produce the estimates given the input. // --------------------------------------------------------------------------- const int num_samples = input.cols(); *output = Eigen::ArrayXXd::Zero(num_channels, num_samples); const double ydt = kReplenishRate_y * dt; const double rdt = kRecoveryRate_r * dt; const double xdt = kReprocessRate_x * dt; const double zdt = kPerm_z * dt; const double k0_pow = std::pow(perm_ca0, kPCa); const double l_plus_rdt = (kLossRate_l + kRecoveryRate_r) * dt; const double dt_over_tauConcCa = dt / kTauConcCa; const double dt_over_tauCaChan = dt / kTauCaChan; UniformRandom u_random; // Uniform random number generator. for (int i = 0; i < num_channels; ++i) { for (int j = 0; j < num_samples; ++j) { // ------------------------------------------------ // Calcium controlled transmitter release function. // ------------------------------------------------ const double v_in = input(i, j); // Calcium current. double &act_ca = channel_vars[i].act_ca; ssact_ca = 1.0 / (1.0 + std::exp(-kGammaCa * v_in) / kBetaCa); act_ca += (ssact_ca - act_ca) * dt_over_tauCaChan; i_ca = g_ca_max * std::pow(act_ca, 3) * (v_in - kCaVRev); // Calcium ion accumulation and diffusion. double &conc_ca = channel_vars[i].conc_ca; if (ca_cond_mode == SUMNER2002_CA_COND_MODE_ORIGINAL) { conc_ca += (-i_ca - conc_ca) * dt_over_tauConcCa; } else { // Note: In DSAM, for this particular branch an output-specific, rather // than input-specific, sample period is used. conc_ca += (-i_ca - conc_ca / kTauConcCa) * dt; } // Power law release function. double kdt = 0.0; if (conc_ca > perm_ca0) { kdt = zdt * (std::pow(conc_ca, kPCa) - k0_pow); } // -------- // Synapse. // -------- if (output_spikes) { // Spike mode. double replenish = 0.0; if (cleft_replenish_mode == SUMNER2002_CLEFT_REPLENISH_MODE_UNITY) { replenish = GeomDistRandom(ydt, 1, &u_random); } else { // SUMNER2002_CLEFT_REPLENISH_MODE_ORIGINAL if (channel_vars[i].reservoir_Q < max_free_pool_m) { replenish = GeomDistRandom( ydt, static_cast<int>( max_free_pool_m - channel_vars[i].reservoir_Q), &u_random); } } const double reuptake_and_lost = l_plus_rdt * channel_vars[i].cleft_C; const double reuptake = rdt * channel_vars[i].cleft_C; double reprocessed = 0.0; if (channel_vars[i].reprocessed_W >= 1.0) { reprocessed = GeomDistRandom(xdt, static_cast<int>(std::floor( channel_vars[i].reprocessed_W)), &u_random); } const double ejected = GeomDistRandom( kdt, static_cast<int>(channel_vars[i].reservoir_Q), &u_random); channel_vars[i].reservoir_Q += (replenish - ejected + reprocessed); channel_vars[i].cleft_C += (ejected - reuptake_and_lost); channel_vars[i].reprocessed_W += (reuptake - reprocessed); if (ejected > 0.0) { (*output)(i, j) = ejected; } } else { // Probability mode. double replenish = 0.0; if (cleft_replenish_mode == SUMNER2002_CLEFT_REPLENISH_MODE_UNITY) { replenish = ydt; } else { if (channel_vars[i].reservoir_Q < max_free_pool_m) { replenish = ydt * (max_free_pool_m - channel_vars[i].reservoir_Q); } } const double ejected = kdt * channel_vars[i].reservoir_Q; const double reuptake_and_lost = l_plus_rdt * channel_vars[i].cleft_C; const double reuptake = rdt * channel_vars[i].cleft_C; const double reprocessed = xdt * channel_vars[i].reprocessed_W; channel_vars[i].reservoir_Q += (replenish - ejected + reprocessed); channel_vars[i].cleft_C += (ejected - reuptake_and_lost); channel_vars[i].reprocessed_W += (reuptake - reprocessed); (*output)(i, j) = ejected; } } } } Sumner2002HairCellSynapseModel::Sumner2002HairCellSynapseModel( const Sumner2002HairCellSynapseConfig &config) : AuditoryModel(MODEL_SUMNER_SYNAPSE_2002, STAGE_AUDITORY_NERVE_SYNAPSE, OUTPUT_SYNAPSE_FIRING_RATES, false /* waveform input */), config_(config) { CheckAndInitDefaults(&config_); } void Sumner2002HairCellSynapseModel::Init( const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); } ChannelProperties Sumner2002HairCellSynapseModel::GetChannelProperties() const { const AuditoryModel *prev_model = previous_model(); GOOGLE_CHECK(prev_model != nullptr); return prev_model->GetChannelProperties();; } void Sumner2002HairCellSynapseModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { const int sample_rate = stimulus_config().sample_rate(); GOOGLE_CHECK_LT(0, sample_rate); Sumner2002HairCellSynapse(config_, input, sample_rate, output); } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
12,737
C++
.cc
293
38.774744
81
0.652732
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,091
gammatone_filterbank_model.cc
google_eidos-audition/third_party/audition/models/gammatone/gammatone_filterbank_model.cc
// Copyright 1998 Malcolm Slaney (Interval Research Corporation) // Copyright 2006 Ning Ma // Copyright 2015 Jo√£o Felipe Santos // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. #include "third_party/audition/models/gammatone/gammatone_filterbank_model.h" #include <cstdint> #include <cmath> #include <complex> #include <tuple> #include <vector> #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/audition/psychoacoustic_scale_utils.h" #include "eidos/port/logging.h" namespace eidos { namespace audition { namespace { // ERB parameters. Please see: // - B.C.J. Moore and B.R. Glasberg (1983), "Suggested formulae for // calculating auditory-filter bandwidths and excitation patterns", // J. Acoust. Soc. Am. 74: 750-753. // - B.R. Glasberg and B.C.J. Moore (1990), "Derivation of auditory filter // shapes from notched-noise data", Hearing Research, 47: 103-138. constexpr double const kEarQ = 9.26449; constexpr double const kMinBandwidth = 24.7; constexpr int const kOrder = 1; // ERB bandwidth correction for the 4th order filter. constexpr double kBandwidthCorrection = 1.019; // Number of filters in the filterbank (per-channel). const int kNumFilters = 4; // \pi constexpr double kPi = 3.14159265358979323846; // Very small number used for clipping the filter coefficients. constexpr double kTinyEpsilon = 1E-200; // Coefficients for a biquadratic digital IIR filter. // // This filter implements the transfer function: // // H(z) = (a0 + a1 z^-1 + a2 z^-2) / (1 + b1 z^-1 + b2 z^-2) // // See https://en.wikipedia.org/wiki/Digital_biquad_filter. class BiquadFilter { public: BiquadFilter() = default; ~BiquadFilter() = default; // Constructs from matrix representation. BiquadFilter(const Eigen::Matrix<double, 5, 1> &coeffs) { coeffs_ = std::make_tuple(coeffs[0], coeffs[1], coeffs[2], coeffs[3], coeffs[4]); } // Applies the filter to the input signal. Eigen::VectorXd Apply(const Eigen::VectorXd &x) { const int num_samples = x.size(); Eigen::VectorXd y(Eigen::VectorXd::Zero(num_samples)); double xi, yi, z0 = 0, z1 = 0; for (int i = 0; i < num_samples; ++i) { xi = x[i]; yi = std::get<0>(coeffs_) * xi + z0; z0 = std::get<1>(coeffs_) * xi - std::get<3>(coeffs_) * yi + z1; z1 = std::get<2>(coeffs_) * xi - std::get<4>(coeffs_) * yi; y[i] = yi; } return y; } private: // Coefficients: a0, a1, a2, b1, b2. std::tuple<double, double, double, double, double> coeffs_ = {}; }; // Computes an array of N frequencies uniformly spaced between high_freq and // low_freq on an ERB scale. // // See: // - Moore, B. C. J., and Glasberg, B. R. (1983). "Suggested formulae for // calculating auditory-filter bandwidths and excitation patterns", J. // Acoust. Soc. Am. 74, 750-753. // - M. Slaney (Apple TR #35), "An Efficient Implementation of the // Patterson-Holdsworth Cochlear Filter Bank.", 33-34. Eigen::VectorXd ERBSpaceSlaney(double low_freq, double high_freq, int num_channels) { Eigen::VectorXd cf_array(num_channels); constexpr double aux = kEarQ * kMinBandwidth; for (int i = 1; i <= num_channels; ++i) { cf_array[i - 1] = -aux + std::exp(i * (-std::log(high_freq + aux) + std::log(low_freq + aux)) / num_channels) * (high_freq + aux); } return cf_array; } // Original comments from Malcom Slaney's Matlab implementation: // // This function computes the filter coefficients for a bank of Gammatone // filters. These filters were defined by Patterson and Holdworth for // simulating the cochlea. // // The result is returned as an array of filter coefficients. Each row // of the filter arrays contains the coefficients for four second order // filters. The transfer function for these four filters share the same // denominator (poles) but have different numerators (zeros). All of these // coefficients are assembled into one vector that the ERBFilterBank can take // apart to implement the filter. // // The filter bank contains "numChannels" channels that extend from half the // sampling rate to "low_freq". Alternatively, if the num_channels input // argument is a vector, then the values of this vector are taken to be the // center frequency of each desired filter. (The low_freq argument is ignored // in this case.) std::vector<std::vector<BiquadFilter>> MakeERBFiltersSlaney( const StimulusConfig &stimulus_config, ChannelProperties *channel_properties) { const double sample_rate = stimulus_config.sample_rate(); const double T = 1.0 / sample_rate; const double low_freq = stimulus_config.lowest_cf_hz(); const double high_freq = stimulus_config.highest_cf_hz(); const int num_channels = stimulus_config.num_channels(); const Eigen::VectorXd cf = ERBSpaceSlaney(low_freq, high_freq, num_channels); GOOGLE_CHECK_EQ(num_channels, cf.size()); auto &center_frequencies = channel_properties->center_frequencies; center_frequencies.resize(num_channels); Eigen::VectorXd::Map(&center_frequencies[0], num_channels) = cf; double A0 = T; double A2 = 0; Eigen::VectorXd B(num_channels); Eigen::VectorXd B1(num_channels); Eigen::VectorXd B2(num_channels); Eigen::VectorXd A11(num_channels); Eigen::VectorXd A12(num_channels); Eigen::VectorXd A13(num_channels); Eigen::VectorXd A14(num_channels); Eigen::VectorXd gain(num_channels); Eigen::VectorXd erb(num_channels); std::vector<std::vector<BiquadFilter>> filterbank(num_channels); const std::complex<double> i(0, 1); std::complex<double> aux1, aux2, aux3, aux4, aux5, aux6; for (int k = 0; k < num_channels; ++k) { const double f_cos = std::cos(2.0 * cf[k] * kPi * T); const double f_sin = std::sin(2.0 * cf[k] * kPi * T); const double sqrt_p = std::sqrt(3.0 + std::pow(2.0, 1.5)); const double sqrt_n = std::sqrt(3.0 - std::pow(2.0, 1.5)); const auto f_im1 = std::complex<double>(2) * i * cf[k] * kPi * T; const auto f_im2 = std::complex<double>(4) * i * cf[k] * kPi * T; const auto f_exp_im2 = std::exp(f_im2); erb[k] = std::pow( std::pow((cf[k] / kEarQ), kOrder) + std::pow(kMinBandwidth, kOrder), 1.0 / kOrder); B[k] = kBandwidthCorrection * 2 * kPi * erb[k]; const double exp_p = std::exp(B[k] * T); const auto f_exp_im1 = std::exp(-B[k] * T + f_im1); B1[k] = -2.0 * f_cos / exp_p; B2[k] = std::exp(-2.0 * B[k] * T); A11[k] = -(-B1[k] * T + 2.0 * sqrt_p * T * f_sin / exp_p) / 2.0; A12[k] = -(-B1[k] * T - 2.0 * sqrt_p * T * f_sin / exp_p) / 2.0; A13[k] = -(-B1[k] * T + 2.0 * sqrt_n * T * f_sin / exp_p) / 2.0; A14[k] = -(-B1[k] * T - 2.0 * sqrt_n * T * f_sin / exp_p) / 2.0; aux1 = std::complex<double>(-2) * f_exp_im2 * T; aux2 = std::complex<double>(2) * f_exp_im1 * T * (f_cos - sqrt_n * f_sin); aux3 = std::complex<double>(2) * f_exp_im1 * T * (f_cos + sqrt_n * f_sin); aux4 = std::complex<double>(2) * f_exp_im1 * T * (f_cos - sqrt_p * f_sin); aux5 = std::complex<double>(2) * f_exp_im1 * T * (f_cos + sqrt_p * f_sin); aux6 = std::pow(-2.0 / std::exp(2 * B[k] * T) - std::complex<double>(2) * f_exp_im2 + std::complex<double>(2) * (std::complex<double>(1) + f_exp_im2) / exp_p, 4); gain[k] = std::abs(std::abs((aux1 + aux2) * (aux1 + aux3) * (aux1 + aux4) * (aux1 + aux5) / aux6)); Eigen::Matrix<double, 5, 1> coeffs1, coeffs2, coeffs3, coeffs4; coeffs1 << A0 * (1.0 / gain[k]), A11[k] * (1.0 / gain[k]), A2 * (1.0 / gain[k]), B1[k], B2[k]; coeffs2 << A0, A12[k], A2, B1[k], B2[k]; coeffs3 << A0, A13[k], A2, B1[k], B2[k]; coeffs4 << A0, A14[k], A2, B1[k], B2[k]; std::vector<BiquadFilter> filters(kNumFilters); filters[0] = BiquadFilter(coeffs1); filters[1] = BiquadFilter(coeffs2); filters[2] = BiquadFilter(coeffs3); filters[3] = BiquadFilter(coeffs4); filterbank[k] = filters; } return filterbank; } // This gammatone filter is based on the implementation by Ning Ma from // University of Sheffield who, in turn, based his implementation on an // original algorithm from Martin Cooke's Ph.D thesis (Cooke, 1993) using // the base-band impulse invariant transformation. This implementation is // highly efficient in that a mathematical rearrangement is used to // significantly reduce the cost of computing complex exponentials. For // more detail on this implementation see // http://www.dcs.shef.ac.uk/~ning/resources/gammatone/ // // Note: Martin Cooke's PhD has been reprinted as M. Cooke (1993): "Modelling // Auditory Processing and Organisation", Cambridge University Press, Series // "Distinguished Dissertations in Computer Science", August. void GammatoneCookeAndMa(const StimulusConfig &stimulus_config, const Eigen::VectorXd &input, // Input signal. ChannelProperties *channel_properties, Eigen::ArrayXXd *output) { const int num_samples = input.size(); const int num_channels = stimulus_config.num_channels(); GOOGLE_CHECK_EQ(num_samples, output->cols()); // Samples. GOOGLE_CHECK_EQ(num_channels, output->rows()); // Channels. auto &center_frequencies = channel_properties->center_frequencies; center_frequencies.resize(num_channels); // Compute characteristic frequencies equally spaced on ERB scale using // the canonical procedure. const double low_erb = erb::HzToErbRate(stimulus_config.lowest_cf_hz()); const double high_erb = erb::HzToErbRate(stimulus_config.highest_cf_hz()); const double step_erb = (high_erb - low_erb) / (num_channels - 1); const int sample_rate = stimulus_config.sample_rate(); const double tpt = (2.0 * kPi) / sample_rate; for (int i = 0; i < num_channels; ++i) { // ================== // Set-up the filter: // ================== const double cf = erb::ErbRateToHz(low_erb + i * step_erb); center_frequencies[i] = cf; const double tptbw = tpt * erb::HzToErb(cf) * kBandwidthCorrection; const double a = std::exp(-tptbw); // Based on integral of impulse response. const double gain = (tptbw * tptbw * tptbw * tptbw) / 3.0; // Filter coefficients. const double a1 = 4.0 * a; const double a2 = -6.0 * a * a; const double a3 = 4.0 * a * a * a; const double a4 = -a * a * a * a; const double a5 = a * a; double p1r = 0.0, p2r = 0.0, p3r = 0.0, p4r = 0.0, p1i = 0.0, p2i = 0.0, p3i = 0.0, p4i = 0.0; // =========================================================== // exp(a+i*b) = exp(a)*(cos(b)+i*sin(b)) // q = exp(-i*tpt*cf*t) = cos(tpt*cf*t) + i*(-sin(tpt*cf*t)) // qcos = cos(tpt*cf*t) // qsin = -sin(tpt*cf*t) // =========================================================== const double coscf = std::cos(tpt * cf); const double sincf = std::sin(tpt * cf ); double qcos = 1, qsin = 0; /* t=0 & q = exp(-i*tpt*t*cf)*/ for (int j = 0; j < num_samples; ++j) { // Filter part 1 & shift down to d.c. double p0r = qcos * input(j) + a1 * p1r + a2 * p2r + a3 * p3r + a4 * p4r; if (p0r < kTinyEpsilon) p0r = 0.0; double p0i = qsin * input(j) + a1 * p1i + a2 * p2i + a3 * p3i + a4 * p4i; if (p0i < kTinyEpsilon) p0i = 0.0; // Filter part 2. const double u0r = p0r + a1 * p1r + a5 * p2r; const double u0i = p0i + a1 * p1i + a5 * p2i; // Update filter results. p4r = p3r; p3r = p2r; p2r = p1r; p1r = p0r; p4i = p3i; p3i = p2i; p2i = p1i; p1i = p0i; // Basilar membrane response // 1. Shift up in frequency first: // (u0r+i*u0i) * exp(i*tpt*cf*t) = (u0r+i*u0i) * // (qcos + i*(-qsin)) // 2. Take the real part only: // bm = real(exp(j*wcf*kT).*u) * gain. (*output)(i, j) = (u0r * qcos + u0i * qsin) * gain; // The basic idea of saving computational load: // cos(a+b) = cos(a)*cos(b) - sin(a)*sin(b) // sin(a+b) = sin(a)*cos(b) + cos(a)*sin(b) // qcos = cos(tpt*cf*t) = cos(tpt*cf + tpt*cf*(t-1)) // qsin = -sin(tpt*cf*t) = -sin(tpt*cf + tpt*cf*(t-1)) const double old_qcos = qcos; qcos = coscf * old_qcos + sincf * qsin; qsin = coscf * qsin - sincf * old_qcos; } } } } // namespace // Default number of processing channels. constexpr int GammatoneFilterbankModel::kDefaultNumChannels; // Minimal characteristic frequency (in Hz) for the analysis. constexpr double GammatoneFilterbankModel::kLowestCFrequency; // Highest characteristic frequency (in Hz) for the analysis. constexpr double GammatoneFilterbankModel::kHighestCFrequency; struct GammatoneHandle { int num_channels; std::vector<std::vector<BiquadFilter>> filterbank; }; GammatoneFilterbankModel::GammatoneFilterbankModel( const GammatoneFilterbankConfig &config) : AuditoryModel( MODEL_GAMMATONE_SLANEY, STAGE_BASILAR_MEMBRANE, OUTPUT_BASILAR_MEMBRANE_DISPLACEMENT, true /* waveform input */), config_(config) {} GammatoneFilterbankModel::~GammatoneFilterbankModel() = default; void GammatoneFilterbankModel::Init(const StimulusConfig &stimulus_config) { AuditoryModel::Init(stimulus_config); impl_.reset(new GammatoneHandle); // Check the stimulus configuration and update its parameters if these are not // set. int num_channels = stimulus_config.num_channels(); if (num_channels <= 0) { // Use defaults. num_channels = kDefaultNumChannels; } mutable_stimulus_config()->set_num_channels(num_channels); float lowest_cf_hz = stimulus_config.lowest_cf_hz(); if (lowest_cf_hz <= 0) { // Choose default. lowest_cf_hz = kLowestCFrequency; } mutable_stimulus_config()->set_lowest_cf_hz(lowest_cf_hz); GOOGLE_CHECK_LT(0, lowest_cf_hz); const GammatoneFilterbankType filter_type = config_.filter_type(); float highest_cf_hz = stimulus_config.highest_cf_hz(); if (highest_cf_hz <= 0) { // Choose default. const double sample_rate = stimulus_config.sample_rate(); GOOGLE_CHECK_LT(0, sample_rate); if (filter_type == GAMMATONE_FILTERBANK_SLANEY) { // In Slaney's implementation the filters extend from half the // sampling rate to "low_freq". highest_cf_hz = sample_rate / 2.0; } else { highest_cf_hz = kHighestCFrequency; } } mutable_stimulus_config()->set_highest_cf_hz(highest_cf_hz); GOOGLE_CHECK_LT(lowest_cf_hz, highest_cf_hz); // Filter-specific one-shot initialization. if (filter_type == GAMMATONE_FILTERBANK_SLANEY) { impl_->filterbank = MakeERBFiltersSlaney(this->stimulus_config(), &channel_properties_); GOOGLE_CHECK_EQ(num_channels, impl_->filterbank.size()); GOOGLE_CHECK_EQ(kNumFilters, impl_->filterbank[0].size()); } else if (config_.filter_type() != GAMMATONE_FILTERBANK_COOKE_AND_MA) { GOOGLE_LOG(FATAL) << "Only Slaney and Ma's filters are implemented."; } } ChannelProperties GammatoneFilterbankModel::GetChannelProperties() const { return channel_properties_; } void GammatoneFilterbankModel::ProcessSegment( const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) { GOOGLE_CHECK(impl_ != nullptr); // Apply filterbank. const int64_t num_samples = input.cols(); const int num_channels = stimulus_config().num_channels(); *output = Eigen::ArrayXXd::Zero(num_channels, num_samples); if (config_.filter_type() == GAMMATONE_FILTERBANK_SLANEY) { const Eigen::VectorXd &input_d = input.row(0).cast<double>(); for (int i = 0; i < num_channels; ++i) { const Eigen::VectorXd y1 = impl_->filterbank[i][0].Apply(input_d); const Eigen::VectorXd y2 = impl_->filterbank[i][1].Apply(y1); const Eigen::VectorXd y3 = impl_->filterbank[i][2].Apply(y2); const Eigen::VectorXd y4 = impl_->filterbank[i][3].Apply(y3); output->row(i) = y4; } } else { // Use Ma's implementation of Cooke's filter. GammatoneCookeAndMa(stimulus_config(), input.row(0), &channel_properties_, output); } } } // namespace audition } // namespace eidos // Local Variables: // mode: c++ // End:
16,690
C++
.cc
370
40.754054
80
0.649748
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,092
resample_test.cc
google_eidos-audition/build/resample_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple test for generic polyphase resampler. #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "resample.h" using ::testing::DoubleNear; using ::testing::Pointwise; namespace eidos { namespace { constexpr double kInputSignal[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 }; // The epsilon is quite large unfortunately. There may be a bug in the resample // library. constexpr double kEpsilon = 0.3; } // namespace TEST(ResampleTest, UpsampleTest) { constexpr int kUpFactor = 24; constexpr int kDownFactor = 13; std::vector<double> input; input.assign(kInputSignal, kInputSignal + 10); std::vector<double> output; resample(kUpFactor, kDownFactor, input, output); // Check against the reference output produced by the Octave resample // function from the signal package. EXPECT_EQ(19, output.size()); const std::vector<double> kRefOutput = { 1.0000, 1.7436, 2.0297, 2.4257, 3.2808, 3.9023, 4.0629, 4.6156, 5.6100, 6.0115, 6.0265, 6.8976, 8.0470, 7.9552, 7.7765, 9.5546, 11.1220, 8.2991, 2.2418 }; EXPECT_THAT(kRefOutput, Pointwise(DoubleNear(kEpsilon), output)); } TEST(ResampleTest, DecimateTest) { constexpr int kUpFactor = 1; constexpr int kDownFactor = 3; std::vector<double> input; input.assign(kInputSignal, kInputSignal + 10); std::vector<double> output; resample(kUpFactor, kDownFactor, input, output); // Check against the reference output produced by the Octave resample // function from the signal package. EXPECT_EQ(4, output.size()); const std::vector<double> kRefOutput = { 1.2429, 3.5969, 7.8041, 6.4141 }; EXPECT_THAT(kRefOutput, Pointwise(DoubleNear(kEpsilon), output)); } } // namespace eidos // Local Variables: // mode: c++ // End:
2,351
C++
.cc
61
36.360656
79
0.733743
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,093
carfac_test.cc
google_eidos-audition/build/carfac_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This is currently empty. #include "cpp/carfac.h" #include "cpp/agc.h" #include "cpp/car.h" #include "cpp/common.h" #include "cpp/ear.h" #include "cpp/ihc.h" #include "gtest/gtest.h" TEST(CarFacTest, DummyTest) {}
807
C++
.cc
22
35.5
75
0.755442
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,094
wave_test.cc
google_eidos-audition/build/wave_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Basic waveform I/O check. #include <vector> #include "absl/strings/str_cat.h" #include "gtest/gtest.h" #include "wave/error.h" #include "wave/file.h" namespace eidos { // Sample waveform. const char kWavePath[] = "build/testdata/Untitled3.wav"; // Sample rate. constexpr int kSampleRate = 44100; TEST(WaveTest, Trivial) { wave::File file; ASSERT_EQ(wave::kNoError, file.Open(kWavePath, wave::OpenMode::kIn)); EXPECT_EQ(file.sample_rate(), kSampleRate); EXPECT_EQ(file.bits_per_sample(), 16); EXPECT_EQ(file.channel_number(), 2); std::vector<float> contents; EXPECT_EQ(wave::kNoError, file.Read(&contents)); EXPECT_EQ(contents.size() / file.channel_number(), 5.558344671201814 * kSampleRate); } } // namespace eidos // Local Variables: // mode: c++ // End:
1,385
C++
.cc
39
33.538462
75
0.736527
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,095
eigen_test.cc
google_eidos-audition/build/eigen_test.cc
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple checks that Eigen behaves. #include "Eigen/Dense" #include "gtest/gtest.h" using Eigen::MatrixXd; using Eigen::VectorXd; namespace eidos { TEST(EigenTest, Trivial) { const MatrixXd m = MatrixXd::Identity(3, 3); EXPECT_EQ(3, m.rows()); EXPECT_EQ(3, m.cols()); EXPECT_EQ(1.0, m(0, 0)); EXPECT_EQ(1.0, m(1, 1)); EXPECT_EQ(1.0, m(2, 2)); VectorXd v(3); v << 1, 2, 3; EXPECT_EQ(1, v(0)); EXPECT_EQ(2, v(1)); EXPECT_EQ(3, v(2)); } TEST(EigenTest, CheckReverse) { MatrixXd m(3, 2); m << 1, 2, 3, 4, 5, 6; EXPECT_EQ(1, m(0, 0)); EXPECT_EQ(2, m(0, 1)); EXPECT_EQ(3, m(1, 0)); EXPECT_EQ(4, m(1, 1)); EXPECT_EQ(5, m(2, 0)); EXPECT_EQ(6, m(2, 1)); m.colwise().reverseInPlace(); EXPECT_EQ(5, m(0, 0)); EXPECT_EQ(6, m(0, 1)); EXPECT_EQ(3, m(1, 0)); EXPECT_EQ(4, m(1, 1)); EXPECT_EQ(1, m(2, 0)); EXPECT_EQ(2, m(2, 1)); } } // namespace eidos // Local Variables: // mode: c++ // End:
1,526
C++
.cc
53
26.660377
75
0.657338
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,536,096
proto_utils.h
google_eidos-audition/eidos/utils/proto_utils.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Utilities for manipulating the protos. #ifndef EIDOS_UTILS_PROTO_UTILS_H_ #define EIDOS_UTILS_PROTO_UTILS_H_ #include <string> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "eidos/port/status_macros.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" namespace eidos { namespace utils { // Reads contents of a file into a string buffer. If <binary_mode> is enabled, // opens the file in binary mode. absl::Status ReadFileContents(absl::string_view filepath, bool binary_mode, std::string *contents); // Writes contents to a file. If <binary_mode> is enabled the file is written // in binary format. absl::Status WriteFileContents(const std::string &contents, bool binary_mode, absl::string_view filepath); // Reads binary protocol buffer message of the supplied type from a given file // path. template <typename ProtoType> absl::Status ReadBinaryProto(absl::string_view filepath, ProtoType *message) { // TODO(agutkin): It may be more efficient to parse directly from // std::istream. std::string contents; RETURN_IF_ERROR(ReadFileContents(filepath, true /* binary_mode */, &contents)); if (!message->ParseFromString(contents)) { return absl::InternalError("Failed to parse binary proto"); } return absl::OkStatus(); } // Reads textual protocol buffer message of the supplied type from a given file // path. template <typename ProtoType> absl::Status ReadTextProto(absl::string_view filepath, ProtoType *message) { // TODO(agutkin): It may be more efficient to parse directly from // io::ZeroCopyInputStream rather than from a string buffer. std::string contents; RETURN_IF_ERROR(ReadFileContents(filepath, false /* binary_mode */, &contents)); using google::protobuf::TextFormat; if (!TextFormat::ParseFromString(contents, message)) { return absl::InternalError("Failed to parse text proto"); } return absl::OkStatus(); } // Writes proto to a given location in binary format. template <typename ProtoType> absl::Status WriteBinaryProto(const ProtoType &message, absl::string_view filepath) { std::string contents; if (!message.SerializeToString(&contents)) { return absl::InternalError("Binary serialization failed!"); } RETURN_IF_ERROR(WriteFileContents(contents, true /* binary mode */, filepath)); return absl::OkStatus(); } // Writes proto to a given location in text format. template <typename ProtoType> absl::Status WriteTextProto(const ProtoType &message, absl::string_view filepath) { using google::protobuf::TextFormat; std::string contents; if (!TextFormat::PrintToString(message, &contents)) { return absl::InternalError("Text serialization failed!"); } RETURN_IF_ERROR(WriteFileContents(contents, false /* binary mode */, filepath)); return absl::OkStatus(); } } // namespace utils } // namespace eidos #endif // EIDOS_UTILS_PROTO_UTILS_H_ // Local Variables: // mode: c++ // End:
3,594
C++
.h
86
39.127907
85
0.746709
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,097
logging.h
google_eidos-audition/eidos/port/logging.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Alias header for the Google logging stubs which are part of Google protobufs. // // See logging documentation here // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/port/logging.h #ifndef EIDOS_PORT_LOGGING_H_ #define EIDOS_PORT_LOGGING_H_ #include "google/protobuf/stubs/logging.h" #endif // EIDOS_PORT_LOGGING_H_ // Local Variables: // mode: c++ // End:
983
C++
.h
24
39.75
95
0.765199
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,098
map_util.h
google_eidos-audition/eidos/port/map_util.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Replacement for map utilities. #ifndef EIDOS_PORT_MAP_UTIL_H_ #define EIDOS_PORT_MAP_UTIL_H_ #include "google/protobuf/port/map_util.h" namespace eidos { using ::google::protobuf::ContainsKey; using ::google::protobuf::FindOrDie; using ::google::protobuf::FindOrNull; using ::google::protobuf::FindWithDefault; } // namespace eidos #endif // EIDOS_PORT_MAP_UTIL_H_ // Local Variables: // mode: c++ // End:
1,006
C++
.h
27
35.962963
75
0.759011
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,101
utils.h
google_eidos-audition/eidos/audition/utils.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef EIDOS_AUDITION_UTILS_H_ #define EIDOS_AUDITION_UTILS_H_ #include <string> #include <vector> #include "eidos/port/logging.h" namespace eidos { namespace audition { // Generates a vector of <n> uniformly distributed random real numbers in the // supplied range [min_val, max_val]. std::vector<double> GetRandomUniformVector(int n, double min_val, double max_val); // Generates a vector of <n> real numbers drawn from standard normal // distribution characterized by the supplied mean and standard deviation. std::vector<double> GetRandomNormalVector(int n, double mu, double sigma); // Checks that the value is within range. template <typename T> void CheckWithinRange(T value, T range_min, T range_max, const std::string &error_message_prefix) { if (value < range_min || value > range_max) { GOOGLE_LOG(FATAL) << error_message_prefix << " (value is " << value << " should be within [" << range_min << ", " << range_max << "] range"; } } } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_UTILS_H_ // Local Variables: // mode: c++ // End:
1,781
C++
.h
43
37.465116
80
0.696181
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,102
psychoacoustic_scale_utils.h
google_eidos-audition/eidos/audition/psychoacoustic_scale_utils.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Miscellaneous utility functions for various hearing critical bands inspired // by psychoacoustic research. #ifndef EIDOS_AUDITION_PSYCHOACOUSTICS_SCALE_UTILS_H_ #define EIDOS_AUDITION_PSYCHOACOUSTICS_SCALE_UTILS_H_ #include <vector> namespace eidos { namespace audition { // Equivalent Rectangular Bandwidth (ERB): // --------------------------------------- // On ERB please consult: // - B.C.J. Moore and B.R. Glasberg (1996), "A revision of Zwicker's loudness // model", Acta Acustica united with Acustica, vol. 82, no. 2:335-345. // - B.C.J. Moore and B.R. Glasberg (1983), "Suggested formulae for // calculating auditory-filter bandwidths and excitation patterns", // J. Acoust. Soc. Am. 74: 750-753. // - B.R. Glasberg and B.C.J. Moore (1990), "Derivation of auditory filter // shapes from notched-noise data", Hearing Research, 47: 103-138. // // For a nice overview of ERB please see Lin, Shoufeng. "Logarithmic Frequency // Scaling and Consistent Frequency Coverage for the Selection of Auditory // Filterbank Center Frequencies.", arXiv preprint arXiv:1801.00075 (2017). namespace erb { // Converts characteristic frequency in Hz to ERB. double HzToErb(double hz); // Converts ERB to characteristic frequency in Hz. double ErbToHz(double erb); // Converts Hertz to Equivalent Rectangular Bandwidth (ERB) rate or scale, where // this quantity ERBS(f) is defined as the number of ERBs below the supplied // frequency in Hertz. See Glasberg and Moore (1996). double HzToErbRate(double hz); // Converts ERB rate back to Hertz. double ErbRateToHz(double erb_rate); // Creates an array of <num_channels> center frequencies (in Hz) equally // spaced along the ERB scale in ascending order between <min_frequency> and // <max_frequency>. std::vector<double> GetFrequenciesHz(int num_channels, double min_frequency, double max_frequency); } // namespace erb } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_PSYCHOACOUSTICS_SCALE_UTILS_H_ // Local Variables: // mode: c++ // End:
2,703
C++
.h
58
44.103448
80
0.726824
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,103
windowing.h
google_eidos-audition/eidos/audition/windowing.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef EIDOS_AUDITION_WINDOWING_H_ #define EIDOS_AUDITION_WINDOWING_H_ #include <vector> #include "Eigen/Core" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { // Signal frame information. struct FrameInfo { // Frame size (in samples). int frame_size = -1; // Frame shift (in samples): Advance frame by specified number of samples. int frame_shift = -1; // Number of frames in a signal. int num_frames = -1; }; // Computes the window function given the window function type, the window // width and the number of channels. Returns a window with dimension // (num_channels, frame_size). Eigen::ArrayXXd ComputeWindowFunction(WindowFunction window_function, int frame_size, int num_channels); // Computes the frame information given the input signal, the duration of the // window and the frame shift, both given in seconds. FrameInfo GetFrameInfo(const Eigen::ArrayXXd &input, const StimulusConfig &config); // Runs windowing function over a two-dimensional input signal with dimensions // (num_channels, num_samples). Returns a vector of <num_frames> two-dimensional // arrays with dimension (num_channels, frame_size). The window width (in // seconds) is provided by <window_duration_sec>. The window is advanced in // steps specified by <frame_shift_sec>, specified in seconds. std::vector<Eigen::ArrayXXd> Window(const Eigen::ArrayXXd &input, const StimulusConfig &config); // Same as above, but also integrates across time dimension in each window by // computing RMS for each channel. Returns an array with dimensions // (num_channels, num_frames). Eigen::ArrayXXd WindowAndIntegrateTime(const Eigen::ArrayXXd &input, const StimulusConfig &config); } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_WINDOWING_H_ // Local Variables: // mode: c++ // End:
2,568
C++
.h
56
41.964286
80
0.728983
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,104
auditory_feature_extractor.h
google_eidos-audition/eidos/audition/auditory_feature_extractor.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Offline auditory feature extractor supporting various models of auditory // periphery. #ifndef EIDOS_AUDITION_AUDITORY_FEATURE_EXTRACTOR_H_ #define EIDOS_AUDITION_AUDITORY_FEATURE_EXTRACTOR_H_ #include "eidos/audition/auditory_feature_extractor_config.pb.h" #include "eidos/audition/auditory_response.h" #include "eidos/audition/waveform.pb.h" namespace eidos { namespace audition { class AuditoryFeatureExtractor { public: AuditoryFeatureExtractor() = default; ~AuditoryFeatureExtractor() = default; // Extracts filterbank features from the supplied mono (single-channel) // waveform and stores them in a matrix of dimension N by M, where // N is the number of filterbank coefficients and M is the number // of samples. // // The features may represent Neural Activity Patterns (NAP), IHC excitation, // Basilar Membrane (BM) displacements and so on. // // Given a filterbank that is producing outputs on a per-sample // basis, we want to downsample to produce outputs on a per-frame // basis. In other words, given that the filterbank has produced // outputs for all the samples in the frame, we would like to // produce a single output [for each channel in the filterbank] that // summarizes the frame. // // Returns false if processing failed, true otherwise. bool ComputeFeatures(const Waveform &wave_data, const AuditoryFeatureExtractorConfig &config, AuditoryResponse *response) const; }; } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_AUDITORY_FEATURE_EXTRACTOR_H_ // Local Variables: // mode: c++ // End:
2,225
C++
.h
52
39.980769
79
0.753697
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,105
carfac_model.h
google_eidos-audition/eidos/audition/carfac_model.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Wrapper around CARFAC library. // // References: // ----------- // [1] Lyon, R. (2017): "The CARFAC Digital Cochlear Model.", In "Human and // Machine Hearing: Extracting Meaning from Sound", Chapter 15, (pp. 293-298), // Cambridge: Cambridge University Press. doi:10.1017/9781139051699.020. // [2] Lyon, R. (2011): "Using a Cascade of Asymmetric Resonators with // Fast-Acting Compression as a Cochlear Model for Machine-Hearing // Applications", Autumn Meeting of the Acoustical Society of Japan (2011), // pp. 509-512. // [3] Lyon, R. (2017): "Human and Machine Hearing", Cambridge University Press. #ifndef EIDOS_AUDITION_CARFAC_MODEL_H_ #define EIDOS_AUDITION_CARFAC_MODEL_H_ #include <memory> #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/carfac_config.pb.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { struct CarfacHandle; class CarfacModel : public AuditoryModel { public: explicit CarfacModel(const CarfacConfig &config); CarfacModel() = delete; ~CarfacModel() override; // Initializes the model from the model-agnostic configuration. // Currently we use the internal CARFAC defaults. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of samples, with input of size // (number of input channels or "ears") by (number of samples). // Note that since the memory layout of an Eigen:ArrayXXd is // column-major, this means that all of the values for the first // time step are stored before all of the values for the second // time step, etc. // // The input is assumed to be normalized within [-1.0, 1.0] range and the // gain already applied. The output is an ArrayXXd of size // GetNumberOfFrequencyChannels() by input.cols(). Depending on the type of // the output given in the configuration (please see <carfac_config.proto>), // the type of the returned output will be *one* of: // - Neural activity patterns (NAPs), // - Basilar membrane displacements, // - Outer hair cell potentials, // - Adaptive gain control levels. // // This is a limitation of the current implementation. Ideally multiple output // types should be returned, if configured. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; // Resets internal state of the filterbank. Call to "forget" the // effect of any previous input on the filterbank. void Reset(); private: // Model configuration. CarfacConfig config_; // Encapsulation of various channel properties. ChannelProperties channel_properties_; // Actual model implementation. std::unique_ptr<CarfacHandle> impl_; }; } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_CARFAC_MODEL_H_ // Local Variables: // mode: c++ // End:
3,583
C++
.h
83
40.783133
80
0.742751
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,106
auditory_response.h
google_eidos-audition/eidos/audition/auditory_response.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple handle encapsulating response from an auditory pipeline. #ifndef EIDOS_AUDITION_AUDITORY_RESPONSE_H_ #define EIDOS_AUDITION_AUDITORY_RESPONSE_H_ #include <utility> #include <string> #include <vector> #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/auditory_model_config.pb.h" namespace eidos { namespace audition { class AuditoryResponse { public: AuditoryResponse() = default; ~AuditoryResponse() = default; // Writes the Eigen matrix to the supplied file in Numpy .npy format. void WriteNpy(const std::string &filename) const; // Writes a named collection of Eigen matrixes to the supplied file in Numpy // .npz format. void WriteNpz(const std::string &filename) const; const std::vector<std::pair<AuditoryOutputType, Eigen::ArrayXXd>> & outputs() const { return outputs_; } std::vector<std::pair<AuditoryOutputType, Eigen::ArrayXXd>> * mutable_outputs() { return &outputs_; } const ChannelProperties &channel_properties() const { return channel_properties_; } ChannelProperties *mutable_channel_properties() { return &channel_properties_; } private: // Collection of the outputs of all the stages in auditory chain. std::vector<std::pair<AuditoryOutputType, Eigen::ArrayXXd>> outputs_; // Encapsulation of various channel properties. ChannelProperties channel_properties_; }; } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_AUDITORY_RESPONSE_H_ // Local Variables: // mode: c++ // End:
2,122
C++
.h
53
37.735849
78
0.759259
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,107
mock_basilar_membrane_model.h
google_eidos-audition/eidos/audition/mock_basilar_membrane_model.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Mock basilar membrane model. Leaves the input stimulus unmodified if it // doesn't look like a monoaural waveform. Otherwise, generates random outputs // with a specified (or fixed) number of channels. #ifndef EIDOS_AUDITION_MOCK_BASILAR_MEMBRANE_MODEL_H_ #define EIDOS_AUDITION_MOCK_BASILAR_MEMBRANE_MODEL_H_ #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { class MockBasilarMembraneModel : public AuditoryModel { public: MockBasilarMembraneModel(); virtual ~MockBasilarMembraneModel() = default; // Initializes the model from the model-agnostic configuration. // Currently we use the internal defaults. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // If the input is a waveform, generates random output with a fixed number of // channels. Otherwise, passes the input to the output unmodified. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; // Number of simulated channels. static constexpr int kDefaultNumChannelsForWaveformInput = 100; private: // Encapsulation of various channel properties. ChannelProperties channel_properties_; }; } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_MOCK_BASILAR_MEMBRANE_MODEL_H_ // Local Variables: // mode: c++ // End:
2,116
C++
.h
48
41.729167
79
0.775182
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,108
waveform_utils.h
google_eidos-audition/eidos/audition/waveform_utils.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Utilities for handling waveform files. #ifndef EIDOS_AUDITION_WAVEFORM_UTIL_H_ #define EIDOS_AUDITION_WAVEFORM_UTIL_H_ #include <string> #include <vector> #include "eidos/audition/waveform.pb.h" namespace eidos { namespace audition { // Given the waveform file path reads it into a proto. Returns false in case // of error. The waveform samples are stored normalized in memory. In order // to retrieve the original values please use "DenormalizeWaveform" API below. bool ReadWaveform(const std::string &filepath, Waveform *proto); // Saves the waveform to the specified file path. Returns false in case of // error. The original waveform is presumed to be normalized in memory. // Denormalization happens before saving it to disk. bool WriteWaveform(const Waveform &proto, const std::string &filepath); // Takes the waveform and scales it to [-1.0,1.0] range applying gain // factor on the result. void ScaleToUnitWaveform(const Waveform &waveform, float scaling_gain, std::vector<float> *samples); // By default the input waveform is normalized by the reader. Denormalize // the waveform restoring the original values. void DenormalizeWaveform(Waveform *waveform); } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_WAVEFORM_UTIL_H_ // Local Variables: // mode: c++ // End:
1,924
C++
.h
42
43.928571
78
0.767914
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,109
auditory_pipeline.h
google_eidos-audition/eidos/audition/auditory_pipeline.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Simple abstraction representing an auditory pipeline consisting of // auditory models. #ifndef EIDOS_AUDITION_AUDITORY_PIPELINE_H_ #define EIDOS_AUDITION_AUDITORY_PIPELINE_H_ #include <memory> #include <utility> #include <vector> #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/audition/auditory_pipeline_config.pb.h" #include "eidos/audition/auditory_response.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { class AuditoryPipeline { public: AuditoryPipeline() = default; ~AuditoryPipeline() = default; // Initializes the pipeline from the configuration proto message. bool Init(const AuditoryPipelineConfig &config); // Initializes the pipeline given the list of models. bool Init(const std::vector<AuditoryModelType> &model_types); // Returns size of the pipeline corresponding to the number of models. int Size() const { return models_.size(); } // Feeds the stimulus to the pipeline. The stimulus described by the // configuration message <stimulus_config> is in <input>. Returns the output // in <response>. Depending on the settings, the response may contain a // single output from the last stage of auditory pipeline or outputs from all // the stages. The outputs always correspond to center frequencies arranged in // ascending order. void Process(const StimulusConfig &stimulus_config, const Eigen::Ref<const Eigen::ArrayXXd> &input, AuditoryResponse *response); protected: // Verifies the pipeline checking that models fit together. bool Verify() const; private: // Model pipeline. std::vector<std::unique_ptr<AuditoryModel>> models_; }; } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_AUDITORY_PIPELINE_H_ // Local Variables: // mode: c++ // End:
2,487
C++
.h
60
39.016667
80
0.762852
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,110
auditory_model.h
google_eidos-audition/eidos/audition/auditory_model.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Interface for auditory models. Concrete filterbank implementations derive // from this class. #ifndef EIDOS_AUDITION_AUDITORY_MODEL_H_ #define EIDOS_AUDITION_AUDITORY_MODEL_H_ #include <string> #include <vector> #include "Eigen/Core" #include "eidos/audition/auditory_model_config.pb.h" #include "eidos/audition/stimulus_config.pb.h" namespace Eigen { // This definition seems to be missing from Eigen. typedef Eigen::Array<double, 1, Eigen::Dynamic> RowArrayXd; } // namespace Eigen namespace eidos { namespace audition { // Encapsulation of various channel properties. struct ChannelProperties { // Returns number of channels. int NumChannels() const { return center_frequencies.size(); } // Center frequencies (CF) for each channel. std::vector<double> center_frequencies; }; class AuditoryModel { public: AuditoryModel() = delete; virtual ~AuditoryModel() = default; // Initializes the model from the model-agnostic configuration. virtual void Init(const StimulusConfig &stimulus_config); // Returns the channel properties for the model. virtual ChannelProperties GetChannelProperties() const = 0; // When the input is audio, the audio is assumed to be monaural (single ear). // In this case the input has size (number of input channels or "ears", which // is 1) by (number of samples). When input is audio, it is assumed to be // normalized within [-1.0, 1.0] range and the gain already applied. // // Note that since the memory layout of an Eigen:ArrayXXd is // column-major, this means that all of the values for the first // time step are stored before all of the values for the second // time step, etc. // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). virtual void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) = 0; AuditoryModelType model_type() const { return model_type_; } AuditoryStageType stage_type() const { return stage_type_; } AuditoryOutputType output_type() const { return output_type_; } bool waveform_input() const { return waveform_input_; } const StimulusConfig &stimulus_config() const { return stimulus_config_; } StimulusConfig *mutable_stimulus_config() { return &stimulus_config_; } const AuditoryModel *previous_model() const { return previous_model_; } void set_previous_model(const AuditoryModel *model) { previous_model_ = model; } // Returns model type as string. std::string ModelTypeAsString() const; protected: AuditoryModel(AuditoryModelType model_type, AuditoryStageType stage_type, AuditoryOutputType output_type, bool waveform_input); private: // Model type. const AuditoryModelType model_type_; // Auditory stage that this model supports. const AuditoryStageType stage_type_; // Type of the output signal that model outputs. In theory we should be // supporting multiple outputs for a single model (especially for the // synapse), but keep it simple for now. const AuditoryOutputType output_type_; // If enabled, the input stimulus is the pressure waveform, i.e. this is the // head model. Otherwise, this is an intermediate model in the auditory chain. const bool waveform_input_; // Model-agnostic configuration. StimulusConfig stimulus_config_; // If models are in a cascade, keep the pointer to the previous model. // The pointer is owned elsewhere. const AuditoryModel *previous_model_; }; // Returns auditory stage corresponding to the given auditory output type. AuditoryStageType OutputType2Stage(AuditoryOutputType output_type); } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_AUDITORY_MODEL_H_ // Local Variables: // mode: c++ // End:
4,371
C++
.h
97
42.195876
80
0.753415
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,111
resampler.h
google_eidos-audition/eidos/audition/resampler.h
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef EIDOS_AUDITION_RESAMPLER_H_ #define EIDOS_AUDITION_RESAMPLER_H_ #include "Eigen/Core" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { // Checks whether resampler should be applied based on the configuration. // Please note, if <downsample_step> is bigger than one, this resampling // API will not be called. bool ShouldResampleOutputs(const StimulusConfig &config); // Simple temporal resampling using <downsample_step> parameter defined // in configuration. Selects every n-th sample in the input. Returns // resampled output with dimension (num_channels, num_original_samples // / downsample_step). Eigen::ArrayXXd DownstepResample(const Eigen::ArrayXXd &input, const StimulusConfig &config); // Resamples the input signal with dimensions (num_channels, num_samples). The // input sample rate and the resampling ratios are provided by the // configuration <config>. Returns the resampled signal with dimensions // (num_cannels, new_num_samples), where each channel is resampled // independently. // // The underlying resampler is from https://github.com/terrygta/SignalResampler. // It reimplements Matlab one-dimensional <resample> function // http://www.mathworks.com.au/help/signal/ref/resample.html // using open-source <upfirdn> implementation by Motorola // http://sourceforge.net/motorola/upfirdn/home/Home/. // // According to the original Matlab documentation: // y = resample(x,p,q) resamples the input sequence, x, at p/q times the // original sample rate. If x is a matrix, then resample treats each column // of x as an independent channel. resample applies an antialiasing FIR // lowpass filter to x and compensates for the delay introduced by the filter. Eigen::ArrayXXd Resample(const Eigen::ArrayXXd &input, const StimulusConfig &config); } // namespace audition } // namespace eidos #endif // EIDOS_AUDITION_RESAMPLER_H_ // Local Variables: // mode: c++ // End:
2,598
C++
.h
54
45.87037
80
0.759369
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,112
jackson_spike_generator.h
google_eidos-audition/third_party/audition/models/bruce_carney/jackson_spike_generator.h
// Copyright 2003 B. Scott Jackson // Copyright 2011 Muhammad S. A. Zilany // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. // Various APIs for generating the spike times given the AN synapse rate // probabilities given Jackson's model. // // Based on the original code by Scott Jackson, Copyright (c) 2003. // // References: // - Jackson B.S., Carney L.H. (2005), "The spontaneous-rate histogram of the // auditory nerve can be explained by only two or three spontaneous rates // and long-range dependence", J. Assoc. Res. Otolaryngol. 6:148-159. // - Zhang X., Heinz M.G., Bruce I.C., Carney L.H. (2001), "A // phenomenological model for the responses of auditorynerve fibers: I. // Nonlinear tuning with compression and suppression.", J. Acoust. Soc. Am. // 109:648-670. // // The original implementation can be found here: // - Documentation: // https://www.urmc.rochester.edu/MediaLibraries/URMCMedia/labs/carney-lab/documents/articles/Jackson-SGfast-2003.pdf // - Code: // https://www.urmc.rochester.edu/MediaLibraries/URMCMedia/labs/carney-lab/codes/SGfast_MEX_files_Updated_08_2011.zip // // For an excellent overview see the handouts of Prof. David Heeger: // http://www.cns.nyu.edu/~david/handouts/poisson.pdf #ifndef THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_JACKSON_SPIKE_GENERATOR_H_ #define THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_JACKSON_SPIKE_GENERATOR_H_ #include <vector> #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { class JacksonSpikeGeneratorModel : public AuditoryModel { public: JacksonSpikeGeneratorModel(); ~JacksonSpikeGeneratorModel() override = default; // Initializes the model from the model-agnostic configuration. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of samples corresponding to firing rate // probabilities, with input of size (number of input channels) by (number of // samples). // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the firing times as fire/no fire boolean mask. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; }; // Generates spike times from an inhomogeneous Poisson process with a fixed // absolute refractory period and a two-exponential relative refractory period. // // This implementation has following important properties: // - Uses the time transformation method. This requires one pseudo-random // number to be generated per spike. // - Uses running approximations to the differential equations of which the // exponentials in the relative refractory equation are solutions. // // Returns spike times in seconds for an inhomogeneous Poisson process with a // driving rate specified by the vector <rates> at sampling period of // <sample_period> (aka <dt>) seconds and with refractoriness. Any negative // elements in <rates> are treated as zeros. Sampling period <dt> is also used // as the the width of discrete time bins in the algorithm, and spike times // will be multiples of <dt>. The input <rates> is repeated <num_repeats> // contiguous times, but the spike times are given relative to the beginning // of the repetition (not from the beginning of the first repetition). The // absolute refractory period (i.e. deadtime) is 0.00075 sec long and the // relative refractory function is: // // (1 - c0 * exp(-(t - td) / s0) - c1 * exp(-(t - td) / s1), // // where 't' is the time since the last spike, 'td' is the length of the // absolute refractory period, c0 = 0.5, s0 = 0.001 sec, c1 = 0.5, and // s1 = 0.0125 sec. // // The number of repetitions parameter <num_repeats> should match the number // of repetitions of the stimulus as defined in the hair cell/synaptic models. std::vector<double> JacksonSpikeGenerator( const std::vector<double> &rates, // Rate probabilities (spikes/sec). double sample_period, // Sampling period of the rate function, in seconds. int num_repeats = 1); // Number of times to repeat the inputs in <rates>. // Computes and returns per-channel spikes given the per-channel firing rates // produced by the synapse model. The rows of <rates> correspond to channels // along the cochlear partition, the columns to the firing rates across time. // The sampling period of the rate function is given by <sample_period>. // // The output has the same dimension as inputs. Each row in the output // corresponds to the binary indicator of whether a given channel fires or not // at a given time. The single-channel API above is used to generate this // information. // // The number of repetitions parameter <num_repeats> should match the number // of repetitions of the stimulus as defined in the hair cell/synaptic models. // // TODO(agutkin): Sparse matrix for the outputs is more efficient. void JacksonSpikeGenerator(const Eigen::Ref<const Eigen::ArrayXXd> &rates, double sample_period, // sec. int num_repeats, Eigen::ArrayXXd *output); } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_JACKSON_SPIKE_GENERATOR_H_ // Local Variables: // mode: c++ // End:
5,865
C++
.h
114
49.315789
119
0.748649
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,113
bruce2018_hair_cell_synapse_model.h
google_eidos-audition/third_party/audition/models/bruce_carney/bruce2018_hair_cell_synapse_model.h
// Copyright 2007 Ian C. Bruce, Yousof Erfani, Muhammad S. A. Zilany // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. // Inner hair cell synaptic model from Carney, Bruce and Zilany labs. The model // is based on the version described in: // // Bruce, I.C., Erfani, Y., and Zilany, M.S.A. (2018). "A phenomenological // model of the synapse between the inner hair cell and auditory nerve: // Implications of limited neurotransmitter release sites", Hearing research, // 360, 40--54, (Special Issue on "Computational Models in Hearing"). // // This library implements the transduction stage between the IHC transmembrane // potentials and AN firing rates. // // See the original documentation and copyright in bruce2018_model.README. #ifndef THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_BRUCE2018_HAIR_CELL_SYNAPSE_MODEL_H_ #define THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_BRUCE2018_HAIR_CELL_SYNAPSE_MODEL_H_ #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { class Bruce2018HairCellSynapseModel : public AuditoryModel { public: Bruce2018HairCellSynapseModel(); ~Bruce2018HairCellSynapseModel() override = default; // Initializes the model from the model-agnostic configuration. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of samples corresponding to IHC transmembrane // potentials, with input of size (number of input channels) by (number of // samples). // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the firing rate probabilities of individual fibers. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; }; // Computes estimates for the firing rate probabilities at each time step given // the transmembrane potentials in <ihc_out>. The sample period of the stimulus // is given by <sample_period>. The characteristic frequency of the fiber in Hz // is specified by <center_freq>, <spont_rate> is the spontaneous firing rate // (Hz). Whether to use exact (slow) or approximate (fast) implementation of the // Power-Law function is controlled by <exact_power_law>. void Bruce2018HairCellSynapse( const Eigen::RowArrayXd &ihc_out, double sample_period, double center_freq, double spont_rate, bool exact_power_law, Eigen::RowArrayXd *rates); } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_BRUCE2018_HAIR_CELL_SYNAPSE_MODEL_H_ // Local Variables: // mode: c++ // End:
3,174
C++
.h
63
48.222222
88
0.771217
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,114
fractional_gaussian_noise.h
google_eidos-audition/third_party/audition/models/bruce_carney/fractional_gaussian_noise.h
// Copyright 2003-2005 Scott Jackson // Copyright 2008-2012 Muhammad S. A. Zilany // Copyright 2019 Google LLC // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd // Fractional Gaussian noise and Brownian motion generators. Brownian motion is // an important continuous-time stochastic process that serves as a // continuous-time analog to the simple symmetric random walk on the one hand, // and shares fundamental properties with the Poisson counting process on the // other hand. // // The APIs in this library are mostly C++ reimplementations of the Matlab // originals. Please see fractional_gaussian_noise.README file in this directory // for pointers to the original code, documentation and licenses. // // See: // - https://en.wikipedia.org/wiki/Fractional_Brownian_motion // - Mandelbrot, B. B., & Van Ness, J. W. (1968)., "Fractional Brownian // motions, fractional noises and applications", SIAM review, 10(4), // 422-437. // - http://www.columbia.edu/~ks20/FE-Notes/4700-07-Notes-BM.pdf #ifndef THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_FRACTIONAL_GAUSSIAN_NOISE_H_ #define THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_FRACTIONAL_GAUSSIAN_NOISE_H_ #include "Eigen/Core" namespace eidos { namespace audition { // FFGN: A fast (exact) fractional Gaussian noise and Brownian motion generator. // Returns a vector containing a sequence of fractional Gaussian noise or // fractional Brownian motion. The generation process uses an FFT which makes // it very fast. // // The length of the output sequence is given by <output_length>. Hurst index // of the resultant noise (<hurst_index>) must be in the range (0 < H <= 2). For // 0 < H <= 1, the output will be fractional Gaussian noise with Hurst index H. // For 1 < H <= 2, the output will be fractional Brownian motion with Hurst index // H-1. Either way, the power spectral density of the output will be nominally // proportional to 1/f^(2H-1). The mean and standard deviation of the resulting // noise are specified by <mu> and <sigma> parameters, respectively. A sensible // choice of these parameters is zero mean and unit standard deviation. // // This method is based on an embedding of the covariance matrix in a circulant // matrix. // // References: // - Davies, R.B. and Harte, D.S. (1987): "Tests for Hurst effect.", // Biometrika, 74(1), pp. 95-101. // - Beran, J. (2017): "Statistics for long-memory processes.", Routledge. // - Bardet, J.M. and Bertrand, P. (2002): "Detecting abrupt change on the // Hurst parameter of a multi-scale fractional Brownian motion with // applications.", Internation Meeting on Self-Similarity and Applications, // pp. 27-30. // // Original implementation: Copyright (c) 2003-2005 by B. Scott Jackson. Eigen::VectorXd JacksonFractionalGaussianNoise(int output_length, double hurst_index, double mu, double sigma); } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_FRACTIONAL_GAUSSIAN_NOISE_H_ // Local Variables: // mode: c++ // End:
3,284
C++
.h
65
47.230769
81
0.716288
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,115
zhang2001_spike_generator.h
google_eidos-audition/third_party/audition/models/bruce_carney/zhang2001_spike_generator.h
// Copyright 2001 Xuedong Zhang // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. // Spike generation algorithm described in Zhang, X., Heinz, M. G., Bruce, // I. C., & Carney, L. H. (2001): "A phenomenological model for the responses // of auditory-nerve fibers: I. Nonlinear tuning with compression and // suppression.", The Journal of the Acoustical Society of America, // 109(2), 648-670. #ifndef THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_ZHANG2001_SPIKE_GENERATOR_H_ #define THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_ZHANG2001_SPIKE_GENERATOR_H_ #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" #include "eidos/audition/zhang2001_spike_generator_config.pb.h" namespace eidos { namespace audition { class Zhang2001SpikeGeneratorModel : public AuditoryModel { public: explicit Zhang2001SpikeGeneratorModel( const Zhang2001SpikeGeneratorConfig &config); Zhang2001SpikeGeneratorModel() = delete; ~Zhang2001SpikeGeneratorModel() override = default; // Initializes the model from the model-agnostic configuration. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of samples corresponding to firing rate // probabilities, with input of size (number of input channels) by (number of // samples). // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the firing times as fire/no fire boolean mask. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; private: // Model configuration. Zhang2001SpikeGeneratorConfig config_; }; // Processes an arbitrary number of samples corresponding to firing rate // probabilities in <input>, with input of size (number of input channels) by // (number of samples). // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the firing times as fire/no fire boolean mask. void Zhang2001SpikeGenerator(const Eigen::Ref<const Eigen::ArrayXXd> &input, double sample_period, // Seconds. int num_repeats, // Number of trials. Eigen::ArrayXXd *output); } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_ZHANG2001_SPIKE_GENERATOR_H_ // Local Variables: // mode: c++ // End:
2,977
C++
.h
62
44.403226
80
0.750172
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,116
bruce2018_spike_generator.h
google_eidos-audition/third_party/audition/models/bruce_carney/bruce2018_spike_generator.h
// Copyright 2007 Ian C. Bruce, Yousof Erfani, Muhammad S. A. Zilany // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. // Spike generator from the auditory nerve synapse model Carney, Bruce and // Zilany labs. The model is based on the version described in: // // Bruce, I.C., Erfani, Y., and Zilany, M.S.A. (2018). "A Phenomenological // model of the synapse between the inner hair cell and auditory nerve: // Implications of limited neurotransmitter release sites", Hearing research, // 360, 40--54, (Special Issue on "Computational Models in Hearing"). // // See the original documentation and copyright in bruce2018_model.README. #ifndef THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_BRUCE2018_SPIKE_GENERATOR_H_ #define THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_BRUCE2018_SPIKE_GENERATOR_H_ #include <vector> #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { class Bruce2018SpikeGeneratorModel : public AuditoryModel { public: Bruce2018SpikeGeneratorModel(); ~Bruce2018SpikeGeneratorModel() override = default; // Initializes the model from the model-agnostic configuration. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of samples corresponding to firing rate // probabilities, with input of size (number of input channels) by (number of // samples). // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the firing times as fire/no fire boolean mask. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; }; // Computes the spike times for a single AN fiber given the synapse output rate // probabilities (in spikes/sec). The <sample_period> is reciprocal of the // sampling rate. It defines the size of each bin. // // Note: Some parameters, such as spontaneous firing rate, are fiber-specific // and depend on the type of the fiber population: low spontaneous rate (LSR), // medium spontaneous rate (MSR) and high spontaneous rate (HSR). std::vector<double> Bruce2018SpikeGenerator( const std::vector<double> &rates, // Rate probabilities (spikes/sec). double sample_period, // Sampling period of the rate function, in seconds. double spont_rate, // Channel-specific spontaneous firing rate // (spikes/sec). double absolute_refractory_period, // In seconds. double relative_refractory_period); // In seconds. // Computes and returns per-channel spikes given the per-channel firing rates // produced by the synapse model. The rows of <rates> correspond to channels // along the cochlear partition, the columns to the firing rates across time. // The sampling period of the rate function is given by <sample_period>. // // The output has the same dimension as inputs. Each row in the output // corresponds to the binary indicator of whether a given channel fires or not // at a given time. The single-channel API above is used to generate this // information. // // TODO(agutkin): Spontaneous rate and refractory periods should be // channel-specific. // TODO(agutkin): Sparse matrix for the outputs is more efficient. void Bruce2018SpikeGenerator( const Eigen::Ref<const Eigen::ArrayXXd> &rates, double sample_period, // Sampling period of the rate function, in seconds. double spont_rate, // Channel-specific spontaneous firing rate // (spikes/sec). double absolute_refractory_period, // In seconds. double relative_refractory_period, // In seconds. Eigen::ArrayXXd *output); } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_BRUCE2018_SPIKE_GENERATOR_H_ // Local Variables: // mode: c++ // End:
4,414
C++
.h
86
48.453488
80
0.750348
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,117
zilany2014_ihc_model.h
google_eidos-audition/third_party/audition/models/bruce_carney/zilany2014_ihc_model.h
// Copyright 2013 Muhammad S. A. Zilany, Ian C. Bruce, Rasha A. Ibrahim, // Paul C. Nelson and Laurel H. Carney // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. // Auditory periphery model of Zilany, Bruce, et. al (2014). /* This is Version 5.2 of the code for auditory periphery model of: Zilany, M.S.A., Bruce, I.C., Nelson, P.C., and Carney, L.H. (2009). "A phenomenological model of the synapse between the inner hair cell and auditory nerve: Long-term adaptation with power-law dynamics, "Journal of the Acoustical Society of America 126(5): 2390-2412. with the modifications and simulation options described in: Zilany, M.S.A., Bruce, I.C., Ibrahim, R.A., and Carney, L.H. (2013). "Improved parameters and expanded simulation options for a model of the auditory periphery," in Abstracts of the 36th ARO Midwinter Research Meeting. Humanization in this version includes: - Human middle-ear filter, based on the linear middle-ear circuit model of Pascal et al. (JASA 1998) - Human BM tuning, based on Shera et al. (PNAS 2002) or Glasberg & Moore (Hear. Res. 1990) - Human frequency-offset of control-path filter (i.e., cochlear amplifier mechanism), based on Greenwood (JASA 1990) The modifications to the BM tuning are described in: Ibrahim, R. A., and Bruce, I. C. (2010). "Effects of peripheral tuning on the auditory nerve's representation of speech envelope and temporal fine structure cues," in The Neurophysiological Bases of Auditory Perception, eds. E. A. Lopez-Poveda and A. R. Palmer and R. Meddis, Springer, NY, pp. 429-438. Please cite these papers if you publish any research results obtained with this code or any modified versions of this code. See the file readme.txt for details of compiling and running the model. %%% (c) M. S. Arefeen Zilany (msazilany@gmail.com), Ian C. Bruce (ibruce@ieee.org), Rasha A. Ibrahim, Paul C. Nelson, and Laurel H. Carney - November 2013 %%% */ #ifndef THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_ZILANY2014_IHC_MODEL_H_ #define THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_ZILANY2014_IHC_MODEL_H_ #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { class Zilany2014IhcModel : public AuditoryModel { public: Zilany2014IhcModel(); ~Zilany2014IhcModel() override = default; // Initializes the model from the model-agnostic configuration. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of monaural audio samples, with input of size // (number of input channels or "ears", which is 1) by (number of samples). // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the estimates of IHC transmembrane potentials. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; private: // Encapsulation of various channel properties. ChannelProperties channel_properties_; }; } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_BRUCE_CARNEY_ZILANY2014_IHC_MODEL_H_ // Local Variables: // mode: c++ // End:
3,886
C++
.h
75
47.653333
80
0.732383
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,118
meddis1986_hair_cell_synapse_model.h
google_eidos-audition/third_party/audition/models/amt/meddis1986_hair_cell_synapse_model.h
// Copyright 1998 Malcolm Slaney (Interval Research Corporation) // Copyright 2016 Piotr Majdak // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. // Inner hair cell synapse model by Ray Meddis, et. al. // // References: // ----------- // - Ray Meddis, Michael J. Hewitt, and Trevor M. Shackleton: "Implementation // details of a computation model of the inner hair‐cell auditory‐nerve // synapse", The Journal of the Acoustical Society of America 87, 1813 (1990). // - Ray Meddis (1986): "Simulation of mechanical to neural transduction in // the auditory receptor", Journal of the Acoustical Society of America 79(3), // 702--711. // // Implementation is based on Malcolm Slaney's Meddis model in AuditoryToolbox // and reimplementation in AMT. A slightly more elaborate implementation can be // found in <MoIHC86Meddis> module of DSAM. #ifndef THIRD_PARTY_AUDITION_MODELS_AMT_MEDDIS1986_HAIR_CELL_SYNAPSE_MODEL_H_ #define THIRD_PARTY_AUDITION_MODELS_AMT_MEDDIS1986_HAIR_CELL_SYNAPSE_MODEL_H_ #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { class Meddis1986HairCellSynapseModel : public AuditoryModel { public: Meddis1986HairCellSynapseModel(); ~Meddis1986HairCellSynapseModel() override = default; // Initializes the model from the model-agnostic configuration. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of samples corresponding to IHC transmembrane // potentials, with input of size (number of input channels) by (number of // samples). // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the firing rate probabilities of individual fibers. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; }; // Computes and returns the per-channel spike rate probabilities given the // instantaneous amplitude of the signal <input> representing the basilar // membrane displacement in each channel. The rows of the input stimulus // correspond to channels along the cochlear partition, the columns to the // response across time. // // Originally the Meddis model was intended to be used in tandem with a // Gammatone filterbank (proposed by Roy Patterson, et. al.), but any model // giving the estimates of basilar membrane displacements in response to // the input stimulus can be used as well. // // The output has the same dimension as inputs. Each row in the output // corresponds to the rate probability of neural spikes (spikes/sec) // corresponding to each channel in the input. // // Generic (not necessarily related to the *instantaneous* firing rate) // note on "rate probabilities": // "The rate is simply the expected number of events per some (time) unit // That could easily be larger than one, there is indeed no upper limit // on a rate, just make the time interval larger, then the rate becomes // larger." void Meddis1986HairCellSynapse(const Eigen::Ref<const Eigen::ArrayXXd> &input, int sample_rate, bool subtract_spontaneous_rate, Eigen::ArrayXXd *output); } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_AMT_MEDDIS1986_HAIR_CELL_SYNAPSE_MODEL_H_ // Local Variables: // mode: c++ // End:
3,965
C++
.h
80
46.975
80
0.758077
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,119
baumgarte_model.h
google_eidos-audition/third_party/audition/models/baumgarte/baumgarte_model.h
// Copyright 1999,2000 Frank Baumgarte // Copyright 2019 Google LLC // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. // Frank Baumgarte's model of hearing periphery described in detail in his // PhD thesis: // // F. Baumgarte: "Ein psychophysiologisches Gehoermodell zur Nachbildung // von Wahrnehmungsschwellen fuer die Audiocodierung", // (in German), PhD Dissertation, University of Hannover, 2000. // // The peripheral ear model is based on the structure of // Eberhard Zwicker's "Analogmodell". That model consists // of analog electrical elements. // // Wolfgang Peisl described the basic WDF algorithm in his // PhD thesis: // W. Peisl: "Beschreibung aktiver nichtlinearer Effekte der // peripheren Schallverarbeitung des Gehoers durch ein Rechnermodell", (in // German), Dissertation, Technical University of Munich. // // This code was originally available from Frank's page at University of // Hannover but the link has been long dead. Please see the original // documentation in "README.txt". #ifndef THIRD_PARTY_AUDITION_MODELS_BAUMGARTE_BAUMGARTE_MODEL_H_ #define THIRD_PARTY_AUDITION_MODELS_BAUMGARTE_BAUMGARTE_MODEL_H_ #include <memory> #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { struct BaumgarteHandle; class BaumgarteModel : public AuditoryModel { public: BaumgarteModel(); ~BaumgarteModel() override; // Initializes the model from the model-agnostic configuration. // Currently we use the internal defaults. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of monaural audio samples, with input of size // (number of input channels or "ears", which is 1) by (number of samples). // Note that since the memory layout of an Eigen:ArrayXXd is // column-major, this means that all of the values for the first // time step are stored before all of the values for the second // time step, etc. // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the estimates of IHC trans-membrane potentials. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; protected: // Updates temporal downsampling step provided by the model. Note, we only use // this for testing that the model outputs match the reference implementation. void set_native_downsample_step(int val) { native_downsample_step_ = val; } private: // Encapsulation of various channel properties. ChannelProperties channel_properties_; // Filterbank implementation. std::unique_ptr<BaumgarteHandle> impl_; // Native downsample step. This is only used for testing. For temporal // downsampling use global downsampling step provided by the stimulus // configuration. int native_downsample_step_ = 1; }; } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_BAUMGARTE_BAUMGARTE_MODEL_H_ // Local Variables: // mode: c++ // End:
3,301
C++
.h
75
41.706667
80
0.765036
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,120
sumner2002_hair_cell_synapse_model.h
google_eidos-audition/third_party/audition/models/dsam/sumner2002_hair_cell_synapse_model.h
// Copyright 2000, 2010 Lowel P. O'Mard // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. // The hair cell synapse model from Sumner, et. al. (2002). The implementation // is based on the reference implementation in DSAM known as <IHC_Meddis2000> // model. // // References: // ----------- // Sumner, C. J, Lopez-Poveda, E. A., O'Mard, L. P. and Meddis, R. (2002): // "A revised model of the inner-hair cell and auditory-nerve complex.", // The Journal of the Acoustical Society of America (JASA), vol.111, no.5, // pp. 2178--2188. #ifndef THIRD_PARTY_AUDITION_MODELS_DSAM_SUMNER2002_HAIR_CELL_SYNAPSE_MODEL_H_ #define THIRD_PARTY_AUDITION_MODELS_DSAM_SUMNER2002_HAIR_CELL_SYNAPSE_MODEL_H_ #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/stimulus_config.pb.h" #include "eidos/audition/sumner2002_hair_cell_synapse_config.pb.h" namespace eidos { namespace audition { class Sumner2002HairCellSynapseModel : public AuditoryModel { public: explicit Sumner2002HairCellSynapseModel( const Sumner2002HairCellSynapseConfig &config); Sumner2002HairCellSynapseModel() = delete; ~Sumner2002HairCellSynapseModel() override = default; // Initializes the model from the model-agnostic configuration. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of samples corresponding to IHC transmembrane // potentials, with input of size (number of input channels) by (number of // samples). // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores the firing rate probabilities of individual fibers. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; private: // Model configuration. Sumner2002HairCellSynapseConfig config_; }; // Computes and returns the per-channel spike rate probabilities given the // instantaneous amplitude of the signal <input> representing the basilar // membrane displacement in each channel. The rows of the input stimulus // correspond to channels along the cochlear partition, the columns to the // response across time. // // The output has the same dimension as inputs. Each row in the output // corresponds to the rate probability of neural spikes (spikes/sec) // corresponding to each channel in the input. void Sumner2002HairCellSynapse( const Sumner2002HairCellSynapseConfig &config, const Eigen::Ref<const Eigen::ArrayXXd> &input, int sample_rate, Eigen::ArrayXXd *output); } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_DSAM_SUMNER2002_HAIR_CELL_SYNAPSE_MODEL_H_ // Local Variables: // mode: c++ // End:
3,259
C++
.h
71
43.619718
81
0.768189
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,121
gammatone_filterbank_model.h
google_eidos-audition/third_party/audition/models/gammatone/gammatone_filterbank_model.h
// Copyright 1998 Malcolm Slaney (Interval Research Corporation) // Copyright 2006 Ning Ma // Copyright 2015 João Felipe Santos // Copyright 2019 Google LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // 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 General Public License for more details. // Gammatone filterbank that can be used to approximate basilar membrane // displacements in response to audio stimulus. // // This version is based on the original Matlab implementation by Malcolm Slaney // originally described in: M. Slaney (1993) "An Efficient Implementation of the // Patterson-Holdsworth Auditory Filter Bank", Apple Tech. Rep. #35. The // original implementation has since been modified by Malcolm to use a 4th order // filter. In particular, this implementation is heavily based on the work // of João Felipe Santos who ported the original code to C++. Please see // README.txt for more information and licensing. #ifndef THIRD_PARTY_AUDITION_MODELS_GAMMATONE_GAMMATONE_FILTERBANK_MODEL_H_ #define THIRD_PARTY_AUDITION_MODELS_GAMMATONE_GAMMATONE_FILTERBANK_MODEL_H_ #include <memory> #include "Eigen/Core" #include "eidos/audition/auditory_model.h" #include "eidos/audition/gammatone_filterbank_config.pb.h" #include "eidos/audition/stimulus_config.pb.h" namespace eidos { namespace audition { struct GammatoneHandle; class GammatoneFilterbankModel : public AuditoryModel { public: GammatoneFilterbankModel(const GammatoneFilterbankConfig &config); GammatoneFilterbankModel() = delete; ~GammatoneFilterbankModel() override; // Initializes the model from the model-agnostic configuration. // Currently we use the internal defaults. void Init(const StimulusConfig &stimulus_config) override; // Returns the channel properties for the model. ChannelProperties GetChannelProperties() const override; // Processes an arbitrary number of monaural audio samples, with input of size // (number of input channels or "ears", which is 1) by (number of samples). // Note that since the memory layout of an Eigen:ArrayXXd is // column-major, this means that all of the values for the first // time step are stored before all of the values for the second // time step, etc. // // The output is an ArrayXXd of size GetNumberOfFrequencyChannels() by // input.cols(). It stores estimates for basilar membrane displacements. void ProcessSegment(const Eigen::Ref<const Eigen::ArrayXXd> &input, Eigen::ArrayXXd *output) override; // Default number of processing channels. static constexpr int kDefaultNumChannels = 251; // Minimal characteristic frequency (in Hz) for the analysis. static constexpr double kLowestCFrequency = 50.0; // Highest characteristic frequency (in Hz) for the analysis. static constexpr double kHighestCFrequency = 10000.0; private: // Model configuration. GammatoneFilterbankConfig config_; // Channel properties. ChannelProperties channel_properties_; // Filterbank implementation. std::unique_ptr<GammatoneHandle> impl_; }; } // namespace audition } // namespace eidos #endif // THIRD_PARTY_AUDITION_MODELS_GAMMATONE_GAMMATONE_FILTERBANK_MODEL_H_ // Local Variables: // mode: c++ // End:
3,522
C++
.h
74
45.175676
80
0.782317
google/eidos-audition
32
8
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,122
rastertoadafruitmini.cpp
edrosten_adafruit-thermal-printer-driver/rastertoadafruitmini.cpp
#include <cups/sidechannel.h> #include <cups/raster.h> #include <iostream> #include <fstream> #include <streambuf> #include <ostream> #include <vector> #include <array> #include <utility> #include <cmath> #include <algorithm> #include <thread> #include <signal.h> #include <unistd.h> #include <sys/fcntl.h> using std::cerr; using std::cerr; using std::cout; using std::flush; using std::endl; using std::min; using std::max; using std::vector; using std::array; using std::string; constexpr unsigned char ESC = 0x1b; constexpr unsigned char GS = 0x1d; constexpr unsigned char DC2 = 0x12; // Write out a std::array of bytes as bytes. template<size_t N> std::ostream& operator<<(std::ostream& out, const array<unsigned char, N>& a){ out.write(reinterpret_cast<const char*>(a.data()), a.size()); return out; } array<unsigned char, 2> binary(uint16_t n){ return {{static_cast<unsigned char>(n&0xff), static_cast<unsigned char>(n >> 8)}}; } void printerInitialise(){ cout << ESC << '\x40'; //If you dont flush here, then the initialise command can kill some of the //data in the buffer, leading to the printer to eat some control codes and //print out junk. cout << flush; } void transmit_status(){ cout << GS << "r1" << flush; } // enter raster mode and set up x and y dimensions void rasterheader(uint16_t xsize, uint16_t ysize) { // Page 33 of the manual // The x size is the number of bytes per row, so the number of pixels // is always a multiple of 8 cout << GS << 'v' << '0' << '\0' << binary((xsize+7)/8) << binary(ysize); } void feed_lines(int n){ for(;n >0 ; n-=255) cout << ESC << 'J' << static_cast<unsigned char>(min(255, n)); } void feed_mm(int mm){ feed_lines(mm*8); } void horizontal_rule(int w=384){ rasterheader(w, 1); cout << string((w+7)/8, '\xff'); } void set_density(int print_density_percent, int print_break_time_us) { // Page 48 of the manual cout << DC2 << '#' << (char)((print_break_time_us / 250 << 5) | ((print_density_percent - 50) / 5 & 0b11111)); } void set_heating_time(int time_factor=80){ // Page 47 of the manual // All the defaults are used if not overridden cout << ESC << '7' << (char)7 << (unsigned char)std::max(3, std::min(255,time_factor)) << '\02'; } constexpr array<array<int, 5>, 3> diffusion_coefficients = {{ {{0, 0, 0, 7, 5}}, {{3, 5, 7, 5, 3}}, {{1, 3, 5, 3, 1}} }}; constexpr double diffusion_divisor=48; double degamma(int p){ return pow(p/255., 1/2.2); } void wait_for_lines(const int lines_sent, int& read_back, int max_diff){ //We've stuffed requests into the command stream which reply with bytes //for each line printed. This waits for replies until the number of //relplies is within some threshold of the number of requests sent. // //This is for buffer management. // //Also, if there's no change in the number of lines read for over some //time threshold then the printer has stopped which means out of paper //since it has only one sensor. using namespace std::literals; using namespace std::chrono; auto time_of_last_change = steady_clock::now(); bool has_paper=true; for(;;){ char buf; ssize_t bytes_read = cupsBackChannelRead(&buf, 1, 0.0); if(bytes_read > 0){ read_back++; if(!has_paper){ cerr << "STATE: -media-empty\n"; cerr << "STATE: -media-needed\n"; cerr << "STATE: -cover-open\n"; cerr << "INFO: Printing\n"; } has_paper = true; time_of_last_change = steady_clock::now(); } else if(auto interval = steady_clock::now() - time_of_last_change; interval > 2500ms){ cerr << "DEBUG: no change for " << duration_cast<seconds>(interval).count() << " seconds, assuming no paper\n"; if(has_paper){ cerr << "STATE: +media-empty\n"; cerr << "STATE: +media-needed\n"; cerr << "STATE: +cover-open\n"; cerr << "INFO: Printer door open or no paper left\n"; } has_paper = false; } cerr << "DEBUG: Lines sent=" << lines_sent << " lines printed=" << read_back << "\n"; if(lines_sent - read_back <= max_diff) break; cerr << "DEBUG: buffer too full (" << lines_sent - read_back << "), pausing...\n"; std::this_thread::sleep_for(100ms); } } volatile sig_atomic_t cancel_job = 0; std::ofstream *wtf; void set_heating_time_basic(int heating_dots, int heating_time_us, int heating_interval_us) { //Reject illegal values if(heating_dots < 8) return; if(heating_time_us < 30) return; int dots = min(255,max(0,heating_dots/8 - 1)); int time = min(255, max(0,heating_time_us / 10)); int interval = min(255,max(0,heating_interval_us / 10)); // Page 47 of the manual // All the defaults are used if not overridden cout << ESC << '7' << (unsigned char)dots << (unsigned char)time << (unsigned char)interval; } int main(int argc, char** argv){ cerr << "STATE: -media-empty\n"; cerr << "STATE: -media-needed\n"; cerr << "STATE: -cover-open\n"; cerr << "INFO: Printing\n"; cerr << "DEBUG: Starting the AdaFruit Mini Driver, by E. Rosten\n"; if(argc !=6 && argc != 7){ cerr << "ERROR: " << argv[0] << " job-id user title copies options [file]\n"; exit(1); } int input_fd = 0; if(argc == 7){ input_fd = open(argv[6], O_RDONLY); if(input_fd == -1){ cerr << "ERROR: could not open file " << argv[6] << ": " << strerror(errno) << endl; exit(1); } } //As recommended by the CUPS documentation https://www.cups.org/doc/api-filter.html#SIGNALS signal(SIGPIPE, SIG_IGN); { struct sigaction int_action; memset(&int_action, 0, sizeof(int_action)); sigemptyset(&int_action.sa_mask); int_action.sa_handler = [](int){ cancel_job=1; }; sigaction(SIGTERM, &int_action, nullptr); } cups_raster_t *ras = cupsRasterOpen(input_fd, CUPS_RASTER_READ); cups_page_header2_t header; int page = 0; int feed_between_pages_mm = 0; int mark_page_boundary = 0; int eject_after_print_mm = 0; int auto_crop = 0; int enhance_resolution = 0; int heating_dots = 64; int heating_time_us = 800; int heating_interval_us = 20; int print_density_percent = 100; int print_break_time_us = 500; printerInitialise(); //This isn't cleared by initialize, so reset it to the //default just in case. set_heating_time(); int lines_sent = 0; int read_back= 0; while (cupsRasterReadHeader2(ras, &header)) { //Read the configuration parameters feed_between_pages_mm = header.cupsInteger[0]; mark_page_boundary = header.cupsInteger[1]; eject_after_print_mm = header.cupsInteger[2]; auto_crop = header.cupsInteger[3]; enhance_resolution = header.cupsInteger[4]; heating_dots = header.cupsInteger[5]; heating_time_us = header.cupsInteger[6]; heating_interval_us = header.cupsInteger[7]; print_density_percent = header.cupsInteger[8]; print_break_time_us = header.cupsInteger[9]; page++; //Write out information to CUPS cerr << "PAGE: " << page << " " << header.NumCopies << "\n"; cerr << "DEBUG: bitsperpixel " << header.cupsBitsPerPixel << endl; cerr << "DEBUG: BitsPerColor " << header.cupsBitsPerColor << endl; cerr << "DEBUG: Width " << header.cupsWidth << endl; cerr << "DEBUG: Height" << header.cupsHeight << endl; cerr << "DEBUG: feed_between_pages_mm " << feed_between_pages_mm << endl; cerr << "DEBUG: mark_page_boundary " << mark_page_boundary << endl; cerr << "DEBUG: eject_after_print_mm " << eject_after_print_mm << endl; cerr << "DEBUG: auto_crop " << auto_crop << endl; cerr << "DEBUG: enhance_resolution " << enhance_resolution << endl; cerr << "DEBUG: heating_dots " << heating_dots << endl; cerr << "DEBUG: heating_time_us " << heating_time_us << endl; cerr << "DEBUG: heating_interval_us " << heating_interval_us << endl; cerr << "DEBUG: print_density_percent " << print_density_percent << endl; cerr << "DEBUG: print_break_time_us " << print_break_time_us << endl; //Set print density set_density(print_density_percent, print_break_time_us); if(!enhance_resolution) set_heating_time_basic(heating_dots,heating_time_us,heating_interval_us); if(page > 1){ cerr << "DEBUG: page feeding " << eject_after_print_mm << "mm\n"; feed_mm(feed_between_pages_mm); } //Avoid double marking the boundary if there's no feed if(mark_page_boundary && (feed_between_pages_mm > 0 || page == 1)){ cerr << "DEBUG: emitting page rule at page top\n"; //Reset the line to all dark for the rule if(enhance_resolution) set_heating_time(); horizontal_rule(); } // Input data buffer for one line vector<unsigned char> buffer(header.cupsBytesPerLine); //Error diffusion data vector<vector<double>> errors(diffusion_coefficients.size(), vector<double>(buffer.size(), 0.0)); /* read raster data */ unsigned int n_blank=0; for (unsigned int y = 0; y < header.cupsHeight; y ++) { if(cancel_job){ //We have ensured by this point that the output is never a half //written raster line, so anything sent here will be interpreted as //a command not simply more data. cerr << "DEBUG: job cancelled\n"; //This causes anything in the buffer to actually be printed //The printer stores segeral lines of bitmap worth and then //prints them. If that buffer is partially full right at the end then //things can go missing print wise. feed_lines(1); cout << flush; //Reset the heater to the default so that the cancelled message appears set_heating_time(); cout << flush<<endl; cout << "*** Cancelled ***\n"; //Unconditionally eject the cancelled job for tearoff //10mm is sufficient to clear the case feed_mm(10); cout << flush; goto finish; } if(cupsRasterReadPixels(ras, buffer.data(), header.cupsBytesPerLine) == 0) break; //Count blank lines rather than printing. Required for auto-cropping if(find_if(buffer.begin(), buffer.end(), [](auto c){return c!=255;}) == buffer.end()){ n_blank++; continue; } //Auto crop means automatically remove white from the beginning and end of the page if(!auto_crop || n_blank != y){ if(n_blank){ cerr << "DEBUG: Feeding " << n_blank << " lines\n"; //Emit blank lines as feed commands, for faster printing. However this messes //up the temperature calibration, so don't do it in resolution enhanced mode. if(!enhance_resolution) feed_lines(n_blank); else{ for(unsigned int i=0; i < n_blank; i++){ rasterheader(header.cupsWidth, 1); for(unsigned int j=0; j < header.cupsBytesPerLine; j++) cout << '\x00'; } } } } else cerr << "DEBUG: AutoCrop skipping start " << n_blank << " lines\n"; n_blank = 0; //Estimate the lowest value pixel in the row double low_val=1.0; for(int i=0; i < (int)buffer.size(); i++) low_val = std::min(low_val, degamma(buffer[i]) + errors[0][i]); //Add some headroom otherwise black areas bleed because it can't go //dark enough low_val*=0.99; if(!enhance_resolution) low_val = 0; //Set the darkness based on the darkest pixel we want //Emperical formula for the effect of the timing double full_white=16; double full_black=16*7; if(enhance_resolution){ set_heating_time(pow(1-low_val,2.0)*(full_black-full_white)+full_white); } //Print in MSB format, one line at a time rasterheader(header.cupsWidth, 1); unsigned char current=0; int bits=0; for(int i=0; i < (int)buffer.size(); i++){ //The actual pixel value with gamma correction double pixel = degamma(buffer[i]) + errors[0][i]; double actual = pixel>(1-low_val)/2 + low_val?1:low_val; double error = pixel - actual; //This error is then distributed //Diffuse forward the error for(int r=0; r < (int)diffusion_coefficients.size(); r++) for(int cc=0; cc < (int)diffusion_coefficients[0].size(); cc++){ int c = cc - diffusion_coefficients[0].size()/2; if(c+i >= 0 && c+i < (int)buffer.size() && diffusion_coefficients[r][cc]){ errors[r][i+c] += error * diffusion_coefficients[r][cc] / diffusion_divisor; } } current |= (actual!=1)<<(7-bits); bits++; if(bits == 8){ cout << current; bits = 0; current = 0; } } if(bits) cout << current; //Roll the buffer round. std::rotate(errors.begin(), errors.begin()+1, errors.end()); for(auto& p:errors.back()) p=0; //Stuff requests for paper status into the command stream //and count the returns. We allow a gap of 80 lines (1cm of printing) transmit_status(); lines_sent++; wait_for_lines(lines_sent, read_back, 80); } //Finish page if(!auto_crop){ cerr << "DEBUG: Feeding " << n_blank << " lines at end\n"; feed_lines(n_blank); } else cerr << "DEBUG: AutoCrop skipping end " << n_blank << " lines\n"; if(mark_page_boundary){ cerr << "DEBUG: emitting page rule at page end\n"; //Reset the line to all dark for the rule if(enhance_resolution) set_heating_time(); horizontal_rule(); } } feed_mm(eject_after_print_mm); finish: cerr << "DEBUG: end of print feeding " << eject_after_print_mm << "mm\n"; cerr << "DEBUG: end status " << cancel_job << "\n"; //Reset the printer to the default state. set_heating_time(); cout << flush; //using namespace std::literals; //std::this_thread::sleep_for(10s); cupsRasterClose(ras); }
13,334
C++
.cpp
374
32.219251
114
0.667368
edrosten/adafruit-thermal-printer-driver
31
4
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,124
HIDLED.h
knuckleslee_RhythmCodes/3E9B9LED_hybrid/leo/HIDLED.h
/* Arduino-HID-Lighting-Library * * This Arduino-HID-Lighting-Library is derived from Arduino-HID-Lighting, whose copyriht owner is mon. * More information about Arduino-HID-Lighting you can find under: * * mon's Arduino-HID-Lighting * https://github.com/mon/Arduino-HID-Lighting * * 2018 (C) Arduino-HID-Lighting-Library, Knuckleslee */ #include "HID.h" #define NUMBER_OF_SINGLE 9 #define NUMBER_OF_RGB 0 #define NUMBER_OF_LIGHTS (NUMBER_OF_SINGLE + NUMBER_OF_RGB*3) extern boolean hidMode; extern char rgbCommon; typedef struct { byte brightness; } SingleLED; typedef struct { byte r; byte g; byte b; } RGBLed; typedef struct { byte pin; } SinglePin; typedef struct { byte r; byte g; byte b; } RGBPin; union { struct { SingleLED singles[NUMBER_OF_SINGLE]; RGBLed rgb[NUMBER_OF_RGB]; } leds; byte raw[NUMBER_OF_LIGHTS]; } led_data;
880
C++
.h
39
20.358974
103
0.742515
knuckleslee/RhythmCodes
30
12
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,125
HIDLED.h
knuckleslee_RhythmCodes/12B12LED_popn/leo/HIDLED.h
/* Arduino-HID-Lighting-Library * * This Arduino-HID-Lighting-Library is derived from Arduino-HID-Lighting, whose copyriht owner is mon. * More information about Arduino-HID-Lighting you can find under: * * mon's Arduino-HID-Lighting * https://github.com/mon/Arduino-HID-Lighting * * 2018 (C) Arduino-HID-Lighting-Library, Knuckleslee */ #include "HID.h" #define NUMBER_OF_SINGLE 12 #define NUMBER_OF_RGB 0 #define NUMBER_OF_LIGHTS (NUMBER_OF_SINGLE + NUMBER_OF_RGB*3) extern boolean hidMode; extern char rgbCommon; typedef struct { byte brightness; } SingleLED; typedef struct { byte r; byte g; byte b; } RGBLed; typedef struct { byte pin; } SinglePin; typedef struct { byte r; byte g; byte b; } RGBPin; union { struct { SingleLED singles[NUMBER_OF_SINGLE]; RGBLed rgb[NUMBER_OF_RGB]; } leds; byte raw[NUMBER_OF_LIGHTS]; } led_data;
881
C++
.h
39
20.384615
103
0.742823
knuckleslee/RhythmCodes
30
12
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,126
HIDLED.h
knuckleslee_RhythmCodes/2E10B10LED_sdvx/leo/HIDLED.h
/* Arduino-HID-Lighting-Library * * This Arduino-HID-Lighting-Library is derived from Arduino-HID-Lighting, whose copyriht owner is mon. * More information about Arduino-HID-Lighting you can find under: * * mon's Arduino-HID-Lighting * https://github.com/mon/Arduino-HID-Lighting * * 2018 (C) Arduino-HID-Lighting-Library, Knuckleslee */ #include "HID.h" #define NUMBER_OF_SINGLE 10 #define NUMBER_OF_RGB 0 #define NUMBER_OF_LIGHTS (NUMBER_OF_SINGLE + NUMBER_OF_RGB*3) extern boolean hidMode; extern char rgbCommon; typedef struct { byte brightness; } SingleLED; typedef struct { byte r; byte g; byte b; } RGBLed; typedef struct { byte pin; } SinglePin; typedef struct { byte r; byte g; byte b; } RGBPin; union { struct { SingleLED singles[NUMBER_OF_SINGLE]; RGBLed rgb[NUMBER_OF_RGB]; } leds; byte raw[NUMBER_OF_LIGHTS]; } led_data;
881
C++
.h
39
20.384615
103
0.742823
knuckleslee/RhythmCodes
30
12
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,127
HIDLED.h
knuckleslee_RhythmCodes/1E11B11LED_iidx/leo/HIDLED.h
/* Arduino-HID-Lighting-Library * * This Arduino-HID-Lighting-Library is derived from Arduino-HID-Lighting, whose copyriht owner is mon. * More information about Arduino-HID-Lighting you can find under: * * mon's Arduino-HID-Lighting * https://github.com/mon/Arduino-HID-Lighting * * 2018 (C) Arduino-HID-Lighting-Library, Knuckleslee */ #include "HID.h" #define NUMBER_OF_SINGLE 11 #define NUMBER_OF_RGB 0 #define NUMBER_OF_LIGHTS (NUMBER_OF_SINGLE + NUMBER_OF_RGB*3) extern boolean hidMode; extern char rgbCommon; typedef struct { byte brightness; } SingleLED; typedef struct { byte r; byte g; byte b; } RGBLed; typedef struct { byte pin; } SinglePin; typedef struct { byte r; byte g; byte b; } RGBPin; union { struct { SingleLED singles[NUMBER_OF_SINGLE]; RGBLed rgb[NUMBER_OF_RGB]; } leds; byte raw[NUMBER_OF_LIGHTS]; } led_data;
881
C++
.h
39
20.384615
103
0.742823
knuckleslee/RhythmCodes
30
12
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,128
HIDLED.h
knuckleslee_RhythmCodes/5E7B7LED_museca/leo/HIDLED.h
/* Arduino-HID-Lighting-Library * * This Arduino-HID-Lighting-Library is derived from Arduino-HID-Lighting, whose copyriht owner is mon. * More information about Arduino-HID-Lighting you can find under: * * mon's Arduino-HID-Lighting * https://github.com/mon/Arduino-HID-Lighting * * 2018 (C) Arduino-HID-Lighting-Library, Knuckleslee */ #include "HID.h" #define NUMBER_OF_SINGLE 7 #define NUMBER_OF_RGB 0 #define NUMBER_OF_LIGHTS (NUMBER_OF_SINGLE + NUMBER_OF_RGB*3) extern boolean hidMode; extern char rgbCommon; typedef struct { byte brightness; } SingleLED; typedef struct { byte r; byte g; byte b; } RGBLed; typedef struct { byte pin; } SinglePin; typedef struct { byte r; byte g; byte b; } RGBPin; union { struct { SingleLED singles[NUMBER_OF_SINGLE]; RGBLed rgb[NUMBER_OF_RGB]; } leds; byte raw[NUMBER_OF_LIGHTS]; } led_data;
880
C++
.h
39
20.358974
103
0.742515
knuckleslee/RhythmCodes
30
12
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,129
HIDLED.h
knuckleslee_RhythmCodes/2E8B8LED1RGB_sdvx/leo/HIDLED.h
/* Arduino-HID-Lighting-Library * * This Arduino-HID-Lighting-Library is derived from Arduino-HID-Lighting, whose copyriht owner is mon. * More information about Arduino-HID-Lighting you can find under: * * mon's Arduino-HID-Lighting * https://github.com/mon/Arduino-HID-Lighting * * 2018 (C) Arduino-HID-Lighting-Library, Knuckleslee */ #include "HID.h" #define NUMBER_OF_SINGLE 8 #define NUMBER_OF_RGB 1 #define NUMBER_OF_LIGHTS (NUMBER_OF_SINGLE + NUMBER_OF_RGB*3) extern boolean hidMode; extern char rgbCommon; typedef struct { byte brightness; } SingleLED; typedef struct { byte r; byte g; byte b; } RGBLed; typedef struct { byte pin; } SinglePin; typedef struct { byte r; byte g; byte b; } RGBPin; union { struct { SingleLED singles[NUMBER_OF_SINGLE]; RGBLed rgb[NUMBER_OF_RGB]; } leds; byte raw[NUMBER_OF_LIGHTS]; } led_data;
880
C++
.h
39
20.358974
103
0.742515
knuckleslee/RhythmCodes
30
12
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,130
main.cpp
timschneeb_LiquidEqualizerWidget/main.cpp
#include "LiquidEqualizerWidget.h" #include <QApplication> #include <QStyle> #include <QTimer> int main(int argc, char *argv[]) { QApplication a(argc, argv); LiquidEqualizerWidget w; //Force standard color palette QApplication::setPalette(w.style()->standardPalette()); //Set bands w.setBands(QVector<double>(std::initializer_list<double>({12.0,2.0,-1.0,1.0,2.0,3.0,0.0}))); //Inherit accent color from palette w.setAccentColor(w.palette().highlight().color()); w.setGridVisible(true); w.show(); //Randomize bands every 3 seconds QTimer timer; srand(time(NULL)); QObject::connect(&timer,&QTimer::timeout,[&w](){ QVector<double> nums; for (int i = 0; i < 15; ++i) nums.push_back((double)rand()/(double)(RAND_MAX/24)-12); w.setBands(nums); }); timer.start(3000); return a.exec(); }
892
C++
.cpp
28
26.857143
96
0.649533
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,131
JdspImpResToolbox.cpp
timschneeb_LiquidEqualizerWidget/3rdparty/JdspImpResToolbox.cpp
#include "JdspImpResToolbox.h" #include "interpolation.h" #include <stdlib.h> #include <string.h> #include <math.h> #include <float.h> using namespace Interpolation; namespace JdspImpResToolbox { static float *decompressedCoefficients = 0; static const double compressedCoeffMQ[701] = { 0.919063234986138511, 0.913619994199411201, 0.897406560667438402, 0.870768836078722797, 0.834273523109754001, 0.788693711602254766, 0.734989263333015286, 0.674282539592362951, 0.607830143521649657, 0.536991457245508341, 0.463194839157173466, 0.387902406850539450, 0.312574364478514499, 0.238633838900749129, 0.167433166845669668, 0.100222526262645231, 0.038121730693097225, -0.017904091793426027, -0.067064330735278010, -0.108757765594775291, -0.142582153044975485, -0.168338357500518510, -0.186029009837402531, -0.195851834439330574, -0.198187933840591440, -0.193585458951914369, -0.182739217157973949, -0.166466876941489483, -0.145682513177707279, -0.121368299577954988, -0.094545192393702127, -0.066243461643369750, -0.037473912797399318, -0.009200603832691301, 0.017684198632122932, 0.042382162574711987, 0.064207571946511041, 0.082602100079150684, 0.097145355203635028, 0.107561011406507381, 0.113718474453852247, 0.115630166683615837, 0.113444644504459249, 0.107435882084395071, 0.097989162055837783, 0.085584105452548076, 0.070775446120293309, 0.054172207614333223, 0.036415971885660689, 0.018158938330246815, 0.000042459196338912, -0.017323296238410713, -0.033377949403731559, -0.047627263300716267, -0.059656793081079629, -0.069142490141500798, -0.075858019256578396, -0.079678658979652428, -0.080581767609623323, -0.078643906863599317, -0.074034819562284179, -0.067008552930955145, -0.057892102695980191, -0.047072022601671190, -0.034979497375161483, -0.022074413174279148, -0.008828977400685476, 0.004288560713652965, 0.016829555699174666, 0.028379479813981756, 0.038570858162652835, 0.047094241683417769, 0.053706909605020871, 0.058239076113395197, 0.060597464446319166, 0.060766202425508065, 0.058805083502616720, 0.054845323789501445, 0.049083025498695095, 0.041770628243703020, 0.033206689594802247, 0.023724383421121997, 0.013679137601712221, 0.003435850879130631, -0.006643868309165797, -0.016214010012738603, -0.024955612937682017, -0.032586990530198853, -0.038872417226545809, -0.043629018879643239, -0.046731678346964158, -0.048115839004410917, -0.047778163016171563, -0.045775074997070689, -0.042219292770236193, -0.037274512912134725, -0.031148477572630149, -0.024084698830208532, -0.016353156105483747, -0.008240309809337577, -0.000038789761018515, 0.007962880277736915, 0.015490170167632772, 0.022291712611484882, 0.028147455724642705, 0.032875542265754551, 0.036337708303315903, 0.038443049556812471, 0.039150063091460026, 0.038466933347880143, 0.036450092517807633, 0.033201143952433128, 0.028862291652591764, 0.023610467168487866, 0.017650385903971395, 0.011206796641134264, 0.004516210167813600, -0.002181595351151269, -0.008651993358287469, -0.014673562407359826, -0.020045503214184583, -0.024594176093158650, -0.028178551235573571, -0.030694406321622035, -0.032077152831841031, -0.032303222419993387, -0.031389996039150381, -0.029394309376722470, -0.026409616804964359, -0.022561940854659814, -0.018004773700230153, -0.012913130046223239, -0.007476976122050557, -0.001894276500050309, 0.003636091270827173, 0.008921304789011335, 0.013781207467236415, 0.018054338893886482, 0.021603186795815136, 0.024318493648450956, 0.026122487293166251, 0.026970945047679402, 0.026854043263213976, 0.025795987570079431, 0.023853461640206807, 0.021112972713804853, 0.017687209024348168, 0.013710556397414673, 0.009333947668859192, 0.004719238361448204, 0.000033314715823999, -0.004557854609777880, -0.008895014112733140, -0.012831064739959125, -0.016235971633599879, -0.019000975419769615, -0.021041973670496809, -0.022301970824562707, -0.022752529440111541, -0.022394191906072568, -0.021255878361951062, -0.019393302279828196, -0.016886478718542881, -0.013836430536684995, -0.010361223853106050, -0.006591484944463394, -0.002665565936317155, 0.001275464342459697, 0.005092825309417521, 0.008654850008311749, 0.011841465274590917, 0.014548176385701671, 0.016689426206986688, 0.018201223316688792, 0.019042961289876651, 0.019198381208357294, 0.018675660452129358, 0.017506641810096972, 0.015745246837337051, 0.013465145155917528, 0.010756776112709417, 0.007723840062309154, 0.004479392878420811, 0.001141688626311485, -0.002170078649346380, -0.005339982462341837, -0.008259373919338373, -0.010830557217282604, -0.012970007990380254, -0.014611030342508765, -0.015705770153788771, -0.016226526478563909, -0.016166328657139784, -0.015538773207899238, -0.014377140707818779, -0.012732837794565421, -0.010673232279050818, -0.008278969379415602, -0.005640873626063710, -0.002856553527664500, -0.000026834265658038, 0.002747852704083721, 0.005370995258360709, 0.007753319014958258, 0.009815785813909824, 0.011492173003678219, 0.012731150958433296, 0.013497795530424229, 0.013774493273929109, 0.013561219484126362, 0.012875191572278549, 0.011749922250546383, 0.010233717662138146, 0.008387684262046795, 0.006283324310867826, 0.003999812773708582, 0.001621057822818793, -0.000767347236997687, -0.003081171091507831, -0.005240483245491547, -0.007172383140908554, -0.008813427537033921, -0.010111676574189758, -0.011028293954650051, -0.011538653669060464, -0.011632924035784708, -0.011316118830412747, -0.010607624279109693, -0.009540229002217340, -0.008158700990423423, -0.006517970800651516, -0.004680992876389242, -0.002716366825287035, -0.000695807329823454, 0.001308445056270027, 0.003226179724201707, 0.004991648959431359, 0.006545794666321473, 0.007838194454033614, 0.008828664063258869, 0.009488466505815606, 0.009801093167340614, 0.009762597931815446, 0.009381481548192093, 0.008678139395534967, 0.007683900954968532, 0.006439703144240938, 0.004994451750326167, 0.003403135115410580, 0.001724761684323746, 0.000020197792912962, -0.001650015947868542, -0.003227792151864713, -0.004659494079420105, -0.005897735119564774, -0.006902920847777659, -0.007644484483944344, -0.008101778413755888, -0.008264597354555087, -0.008133322264400958, -0.007718687720230902, -0.007041188742854554, -0.006130155461650219, -0.005022535167821778, -0.003761430832691131, -0.002394452762763960, -0.000971945496911797, 0.000454844825025831, 0.001835596641714852, 0.003122668316617104, 0.004272722114380925, 0.005248162177843576, 0.006018339594106877, 0.006560486855847911, 0.006860354383749922, 0.006912532886871314, 0.006720456790559610, 0.006296095343184246, 0.005659348921651181, 0.004837178114662079, 0.003862502033291890, 0.002772909691220670, 0.001609233980906675, 0.000414041581645497, -0.000769906024675906, -0.001901165407831948, -0.002941044990442539, -0.003854910802244932, -0.004613320774623974, -0.005192951162290093, -0.005577286818932973, -0.005757056020769449, -0.005730399990410974, -0.005502776877353867, -0.005086609356845171, -0.004500693886508907, -0.003769397706347888, -0.002921676615038254, -0.001989952181071211, -0.001008891180284735, -0.000014132577398601, 0.000958991766382216, 0.001876697269289887, 0.002707904681562794, 0.003425276863778077, 0.004006100299408528, 0.004432983601002821, 0.004694352366032693, 0.004784727410211850, 0.004704781367912914, 0.004461176612085595, 0.004066195127045020, 0.003537178100163921, 0.002895799341758980, 0.002167201988627001, 0.001379032128141500, 0.000560405874095270, -0.000259152041390146, -0.001050759947470964, -0.001787184184342184, -0.002443762818329620, -0.002999217281793143, -0.003436325772772713, -0.003742437746853627, -0.003909814939345641, -0.003935790838753386, -0.003822747153675574, -0.003577912336230492, -0.003212993416401785, -0.002743658050835511, -0.002188888608264336, -0.001570234143874397, -0.000910989133812205, -0.000235329764723561, 0.000432560641279413, 0.001069345839998360, 0.001653340745377959, 0.002165238082962834, 0.002588733711954676, 0.002911030869493576, 0.003123208352342977, 0.003220442832479460, 0.003202080909987641, 0.003071561941475896, 0.002836197950977609, 0.002506821849485185, 0.002097319592184942, 0.001624065644771860, 0.001105284094542681, 0.000560359841433201, 0.000009125484808694, -0.000528850236297424, -0.001034947274672293, -0.001492128764321782, -0.001885503916298735, -0.002202801129643487, -0.002434736758218434, -0.002575269035034838, -0.002621730990172647, -0.002574840645573092, -0.002438591168737718, -0.002220027862259672, -0.001928922712789991, -0.001577360593112676, -0.001179253996234489, -0.000749805296090004, -0.000304936916893765, 0.000139289578942291, 0.000567244609490058, 0.000964271897894877, 0.001317181565737385, 0.001614678737960774, 0.001847714105275549, 0.002009746006742852, 0.002096907004167219, 0.002108071492117578, 0.002044824491385029, 0.001911335280223238, 0.001714142804308648, 0.001461862761483392, 0.001164828784166054, 0.000834682161765550, 0.000483925998593740, 0.000125460552453497, -0.000227883269383389, -0.000563795658925073, -0.000870909262856999, -0.001139175997920627, -0.001360187135536317, -0.001527426803455576, -0.001636451679881492, -0.001684992470943874, -0.001672975660262524, -0.001602466894019970, -0.001477540114542411, -0.001304079085075351, -0.001089520173828018, -0.000842547115162114, -0.000572749884052837, -0.000290260767615715, -0.000005381173403155, 0.000271787324682131, 0.000531694720882059, 0.000765665077860444, 0.000966179147256847, 0.001127108176071712, 0.001243891947014572, 0.001313656276814221, 0.001335267482640161, 0.001309323638539731, 0.001238084697878249, 0.001125345675261167, 0.000976258990458714, 0.000797113715033597, 0.000595080778704776, 0.000377934148912837, 0.000153758569481225, -0.000069345376995143, -0.000283548328671139, -0.000481561352316614, -0.000656878246049437, -0.000803983100343503, -0.000918516742461215, -0.000997397336828164, -0.001038892182663637, -0.001042639573678904, -0.001009621396079384, -0.000942088876021349, -0.000843445486235168, -0.000718092430499951, -0.000571243299133416, -0.000408715393446694, -0.000236705827693455, -0.000061560820167541, 0.000110453421068778, 0.000273370118506192, 0.000421724138601977, 0.000550730322629083, 0.000656432310144007, 0.000735817450677950, 0.000786894740519778, 0.000808734131933592, 0.000801466989262860, 0.000766248858509478, 0.000705187025332569, 0.000621236516650982, 0.000518069214751335, 0.000399921568730665, 0.000271426983019702, 0.000137439322056229, 0.000002854088234340, -0.000127566289796932, -0.000249356967950712, -0.000358499459727905, -0.000451549869015331, -0.000525742663600061, -0.000579067066332711, -0.000610314210246149, -0.000619094306052033, -0.000605824164738963, -0.000571686465475047, -0.000518563123569660, -0.000448945962885840, -0.000365828604967228, -0.000272584032349123, -0.000172832651673869, -0.000070305865763902, 0.000031289837955523, 0.000128403456337462, 0.000217760218406138, 0.000296468531144650, 0.000362109765670523, 0.000412808249833617, 0.000447279627497663, 0.000464856578836417, 0.000465491738613502, 0.000449738470059130, 0.000418710921836804, 0.000374025488711351, 0.000317726390511799, 0.000252198560764628, 0.000180071382714710, 0.000104117018254314, 0.000027147141711448, -0.000048088182130861, -0.000118995940709898, -0.000183226726188442, -0.000238749615318076, -0.000283913107803554, -0.000317490431754438, -0.000338708143110164, -0.000347257581417331, -0.000343289373546324, -0.000327391777412823, -0.000300554208881314, -0.000264117778630104, -0.000219715066774411, -0.000169201669906033, -0.000114582260151285, -0.000057933995063949, -0.000001330110803372, 0.000053233576939992, 0.000103906741924272, 0.000149044949497856, 0.000187260510974094, 0.000217462319983746, 0.000238883649294571, 0.000251097355835207, 0.000254018413730855, 0.000247894152903089, 0.000233283008194432, 0.000211022966716673, 0.000182191226994878, 0.000148056842795767, 0.000110028310364557, 0.000069598166140896, 0.000028286691831679, -0.000012413223177511, -0.000051088131137235, -0.000086451240238396, -0.000117383287411682, -0.000142965848616867, -0.000162506184310969, -0.000175553056891817, -0.000181903303379713, -0.000181599287597338, -0.000174917679492114, -0.000162350303974188, -0.000144578058136870, -0.000122439106161612, -0.000096892719738482, -0.000068980234721197, -0.000039784640417051, -0.000010390306964679, 0.000018155708707897, 0.000044879452343343, 0.000068911789142910, 0.000089515073669816, 0.000106104020030281, 0.000118260259226232, 0.000125740319217347, 0.000128477011389261, 0.000126574445796332, 0.000120297118433995, 0.000110053709582710, 0.000096376396848920, 0.000079896615190895, 0.000061318285745045, 0.000041389584008291, 0.000020874325790195, 0.000000524017729422, -0.000018948449136533, -0.000036892585232981, -0.000052740818819573, -0.000066025144314650, -0.000076389469747209, -0.000083597404911355, -0.000087535408131387, -0.000088211381288728, -0.000085748963835814, -0.000080377921496540, -0.000072421149619506, -0.000062278911057702, -0.000050411001395778, -0.000037317578835504, -0.000023519411693731, -0.000009538283954733, 0.000004121739654397, 0.000016991550435446, 0.000028652179052461, 0.000038747470023706, 0.000046993903986995, 0.000053187343852112, 0.000057206603209622, 0.000059013855762422, 0.000058652018744224, 0.000056239347370971, 0.000051961567969763, 0.000046061951828715, 0.000038829788015541, 0.000030587750191730, 0.000021678669346899, 0.000012452221695327, 0.000003252019725938, -0.000005596443768274, -0.000013796601731427, -0.000021090036946349, -0.000027263866219030, -0.000032156106624670, -0.000035658928433894, -0.000037719781474555, -0.000038340460301533, -0.000037574245901964, -0.000035521325378456, -0.000032322744186229, -0.000028153186597604, -0.000023212908194301, -0.000017719158939021, -0.000011897436866734, -0.000005972901266780, -0.000000162251446552, 0.000005333655793588, 0.000010336218246169, 0.000014694346087313, 0.000018288433744639, 0.000021032968627464, 0.000022877753957232, 0.000023807775391314, 0.000023841789731823, 0.000023029757133319, 0.000021449274538926, 0.000019201196577477, 0.000016404650185715, 0.000013191660473528, 0.000009701607868611, 0.000006075730729441, 0.000002451874068818, -0.000001040335292299, -0.000004283732788372, -0.000007177155365100, -0.000009638185206925, -0.000011605042076524, -0.000013037603419542, -0.000013917565218600, -0.000014247788012456, -0.000014050900469913, -0.000013367256554309, -0.000012252360976939, -0.000010773890887184, -0.000009008449384796, -0.000007038188493661, -0.000004947435946560, -0.000002819451929447, -0.000000733429418017, 0.000001238164361723, 0.000003031826677860, 0.000004594780305705, 0.000005886220575305, 0.000006878033995645, 0.000007554995005623, 0.000007914466875845, 0.000007965650064675, 0.000007728435880102, 0.000007231934716903, 0.000006512756173231, 0.000005613122895949, 0.000004578901096601, 0.000003457628489583, 0.000002296615219305, 0.000001141185552533, 0.000000033118183302, -0.000000990668545558, -0.000001899152803076, -0.000002667946210802, -0.000003279724008567, -0.000003724353373815, -0.000003998736284580, -0.000004106393367485, -0.000004056823505075, -0.000003864680371659, -0.000003548811395079, -0.000003131206866384, -0.000002635907089885, -0.000002087913711897, -0.000001512147886406, -0.000000932492985725, -0.000000370953442845, 0.000000153045653294, 0.000000623201057861, 0.000001026706448750, 0.000001354458044511, 0.000001601095747237, 0.000001764891111188, 0.000001847498832724, 0.000001853592772907, 0.000001790410657756, 0.000001667233505382, 0.000001494826511430, 0.000001284867642241, 0.000001049388641653, 0.000000800250692844, 0.000000548673760673, 0.000000304834862491, 0.000000077546377014, -0.000000125978796206, -0.000000300272674786, -0.000000441669721214, -0.000000548281621807, -0.000000619897641839, -0.000000657821438861, -0.000000664657100282, -0.000000644058349094, -0.000000600455333568, -0.000000538773213853, -0.000000464155939282, -0.000000381707256690, -0.000000296259201847, -0.000000212176215381, -0.000000133200709942, -0.000000062343516559, 0.0 }; ierper pch1, pch2, pch3; #define BANDS_NUM 15 // hardcoding this is not good #define NUMPTS_DRS (7) static void decompressResamplerMQ(const double y[701], float *yi) { double breaks[701]; double coefs[2800]; int32_t k; double s[701]; double dx[700]; double dvdf[700]; double r, dzzdx, dzdxdx; for (k = 0; k < 700; k++) { r = 0.0014285714285714286 * ((double)k + 1.0) - 0.0014285714285714286 * (double)k; dx[k] = r; dvdf[k] = (y[k + 1] - y[k]) / r; } s[0] = ((dx[0] + 0.0057142857142857143) * dx[1] * dvdf[0] + dx[0] * dx[0] * dvdf[1]) / 0.0028571428571428571; s[700] = ((dx[699] + 0.0057142857142857828) * dx[698] * dvdf[699] + dx[699] * dx[699] * dvdf[698]) / 0.0028571428571428914; breaks[0] = dx[1]; breaks[700] = dx[698]; for (k = 0; k < 699; k++) { r = dx[k + 1]; s[k + 1] = 3.0 * (r * dvdf[k] + dx[k] * dvdf[k + 1]); breaks[k + 1] = 2.0 * (r + dx[k]); } r = dx[1] / breaks[0]; breaks[1] -= r * 0.0028571428571428571; s[1] -= r * s[0]; for (k = 0; k < 698; k++) { r = dx[k + 2] / breaks[k + 1]; breaks[k + 2] -= r * dx[k]; s[k + 2] -= r * s[k + 1]; } r = 0.0028571428571428914 / breaks[699]; breaks[700] -= r * dx[698]; s[700] -= r * s[699]; s[700] /= breaks[700]; for (k = 698; k >= 0; k--) s[k + 1] = (s[k + 1] - dx[k] * s[k + 2]) / breaks[k + 1]; s[0] = (s[0] - 0.0028571428571428571 * s[1]) / breaks[0]; for (k = 0; k < 701; k++) breaks[k] = 0.0014285714285714286 * (double)k; for (k = 0; k < 700; k++) { r = 1.0 / dx[k]; dzzdx = (dvdf[k] - s[k]) * r; dzdxdx = (s[k + 1] - dvdf[k]) * r; coefs[k] = (dzdxdx - dzzdx) * r; coefs[k + 700] = 2.0 * dzzdx - dzdxdx; coefs[k + 1400] = s[k]; coefs[k + 2100] = y[k]; } double d = 1.0 / 22437.0; int32_t low_i, low_ip1, high_i, mid_i; for (k = 0; k < 22438; k++) { low_i = 0; low_ip1 = 2; high_i = 701; r = k * d; while (high_i > low_ip1) { mid_i = ((low_i + high_i) + 1) >> 1; if (r >= breaks[mid_i - 1]) { low_i = mid_i - 1; low_ip1 = mid_i + 1; } else high_i = mid_i; } double xloc = r - breaks[low_i]; yi[k] = xloc * (xloc * (xloc * coefs[low_i] + coefs[low_i + 700]) + coefs[low_i + 1400]) + coefs[low_i + 2100]; } } __attribute__((constructor)) static void initialize(void) { if (decompressedCoefficients) free(decompressedCoefficients); decompressedCoefficients = (float*)malloc(22438 * sizeof(float)); decompressResamplerMQ(compressedCoeffMQ, decompressedCoefficients); initIerper(&pch1, BANDS_NUM + 2); initIerper(&pch2, BANDS_NUM + 2); initIerper(&pch3, NUMPTS_DRS + 2); } __attribute__((destructor)) static void destruction(void) { free(decompressedCoefficients); decompressedCoefficients = 0; freeIerper(&pch1); freeIerper(&pch2); freeIerper(&pch3); } int ComputeEqResponse(const double* jfreq, double* jgain, int interpolationMode, int queryPts, double* dispFreq, float* response) { double freq[BANDS_NUM + 2]; double gain[BANDS_NUM + 2]; memcpy(freq + 1, jfreq, BANDS_NUM * sizeof(double)); memcpy(gain + 1, jgain, BANDS_NUM * sizeof(double)); freq[0] = 0.0; gain[0] = gain[1]; freq[BANDS_NUM + 1] = 24000.0; gain[BANDS_NUM + 1] = gain[BANDS_NUM]; ierper *lerpPtr; if (!interpolationMode) { pchip(&pch1, freq, gain, BANDS_NUM + 2, 1, 1); lerpPtr = &pch1; } else { makima(&pch2, freq, gain, BANDS_NUM + 2, 1, 1); lerpPtr = &pch2; } for (int i = 0; i < queryPts; i++) { response[i] = (float)getValueAt(&lerpPtr->cb, dispFreq[i]); } return 0; } int ComputeCompResponse(const double* jfreq, const double* jgain, int queryPts, const double* dispFreq, float* response) { double freqComp[NUMPTS_DRS + 2]; double gainComp[NUMPTS_DRS + 2]; memcpy(freqComp + 1, jfreq, NUMPTS_DRS * sizeof(double)); memcpy(gainComp + 1, jgain, NUMPTS_DRS * sizeof(double)); freqComp[0] = 0.0; gainComp[0] = gainComp[1]; freqComp[NUMPTS_DRS + 1] = 24000.0; gainComp[NUMPTS_DRS + 1] = gainComp[NUMPTS_DRS]; makima(&pch3, freqComp, gainComp, NUMPTS_DRS + 2, 1, 1); ierper *lerpPtr = &pch3; for (int i = 0; i < queryPts; i++) response[i] = (float)getValueAt(&lerpPtr->cb, dispFreq[i]); return 0; } }
20,684
C++
.cpp
151
131.278146
15,802
0.777567
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,132
interpolation.cpp
timschneeb_LiquidEqualizerWidget/3rdparty/interpolation.cpp
#include "interpolation.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> namespace Interpolation { int upper_bound(double *a, int n, double x) { int l = 0; int h = n; while (l < h) { int mid = l + (h - l) / 2; if (x >= a[mid]) l = mid + 1; else h = mid; } return l; } void cubic_hermite_init(cubic_hermite *cuher, double* x, double* y, double* dydx, int n) { cuher->x_ = x; cuher->y_ = y; cuher->dydx_ = dydx; if (n < 4) { printf("Must be at least four data points."); } cuher->n = n; double x0 = cuher->x_[0]; for (int i = 1; i < n; ++i) { double x1 = cuher->x_[i]; if (x1 <= x0) printf("Abscissas must be listed in strictly increasing order x0 < x1 < ... < x_{n-1}"); x0 = x1; } } double getValueAt(cubic_hermite *cuher, double x) { // We need t := (x-x_k)/(x_{k+1}-x_k) \in [0,1) for this to work. // Sadly this neccessitates this loathesome check, otherwise we get t = 1 at x = xf. if (x == cuher->x_[cuher->n - 1]) return cuher->y_[cuher->n - 1]; int it = upper_bound(cuher->x_, cuher->n, x); if (it == 0) it = 1; if (it == cuher->n) it = cuher->n - 1; double x0 = cuher->x_[it - 1]; double x1 = cuher->x_[it]; double y0 = cuher->y_[it - 1]; double y1 = cuher->y_[it]; double s0 = cuher->dydx_[it - 1]; double s1 = cuher->dydx_[it]; double dx = (x1 - x0); double t = (x - x0) / dx; // See the section 'Representations' in the page // https://en.wikipedia.org/wiki/Cubic_Hermite_spline // This uses the factorized form: //double y = y0*(1+2*t)*(1-t)*(1-t) + dx*s0*t*(1-t)*(1-t) // + y1*t*t*(3-2*t) + dx*s1*t*t*(t-1); // And then factorized further: return (1.0 - t)*(1.0 - t)*(y0*(1.0 + 2.0 * t) + s0 * (x - x0)) + t * t*(y1*(3.0 - 2.0 * t) + dx * s1*(t - 1.0)); } double getDerivativeAt(cubic_hermite *cuher, double x) { if (x == cuher->x_[cuher->n - 1]) return cuher->dydx_[cuher->n - 1]; int it = upper_bound(cuher->x_, cuher->n, x); if (it == 0) it = 1; if (it == cuher->n) it = cuher->n - 1; double x0 = cuher->x_[it - 1]; double x1 = cuher->x_[it]; double s0 = cuher->dydx_[it - 1]; double s1 = cuher->dydx_[it]; // Ridiculous linear interpolation. Fine for now: return (s0 * (x1 - x) + s1 * (x - x0)) / (x1 - x0); } void initIerper(ierper *intp, int n) { intp->s = (double*)malloc(n * sizeof(double)); } void freeIerper(ierper *intp) { free(intp->s); } void pchip(ierper *intp, double * x, double * y, int n, int left_endpoint_derivative, int right_endpoint_derivative) { if (n < 4) { printf("Must be at least four data points."); } if (left_endpoint_derivative) { // O(h) finite difference derivative: // This, I believe, is the only derivative guaranteed to be monotonic: intp->s[0] = (y[1] - y[0]) / (x[1] - x[0]); } else intp->s[0] = left_endpoint_derivative; for (int k = 1; k < n - 1; ++k) { double hkm1 = x[k] - x[k - 1]; double dkm1 = (y[k] - y[k - 1]) / hkm1; double hk = x[k + 1] - x[k]; double dk = (y[k + 1] - y[k]) / hk; double w1 = 2.0 * hk + hkm1; double w2 = hk + 2.0 * hkm1; if ((dk > 0 && dkm1 < 0.0) || (dk < 0.0 && dkm1 > 0.0) || dk == 0.0 || dkm1 == 0.0) intp->s[k] = 0.0; else intp->s[k] = (w1 + w2) / (w1 / dkm1 + w2 / dk); } // Quadratic extrapolation at the other end: if (right_endpoint_derivative) intp->s[n - 1] = (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2]); else intp->s[n - 1] = right_endpoint_derivative; cubic_hermite_init(&intp->cb, x, y, intp->s, n); } void makima(ierper *intp, double * x, double * y, int n, int left_endpoint_derivative, int right_endpoint_derivative) { if (n < 4) { printf("Must be at least four data points."); } double m2 = (y[3] - y[2]) / (x[3] - x[2]); double m1 = (y[2] - y[1]) / (x[2] - x[1]); double m0 = (y[1] - y[0]) / (x[1] - x[0]); // Quadratic extrapolation: m_{-1} = 2m_0 - m_1: double mm1 = 2.0 * m0 - m1; // Quadratic extrapolation: m_{-2} = 2*m_{-1}-m_0: double mm2 = 2.0 * mm1 - m0; double w1 = fabs(m1 - m0) + fabs(m1 + m0) * 0.5; double w2 = fabs(mm1 - mm2) + fabs(mm1 + mm2) * 0.5; if (left_endpoint_derivative) { if ((w1 + w2) < DBL_EPSILON) intp->s[0] = 0.0; else intp->s[0] = (w1*mm1 + w2 * m0) / (w1 + w2); } else intp->s[0] = left_endpoint_derivative; w1 = fabs(m2 - m1) + fabs(m2 + m1) * 0.5; w2 = fabs(m0 - mm1) + fabs(m0 + mm1) * 0.5; if ((w1 + w2) < DBL_EPSILON) intp->s[1] = 0.0; else intp->s[1] = (w1*m0 + w2 * m1) / (w1 + w2); for (int i = 2; i < n - 2; ++i) { double mim2 = (y[i - 1] - y[i - 2]) / (x[i - 1] - x[i - 2]); double mim1 = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); double mi = (y[i + 1] - y[i]) / (x[i + 1] - x[i]); double mip1 = (y[i + 2] - y[i + 1]) / (x[i + 2] - x[i + 1]); w1 = fabs(mip1 - mi) + fabs(mip1 + mi) * 0.5; w2 = fabs(mim1 - mim2) + fabs(mim1 + mim2) * 0.5; if ((w1 + w2) < DBL_EPSILON) intp->s[i] = 0.0; else intp->s[i] = (w1*mim1 + w2 * mi) / (w1 + w2); } // Quadratic extrapolation at the other end: double mnm4 = (y[n - 3] - y[n - 4]) / (x[n - 3] - x[n - 4]); double mnm3 = (y[n - 2] - y[n - 3]) / (x[n - 2] - x[n - 3]); double mnm2 = (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2]); double mnm1 = 2.0 * mnm2 - mnm3; double mn = 2.0 * mnm1 - mnm2; w1 = fabs(mnm1 - mnm2) + fabs(mnm1 + mnm2) * 0.5; w2 = fabs(mnm3 - mnm4) + fabs(mnm3 + mnm4) * 0.5; if ((w1 + w2) < DBL_EPSILON) intp->s[n - 2] = 0.0; else intp->s[n - 2] = (w1*mnm3 + w2 * mnm2) / (w1 + w2); w1 = fabs(mn - mnm1) + fabs(mn + mnm1) * 0.5; w2 = fabs(mnm2 - mnm3) + fabs(mnm2 + mnm3) * 0.5; if (right_endpoint_derivative) { if ((w1 + w2) < DBL_EPSILON) intp->s[n - 1] = 0.0; else intp->s[n - 1] = (w1*mnm2 + w2 * mnm1) / (w1 + w2); } else intp->s[n - 1] = right_endpoint_derivative; cubic_hermite_init(&intp->cb, x, y, intp->s, n); } }
5,850
C++
.cpp
193
27.803109
117
0.544859
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,133
BaseLiquidEqualizerWidget.cpp
timschneeb_LiquidEqualizerWidget/src/BaseLiquidEqualizerWidget.cpp
/* * This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. ThePBone <tim.schneeberger(at)outlook.de> (c) 2020 Design inspired by https://github.com/vipersaudio/viper4android_fx */ #include "BaseLiquidEqualizerWidget.h" #include <QDebug> #include <QLinearGradient> #include <QPainterPath> #include <cstring> using namespace std; #ifndef M_PI #define M_PI 3.14159265358979323846 #endif BaseLiquidEqualizerWidget::BaseLiquidEqualizerWidget(int bandsNum, int minFreq, int maxFreq, double minDb, double maxDb, int resolution, double horizLineInterval, QWidget *parent) : QWidget(parent), mBandsNum(bandsNum), mResolution(resolution), mMinFreq(minFreq), mMaxFreq(maxFreq), mMinDb(minDb), mMaxDb(maxDb), mHorizLineInterval(horizLineInterval) { mLevels = new double[mBandsNum]; mActualLevels = new double[mBandsNum]; mAnimators.reserve(mBandsNum); for (int i = 0; i < mBandsNum; i++) { mAnimators.append(new QVariantAnimation(this)); mLevels[i] = 0; mActualLevels[i] = 0; } dispFreq = new double[resolution]; response = new float[resolution]; precomputeCurveXAxis = new float[resolution]; for (int i = 0; i < resolution; i++) { response[i] = 0; dispFreq[i] = reverseProjectX(i / (float) (resolution - 1)); } for (int i = 0; i < resolution; i++) { precomputeCurveXAxis[i] = projectX(dispFreq[i]); } int i = 0; for (int freq = minFreq; freq < maxFreq;) { precomputeFreqAxis[i] = projectX(freq); if (freq < 100) { freq += 10; } else if (freq < 1000) { freq += 100; } else if (freq < 10000) { freq += 1000; } else { freq += 10000; } i++; } connect(this, &BaseLiquidEqualizerWidget::redrawRequired, [this]() { repaint(); }); } BaseLiquidEqualizerWidget::~BaseLiquidEqualizerWidget() { delete [] dispFreq; delete [] response; delete [] precomputeCurveXAxis; delete [] precomputeFreqAxis; delete [] mLevels; delete [] mActualLevels; } void BaseLiquidEqualizerWidget::mouseDoubleClickEvent(QMouseEvent *event) { #if QT_VERSION < QT_VERSION_CHECK(6, 0 ,0) float y = (float) event->y() / (float) height(); #else float y = (float) event->position().y() / (float) height(); #endif if (y < 0 || y > 1) { return; } float dB = reverseProjectY(y); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) setBand(getIndexUnderMouse(event->x()), dB, false); #else setBand(getIndexUnderMouse(event->position().x()), dB, false); #endif } int BaseLiquidEqualizerWidget::bandsNum() const { return mBandsNum; } int BaseLiquidEqualizerWidget::resolution() const { return mResolution; } int BaseLiquidEqualizerWidget::getAnimationDuration() const { return mAnimationDuration; } void BaseLiquidEqualizerWidget::setAnimationDuration(int animationDuration) { mAnimationDuration = animationDuration; } QColor BaseLiquidEqualizerWidget::getAccentColor() const { return mAccentColor; } void BaseLiquidEqualizerWidget::setAccentColor(const QColor &accentColor) { mAccentColor = accentColor; emit redrawRequired(); } bool BaseLiquidEqualizerWidget::getAlwaysDrawHandles() const { return mAlwaysDrawHandles; } void BaseLiquidEqualizerWidget::setAlwaysDrawHandles(bool alwaysDrawHandles) { mAlwaysDrawHandles = alwaysDrawHandles; emit redrawRequired(); } bool BaseLiquidEqualizerWidget::getGridVisible() const { return mGridVisible; } void BaseLiquidEqualizerWidget::setGridVisible(bool gridVisible) { mGridVisible = gridVisible; emit redrawRequired(); } void BaseLiquidEqualizerWidget::mousePressEvent(QMouseEvent *event) { Q_UNUSED(event) mHoldDown = true; } void BaseLiquidEqualizerWidget::mouseReleaseEvent(QMouseEvent *event) { Q_UNUSED(event) mHoldDown = false; emit bandsUpdated(); emit mouseReleased(); repaint(); } void BaseLiquidEqualizerWidget::mouseMoveEvent(QMouseEvent *event) { if (mHoldDown) { #if QT_VERSION < QT_VERSION_CHECK(6, 0 ,0) float y = (float) event->y() / (float) height(); #else float y = (float) event->position().y() / (float) height(); #endif if (y < 0 || y > 1) { return; } float dB = reverseProjectY(y); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) setBand(getIndexUnderMouse(event->x()), dB, false, true); #else setBand(getIndexUnderMouse(event->position().x()), dB, false, true); #endif } } void BaseLiquidEqualizerWidget::keyPressEvent(QKeyEvent *event) { QPoint point = this->mapFromGlobal(QCursor::pos()); int index = getIndexUnderMouse(point.x()); QRect widgetRect = this->geometry(); widgetRect.moveTopLeft(this->parentWidget()->mapToGlobal(widgetRect.topLeft())); if (widgetRect.contains(QCursor::pos())) { mHoldDown = true; if (mKey_LastMousePos != QCursor::pos()) { mKey_CurrentIndex = index; } if (event->key() == Qt::Key::Key_Up) { float cur = getBand(mKey_CurrentIndex); setBand(mKey_CurrentIndex, cur >= mMaxDb ? mMaxDb : cur + 0.5, false, true); emit bandsUpdated(); } else if (event->key() == Qt::Key::Key_Down) { float cur = getBand(mKey_CurrentIndex); setBand(mKey_CurrentIndex, cur <= mMinDb ? mMinDb : cur - 0.5, false, true); emit bandsUpdated(); } else if (event->key() == Qt::Key::Key_Left && mKey_LastMousePos == QCursor::pos()) { if (mKey_CurrentIndex > 0) { mKey_CurrentIndex--; } setBand(mKey_CurrentIndex, getBand(mKey_CurrentIndex), false, true); } else if (event->key() == Qt::Key::Key_Right && mKey_LastMousePos == QCursor::pos()) { if (mKey_CurrentIndex < mBandsNum) { mKey_CurrentIndex++; } setBand(mKey_CurrentIndex, getBand(mKey_CurrentIndex), false, true); } } mKey_LastMousePos = QCursor::pos(); } void BaseLiquidEqualizerWidget::keyReleaseEvent(QKeyEvent *event) { Q_UNUSED(event) QPoint point = this->mapFromGlobal(QCursor::pos()); int index = getIndexUnderMouse(point.x()); if (index == mKey_CurrentIndex) { mHoldDown = false; repaint(); } } void BaseLiquidEqualizerWidget::paintEvent(QPaintEvent *event) { Q_UNUSED(event) mWidth = this->width() + 1; mHeight = this->height() + 1; QColor color = mAccentColor; if(!isEnabled()) { color.setHsl(color.hslHue(), 0, color.lightness()); color.setAlpha(128); } QPainterPath frequencyResponse; float x, y; if(mFreqs.empty()) { mFreqs = getFrequencyPoints(); } computeCurve(mFreqs.constData(), mLevels, mResolution, dispFreq, response); for (int i = 0; i < mResolution; i++) { /* Magnitude response, dB */ x = precomputeCurveXAxis[i] * mWidth; y = projectY(response[i]) * mHeight; /* Set starting point at first point */ if (i == 0) { frequencyResponse.moveTo(x, y); } else { frequencyResponse.lineTo(x, y); } } QPainterPath frequencyResponseBackground; frequencyResponseBackground.addPath(frequencyResponse); frequencyResponseBackground.lineTo(mWidth, mHeight); frequencyResponseBackground.lineTo(0.0f, mHeight); QLinearGradient gradient(QPoint(width(), 0), QPoint(width(), height())); gradient.setColorAt(0.0, color); gradient.setColorAt(1.0, QColor(0, 0, 0, 0)); if (mGridVisible) { mGridLines.begin(this); mGridLines.setPen(QPen(palette().mid(), isEnabled() ? 0.75 : 0.5, Qt::PenStyle::SolidLine, Qt::PenCapStyle::SquareCap)); mGridLines.setRenderHint(QPainter::RenderHint::Antialiasing, true); float decibel = mMinDb + mHorizLineInterval; while (decibel <= mMaxDb - mHorizLineInterval) { float y = projectY(decibel) * mHeight; mGridLines.drawLine(0.0f, y, mWidth - 1, y); decibel += mHorizLineInterval; } mGridLines.end(); } mFrequencyResponseBg.begin(this); mFrequencyResponseBg.setBrush(gradient); mFrequencyResponseBg.setRenderHint(QPainter::RenderHint::Antialiasing, true); mFrequencyResponseBg.drawPath(frequencyResponseBackground); mFrequencyResponseBg.end(); mFrequencyResponseHighlight.begin(this); mFrequencyResponseHighlight.setPen(QPen(QBrush(color), 3, Qt::PenStyle::SolidLine, Qt::PenCapStyle::SquareCap)); mFrequencyResponseHighlight.setRenderHint(QPainter::RenderHint::Antialiasing, true); mFrequencyResponseHighlight.drawPath(frequencyResponse); mFrequencyResponseHighlight.end(); for (int i = 0; i < mBandsNum; i++) { double frequency = mFreqs[i]; double x = projectX(frequency) * mWidth; double y = projectY(mLevels[i]) * mHeight; QString frequencyText = QString::asprintf(frequency < 1000 ? "%.0f" : "%.0fk", frequency < 1000 ? frequency : frequency / 1000); QString gainText = QString::asprintf("%.1f", mLevels[i]); if ((mManual && i == mSelectedBand && mHoldDown) || mAlwaysDrawHandles) { mControlBarKnob.begin(this); mControlBarKnob.setBrush(color); mControlBarKnob.setPen(color.lighter(50)); mControlBarKnob.setRenderHint(QPainter::RenderHint::Antialiasing, true); mControlBarKnob.drawEllipse(x - 8, y - 9, 18.0f, 18.0f); mControlBarKnob.end(); } mControlBarText.begin(this); QFont font = mControlBarText.font(); font.setPointSize(8); mControlBarText.setFont(font); mControlBarText.drawText(x, 19, gainText); mControlBarText.drawText(x, mHeight - 16.0f, frequencyText); mControlBarText.end(); #ifdef UI_DEBUG mGridLines.begin(this); mGridLines.setPen(QPen(Qt::green, 0.75, Qt::PenStyle::SolidLine, Qt::PenCapStyle::SquareCap)); mGridLines.setRenderHint(QPainter::RenderHint::Antialiasing, true); mGridLines.drawLine(x, 0, x, mHeight - 1); mGridLines.end(); #endif } #ifdef UI_DEBUG auto cursor = mapFromGlobal(QCursor::pos()); mGridLines.begin(this); mGridLines.setPen(QPen(Qt::red, 0.75, Qt::PenStyle::SolidLine, Qt::PenCapStyle::SquareCap)); mGridLines.setRenderHint(QPainter::RenderHint::Antialiasing, true); mGridLines.drawLine(0, cursor.y(), mWidth - 1, cursor.y()); mGridLines.end(); #endif } void BaseLiquidEqualizerWidget::setBand(int i, double value, bool animate, bool manual) { mSelectedBand = i; mManual = manual; mActualLevels[i] = value; if (animate) { if (mAnimators[i] != nullptr) { mAnimators[i]->stop(); } mAnimators[i] = new QVariantAnimation(this); mAnimators[i]->setDuration(500); mAnimators[i]->setEasingCurve(QEasingCurve(QEasingCurve::Type::InOutCirc)); mAnimators[i]->setStartValue(mLevels[i]); mAnimators[i]->setEndValue(value); mAnimators[i]->setDirection(QVariantAnimation::Direction::Forward); connect(mAnimators[i], QOverload<const QVariant &>::of(&QVariantAnimation::valueChanged), this, [this, i](const QVariant &v) { mLevels[i] = v.toFloat(); repaint(); }); mAnimators[i]->start(); } else { mLevels[i] = value; repaint(); } } double BaseLiquidEqualizerWidget::getBand(int i) { return mActualLevels[i]; } void BaseLiquidEqualizerWidget::setBands(const QVector<double> &vector, bool animate) { int availableBandCount = (vector.count() < mBandsNum) ? vector.count() - 1 : mBandsNum; for (int i = 0; i < availableBandCount; i++) { setBand(i, vector.at(i), animate); } repaint(); } QVector<double> BaseLiquidEqualizerWidget::getBands() { QVector<double> vector; for (int i = 0; i < mBandsNum; i++) { vector.push_back(mActualLevels[i]); } return vector; }
12,332
C++
.cpp
390
27.566667
179
0.693864
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,134
LiquidCompanderWidget.cpp
timschneeb_LiquidEqualizerWidget/src/LiquidCompanderWidget.cpp
/* * This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. ThePBone <tim.schneeberger(at)outlook.de> (c) 2020 Design inspired by https://github.com/vipersaudio/viper4android_fx */ #include "LiquidCompanderWidget.h" #include "../3rdparty/JdspImpResToolbox.h" LiquidCompanderWidget::LiquidCompanderWidget(QWidget *parent) : BaseLiquidEqualizerWidget(7, 40, 20000, -1.2, 1.2, 128, 0.2, parent){} LiquidCompanderWidget::~LiquidCompanderWidget(){} void LiquidCompanderWidget::computeCurve(const double *freqs, double *gains, int resolution, double *dispFreq, float *response) { JdspImpResToolbox::ComputeCompResponse(freqs, gains, resolution, dispFreq, response); } QVector<double> LiquidCompanderWidget::getFrequencyPoints() { return QVector<double>({ 95.0f, 200.0f, 400.0f, 800.0f, 1600.0f, 3400.0f, 7500.0f }); }
1,437
C++
.cpp
27
49.703704
134
0.766429
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,135
LiquidEqualizerWidget.cpp
timschneeb_LiquidEqualizerWidget/src/LiquidEqualizerWidget.cpp
/* * This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. ThePBone <tim.schneeberger(at)outlook.de> (c) 2020 Design inspired by https://github.com/vipersaudio/viper4android_fx */ #include "LiquidEqualizerWidget.h" #include "../3rdparty/JdspImpResToolbox.h" LiquidEqualizerWidget::LiquidEqualizerWidget(QWidget *parent) : BaseLiquidEqualizerWidget(15, 21, 24000, -12.0, 12.0, 128, 3, parent){} LiquidEqualizerWidget::~LiquidEqualizerWidget(){} void LiquidEqualizerWidget::computeCurve(const double *freqs, double *gains, int resolution, double *dispFreq, float *response) { JdspImpResToolbox::ComputeEqResponse(freqs, gains, 1, resolution, dispFreq, response); } QVector<double> LiquidEqualizerWidget::getFrequencyPoints() { return QVector<double>({ 25.0f, 40.0f, 63.0f, 100.0f, 160.0f, 250.0f, 400.0f, 630.0f, 1000.0f, 1600.0f, 2500.0f, 4000.0f, 6300.0f, 10000.0f, 16000.0f }); }
1,508
C++
.cpp
27
52.333333
157
0.760027
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,136
JdspImpResToolbox.h
timschneeb_LiquidEqualizerWidget/3rdparty/JdspImpResToolbox.h
#ifndef JDSPIMPRESTOOLBOX_H #define JDSPIMPRESTOOLBOX_H namespace JdspImpResToolbox { int ComputeEqResponse(const double* jfreq, double* jgain, int interpolationMode, int queryPts, double* dispFreq, float* response); int ComputeCompResponse(const double* jfreq, const double* jgain, int queryPts, const double* dispFreq, float* response); } #endif // JDSPIMPRESTOOLBOX_H
381
C++
.h
7
52
134
0.803763
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,137
interpolation.h
timschneeb_LiquidEqualizerWidget/3rdparty/interpolation.h
namespace Interpolation { typedef struct { double* x_; double* y_; double* dydx_; int n; } cubic_hermite; typedef struct { cubic_hermite cb; double *s; } ierper; void initIerper(ierper *intp, int n); void freeIerper(ierper *intp); double getValueAt(cubic_hermite *cuher, double x); double getDerivativeAt(cubic_hermite *cuher, double x); void pchip(ierper *intp, double * x, double * y, int n, int left_endpoint_derivative, int right_endpoint_derivative); void makima(ierper *intp, double * x, double * y, int n, int left_endpoint_derivative, int right_endpoint_derivative); }
673
C++
.h
20
27.85
122
0.656968
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,138
BaseLiquidEqualizerWidget.h
timschneeb_LiquidEqualizerWidget/src/BaseLiquidEqualizerWidget.h
/* * This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. * * ThePBone <tim.schneeberger(at)outlook.de> (c) 2020 */ #ifndef QBASEFLUENTEQUALIZERWIDGET_H #define QBASEFLUENTEQUALIZERWIDGET_H #include <QPainter> #include <QPaintEvent> #include <QTimer> #include <QVariantAnimation> #include <QVector> #include <QWidget> #include <cmath> class BaseLiquidEqualizerWidget : public QWidget { Q_OBJECT Q_PROPERTY(bool gridVisible READ getGridVisible WRITE setGridVisible NOTIFY redrawRequired) Q_PROPERTY(bool alwaysDrawHandles READ getAlwaysDrawHandles WRITE setAlwaysDrawHandles NOTIFY redrawRequired) Q_PROPERTY(QColor accentColor READ getAccentColor WRITE setAccentColor NOTIFY redrawRequired) Q_PROPERTY(int animationDuration READ getAnimationDuration WRITE setAnimationDuration NOTIFY redrawRequired) public: ~BaseLiquidEqualizerWidget(); void setBand(int i, double value, bool animate = true, bool manual = false); double getBand(int i); void setBands(const QVector<double> &vector, bool animate = true); QVector<double> getBands(); bool getGridVisible() const; void setGridVisible(bool gridVisible); bool getAlwaysDrawHandles() const; void setAlwaysDrawHandles(bool alwaysDrawHandles); QColor getAccentColor() const; void setAccentColor(const QColor &accentColor); int getAnimationDuration() const; void setAnimationDuration(int animationDuration); int resolution() const; int bandsNum() const; signals: void mouseReleased(); void redrawRequired(); void bandsUpdated(); void cancelAnimations(); protected: BaseLiquidEqualizerWidget(int bandsNum, int minFreq, int maxFreq, double minDb, double maxDb, int resolution, double horizLineInterval, QWidget *parent = nullptr); virtual void computeCurve(const double* freqs, double* gains, int resolution, double* dispFreq, float* response) = 0; virtual QVector<double> getFrequencyPoints() = 0; void paintEvent(QPaintEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; void keyPressEvent(QKeyEvent *event) override; void keyReleaseEvent(QKeyEvent *event) override; void mouseDoubleClickEvent(QMouseEvent *event) override; private: QList<QVariantAnimation*> mAnimators; QPainter mGridLines; QPainter mControlBarText; QPainter mFrequencyResponseBg; QPainter mFrequencyResponseHighlight; QPainter mControlBarKnob; double *mLevels = nullptr; double *mActualLevels = nullptr; int mHeight = 0; int mWidth = 0; int mSelectedBand = 0; bool mManual = false; bool mHoldDown = false; int mKey_CurrentIndex; QPoint mKey_LastMousePos; bool mGridVisible = true; bool mAlwaysDrawHandles = false; QColor mAccentColor = QColor(98, 0, 238, 255); int mAnimationDuration = 500; int mBandsNum; const int mResolution; int mMinFreq; int mMaxFreq; double mMinDb; double mMaxDb; double mHorizLineInterval; QVector<double> mFreqs; double *dispFreq; float *response; float *precomputeCurveXAxis; float *precomputeFreqAxis = new float[64]; inline double reverseProjectX(double position) { double minimumPosition = log(mMinFreq); double maximumPosition = log(mMaxFreq); return exp(position * (maximumPosition - minimumPosition) + minimumPosition); } inline float projectX(double frequency) { double position = log(frequency); double minimumPosition = log(mMinFreq); double maximumPosition = log(mMaxFreq); return (position - minimumPosition) / (maximumPosition - minimumPosition); } inline float projectY(float dB) { float pos = (dB - mMinDb) / (mMaxDb - mMinDb); return 1.0f - pos; } inline float reverseProjectY(float pos) { float i = abs(pos - 1); return -i * mMinDb + i * mMaxDb + mMinDb; } inline float lin2dB(double rho) { if (rho != 0.0) { return log(rho) / log(10.0) * 20; } else { return -99.9f; } } inline int getIndexUnderMouse(int pos_x) { int idx = 0; double best = 1e8; for (int i = 0; i < mBandsNum; i++) { double freq = mFreqs[i]; double cx = projectX(freq) * mWidth; double distance = abs(cx - pos_x); if (distance < best) { idx = i; best = distance; } } return idx; } }; #endif // QBASEFLUENTEQUALIZERWIDGET_H
5,474
C++
.h
151
32.344371
167
0.687193
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,139
LiquidCompanderWidget.h
timschneeb_LiquidEqualizerWidget/src/LiquidCompanderWidget.h
/* * This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. * * ThePBone <tim.schneeberger(at)outlook.de> (c) 2020 */ #ifndef QFLUENTCOMPANDERWIDGET_H #define QFLUENTCOMPANDERWIDGET_H #include "BaseLiquidEqualizerWidget.h" class LiquidCompanderWidget : public BaseLiquidEqualizerWidget { Q_OBJECT public: LiquidCompanderWidget(QWidget *parent = nullptr); ~LiquidCompanderWidget(); protected: virtual void computeCurve(const double* freqs, double* gains, int resolution, double* dispFreq, float* response); virtual QVector<double> getFrequencyPoints(); }; #endif // QFLUENTCOMPANDERWIDGET_H
1,213
C++
.h
28
40
117
0.776551
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,140
LiquidEqualizerWidget.h
timschneeb_LiquidEqualizerWidget/src/LiquidEqualizerWidget.h
/* * This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. * * ThePBone <tim.schneeberger(at)outlook.de> (c) 2020 */ #ifndef QFLUENTEQUALIZERWIDGET_H #define QFLUENTEQUALIZERWIDGET_H #include "BaseLiquidEqualizerWidget.h" class LiquidEqualizerWidget : public BaseLiquidEqualizerWidget { Q_OBJECT public: LiquidEqualizerWidget(QWidget *parent = nullptr); ~LiquidEqualizerWidget(); protected: virtual void computeCurve(const double* freqs, double* gains, int resolution, double* dispFreq, float* response); virtual QVector<double> getFrequencyPoints(); }; #endif // QFLUENTEQUALIZERWIDGET_H
1,213
C++
.h
28
40
117
0.776551
timschneeb/LiquidEqualizerWidget
39
10
0
GPL-3.0
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false