Improve Max Function

🛠️ 1.1.3
This topic is closed (tagged ).
11 days ago

If the output included also a pin for index of the min and index of the max this could directly be used to make a selection

10 days ago

Thanks to Deznek; I tried making this work but wasn't knowledgeable enough; Deznek showing me the proper way to do this. below is the MaxI block that will do what Max does but outputs the index of the max and min also. I use this to check which storage has lowest level and the Id lets me assign farms to produce that product.

from Core.categories import DefaultCategories
from Core.io import Input, Output
from Core.mafi import fix
from Mafi import Fix32
from Core.module import DefaultControllers, Module, ModuleStatus

Modification of File originally written by Nightinggale

Select Min & Max and output the index of each

Solved problem of selector being outside the block and next scan the min had changed and could not be matched up

class Runtime_MaxI(Module):
name = "MaxI"
description = "Outputs the min and max of all connected inputs (same as MAX), plus index of min and max. Expand input pins to add inputs, expand output pins to get indexes"
symbol = "MAXI"

inputs = [
    Input("A", "A"),
    Input("B", "B")
]

outputs = [
    Output("min", "Min"),
    Output("max", "Max")
]

width = 2

# 2 static + up to 6 extensions = 8 inputs total — covers the full range
# of the deprecated Max_2/3/4/6/8 set without further fragmentation.
input_extensions = 6

# Add option to get index
output_extensions = 2
output_extension_names = [
    ["indexmin", "Index Min"],
    ["indexmax", "Index Max"]
]

# Save-compat: each old fixed-arity proto maps to this one with the
# extension count that reproduces its pin layout.
deprecates = [
    ["Runtime_Max_2", 0],
    ["Runtime_Max_3", 1],
    ["Runtime_Max_4", 2],
    ["Runtime_Max_6", 4],
    ["Runtime_Max_8", 6]
]

categories = [ DefaultCategories.Arithmetic ]
controllers = [ DefaultControllers.Controller ]

def action(self):
    n = self.effective_input_count
    if n == 0:
        return
    # Seed both extremes with the first input — using the seed as the
    # default for unconnected inputs in the recursion lets later
    # disconnected pins skip past min/max updates entirely.
    seed = self.Input.get(self.effective_input_id(0), Fix32.Zero)
    self._scan(1, n, seed, seed, 0, 0)

def _scan(self, idx, n, current_min, current_max, index_min, index_max):
    if idx >= n:
        self.Output.set("min", current_min)
        self.Output.set("max", current_max)
        self.Output.set("indexmin", fix(index_min))
        self.Output.set("indexmax", fix(index_max))
        return
    v = self.Input.get(self.effective_input_id(idx), current_min)
    if v < current_min:
        current_min = v
        index_min = idx
    if v > current_max:
        current_max = v
        index_max = idx
    self._scan(idx + 1, n, current_min, current_max, index_min, index_max)
36 Showing 12 of 2
Log in to reply.