From 68b533687b5f5deb0bce5d1a8f57976ed2489be3 Mon Sep 17 00:00:00 2001
From: Olivier BICHLER <olivier.bichler@cea.fr>
Date: Thu, 29 Aug 2024 14:54:21 +0200
Subject: [PATCH] Added adaptToBackend() recipe

---
 include/aidge/recipes/Recipes.hpp |  7 +++++++
 src/recipes/AdaptToBackend.cpp    | 35 +++++++++++++++++++++++++++++++
 2 files changed, 42 insertions(+)
 create mode 100644 src/recipes/AdaptToBackend.cpp

diff --git a/include/aidge/recipes/Recipes.hpp b/include/aidge/recipes/Recipes.hpp
index 205c9f966..6cdd89f2e 100644
--- a/include/aidge/recipes/Recipes.hpp
+++ b/include/aidge/recipes/Recipes.hpp
@@ -147,6 +147,13 @@ size_t fuseToMetaOps(std::shared_ptr<GraphView> graph, const std::string& query,
 */
 size_t convToMatMul(std::shared_ptr<GraphView> graph);
 
+/**
+ * @brief Adapt a graph to the available kernels of a backend.
+ * 
+ * @param graph Graph to manipulate
+ */
+void adaptToBackend(std::shared_ptr<GraphView> graph);
+
 } // namespace Aidge
 
 #endif /* AIDGE_CORE_UTILS_RECIPES_H_ */
diff --git a/src/recipes/AdaptToBackend.cpp b/src/recipes/AdaptToBackend.cpp
new file mode 100644
index 000000000..b1e62c02b
--- /dev/null
+++ b/src/recipes/AdaptToBackend.cpp
@@ -0,0 +1,35 @@
+/********************************************************************************
+ * Copyright (c) 2023 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 "aidge/graph/Node.hpp"
+#include "aidge/graph/GraphView.hpp"
+#include "aidge/graph/Matching.hpp"
+#include "aidge/operator/MetaOperator.hpp"
+#include "aidge/recipes/Recipes.hpp"
+
+void Aidge::adaptToBackend(std::shared_ptr<GraphView> graphView) {
+    for (auto node : graphView->getNodes()) {
+        auto impl = node->getOperator()->getImpl();
+        auto adaptedNode = impl->getBestAdaptation(impl->getRequiredSpec());
+
+        if (adaptedNode == nullptr) {
+            Log::notice("Unable to adapt node {} (of type {}) to backend {}",
+                node->name(), node->type(), impl->backend());
+        }
+        else if (!node->getOperator()->isAtomic()) {
+            Log::info("Adapted node {} (of type {}) to backend {}",
+                node->name(), node->type(), impl->backend());
+            AIDGE_ASSERT(GraphView::replace({node}, {adaptedNode}), "Unable to replace adapted node!");
+        }
+    }
+}
-- 
GitLab