hio.base.hier.boxing

hio.base.hier.boxing Module

Provides hierarchical box work support

Module Contents

hio.base.hier.boxing.Rexlps

Example usage.

Usage:

if m := Rexlps.match("lapse >= 1.0"):
    lps, cmp = m.group("lps","cmp")

if not Rexlps.match("lapse >= 1.0"):
    return
hio.base.hier.boxing.Rexrlp

Example usage.

Usage:

if m := Rexrlp.match("relapse >= 1.0"):
    rel, cmp = m.group("rlp","cmp")

if rel Rexrlp.match("relapse >= 1.0"):
    return
hio.base.hier.boxing.Rexcnt

Example usage.

Usage:

if m := Rexcnt.match("count >= 1"):
    cnt, cmp = m.group("cnt","cmp")

if not Rexcnt.match("count >= 1"):
    return
class hio.base.hier.boxing.Box(*, name='box', hold=None, over=None, **kwa)

Bases: hio.base.tyming.Tymee

Box Class for hierarchical action framework (boxwork) instances. Box instance holds reference to in-memory data mine shared by all the boxes in a given boxwork as well as its executing Boxer. Box instance holds references (links) to its over box and its under boxes. Box instance holds the acts to be executed in their nabe.

Inherited Properties:

.tyme (float | None):  relative cycle time of associated Tymist which is
    provided by calling .tymth function wrapper closure which is obtained
    from Tymist.tymen().
    None means not assigned yet.
.tymth (Callable | None): function wrapper closure returned by
    Tymist.tymen() method. When .tymth is called it returns associated
    Tymist.tyme. Provides injected dependency on Tymist cycle tyme base.
    None means not assigned yet.

Attributes:

hold (Hold): data shared by boxwork
over (Box | None): this box's over box instance or None
unders (list[Box]): this box's under box instances or empty
                    zeroth entry is primary under
preacts (list[act]): predo (pre-conditions for endo) nabe acts
remarks (list[act]): remark re-endo mark subcontext acts (retained)
renacts (list[act]): rendo (re-endo) nabe acts  (retained)
enmarks (list[act]): enmark endo mark subcontext acts
enacts (list[act]):  endo nabe acts
reacts (list[act]): redo nabe acts
afacts (list[act]): afdo nabe acts
tracts (list[act]): godo nabe acts
exacts (list[act]): exdo nabe acts
rexacts (list[act]): rexdo (re-exdo) nabe acts  (retained)

Properties:

name (str): unique identifier of instance
pile (list[Box]): this box's pile of boxes generated by tracing .over up
                  and .unders[0] down if any. This is generated lazily.
                  To refresh call ._trace()
trail (str): human friendly represetion of pile as delimited string of
                box names from .pile. This is generated lazily.
                To refresh call ._trace()

Hidden:

_name (str): unique identifier of instance
_pile (list[Box] | None): pile of Boxes to which this box belongs.
                          None means not yet traced.
_spot (int | None): zero based offset into .pile of this box. This is
                    computed by ._trace
_trail (int | None): human friendly represetion of pile as delimited
                     string of box names from .pile.
                    This is computed by ._trace
_trace(): function to trace and update ._pile from .over and .unders[0]
          and update ._spot and ._trail
_next (Box | None): this box's next box if any lexically
property name

Property getter for ._name

Returns:

name (str): unique identifier of instance
property pile

Property getter for ._pile

Returns:

pile (list[Box]): this box's pile of boxes generated by tracing
                  .over up and .unders[0] down if any. This is
                  generated lazily to refresh call ._trace().
                  pile always includes self once traced.
property spot

Property getter for ._spot

Returns:

spot (int): zero based offset of this box into its pile of boxes
            generated by tracing .over up and .unders[0] down if any.
            This is generated lazily. To refresh call ._trace().
            Since pile always includes self, spot is always defined
            once traced.
property trail

Property getter for ._trail

Returns:

trail (str): human frieldly delimited string of box names from .pile.
            This is generated lazily. To refresh call ._trace().
            Since pile always includes self, trail is always defined
            once traced.
predo()

Action predo nabe

Returns:

met (bool): True if all preconditions met, True if no preconditions
            False if any precondition not met
rendo()

Action rendo (remark sub-nabe) nabe

endo()

Action endo (enmark sub-nabe) nabe

redo()

Action redo nabe

afdo()

Action afdo nabe

exdo()

Action exdo nabe

rexdo()

Action rexdo nabe

