Skip to main content

Important Lot Functions

FunctionWhat it does
system.kanoa.lot.executeLotOperationCreates 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.getLotActivityReturns 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:

  1. The user picks a source asset, and getLotActivity lists the lots there.
  2. The user picks a lot, a quantity and a destination.
  3. executeLotOperation runs a Transfer: an input at the source and an output at the destination.
  4. The screen calls getLotActivity again 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:

  1. The operation: which lot operation, at which asset, at what time.
  2. Its inputs: existing lots, how much is taken, and the asset they're taken from.
  3. Its outputs: the same lot at a new asset, as a transfer does, or a new lot with a new name, item and unit.
  4. One call to executeLotOperation with all of them, so the operation and its lot events are written together.
FunctionHow the script uses it
system.kanoa.serial.getNextSerialNumberNames each new lot from its serialization, such as RAL0000000001
system.kanoa.lot.executeLotOperationRecords each operation. An output lot with no lotId is created from its name, item and unit
system.kanoa.lot.getLotsFinds the new lots' ids by name, for the operations that use them next
system.kanoa.lot.traceLotReturns every lot event linked to the package, backward and forward
system.kanoa.lot.getLotActivityShows 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
  1. 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.
  2. 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 to D: 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.

Reference Materials: executeLotOperation

Creates or updates a lot operation event with input and output lot events


Parameters​

lotOperationEventInfo Dictionary

- assetIdIntegerasset the operation is performed on
- enabledBoolean
- lotOperationEventIdIntegerSet to None for a new lot operation or use an existing operation event
- lotOperationIdInteger
- tStampDateTime

inputLotEvents List of Dictionaries: list of input lotEventInfo dictionaries to be consumed by this operation. All keys are required unless stated.

- assetIdInteger
- assetTransportIdIntegerNot required
- commentStringNot required
- itemIdIntegerRequired if this is a new lot
- itemUnitIdInteger
- lotEventQtyFloat
- lotIdIntegerEither lotId or lotName must be provided
- lotNameStringEither lotId or lotName must be provided
- lotStateIdInteger
- lotStateReasonIdIntegerNot required
- shiftIdIntegerNot required
- tStampDateTime
- workOrderIdIntegerNot required

outputLotEvents List of Dictionaries: list of output lotEventInfo dictionaries that are to be created by this operation

- assetIdInteger
- assetTransportIdIntegerNot required
- commentStringNot required
- itemIdIntegerRequired if this is a new lot
- itemUnitIdInteger
- lotEventQtyFloat
- lotIdIntegerEither lotId or lotName must be provided
- lotNameStringEither lotId or lotName must be provided
- lotStateIdInteger
- lotStateReasonIdIntegerNot required
- shiftIdIntegerNot required
- tStampDateTime
- workOrderIdIntegerNot required

userId Integer:Id of the user executing the function


Returns​

lotOperationEventId Integer
message String None if success


Example​


Receive a new lot

lotOperationId = system.kanoa.utilities.getFieldValue('lotOperationId', system.kanoa.lot.getLotOperations({'lotOperationName': 'Receive'}))
assetPath = 'Kanoa Safety Inc\Chatillon\Receiving'
assetId = system.kanoa.utilities.getFieldValue('assetId', system.kanoa.asset.getAssets({'assetPath': assetPath}))
sources = system.kanoa.utilities.convertDatasetToDict(system.kanoa.item.getItemSource({}), 'itemSourceName', 'itemSourceId')
lotStates = system.kanoa.utilities.convertDatasetToDict(system.kanoa.lot.getLotStates({}), 'lotStateName', 'lotStateId')

lotOperationEventInfo = {
'lotOperationEventId': None,
'lotOperationId': lotOperationId,
'assetId': assetId,
'tStamp': system.date.now(),
'enabled': True
}
inputLotEvents = []
outputLotEvents = [{
'lotEventId': None,
'lotId': 1,
'lotEventQty': 100,
'workOrderId': None,
'assetId':1,
'itemSourceId': sources['output'],
'lotStateId': lotStates['OK'],
'lotStateReasonId': None,
'shiftId': None,
'tStamp': system.date.now(),
'comment':None,
'lotOperationEventId': None,
'assetTransportId': None
}]
lotOperationEventId, msg = system.kanoa.lot.executeLotOperation(lotOperationEventInfo, inputLotEvents, outputLotEvents, userId)

--------------------------

Transfer lots from a transport to a new location

#Create some useful data sources
sources = system.kanoa.utilities.convertDatasetToDict(system.kanoa.item.getItemSource({}), 'itemSourceName', 'itemSourceId')
userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})
assetPath = 'Kanoa Safety Inc\Chatillon\Production\Line 1'
assetId = system.kanoa.utilities.getFieldValue('assetId', system.kanoa.asset.getAssets({'assetPath': assetPath}))
timeNow = system.date.now()

#Create new lot Operation event to transfer lots
lotOperationId = system.kanoa.utilities.getFieldValue('lotOperationId', system.kanoa.lot.getLotOperations({'lotOperationName': 'Transfer'}))
lotOperationEventInfo = {
'lotOperationEventId': None,
'lotOperationId': lotOperationId,
'assetId': assetId,
'tStamp': timeNow,
'enabled': True
}

#Get lots at the assetTransport
data = system.kanoa.utilities.convertDatasetToJSON(system.kanoa.lot.getLotActivity({'assetTransportName': '2'}))

#Create lotEvents
keysToKeep = {'lotId', 'lotEventQty', 'workOrderId', 'assetId', 'lotStateId', 'lotStateReasonId'}
inputLotEvents = []
outputLotEvents = []
for lotActivity in data:
lotEventInfo = {k: v for k, v in lotActivity.items() if k in keysToKeep}

inputLotEventInfo = dict(lotEventInfo)
inputLotEventInfo['tStamp'] = timeNow
inputLotEventInfo['itemSourceId'] = sources['input']
inputLotEvents.append(inputLotEventInfo)

outputLotEventInfo = dict(lotEventInfo)
outputLotEventInfo['itemSourceId'] = sources['output']
outputLotEventInfo['assetId'] = assetId
outputLotEventInfo['assetTransportId'] = None #If you want to clear it

outputLotEvents.append(lotEventInfo)

lotOperationEventId, msg = system.kanoa.lot.executeLotOperation(lotOperationEventInfo, inputLotEvents, outputLotEvents, userId)
print lotOperationEventId, msg


Reference Materials: getLotActivity

Returns lots along with quantities grouped by location (asset) and state, filtered by the given parameters


Parameters​

paramsDict Dictionary

- assetIdInteger
- assetPathString
- assetTransportNameString
- endDateDateTime
- hasQtyBooleanOnly return lots that have some quantity
- itemIdInteger
- itemNameString
- itemPathString
- lotIdInteger
- lotNameString
- lotStateNameString
- lotStateReasonNameString
- startDateDateTime
- workOrderIdInteger
- workOrderNameString

Returns​

lotActivityData pyDataset


Example​

paramsDict = {'lotName': 'ACRT123'}
lotData = system.kanoa.lot.getLotActivity(paramsDict)
print lotData