Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
SpikeGen.cpp 1.22 KiB
/********************************************************************************
 * Copyright (c) 2025 CEA-List
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 ********************************************************************************/

#include <memory>
#include <random>

#include "aidge/data/Spikegen.hpp"

namespace Aidge {
static Tensor rateConvert(const Tensor& tensor) {

    auto result = tensor.clone();

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<float> dis(0.0f, 1.0f);

    // Clip values between 0 and 1, equivalent to torch.clamp(min=0, max=1)
    for (size_t i = 0; i < tensor.size(); i++) {
        auto val = tensor.get<float>(i);
        val = (val < 0.0f) ? 0.0f : ((val > 1.0f) ? 1.0f : val);
        auto randomValue = dis(gen);
        result.set(i, randomValue < val ? 1.0f : 0.0f);
    }

    return result;
}

Tensor spikegenRate(std::shared_ptr<Tensor> tensor, std::uint32_t numSteps) {
    auto newTensor = tensor->repeat(numSteps);
    return rateConvert(newTensor);
}
}  // namespace Aidge