class hio.base.hier.boxing.Boxer(*, name='boxer', hold=None, fun=None, durable=False, **kwa)

Bases: hio.base.tyming.Tymee

Boxer Class that executes hierarchical action framework (boxwork) instances. Boxer instance holds reference to in-memory data mine shared by all its boxes and other Boxers in a given boxwork. Box instance holds a reference to its first (beginning) box. Box instance holds references to all its boxes in dict keyed by box name.

Inherited Properties: (Tymee):

.tyme (float | None):  relative cycle time of associated Tymist which is
    provided by calling .tymth function wrapper closure which is obtained
    from Tymist.tymen().
    None means not assigned yet.
.tymth (Callable | None): function wrapper closure returned by
    Tymist.tymen() method. When .tymth is called it returns associated
    Tymist.tyme. Provides injected dependency on Tymist cycle tyme base.
    None means not assigned yet.

Attributes:

hold (Hold): data shared by boxwork
fun (Callable): function to make boxwork
boxes (dict): all boxes mapping of (box name, box) pairs
first (Box | None):  beginning box
box (Box | None):  active box
durable (bool): default value for durable arg to .make

Properties:

name (str): unique identifier of instance

Hidden:

_name (str): unique identifier of instance
._tymth is injected function wrapper closure returned by .tymen() of
    associated Tymist instance that returns Tymist .tyme. when called.
property name

Property getter for ._name

Returns:

name (str): unique identifier of instance
wind(tymth)

Inject new tymist.tymth as new ._tymth. Changes tymist.tyme base. Override in subclasses to update any dependencies on a change in tymist.tymth base

Parameters:

tymth (Callable):  closure of injected tyme from tymist.tymen()
rewind(tymth=None)

Inject new tymist.tymth as new ._tymth when tymth is not None. Changes tymist.tyme base when not None. Winds bags in .mine. When tymth is None then use .tymth

Parameters:

tymth (Callable|None):  closure of injected tyme from tymist.tymen()
                        None if not yet injected
run(tock=0.0)

Run boxer hierarchical state machine (boxwork) as generator.

Parameters:

  tock (float|None): creation of generator supplies tock as parameter.
      The doist tyme is delegated through 'yield from' delegations
      to the eventual target yield at bottom of 'yield from' delegation
      chain.
      A tock value fed back to doist of None or 0.0 indicates to doist
      to run again ASAP (on next iteration of doist.do)


Returns::

    completion (bool): completion state boxwork.
                    True means completed successfully
                    False completed unsuccessfully

Note that “tyme” is not a parameter. The doist tyme is injected through the explicit yields below.

end()

Exit all active boxes.

endial()

Check for desire to end execution and return True otherwise False End condition if bag value at .hold[‘_boxer_boxername_end’].value == True

Returns:

end (bool): True means end condition satisfied
            False otherwise
predo(predos)

Evaluate preconditions for entry of boxes in endos in top down order

Parameters:

predos (list[Box]): boxes to be predo (checked for entry)
             given all their preacts are  satisfied

Returns:

met (bool): True means all preconditions are satisfied for predos
            False otherwise
        When no preconditions then returns True.
rendo(rendos)

Action re-mark (remarks) and re-endo (renacts) acts of boxes in .rendos in top down order. Boxes retained in hierarchical state. Re-enter box

Parameters:

rendos (list[Box]): boxes to be rendo (re-entered)
endo(endos)

Action e-mark (emacts) and endo (enacts) acts of boxes in .endos in top down order. Enter box.

Parameters:

endos (list[Box]): boxes to be endo (entered)
redo()

Action redo nabe for current .box.pile in top down order

exdo(exdos)

Action exacts of boxes in exdos in bottom up order. Exit box.

Parameters:

exdos (list[Box]): boxes to be exdo in bottom up order
rexdo(rexdos)

Action rexacts of boxes in rexdos (re-exdos) in bottom up order. Boxes retained in hierarchical state. Re-exit box.

Parameters:

rexdos (list[Box]): boxes to be re-exdo in bottom up order
resolve()

Resolve both over box names and goact dest box names into boxes for all boxes in .boxes

make(fun=None, *, durable=None, temp=False)

Make box work for this boxer from function fun Parameters:

fun (Callable|None):  employs be, go, do, on, at, be, verb functions with
    injected mods of boxwork state vars
    When None use self.fun
    Signature:

        fun(H: (Hold),
            bx: (Callable),
            go: (Callable),
            do: (Callable),
            on: (Callable),
            at: (Callable),
            be: (Callable))
