Important Lot Functions
| Function | What it does |
|---|---|
system.kanoa.lot.executeLotOperation | Creates a lot operation event with all its input and output lot events in one call, so the genealogy is never left half-written |
system.kanoa.lot.getLotActivity | Returns the lots that currently have material, with quantity by asset and state, filtered by asset, lot name, transport and more |
A transfer screen uses both in a loop:
- The user picks a source asset, and
getLotActivitylists the lots there. - The user picks a lot, a quantity and a destination.
executeLotOperationruns aTransfer: an input at the source and an output at the destination.- The screen calls
getLotActivityagain to refresh.
A receiving screen only needs the second function: an operation with no inputs and one output.
Build a Whole Trace from a Script
The script below runs every lot operation from Execute the Trace with the lot functions: it receives the aluminum and coating ingredients, machines, blends, coats, inspects, packs and ships, then prints the package's trace. Every operation follows the same pattern:
- The operation: which lot operation, at which asset, at what time.
- Its inputs: existing lots, how much is taken, and the asset they're taken from.
- Its outputs: the same lot at a new asset, as a transfer does, or a new lot with a new name, item and unit.
- One call to
executeLotOperationwith all of them, so the operation and its lot events are written together.
| Function | How the script uses it |
|---|---|
system.kanoa.serial.getNextSerialNumber | Names each new lot from its serialization, such as RAL0000000001 |
system.kanoa.lot.executeLotOperation | Records each operation. An output lot with no lotId is created from its name, item and unit |
system.kanoa.lot.getLots | Finds the new lots' ids by name, for the operations that use them next |
system.kanoa.lot.traceLot | Returns every lot event linked to the package, backward and forward |
system.kanoa.lot.getLotActivity | Shows the material left in inventory |
It writes lot data
Run it only on a training gateway that has finished Lot Configuration. Every run receives new material and makes a new set of lots.
Run the trace from a script
- Copy the script into the Ignition Designer Script Console (Tools → Script Console) and run it. It prints each operation, the package's trace, and the material left.
- In Ops → Lots → Lot Manager, find the new package lot (
FGP000000000x), clear Active and click Get lots to show lots with no material, and compare its Trace tab with the trace the script printed. Set the depth button toD: the script traces to the same depth.
Show the script
executeTheTrace.py
# Kanoa Trace Training - Execute the Trace, as a script
#
# Runs every lot operation from the Execute the Trace lesson with the system.kanoa.lot
# functions, from receiving 2024 aluminum to shipping a package of hardened coupling pins,
# then prints the package's backward trace.
#
# Run it in the Ignition Designer Script Console (Tools > Script Console), in the project that
# inherits KANOA_SCRIPTS, on a training gateway that has finished Lot Configuration.
# It WRITES lot data: every run receives new material and makes a new set of lots.
#
# The pattern is the same for every operation:
# 1. Describe the operation: which lot operation, at which asset, at what time.
# 2. Describe its inputs: existing lots, the quantity taken, and where they're taken from.
# 3. Describe its outputs: the same lot at a new place, or a new lot with a new name.
# 4. Call system.kanoa.lot.executeLotOperation() once, so the operation and all its lot events
# are written together.
USER = system.security.getUsername() # the operations are recorded as done by you
P = 'CoreForge\\Philadelphia\\' # every asset in the flow is under the Philadelphia site
U = system.kanoa.utilities
userId = system.kanoa.security.getIDPUserId({'userName': USER})
# ---------------------------------------------------------------------------------------------
# Look up the ids the lot functions need. Everything is configured by name in Lot Configuration;
# the functions work with ids, so fetch each one once.
# ---------------------------------------------------------------------------------------------
def need(value, what):
"""Stop with a clear message when something from Lot Configuration is missing."""
if value is None:
raise Exception('%s not found. Finish Lot Configuration first.' % what)
return value
operations = U.convertDatasetToDict(system.kanoa.lot.getLotOperations({}), 'lotOperationName', 'lotOperationId')
states = U.convertDatasetToDict(system.kanoa.lot.getLotStates({}), 'lotStateName', 'lotStateId')
sources = U.convertDatasetToDict(system.kanoa.item.getItemSource({}), 'itemSourceName', 'itemSourceId')
units = dict((name.lower(), unitId) for name, unitId in
U.convertDatasetToDict(system.kanoa.item.getItemUnits({'enabled': True}), 'itemUnitName', 'itemUnitId').items())
serials = U.convertDatasetToDict(system.kanoa.serial.getSerialNumbers({}), 'serialName', 'serialId')
def assetId(path):
return need(U.getFieldValue('assetId', system.kanoa.asset.getAssets({'assetPath': P + path})), 'Asset ' + path)
def itemId(name):
return need(U.getFieldValue('itemId', system.kanoa.item.getItems({'itemName': name})), 'Item ' + name)
def unitId(name):
return need(units.get(name.lower()), 'Item unit ' + name)
def reasonId(name):
return need(U.getFieldValue('lotStateReasonId', system.kanoa.lot.getLotStateReasons({'lotStateReasonName': name})), 'Lot state reason ' + name)
def nextLotName(serialName):
"""The next lot name from a serialization, such as RAL0000000001. Each call uses up a number."""
lotName, msg = system.kanoa.serial.getNextSerialNumber(need(serials.get(serialName), 'Serialization ' + serialName), userId)
if msg:
raise Exception("Couldn't get a lot name from %s: %s" % (serialName, msg))
return lotName
# ---------------------------------------------------------------------------------------------
# Building blocks: a lot, a lot event and a lot operation.
# ---------------------------------------------------------------------------------------------
# Operations get times a minute apart, starting 30 minutes ago. Each lot's events must be in
# time order, or the trace graph runs backwards.
clock = [system.date.addMinutes(system.date.now(), -30)]
def nextTime():
clock[0] = system.date.addMinutes(clock[0], 1)
return clock[0]
def newLot(serialName, item, unit, lotName=None):
"""A lot that doesn't exist yet. executeLotOperation creates it from its name, item and unit
when it's used as an output."""
return {'lotId': None, 'lotName': lotName or nextLotName(serialName), 'itemId': itemId(item), 'itemUnitId': unitId(unit)}
def lotEvent(lot, qty, asset, state='OK', reason=None, comment=None):
"""One lot taking part in an operation: how much, at which asset, and its resulting state.
executeLotOperation sets whether it's an input or an output from the list it's passed in."""
return {
'lotEventId': None, 'lotOperationEventId': None,
'lotId': lot['lotId'], 'lotName': lot['lotName'], 'itemId': lot['itemId'], 'itemUnitId': lot['itemUnitId'],
'lotEventQty': qty, 'assetId': assetId(asset),
'lotStateId': need(states.get(state), 'Lot state ' + state), 'lotStateReasonId': reasonId(reason) if reason else None,
'workOrderId': None, 'shiftId': None, 'comment': comment, 'assetTransportId': None,
}
def run(operation, asset, inputs, outputs):
"""Record one lot operation at an asset, with its input and output lot events, in one call.
Returns the lots it output, with the ids the new ones were given."""
tStamp = nextTime()
operationInfo = {'lotOperationEventId': None, 'lotOperationId': need(operations.get(operation), 'Lot operation ' + operation),
'assetId': assetId(asset), 'tStamp': tStamp, 'enabled': True}
for event in inputs + outputs:
event['tStamp'] = tStamp
lotOperationEventId, msg = system.kanoa.lot.executeLotOperation(operationInfo, inputs, outputs, userId)
if msg:
raise Exception('%s at %s failed: %s' % (operation, asset, msg))
# Look the output lots up by name, so new lots have their lotId for the operations that follow
made = []
for event in outputs:
row = U.convertDatasetRowToJSON(system.kanoa.lot.getLots({'lotName': event['lotName']}), 0)
made.append({'lotId': row['lotId'], 'lotName': row['lotName'], 'itemId': row['itemId'], 'itemUnitId': row['itemUnitId']})
ins = ', '.join('%s %s' % (e['lotName'], e['lotEventQty']) for e in inputs) or '-'
outs = ', '.join('%s %s' % (e['lotName'], e['lotEventQty']) for e in outputs) or '-'
print '%-9s at %-22s in: %-40s out: %s' % (operation, asset.split('\\')[-1], ins, outs)
return made
# ---------------------------------------------------------------------------------------------
# The flow, in the order of the Execute the Trace lesson.
# ---------------------------------------------------------------------------------------------
# Check everything the flow needs before writing anything, so a missing piece can't leave half a trace.
NEEDED = [
(assetId, ['Storage\\Receiving', 'Storage\\Shipping', 'Machining\\Machine 1', 'Mixing\\Mixer 1', 'Coating\\Spray Line 1',
'Finishing\\QA Station', 'Finishing\\Auto Pack 1']),
(itemId, ['AL2024', 'STD-COAT', 'PRM-COAT', 'CP-2024', 'BL-HRD', 'CP-2024-HRD', 'FG-CP-2024-HRD-250']),
(unitId, ['lbs', 'Gallons', 'units', 'Cases']),
(reasonId, ['Failed visual inspection']),
(lambda name: need(operations.get(name), 'Lot operation ' + name), ['Receive', 'Transfer', 'Machine', 'Blend', 'Coat', 'Inspect', 'Scrap', 'Pack', 'Ship']),
(lambda name: need(states.get(name), 'Lot state ' + name), ['OK', 'Scrap']),
(lambda name: need(serials.get(name), 'Serialization ' + name), ['Raw Aluminum', 'Raw Blending Ingredients', 'WIP Machined Parts',
'WIP Coatings/Blends', 'WIP Coated Parts', 'Finished Goods Packages']),
]
missing = []
for lookup, names in NEEDED:
for name in names:
try:
lookup(name)
except Exception, e:
missing.append(str(e.message if hasattr(e, 'message') else e).replace(' not found. Finish Lot Configuration first.', ''))
def executeTheTrace():
"""The whole flow: every operation, then the trace and the material left."""
print 'Execute the Trace, as user %s' % USER
print '-' * 110
# Receive the raw materials. A receive has no inputs; its outputs are new lots.
[aluminum] = run('Receive', 'Storage\\Receiving', [], [
lotEvent(newLot('Raw Aluminum', 'AL2024', 'lbs'), 1000, 'Storage\\Receiving')])
[stdCoat, prmCoat] = run('Receive', 'Storage\\Receiving', [], [
lotEvent(newLot('Raw Blending Ingredients', 'STD-COAT', 'Gallons'), 100, 'Storage\\Receiving'),
lotEvent(newLot('Raw Blending Ingredients', 'PRM-COAT', 'Gallons'), 50, 'Storage\\Receiving')])
# Transfer 100 lbs to Machine 1. A transfer's input and output are the same lot: the input takes it
# from where it is, the output puts it at the new asset.
# (Every run() result is assigned, even when it isn't used, so the Script Console doesn't print it.)
[aluminum] = run('Transfer', 'Machining\\Machine 1',
[lotEvent(aluminum, 100, 'Storage\\Receiving')],
[lotEvent(aluminum, 100, 'Machining\\Machine 1')])
# Machine the aluminum into coupling pins: a transformation, from one lot into a new one.
[machined] = run('Machine', 'Machining\\Machine 1',
[lotEvent(aluminum, 100, 'Machining\\Machine 1')],
[lotEvent(newLot('WIP Machined Parts', 'CP-2024', 'units'), 50, 'Machining\\Machine 1')])
# Blend two ingredients into a coating: one operation with two inputs.
[blend] = run('Blend', 'Mixing\\Mixer 1',
[lotEvent(stdCoat, 10, 'Storage\\Receiving'), lotEvent(prmCoat, 5, 'Storage\\Receiving')],
[lotEvent(newLot('WIP Coatings/Blends', 'BL-HRD', 'Gallons'), 15, 'Mixing\\Mixer 1')])
# Move the blend and the machined parts to the spray line, then coat the parts.
[blend] = run('Transfer', 'Coating\\Spray Line 1',
[lotEvent(blend, 15, 'Mixing\\Mixer 1')], [lotEvent(blend, 15, 'Coating\\Spray Line 1')])
[machined] = run('Transfer', 'Coating\\Spray Line 1',
[lotEvent(machined, 50, 'Machining\\Machine 1')], [lotEvent(machined, 50, 'Coating\\Spray Line 1')])
[coated] = run('Coat', 'Coating\\Spray Line 1',
[lotEvent(blend, 2, 'Coating\\Spray Line 1'), lotEvent(machined, 50, 'Coating\\Spray Line 1')],
[lotEvent(newLot('WIP Coated Parts', 'CP-2024-HRD', 'units'), 50, 'Coating\\Spray Line 1')])
# Inspect the coated parts: a split. 45 stay on the same lot as OK; 5 go to a new scrap lot,
# named after the coated lot, with the reason they failed.
scrapLot = newLot(None, 'CP-2024-HRD', 'units', lotName=coated['lotName'] + '-SCRAP')
[passed, scrap] = run('Inspect', 'Finishing\\QA Station',
[lotEvent(coated, 50, 'Coating\\Spray Line 1')],
[lotEvent(coated, 45, 'Finishing\\QA Station'),
lotEvent(scrapLot, 5, 'Finishing\\QA Station', state='Scrap', reason='Failed visual inspection')])
# Scrap removes the failed parts from inventory: an input with no output. The lot keeps its history.
# An input names the stock it takes by asset, state and reason, so it repeats the reason Inspect gave.
done = run('Scrap', 'Finishing\\QA Station', [lotEvent(scrap, 5, 'Finishing\\QA Station', state='Scrap', reason='Failed visual inspection')], [])
# Pack the passed parts into a case of finished goods, then ship it: another input with no output.
[package] = run('Pack', 'Finishing\\Auto Pack 1',
[lotEvent(passed, 45, 'Finishing\\QA Station')],
[lotEvent(newLot('Finished Goods Packages', 'FG-CP-2024-HRD-250', 'Cases'), 1, 'Finishing\\Auto Pack 1')])
done = run('Ship', 'Storage\\Shipping', [lotEvent(package, 1, 'Finishing\\Auto Pack 1')], [])
# ---------------------------------------------------------------------------------------------
# What went into the package? traceLot follows the lot events backward and forward from a lot.
# ---------------------------------------------------------------------------------------------
print '-' * 110
print 'Trace of %s, oldest first:' % package['lotName']
for e in U.convertDatasetToJSON(system.kanoa.lot.traceLot(package['lotId'], 20)):
when = system.date.format(e['operationtStamp'], 'HH:mm')
print ' %s %-9s %-6s %-22s %6s %s' % (when, e['lotOperationName'], e['itemSourceName'], e['lotName'], e['lotEventQty'], e['itemUnitName'])
# What's left in inventory from this run? getLotActivity adds up each lot's events.
print '-' * 110
print 'Material left from this run:'
names = [aluminum['lotName'], stdCoat['lotName'], prmCoat['lotName'], blend['lotName']]
for row in U.convertDatasetToJSON(system.kanoa.lot.getLotActivity({'hasQty': True})):
if row['lotName'] in names:
print ' %-15s %8s %-8s at %s' % (row['lotName'], row['lotEventQty'], row['itemUnitName'], row['assetPath'].replace(P, ''))
if missing:
print 'Nothing was run. These are missing; finish Lot Configuration first:'
for m in missing:
print ' - ' + m
else:
executeTheTrace()
Building your own screen
Run the operation by hand in Lot Manager first. Note its inputs and outputs, build the same payload in your script, check quantities before you call executeLotOperation, and show a clear success or error message.