From e0aa3e87e2e768219d2aed8adee27747276fec37 Mon Sep 17 00:00:00 2001
From: Simon Bjurek <simbj106@student.liu.se>
Date: Thu, 13 Feb 2025 16:13:11 +0100
Subject: [PATCH] added SlackTime MaxFanOut and a Hybrid Scheduler, also
 started on example with ldlt matrix inverse.

---
 b_asic/core_operations.py        |  31 ++++++++
 b_asic/core_schedulers.py        |  80 ++++++++++++++++++++-
 b_asic/gui_utils/about_window.py |   2 +-
 b_asic/scheduler.py              |   9 +++
 docs_sphinx/conf.py              |   2 +-
 examples/ldlt_matrix_inverse.py  | 120 +++++++++++++++++++++++++++++++
 6 files changed, 241 insertions(+), 3 deletions(-)
 create mode 100644 examples/ldlt_matrix_inverse.py

diff --git a/b_asic/core_operations.py b/b_asic/core_operations.py
index 3a1474cc..0a321f90 100644
--- a/b_asic/core_operations.py
+++ b/b_asic/core_operations.py
@@ -77,6 +77,37 @@ class Constant(AbstractOperation):
     def __str__(self) -> str:
         return f"{self.value}"
 
+    def get_plot_coordinates(
+        self,
+    ) -> tuple[tuple[tuple[float, float], ...], tuple[tuple[float, float], ...]]:
+        # Doc-string inherited
+        return (
+            (
+                (-0.5, 0),
+                (-0.5, 1),
+                (-0.25, 1),
+                (0, 0.5),
+                (-0.25, 0),
+                (-0.5, 0),
+            ),
+            (
+                (-0.5, 0),
+                (-0.5, 1),
+                (-0.25, 1),
+                (0, 0.5),
+                (-0.25, 0),
+                (-0.5, 0),
+            ),
+        )
+
+    def get_input_coordinates(self) -> tuple[tuple[float, float], ...]:
+        # doc-string inherited
+        return tuple()
+
+    def get_output_coordinates(self) -> tuple[tuple[float, float], ...]:
+        # doc-string inherited
+        return ((0, 0.5),)
+
 
 class Addition(AbstractOperation):
     """
diff --git a/b_asic/core_schedulers.py b/b_asic/core_schedulers.py
index 05bcc3f4..1b5b4f18 100644
--- a/b_asic/core_schedulers.py
+++ b/b_asic/core_schedulers.py
@@ -119,6 +119,84 @@ class EarliestDeadlineScheduler(ListScheduler):
 
     @staticmethod
     def _get_sorted_operations(schedule: "Schedule") -> list["GraphID"]:
-        schedule_copy = copy.deepcopy(schedule)
+        schedule_copy = copy.copy(schedule)
         ALAPScheduler().apply_scheduling(schedule_copy)
+
+        deadlines = {}
+        for op_id, start_time in schedule_copy.start_times.items():
+            deadlines[op_id] = start_time + schedule.sfg.find_by_id(op_id).latency
+
+        return sorted(deadlines, key=deadlines.get)
+
+
+class LeastSlackTimeScheduler(ListScheduler):
+    """Scheduler that implements the least slack time first algorithm."""
+
+    @staticmethod
+    def _get_sorted_operations(schedule: "Schedule") -> list["GraphID"]:
+        schedule_copy = copy.copy(schedule)
+        ALAPScheduler().apply_scheduling(schedule_copy)
+
         return sorted(schedule_copy.start_times, key=schedule_copy.start_times.get)
+
+
+class MaxFanOutScheduler(ListScheduler):
+    """Scheduler that implements the maximum fan-out algorithm."""
+
+    @staticmethod
+    def _get_sorted_operations(schedule: "Schedule") -> list["GraphID"]:
+        schedule_copy = copy.copy(schedule)
+        ALAPScheduler().apply_scheduling(schedule_copy)
+
+        fan_outs = {}
+        for op_id, start_time in schedule_copy.start_times.items():
+            fan_outs[op_id] = len(schedule.sfg.find_by_id(op_id).output_signals)
+
+        return sorted(fan_outs, key=fan_outs.get, reverse=True)
+
+
+class HybridScheduler(ListScheduler):
+    """Scheduler that implements a hybrid algorithm. Will receive a new name once finalized."""
+
+    @staticmethod
+    def _get_sorted_operations(schedule: "Schedule") -> list["GraphID"]:
+        # sort least-slack and then resort ties according to max-fan-out
+        schedule_copy = copy.copy(schedule)
+        ALAPScheduler().apply_scheduling(schedule_copy)
+
+        sorted_items = sorted(
+            schedule_copy.start_times.items(), key=lambda item: item[1]
+        )
+
+        fan_out_sorted_items = []
+
+        last_value = sorted_items[0][0]
+        current_group = []
+        for key, value in sorted_items:
+
+            if value != last_value:
+                # the group is completed, sort it internally
+                sorted_group = sorted(
+                    current_group,
+                    key=lambda pair: len(
+                        schedule.sfg.find_by_id(pair[0]).output_signals
+                    ),
+                    reverse=True,
+                )
+                fan_out_sorted_items += sorted_group
+                current_group = []
+
+            current_group.append((key, value))
+
+            last_value = value
+
+        sorted_group = sorted(
+            current_group,
+            key=lambda pair: len(schedule.sfg.find_by_id(pair[0]).output_signals),
+            reverse=True,
+        )
+        fan_out_sorted_items += sorted_group
+
+        sorted_op_list = [pair[0] for pair in fan_out_sorted_items]
+
+        return sorted_op_list
diff --git a/b_asic/gui_utils/about_window.py b/b_asic/gui_utils/about_window.py
index d702a459..08bc42e2 100644
--- a/b_asic/gui_utils/about_window.py
+++ b/b_asic/gui_utils/about_window.py
@@ -59,7 +59,7 @@ class AboutWindow(QDialog):
             " href=\"https://gitlab.liu.se/da/B-ASIC/-/blob/master/LICENSE\">"
             "MIT-license</a>"
             " and any extension to the program should follow that same"
-            f" license.\n\n*Version: {__version__}*\n\nCopyright 2020-2023,"
+            f" license.\n\n*Version: {__version__}*\n\nCopyright 2020-2025,"
             " Oscar Gustafsson et al."
         )
         label1.setTextFormat(Qt.MarkdownText)
diff --git a/b_asic/scheduler.py b/b_asic/scheduler.py
index cc472945..22052b60 100644
--- a/b_asic/scheduler.py
+++ b/b_asic/scheduler.py
@@ -45,6 +45,15 @@ class Scheduler(ABC):
 
 class ListScheduler(Scheduler, ABC):
     def __init__(self, max_resources: Optional[dict[TypeName, int]] = None) -> None:
+        if max_resources:
+            if not isinstance(max_resources, dict):
+                raise ValueError("max_resources must be a dictionary.")
+            for key, value in max_resources.items():
+                if not isinstance(key, str):
+                    raise ValueError("max_resources key must be a valid type_name.")
+                if not isinstance(value, int):
+                    raise ValueError("max_resources value must be an integer.")
+
         if max_resources:
             self._max_resources = max_resources
         else:
diff --git a/docs_sphinx/conf.py b/docs_sphinx/conf.py
index b56dcfbe..ed0e0e06 100644
--- a/docs_sphinx/conf.py
+++ b/docs_sphinx/conf.py
@@ -9,7 +9,7 @@
 import shutil
 
 project = 'B-ASIC'
-copyright = '2020-2023, Oscar Gustafsson et al'
+copyright = '2020-2025, Oscar Gustafsson et al'
 author = 'Oscar Gustafsson et al'
 html_logo = "../logos/logo_tiny.png"
 
diff --git a/examples/ldlt_matrix_inverse.py b/examples/ldlt_matrix_inverse.py
new file mode 100644
index 00000000..b859fec2
--- /dev/null
+++ b/examples/ldlt_matrix_inverse.py
@@ -0,0 +1,120 @@
+"""
+=========================================
+LDLT Matrix Inversion Algorithm
+=========================================
+
+"""
+
+from b_asic.architecture import Architecture, Memory, ProcessingElement
+from b_asic.core_operations import MADS, Constant, Reciprocal
+from b_asic.core_schedulers import (
+    ALAPScheduler,
+    ASAPScheduler,
+    EarliestDeadlineScheduler,
+    HybridScheduler,
+    LeastSlackTimeScheduler,
+    MaxFanOutScheduler,
+)
+from b_asic.schedule import Schedule
+from b_asic.sfg_generators import ldlt_matrix_inverse
+
+sfg = ldlt_matrix_inverse(N=3, is_complex=False)
+
+# %%
+# The SFG is
+sfg
+
+# %%
+# Set latencies and execution times.
+sfg.set_latency_of_type(Constant.type_name(), 0)
+sfg.set_latency_of_type(MADS.type_name(), 3)
+sfg.set_latency_of_type(Reciprocal.type_name(), 2)
+sfg.set_execution_time_of_type(Constant.type_name(), 0)
+sfg.set_execution_time_of_type(MADS.type_name(), 1)
+sfg.set_execution_time_of_type(Reciprocal.type_name(), 1)
+
+# %%
+# Create an ASAP schedule.
+schedule = Schedule(sfg, scheduler=ASAPScheduler())
+print("Scheduling time:", schedule.schedule_time)
+# schedule.show()
+
+# %%
+# Create an ALAP schedule.
+schedule = Schedule(sfg, scheduler=ALAPScheduler())
+print("Scheduling time:", schedule.schedule_time)
+# schedule.show()
+
+# %%
+# Create an EarliestDeadline schedule that satisfies the resource constraints.
+resources = {MADS.type_name(): 1, Reciprocal.type_name(): 1}
+schedule = Schedule(sfg, scheduler=EarliestDeadlineScheduler(resources))
+print("Scheduling time:", schedule.schedule_time)
+# schedule.show()
+
+# %%
+# Create a LeastSlackTime schedule that satisfies the resource constraints.
+schedule = Schedule(sfg, scheduler=LeastSlackTimeScheduler(resources))
+print("Scheduling time:", schedule.schedule_time)
+# schedule.show()
+
+# %%
+# Create a MaxFanOutScheduler schedule that satisfies the resource constraints.
+schedule = Schedule(sfg, scheduler=MaxFanOutScheduler(resources))
+print("Scheduling time:", schedule.schedule_time)
+# schedule.show()
+
+# %%
+# Create a HybridScheduler schedule that satisfies the resource constraints.
+schedule = Schedule(sfg, scheduler=HybridScheduler(resources))
+print("Scheduling time:", schedule.schedule_time)
+# schedule.edit()
+
+# %%
+operations = schedule.get_operations()
+mads = operations.get_by_type_name("mads")
+mads.show(title="MADS executions")
+reciprocals = operations.get_by_type_name("rec")
+reciprocals.show(title="Reciprocal executions")
+consts = operations.get_by_type_name("c")
+consts.show(title="Const executions")
+inputs = operations.get_by_type_name("in")
+inputs.show(title="Input executions")
+outputs = operations.get_by_type_name("out")
+outputs.show(title="Output executions")
+
+mads_pe = ProcessingElement(mads, entity_name="mad")
+reciprocal_pe = ProcessingElement(reciprocals, entity_name="rec")
+
+const_pe = ProcessingElement(consts, entity_name="c")
+
+pe_in = ProcessingElement(inputs, entity_name='input')
+pe_out = ProcessingElement(outputs, entity_name='output')
+
+mem_vars = schedule.get_memory_variables()
+mem_vars.show(title="All memory variables")
+direct, mem_vars = mem_vars.split_on_length()
+mem_vars.show(title="Non-zero time memory variables")
+mem_vars_set = mem_vars.split_on_ports(read_ports=1, write_ports=1, total_ports=2)
+
+# %%
+memories = []
+for i, mem in enumerate(mem_vars_set):
+    memory = Memory(mem, memory_type="RAM", entity_name=f"memory{i}")
+    memories.append(memory)
+    mem.show(title=f"{memory.entity_name}")
+    memory.assign("left_edge")
+    memory.show_content(title=f"Assigned {memory.entity_name}")
+
+direct.show(title="Direct interconnects")
+
+# %%
+arch = Architecture(
+    {mads_pe, reciprocal_pe, const_pe, pe_in, pe_out},
+    memories,
+    direct_interconnects=direct,
+)
+
+# %%
+arch
+# schedule.edit()
-- 
GitLab