durable (None|bool):  True means ensure .hold has opened subery
                      False do nothing
                      None means use .durable
temp (bool): when reopen .hold.subery open with temp.
             True means use temp directory False use default

Injects mods as WorkDom dataclass instance whose attributes are used to construct boxwork.

bx(name: None | str = None, over: None | str | Box = '', first: bool = False, *, mods: hio.base.hier.hiering.WorkDom | None = None) Box

Make a box and add to box work

Parameters:

name (None | str): when None then create name from bepre and beidx
                   items in works.
                   if non-empty string then use provided
                   otherwise raise exception

over (None | str | Box): over box for new box.
                        when str then name of new over box
                        when box then actual over box
                        when None then no over box (top level)
                        when empty then same level use _over
first (bool): True means set this box as boxer.first
              False (default) to not change boxer.first

mods (None | WorkDom):  state variables used to construct box work
    None is just to allow definition as keyword arg. Assumes in
    actual usage that mods is always provided as WorkDom instance of
    form:

        box (Box|None): current box in box work. None if not yet a box
        over (Box|None): current over Box in box work. None if top level
        bxpre (str): default name prefix used to generate unique box
            name relative to boxer.boxes
        bxidx (int): default box index used to generate unique box
            name relative to boxer.boxes
go(dest: None | str = None, expr: None | str | hio.base.hier.needing.Need = None, *, mods: hio.base.hier.hiering.WorkDom | None = None, **kwa) hio.base.hier.acting.Goact

Make a Goact and add it to the tracts nabe of the current box.

Returns:

goact (Goact):  newly created goact

Parameters:

dest (None|str|Box): destination box its name for transition.
    When None use next box if any
    When str then resolve name to box if possible else save for
        later resolution
    When Box instance that already resolved

expr (None|str|Need): need for transition to dest.
    When None then conditional always True. Always godo.
    When str then evaluable python boolean expression to be
        resolved into a Need instance for eval at run time
    When Need instance then use as is

mods (None | WorkDom):  state variables used to construct box work
    None is just to allow definition as keyword arg. Assumes in
    actual usage that mods is always provided as WorkDom instance of
    form:

        box (Box|None): current box in box work. None if not yet a box
        over (Box|None): current over Box in box work. None if top level
        bxpre (str): default name prefix used to generate unique box
            name relative to boxer.boxes
        bxidx (int): default box index used to generate unique box
            name relative to boxer.boxes
do(deed: None | str | Type[hio.base.hier.acting.ActBase] | collections.abc.Callable = None, nabe=None, *, name: str | None = None, mods: hio.base.hier.hiering.WorkDom | None = None, **iops) str

Make an act and add to box work

Parameters:

deed (None|str|Type[ActBase]|Callable):
        When None use Act with default lambda and iops as parameters
        When str name of class in ActBase registry.
        When subclass of ActBase then create instance
        When Callable use Act with iops as parameters.
name (None|str): name of act instance created by do.
        When None use default indexed name created by Act.
nabe (None|str): action nabe (context) for act instance created by do.
        None means use nabe from mods.
mods (None | WorkDom):  state variables used to construct box work
    None is just to allow definition as keyword arg. Assumes in
    actual usage that mods is always provided as WorkDom instance.

iops (dict): input-output-parameters for Act
on(cond: None | str = None, key: None | str = None, expr: None | str = None, *, mods: hio.base.hier.hiering.WorkDom | None = None, **iops) hio.base.hier.needing.Need

Make a Need with support for special Need conditions and return it. Use inside go verb as need argument for special need condition Use inside do verb as deed argument for preact

Returns:

need (Need):  newly created special need

Parameters:

cond (None|str): special need condition to be satisfied. This is
    resolved in evaluable boolean expression.
    When None then ignore
    When str then special need condition to be resolved into evaluable
    boolean expression

key (None|str): key to mine item ref for special need cond when
    applicable, i.e. cond is with respect to mine at key that is
    not predetermined solely by cond. Otherwise None.
    When None use default for cond
    When str then resolve key to mine at key


expr (None|str): evaluable boolean expression as additional constraint(s)
    ANDed with result of cond.
    When None or empty then ignore
    When str then evaluable python boolean expression to be ANDed with
        the result of cond resolution.

