Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stateful blocks #16

Draft
wants to merge 6 commits into
base: jeff/iteration-and-functions
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion blocks/flojoy/logic/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


def clock():
return rx.interval(1 / 60)
return rx.interval(1)
14 changes: 14 additions & 0 deletions blocks/flojoy/math/fibs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from captain.lib.block import FlojoyBlock


class fibs(FlojoyBlock):
def setup(self):
self.prev = 0
self.cur = 1

def on_next(self, x=None):
temp = self.cur
self.cur += self.prev
self.prev = temp

return temp
25 changes: 14 additions & 11 deletions captain/controllers/reactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
from reactivex.abc import DisposableBase, SchedulerBase
from reactivex.scheduler import ThreadPoolScheduler

from captain.lib.block_import import FlojoyBlock, import_blocks
from captain.lib.block import FlojoyBlock
from captain.lib.block_import import import_blocks
from captain.logging import logger
from captain.types.builtins import Ignore
from captain.types.events import FlowControlEvent
from captain.types.flowchart import BlockID, BlockType, FCBlock, FlowChart
from captain.types.flowchart import BlockID, FCBlock, FlowChart

BLOCKS_DIR = "blocks"

Expand Down Expand Up @@ -87,6 +88,7 @@ class Flow:

flowchart: FlowChart
control_subjects: dict[BlockID, Subject]
blocks: dict[BlockID, FlojoyBlock]

