YJack0000 / SimEvo

A Customizable Python Framework written in C++ for Simulating Dynamic Evolutionary Phenomena.
https://pypi.org/project/simevopy/
MIT License
10 stars 0 forks source link

Make `simulationIteration` directly return results metric of result #8

Open YJack0000 opened 3 months ago

YJack0000 commented 3 months ago

I want to make

void simulateIteration(
        int, std::function<void(const Environment&)> on_each_iteration = nullptr);

to

std::map<std::string, std::any> simulateIteration(
        int, std::function<void(const Environment&)> on_each_iteration = nullptr);

And might cast the result into an python dictionary if its possible.

Tried this but not working

py::object any_to_pyobject(const std::any& operand) {
    std::cout << "Casting std::any to Python object. Actual type: " << operand.type().name()
              << std::endl;
    if (std::type_index(operand.type()) ==
        std::type_index(typeid(std::vector<std::shared_ptr<Organism>>))) {
        return py::cast(std::any_cast<std::vector<std::shared_ptr<Organism>>>(operand));
    } else if (std::type_index(operand.type()) ==
               std::type_index(typeid(std::vector<std::shared_ptr<Food>>))) {
        return py::cast(std::any_cast<std::vector<std::shared_ptr<Food>>>(operand));
    } else if (std::type_index(operand.type()) == std::type_index(typeid(std::vector<int>))) {
        return py::cast(std::any_cast<std::vector<int>>(operand));
    } else {
        std::cout << "Failed to cast std::any. Actual type: " << operand.type().name() << std::endl;
        return py::none();
        // throw std::runtime_error("Unsupported type in std::any");
    }
}

std::map<std::string, py::object> convert_any_map_to_py_map(
    const std::map<std::string, std::any>& any_map) {
    std::map<std::string, py::object> py_map;
    for (const auto& [key, value] : any_map) {
        py_map[key] = any_to_pyobject(value);
    }
    return py_map;
}
.def(
            "simulate_iteration",
            [](Environment& env, int iterations, py::function on_each_iteration) {
                auto result = env.simulateIteration(
                    iterations,
                    [&on_each_iteration](const Environment& env) {  // Capture 'env' as const
                        if (!on_each_iteration.is_none()) {
                            on_each_iteration(py::cast(env));
                        }
                    });
                return convert_any_map_to_py_map(result);
            },
YJack0000 commented 1 month ago

@MarkLai0317 Do you think it is a proper way to this api? Or there is better way to make user accesible to the data in simulation

I currently use callback on the simulationIterations()

MarkLai0317 commented 1 month ago

Can you provide the context of this API, such as the requirement of this api and what role does it play? thank you