mods (None | WorkDom):  state variables used to construct box work
    None is just to allow definition as keyword arg. Assumes that
    mods is always provided as WorkDom instance of form:

        box (Box| None): current box in box work. None if not yet a box
        over (Box | None): current over Box in box work. None if top level
        bxpre (str):  default box name prefix used to generate unique box name
                    relative to boxer.boxes
        bxidx (int): default box name index used to generate unique box name
                    relative to boxer.boxes
        acts (dict):  registry of ActBase subclasses by name (including aliases)
        nabe (str): action nabe (context) for act

iops (dict): input-output-parameters for Act
at(nabe: str = Nabes.native, *, mods: hio.base.hier.hiering.WorkDom | None = None) str

Make set mods.nabe to nabe

Parameters:

nabe (str): action nabe (context) for mods. Default is native

mods (None | WorkDom):  state variables used to construct box work
    None is just to allow definition as keyword arg. Assumes in
    actual usage that mods is always provided as WorkDom instance.
be(lhs: str | tuple[str], rhs: None | str | collections.abc.Callable = None, nabe=None, *, name: str | None = None, mods: hio.base.hier.hiering.WorkDom | None = None, **iops) str

Make Beact instance that assigns mine bag at lhs to value from rhs. lhs is of form “key.field” rhs may be either a Callable or an evaluable expression or None. Resulting act performs one of:

H.key.field = None   when rhs is None
H.key.field = eval(rhs)  when rhs is evaluable str
H.key.field = rhs(``**parms``)  when rhs is callable

Usage:

be(lhs, rhs)

Parameters:

lhs (str|tuple[str]): key.field in mine to be assigned.
    Resolves lhs to (key, field)
rhs (None|str|Callable):
    When None assign directly
    When str compiles to evaluable expression
    When Callable then call directly with iops
nabe (None|str): action nabe (context) for act instance created by do.
        None means use nabe from mods.
name (None|str): name of act instance created by do.
        When None use default indexed name created by Act.
mods (None | WorkDom):  state variables used to construct box work
    None is just to allow definition as keyword arg. Assumes in
    actual usage that mods is always provided as WorkDom instance.
iops (dict): input-output-parameters for Beact
static exen(near, far)

Computes the relative differences (uncommon and common parts) between the box pile lists nears passed in and fars from box far.pile

Parameters:

near (Box): near box giving nears =near.pile in top down order
far (Box): far box giving fars = far.pile in top down order.

Assumes piles nears and fars are in top down order

Returns:

quadruple (tuple[list]): quadruple of lists of form::

    (exdos, endos, rendos, rexdos) where:
    exdos is list of uncommon boxes in nears but not in fars to be exited.
        Reversed to bottom up order.
    endos is list of uncommon boxes in fars but not in nears to be entered
    rexdos is list of common boxes in both nears and fars to be re-exited
        Reversed to bottom up order. These are boxes retained in pile.
    rendos is list of common boxes in both nears and fars to be re-entered
        These are boxes retained in pile.
    The sets of boxes in rexdos and rendos are the same set but rexdos
    is reversed to bottom up order. These are boxes retained in the
    pile before and after the transition. This is where common exdo/endo
    actions for the non-common boxes can be actioned non-redundantly.

Supports forced reentry transitions when far is in nears. This means fars == nears. In this case: The common part of nears/fars from far down is force exited The common part of nears/fars from far down is force entered

When far in nears then forced endo at far so far is nears[i] catches that case for forced endo at some far in nears. Since far is in fars, then when far == nears[i] then fars == nears.

Since a given box’s pile is always traced up via its .over if any and down via its primary under i.e. .unders[0] if any, when far is in nears the anything below far is same in both fars and nears.

Otherwise when far not in nears then i where fars[i] is not nears[i] indicates first box where fars down and nears down is uncommon i.e. the pile tree branches at i. This is the normal non-forced endo case for transition.

Two different topologies are accounted for with this code. Recall that python slice of list is zero based where: fars[i] not in fars[:i] and fars[i] in fars[i:] nears[i] not in nears[:i] and nears[i] in nears[i:] this means fars[:0] == nears[:0] == [] empty list

1.0 near and far in same tree either on same branch or different branches
1.1 on same branch forced endo where nears == fars so far in nears.

Walk down from shared root to find where far is nears[i]. Boxes above far given by fars[:i] == nears[:i] are re-exdo re-endo set of boxes. Boxes at far and below are forced exdo endo.

1.2 on different branch to walk down from root until find fork where

fars[i] is not nears[i]. So fars[:i] == nears[:i] above fork at i, and are re-exdo and re-endo set of boxes. Boxes at i and below in nears are exdo and boxes at i and below in fars are endo