def __init__(
self,
Expand All @@ -101,17 +103,20 @@ def __init__(
self.on_publish = publish_fn
self.start_obs = start_obs
self.publish_scheduler = publish_scheduler
self.blocks = {}

funcs = import_blocks(BLOCKS_DIR)
block_imports = import_blocks(BLOCKS_DIR)

for block in flowchart.blocks:
if funcs[block.block_type].is_ui_input:
block_import = block_imports[block.block_type]
if block_import.is_ui_input:
logger.info(
f"Creating a Subject for {block.block_type}({block.id}) to react to changes."
)
self.control_subjects[block.id] = Subject()
self.blocks[block.id] = block_import.make_instance()

self.subscriptions = self.connect(funcs, publish_sample_time)
self.subscriptions = self.connect(publish_sample_time)

@staticmethod
def from_json(data: str, publish_fn: Callable, start_obs: Observable):
Expand All @@ -125,9 +130,7 @@ def destroy(self):
for sub in self.subscriptions:
sub.dispose()

def connect(
self, block_funcs: Mapping[BlockType, FlojoyBlock], publish_sample_time: float
):
def connect(self, publish_sample_time: float):
"""Connects all of block functions in a flow chart using RxPY.

To run the flow chart, push an item to the start observable.
Expand Down Expand Up @@ -161,15 +164,13 @@ def connect(
on_error=lambda e: logger.error(e),
)

fj_block = block_funcs[block.block_type]

# A lot of the lambdas being passed created are partially applied,
# this is because Python has weird late binding with lambdas in a loop.
# Instead of using captured values, we need to pass it as a parameter
# so that it binds to the value and not the name.
#
def run_block(blk: FCBlock, kwargs: dict[str, Any]):
fn = block_funcs[blk.block_type]
fn = self.blocks[blk.id]
logger.info(f"Running block {blk.block_type} ({blk.id})")
res = fn(**kwargs)
match res:
Expand Down Expand Up @@ -207,6 +208,8 @@ def make_block_fn_props(
) # for logging purpose only
subscriptions.append(disposable)

fj_block = self.blocks[block.id]

# Split blocks that return multiple things into individual observables
if is_typeddict(fj_block.output):
output_observables = {
Expand Down
91 changes: 91 additions & 0 deletions captain/lib/block.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from typing import TypeVar, Callable, Any, Mapping, Type, TypeAlias
from abc import ABCMeta

T = TypeVar("T")
Name: TypeAlias = str


class FlojoyBlock(metaclass=ABCMeta):
__inputs: Mapping[Name, Type]
__output: Type
__hooks: list
__hook_index: int
on_next: Callable

def __init__(self, inputs: Mapping[Name, Type], output: Type):
self.__inputs = inputs
self.__output = output
self.__hooks = []
self.__hook_index = 0
self.setup()

def setup(self) -> None:
pass

@property
def name(self) -> str:
return self.__class__.__name__

@property
def inputs(self) -> Mapping[Name, Type]:
return self.__inputs

@property
def output(self) -> Type:
return self.__output

@property
def description(self) -> str | None:
return self.__doc__

def __call__(self, *args, **kwargs) -> Any:
self.__hook_index = 0
return self.on_next(*args, **kwargs)

def publish(self):
pass

def memoize(self, func: Callable[[], T], deps: list[Any]) -> T:
# First time calling the hook
if self.__hook_index >= len(self.__hooks):
val = func()
self.__hooks.append((val, deps))
self.__hook_index += 1
return val

memoized_val, prev_deps = self.__hooks[self.__hook_index]

if len(prev_deps) != len(deps):
raise ValueError("Number of dependencies for hook should not change")

if all(a == b for a, b in zip(deps, prev_deps)):
val = memoized_val
else:
# deps changed, recompute value
val = func()
self.__hooks[self.__hook_index] = (val, deps)

self.__hook_index += 1
return val

def effect(self, func: Callable[[], None], deps: list[Any]) -> None:
self.memoize(func, deps)


class LambdaBlock(FlojoyBlock):
__func: Callable

def __init__(self, func: Callable, inputs: Mapping[Name, Type], output: Type):
self.__func = func
super().__init__(inputs, output)

@property
def name(self):
return self.__func.__name__

@property
def description(self):
return self.__func.__doc__

def on_next(self, *args, **kwargs):
return self.__func(*args, **kwargs)
47 changes: 37 additions & 10 deletions captain/lib/block_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,34 @@
from dataclasses import dataclass

from captain.types.flowchart import BlockType
from captain.logging import logger
from captain.lib.block import FlojoyBlock, LambdaBlock

Name: TypeAlias = str

ClassBlock: TypeAlias = type[FlojoyBlock]
FunctionBlock: TypeAlias = Callable


@dataclass
class FlojoyBlock:
func: Callable
class BlockImport:
block: ClassBlock | FunctionBlock
inputs: Mapping[Name, Type]
output: Type

def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)

@property
def is_ui_input(self) -> bool:
return getattr(self.func, "ui_input", False)
return getattr(self.block, "ui_input", False)

def make_instance(self) -> FlojoyBlock:
match self.block:
case type():
return self.block(self.inputs, self.output)
case _:
return LambdaBlock(self.block, self.inputs, self.output)


def import_blocks(blocks_dir: str) -> Mapping[BlockType, FlojoyBlock]:
def import_blocks(blocks_dir: str) -> Mapping[BlockType, BlockImport]:
folder_path = os.path.join(blocks_dir, "flojoy")
if not os.path.exists(folder_path):
raise ValueError(
Expand Down Expand Up @@ -54,12 +63,30 @@ def import_blocks(blocks_dir: str) -> Mapping[BlockType, FlojoyBlock]:
raise ValueError(f"Could not get loader from {block_path}")

spec.loader.exec_module(module)
func = getattr(module, block_name)
block = getattr(module, block_name)

match block:
case type():
if not issubclass(block, FlojoyBlock):
raise ImportError(
f"Class block imported from {block_path} does not inherit from FlojoyBlock"
)
sig = inspect.signature(block.on_next)
# methods have a self parameter that needs to be ignored
parameters = [
param
for name, param in sig.parameters.items()
if name != "self"
]
sig = sig.replace(parameters=parameters)
case _:
sig = inspect.signature(block)

logger.info(sig)

sig = inspect.signature(func)
inputs = {name: param.annotation for name, param in sig.parameters.items()}
outputs = sig.return_annotation

functions[block_type] = FlojoyBlock(func, inputs, outputs)
functions[block_type] = BlockImport(block, inputs, outputs)

return functions
1 change: 1 addition & 0 deletions captain/types/flowchart.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"flojoy.math.arithmetic.subtract",
"flojoy.math.constant",
"flojoy.math.rand",
"flojoy.math.fibs",
"flojoy.logic.sequence",
"flojoy.logic.clock",
"flojoy.logic.conditional",
Expand Down
13 changes: 13 additions & 0 deletions src/renderer/src/components/blocks/flow/FibsBlock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Handle, Position } from 'reactflow';

const FibsBlock = () => {
return (
<>
<div className="border p-3">Fibs</div>
<Handle type="target" position={Position.Left} id="x" />
<Handle type="source" position={Position.Right} id="value" />
</>
);
};

export default FibsBlock;
1 change: 1 addition & 0 deletions src/renderer/src/components/flow/BlocksLibrary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const BlocksLibrary = () => {
<BlockCard name="Clock" desc="tick tock" block_type="flojoy.logic.clock" />
<BlockCard name="Constant" desc="2" block_type="flojoy.math.constant" />
<BlockCard name="Rand" desc="?" block_type="flojoy.math.rand" />
<BlockCard name="Fibs" desc="1 1 2 3 5 8 13 ..." block_type="flojoy.math.fibs" />
<BlockCard
name="Conditional"
desc="if ... then ... else"
Expand Down
2 changes: 2 additions & 0 deletions src/renderer/src/configs/flowchart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ import ToggleBlock from '@/components/blocks/flow/ToggleBlock';
import ClockBlock from '@/components/blocks/flow/ClockBlock';
import FunctionDefinitionBlock from '@/components/blocks/flow/FunctionDefinitionBlock';
import FunctionInstanceBlock from '@/components/blocks/flow/FunctionInstanceBlock';
import FibsBlock from '@/components/blocks/flow/FibsBlock';

export const nodeTypes = {
'flojoy.control.slider': SliderBlock,
'flojoy.control.toggle': ToggleBlock,
'flojoy.math.arithmetic.add': AddBlock,
'flojoy.math.constant': ConstantBlock,
'flojoy.math.rand': RandBlock,
'flojoy.math.fibs': FibsBlock,
'flojoy.logic.conditional': ConditionalBlock,
'flojoy.logic.sequence': SequenceBlock,
'flojoy.logic.clock': ClockBlock,
Expand Down
1 change: 1 addition & 0 deletions src/renderer/src/types/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export type BlockType =
| 'flojoy.math.arithmetic.subtract'
| 'flojoy.math.constant'
| 'flojoy.math.rand'
| 'flojoy.math.fibs'
| 'flojoy.logic.sequence'
| 'flojoy.logic.clock'
| 'flojoy.logic.conditional'
Expand Down