2.0 near and far not in same tree. In this case top of nears at nears[0] is

not top of fars ar fars[0] i.e. different tree roots, far[0] != near[0] and fars[:0] == nears[:0] = [] means empty re-exdos and re-endos and all nears are exdo and all fars are endo.

class hio.base.hier.boxing.Boxery(*, name='maker', hold=None, **kwa)

Bases: hio.hioing.Mixin

Boxery Class builds multiple boxworks of Boxer and Box instances. Holds reference to in-memory mine shared by all boxers and their boxes in multi-boxer boxworks Holds reference to current Boxer and Box being built

Placeholder for now. Future: enable multiple boxers from a single fun or across multiple iterations.

Attributes:

hold (Hold): data shared by boxwork
boxer (Boxer | None): current boxer
box (Box | None): cureent box

Properties:

name (str): unique identifier of instance

Hidden:

_name (str): unique identifier of instance
property name

Property getter for ._name

Returns:

name (str): unique identifier of instance
make(fun, hold=None, boxes=None)

Make box work from function fun Parameters:

fun (function):  employs be, do, on, go maker functions with
                  globals
hold (None|Hold):  data shared by boxwork
boxes (None|dict): shared boxes map

bags, boxes, and boxers can be referenced by fun in its nonlocal enclosing scope. collections references so do not need to be global

class hio.base.hier.boxing.BoxerDoer(boxer, **kwa)

Bases: hio.base.doing.Doer

BoxerDoer .recur method is a generator method that runs its boxer.run() generator method with ‘yield from’ delegation. A Doer subclass whose recur is a generator method is in turn run by its .do method using ‘yield from’ delegation which is in turn run by a Doist or DoDoer using next() and generator .send().

Inherited Attributes:

done (bool | None): completion state: True means completed
    Otherwise incomplete. Incompletion maybe due to close or abort.
opts (dict): injected options into its .do generator by scheduler
temp (bool | None): use temporary file resources if any

Inherited Properties:

tyme (float): relative cycle time of associated Tymist .tyme obtained
    via injected .tymth function wrapper closure.
tymth (closure): function wrapper closure returned by Tymist.tymen() method.
    When .tymth is called it returns associated Tymist.tyme.
    .tymth provides injected dependency on Tymist tyme base.
tock (float): desired time in seconds between runs or until next run,
         non negative, zero means run asap

Inherited Methods:

- wind: injects ._tymth dependency from associated Tymist to get its .tyme
- __call__: makes instance callable. Appears as generator function
    that returns generator
- do: is generator method that returns generator
- enter: is enter context action method
- recur: is recur context action method or generator method
- exit: is exit context method
- close: is close context method
- abort: is abort context method

Attributes:

boxer (Boxer): boxwork instance this doer runs

Overridden Methods:

- recur

Hidden:

._tymth is injected function wrapper closure returned by .tymen() of
     associated Tymist instance that returns Tymist .tyme. when called.
._tock is hidden attribute for .tock property
wind(tymth)

Inject new tymist.tymth as new ._tymth. Changes tymist.tyme base. Updates winds .tymer .tymth

enter(*, temp=None)

Do ‘enter’ context actions. Not a generator method. Set up resources. Comparable to context manager enter.

Parameters:

temp (bool | None): True means use temporary file resources if any
                    None means ignore parameter value. Use self.temp

Inject temp or self.temp into file resources here if any

recur(tock=None)

Do ‘recur’ context actions as a generator method.

Parameters:

  tock (float|None): this doer when creating this generator in recur
      section of its .do method supplies its .tock as this method's
      tock parameter.
      Note, the doist tyme is delegated through the 'yield from'
      to the eventual target yield at the  bottom of delegation chain.
      when tock fed back to doist is None or 0.0 it indicates to
      run again ASAP (on next iteration of doist.do)


Returns::

    completion (bool): completion state of recurrence actions.
                    True means completed successfully
                    False completed unsuccessfully

Note that “tyme” is not a parameter when recur is a generator method since doist tyme is injected into the explicit yield below by the Doist or DoDoer send(tyme) in their recur method for generator Doers. The recur method itself returns a generator so parameters to this method are to setup the generator not to be used at recur time.

Assumes resource setup in .enter() and resource takedown in .exit()

exit()

Do ‘exit’ context actions. Override in subclass. Not a generator method. Clean up resources. Comparable to context manager exit. Called by finally after normal return, close, or abort. After .exit() do returns resulting in StopIteration.