repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.getInstIdFromIndices | def getInstIdFromIndices(self, *indices):
"""Return column instance identification from indices"""
try:
return self._idxToIdCache[indices]
except TypeError:
cacheable = False
except KeyError:
cacheable = True
idx = 0
instId = ()
parentIndices = []
for impliedFlag, modName, symName in self._indexNames:
if idx >= len(indices):
break
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax = mibObj.syntax.clone(indices[idx])
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
idx += 1
if cacheable:
self._idxToIdCache[indices] = instId
return instId | python | def getInstIdFromIndices(self, *indices):
"""Return column instance identification from indices"""
try:
return self._idxToIdCache[indices]
except TypeError:
cacheable = False
except KeyError:
cacheable = True
idx = 0
instId = ()
parentIndices = []
for impliedFlag, modName, symName in self._indexNames:
if idx >= len(indices):
break
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax = mibObj.syntax.clone(indices[idx])
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
idx += 1
if cacheable:
self._idxToIdCache[indices] = instId
return instId | [
"def",
"getInstIdFromIndices",
"(",
"self",
",",
"*",
"indices",
")",
":",
"try",
":",
"return",
"self",
".",
"_idxToIdCache",
"[",
"indices",
"]",
"except",
"TypeError",
":",
"cacheable",
"=",
"False",
"except",
"KeyError",
":",
"cacheable",
"=",
"True",
"idx",
"=",
"0",
"instId",
"=",
"(",
")",
"parentIndices",
"=",
"[",
"]",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"if",
"idx",
">=",
"len",
"(",
"indices",
")",
":",
"break",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"syntax",
"=",
"mibObj",
".",
"syntax",
".",
"clone",
"(",
"indices",
"[",
"idx",
"]",
")",
"instId",
"+=",
"self",
".",
"valueToOid",
"(",
"syntax",
",",
"impliedFlag",
",",
"parentIndices",
")",
"parentIndices",
".",
"append",
"(",
"syntax",
")",
"idx",
"+=",
"1",
"if",
"cacheable",
":",
"self",
".",
"_idxToIdCache",
"[",
"indices",
"]",
"=",
"instId",
"return",
"instId"
] | Return column instance identification from indices | [
"Return",
"column",
"instance",
"identification",
"from",
"indices"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3308-L3329 | train | 232,300 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.getInstNameByIndex | def getInstNameByIndex(self, colId, *indices):
"""Build column instance name from components"""
return self.name + (colId,) + self.getInstIdFromIndices(*indices) | python | def getInstNameByIndex(self, colId, *indices):
"""Build column instance name from components"""
return self.name + (colId,) + self.getInstIdFromIndices(*indices) | [
"def",
"getInstNameByIndex",
"(",
"self",
",",
"colId",
",",
"*",
"indices",
")",
":",
"return",
"self",
".",
"name",
"+",
"(",
"colId",
",",
")",
"+",
"self",
".",
"getInstIdFromIndices",
"(",
"*",
"indices",
")"
] | Build column instance name from components | [
"Build",
"column",
"instance",
"name",
"from",
"components"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3333-L3335 | train | 232,301 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.getInstNamesByIndex | def getInstNamesByIndex(self, *indices):
"""Build column instance names from indices"""
instNames = []
for columnName in self._vars.keys():
instNames.append(
self.getInstNameByIndex(*(columnName[-1],) + indices)
)
return tuple(instNames) | python | def getInstNamesByIndex(self, *indices):
"""Build column instance names from indices"""
instNames = []
for columnName in self._vars.keys():
instNames.append(
self.getInstNameByIndex(*(columnName[-1],) + indices)
)
return tuple(instNames) | [
"def",
"getInstNamesByIndex",
"(",
"self",
",",
"*",
"indices",
")",
":",
"instNames",
"=",
"[",
"]",
"for",
"columnName",
"in",
"self",
".",
"_vars",
".",
"keys",
"(",
")",
":",
"instNames",
".",
"append",
"(",
"self",
".",
"getInstNameByIndex",
"(",
"*",
"(",
"columnName",
"[",
"-",
"1",
"]",
",",
")",
"+",
"indices",
")",
")",
"return",
"tuple",
"(",
"instNames",
")"
] | Build column instance names from indices | [
"Build",
"column",
"instance",
"names",
"from",
"indices"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3337-L3345 | train | 232,302 |
etingof/pysnmp | pysnmp/hlapi/v3arch/asyncore/sync/cmdgen.py | nextCmd | def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Creates a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication : str
True value indicates SNMP engine error.
errorStatus : str
True value indicates SNMP PDU error.
errorIndex : int
Non-zero value refers to `varBinds[errorIndex-1]`
varBinds : tuple
A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi import *
>>> g = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))])
>>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] )
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))])
"""
# noinspection PyShadowingNames
def cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
cbCtx['errorIndication'] = errorIndication
cbCtx['errorStatus'] = errorStatus
cbCtx['errorIndex'] = errorIndex
cbCtx['varBindTable'] = varBindTable
lexicographicMode = options.get('lexicographicMode', True)
ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False)
maxRows = options.get('maxRows', 0)
maxCalls = options.get('maxCalls', 0)
cbCtx = {}
vbProcessor = CommandGeneratorVarBinds()
initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine.cache, varBinds)]
totalRows = totalCalls = 0
while True:
previousVarBinds = varBinds
if varBinds:
cmdgen.nextCmd(snmpEngine, authData, transportTarget, contextData,
*[(x[0], Null('')) for x in varBinds],
cbFun=cbFun, cbCtx=cbCtx,
lookupMib=options.get('lookupMib', True))
snmpEngine.transportDispatcher.runDispatcher()
errorIndication = cbCtx['errorIndication']
errorStatus = cbCtx['errorStatus']
errorIndex = cbCtx['errorIndex']
if ignoreNonIncreasingOid and errorIndication and isinstance(errorIndication, errind.OidNotIncreasing):
errorIndication = None
if errorIndication:
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
else:
stopFlag = True
varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0]
for col, varBind in enumerate(varBinds):
name, val = varBind
if isinstance(val, Null):
varBinds[col] = previousVarBinds[col][0], endOfMibView
if not lexicographicMode and not initialVars[col].isPrefixOf(name):
varBinds[col] = previousVarBinds[col][0], endOfMibView
if stopFlag and varBinds[col][1] is not endOfMibView:
stopFlag = False
if stopFlag:
return
totalRows += 1
totalCalls += 1
else:
errorIndication = errorStatus = errorIndex = None
varBinds = []
initialVarBinds = (yield errorIndication, errorStatus, errorIndex, varBinds)
if initialVarBinds:
varBinds = initialVarBinds
initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine.cache, varBinds)]
if maxRows and totalRows >= maxRows:
return
if maxCalls and totalCalls >= maxCalls:
return | python | def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Creates a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication : str
True value indicates SNMP engine error.
errorStatus : str
True value indicates SNMP PDU error.
errorIndex : int
Non-zero value refers to `varBinds[errorIndex-1]`
varBinds : tuple
A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi import *
>>> g = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))])
>>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] )
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))])
"""
# noinspection PyShadowingNames
def cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
cbCtx['errorIndication'] = errorIndication
cbCtx['errorStatus'] = errorStatus
cbCtx['errorIndex'] = errorIndex
cbCtx['varBindTable'] = varBindTable
lexicographicMode = options.get('lexicographicMode', True)
ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False)
maxRows = options.get('maxRows', 0)
maxCalls = options.get('maxCalls', 0)
cbCtx = {}
vbProcessor = CommandGeneratorVarBinds()
initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine.cache, varBinds)]
totalRows = totalCalls = 0
while True:
previousVarBinds = varBinds
if varBinds:
cmdgen.nextCmd(snmpEngine, authData, transportTarget, contextData,
*[(x[0], Null('')) for x in varBinds],
cbFun=cbFun, cbCtx=cbCtx,
lookupMib=options.get('lookupMib', True))
snmpEngine.transportDispatcher.runDispatcher()
errorIndication = cbCtx['errorIndication']
errorStatus = cbCtx['errorStatus']
errorIndex = cbCtx['errorIndex']
if ignoreNonIncreasingOid and errorIndication and isinstance(errorIndication, errind.OidNotIncreasing):
errorIndication = None
if errorIndication:
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
else:
stopFlag = True
varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0]
for col, varBind in enumerate(varBinds):
name, val = varBind
if isinstance(val, Null):
varBinds[col] = previousVarBinds[col][0], endOfMibView
if not lexicographicMode and not initialVars[col].isPrefixOf(name):
varBinds[col] = previousVarBinds[col][0], endOfMibView
if stopFlag and varBinds[col][1] is not endOfMibView:
stopFlag = False
if stopFlag:
return
totalRows += 1
totalCalls += 1
else:
errorIndication = errorStatus = errorIndex = None
varBinds = []
initialVarBinds = (yield errorIndication, errorStatus, errorIndex, varBinds)
if initialVarBinds:
varBinds = initialVarBinds
initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine.cache, varBinds)]
if maxRows and totalRows >= maxRows:
return
if maxCalls and totalCalls >= maxCalls:
return | [
"def",
"nextCmd",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"# noinspection PyShadowingNames",
"def",
"cbFun",
"(",
"snmpEngine",
",",
"sendRequestHandle",
",",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
",",
"cbCtx",
")",
":",
"cbCtx",
"[",
"'errorIndication'",
"]",
"=",
"errorIndication",
"cbCtx",
"[",
"'errorStatus'",
"]",
"=",
"errorStatus",
"cbCtx",
"[",
"'errorIndex'",
"]",
"=",
"errorIndex",
"cbCtx",
"[",
"'varBindTable'",
"]",
"=",
"varBindTable",
"lexicographicMode",
"=",
"options",
".",
"get",
"(",
"'lexicographicMode'",
",",
"True",
")",
"ignoreNonIncreasingOid",
"=",
"options",
".",
"get",
"(",
"'ignoreNonIncreasingOid'",
",",
"False",
")",
"maxRows",
"=",
"options",
".",
"get",
"(",
"'maxRows'",
",",
"0",
")",
"maxCalls",
"=",
"options",
".",
"get",
"(",
"'maxCalls'",
",",
"0",
")",
"cbCtx",
"=",
"{",
"}",
"vbProcessor",
"=",
"CommandGeneratorVarBinds",
"(",
")",
"initialVars",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"vbProcessor",
".",
"makeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
")",
"]",
"totalRows",
"=",
"totalCalls",
"=",
"0",
"while",
"True",
":",
"previousVarBinds",
"=",
"varBinds",
"if",
"varBinds",
":",
"cmdgen",
".",
"nextCmd",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"*",
"[",
"(",
"x",
"[",
"0",
"]",
",",
"Null",
"(",
"''",
")",
")",
"for",
"x",
"in",
"varBinds",
"]",
",",
"cbFun",
"=",
"cbFun",
",",
"cbCtx",
"=",
"cbCtx",
",",
"lookupMib",
"=",
"options",
".",
"get",
"(",
"'lookupMib'",
",",
"True",
")",
")",
"snmpEngine",
".",
"transportDispatcher",
".",
"runDispatcher",
"(",
")",
"errorIndication",
"=",
"cbCtx",
"[",
"'errorIndication'",
"]",
"errorStatus",
"=",
"cbCtx",
"[",
"'errorStatus'",
"]",
"errorIndex",
"=",
"cbCtx",
"[",
"'errorIndex'",
"]",
"if",
"ignoreNonIncreasingOid",
"and",
"errorIndication",
"and",
"isinstance",
"(",
"errorIndication",
",",
"errind",
".",
"OidNotIncreasing",
")",
":",
"errorIndication",
"=",
"None",
"if",
"errorIndication",
":",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
")",
"return",
"elif",
"errorStatus",
":",
"if",
"errorStatus",
"==",
"2",
":",
"# Hide SNMPv1 noSuchName error which leaks in here",
"# from SNMPv1 Agent through internal pysnmp proxy.",
"errorStatus",
"=",
"errorStatus",
".",
"clone",
"(",
"0",
")",
"errorIndex",
"=",
"errorIndex",
".",
"clone",
"(",
"0",
")",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
")",
"return",
"else",
":",
"stopFlag",
"=",
"True",
"varBinds",
"=",
"cbCtx",
"[",
"'varBindTable'",
"]",
"and",
"cbCtx",
"[",
"'varBindTable'",
"]",
"[",
"0",
"]",
"for",
"col",
",",
"varBind",
"in",
"enumerate",
"(",
"varBinds",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"if",
"isinstance",
"(",
"val",
",",
"Null",
")",
":",
"varBinds",
"[",
"col",
"]",
"=",
"previousVarBinds",
"[",
"col",
"]",
"[",
"0",
"]",
",",
"endOfMibView",
"if",
"not",
"lexicographicMode",
"and",
"not",
"initialVars",
"[",
"col",
"]",
".",
"isPrefixOf",
"(",
"name",
")",
":",
"varBinds",
"[",
"col",
"]",
"=",
"previousVarBinds",
"[",
"col",
"]",
"[",
"0",
"]",
",",
"endOfMibView",
"if",
"stopFlag",
"and",
"varBinds",
"[",
"col",
"]",
"[",
"1",
"]",
"is",
"not",
"endOfMibView",
":",
"stopFlag",
"=",
"False",
"if",
"stopFlag",
":",
"return",
"totalRows",
"+=",
"1",
"totalCalls",
"+=",
"1",
"else",
":",
"errorIndication",
"=",
"errorStatus",
"=",
"errorIndex",
"=",
"None",
"varBinds",
"=",
"[",
"]",
"initialVarBinds",
"=",
"(",
"yield",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
")",
"if",
"initialVarBinds",
":",
"varBinds",
"=",
"initialVarBinds",
"initialVars",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"vbProcessor",
".",
"makeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
")",
"]",
"if",
"maxRows",
"and",
"totalRows",
">=",
"maxRows",
":",
"return",
"if",
"maxCalls",
"and",
"totalCalls",
">=",
"maxCalls",
":",
"return"
] | Creates a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication : str
True value indicates SNMP engine error.
errorStatus : str
True value indicates SNMP PDU error.
errorIndex : int
Non-zero value refers to `varBinds[errorIndex-1]`
varBinds : tuple
A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi import *
>>> g = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))])
>>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] )
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) | [
"Creates",
"a",
"generator",
"to",
"perform",
"one",
"or",
"more",
"SNMP",
"GETNEXT",
"queries",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/asyncore/sync/cmdgen.py#L229-L413 | train | 232,303 |
etingof/pysnmp | pysnmp/entity/rfc3413/cmdrsp.py | CommandResponderBase._storeAccessContext | def _storeAccessContext(snmpEngine):
"""Copy received message metadata while it lasts"""
execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request')
return {
'securityModel': execCtx['securityModel'],
'securityName': execCtx['securityName'],
'securityLevel': execCtx['securityLevel'],
'contextName': execCtx['contextName'],
'pduType': execCtx['pdu'].getTagSet()
} | python | def _storeAccessContext(snmpEngine):
"""Copy received message metadata while it lasts"""
execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request')
return {
'securityModel': execCtx['securityModel'],
'securityName': execCtx['securityName'],
'securityLevel': execCtx['securityLevel'],
'contextName': execCtx['contextName'],
'pduType': execCtx['pdu'].getTagSet()
} | [
"def",
"_storeAccessContext",
"(",
"snmpEngine",
")",
":",
"execCtx",
"=",
"snmpEngine",
".",
"observer",
".",
"getExecutionContext",
"(",
"'rfc3412.receiveMessage:request'",
")",
"return",
"{",
"'securityModel'",
":",
"execCtx",
"[",
"'securityModel'",
"]",
",",
"'securityName'",
":",
"execCtx",
"[",
"'securityName'",
"]",
",",
"'securityLevel'",
":",
"execCtx",
"[",
"'securityLevel'",
"]",
",",
"'contextName'",
":",
"execCtx",
"[",
"'contextName'",
"]",
",",
"'pduType'",
":",
"execCtx",
"[",
"'pdu'",
"]",
".",
"getTagSet",
"(",
")",
"}"
] | Copy received message metadata while it lasts | [
"Copy",
"received",
"message",
"metadata",
"while",
"it",
"lasts"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/entity/rfc3413/cmdrsp.py#L174-L184 | train | 232,304 |
etingof/pysnmp | pysnmp/entity/rfc3413/cmdrsp.py | NextCommandResponder._getManagedObjectsInstances | def _getManagedObjectsInstances(self, varBinds, **context):
"""Iterate over Managed Objects fulfilling SNMP query.
Returns
-------
:py:class:`list` - List of Managed Objects Instances to respond with or
`None` to indicate that not all objects have been gathered
so far.
"""
rspVarBinds = context['rspVarBinds']
varBindsMap = context['varBindsMap']
rtrVarBinds = []
for idx, varBind in enumerate(varBinds):
name, val = varBind
if (exval.noSuchObject.isSameTypeWith(val) or
exval.noSuchInstance.isSameTypeWith(val)):
varBindsMap[len(rtrVarBinds)] = varBindsMap.pop(idx, idx)
rtrVarBinds.append(varBind)
else:
rspVarBinds[varBindsMap.pop(idx, idx)] = varBind
if rtrVarBinds:
snmpEngine = context['snmpEngine']
# Need to unwind stack, can't recurse any more
def callLater(*args):
snmpEngine.transportDispatcher.unregisterTimerCbFun(callLater)
mgmtFun = context['mgmtFun']
mgmtFun(*varBinds, **context)
snmpEngine.transportDispatcher.registerTimerCbFun(callLater, 0.01)
else:
return rspVarBinds | python | def _getManagedObjectsInstances(self, varBinds, **context):
"""Iterate over Managed Objects fulfilling SNMP query.
Returns
-------
:py:class:`list` - List of Managed Objects Instances to respond with or
`None` to indicate that not all objects have been gathered
so far.
"""
rspVarBinds = context['rspVarBinds']
varBindsMap = context['varBindsMap']
rtrVarBinds = []
for idx, varBind in enumerate(varBinds):
name, val = varBind
if (exval.noSuchObject.isSameTypeWith(val) or
exval.noSuchInstance.isSameTypeWith(val)):
varBindsMap[len(rtrVarBinds)] = varBindsMap.pop(idx, idx)
rtrVarBinds.append(varBind)
else:
rspVarBinds[varBindsMap.pop(idx, idx)] = varBind
if rtrVarBinds:
snmpEngine = context['snmpEngine']
# Need to unwind stack, can't recurse any more
def callLater(*args):
snmpEngine.transportDispatcher.unregisterTimerCbFun(callLater)
mgmtFun = context['mgmtFun']
mgmtFun(*varBinds, **context)
snmpEngine.transportDispatcher.registerTimerCbFun(callLater, 0.01)
else:
return rspVarBinds | [
"def",
"_getManagedObjectsInstances",
"(",
"self",
",",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"rspVarBinds",
"=",
"context",
"[",
"'rspVarBinds'",
"]",
"varBindsMap",
"=",
"context",
"[",
"'varBindsMap'",
"]",
"rtrVarBinds",
"=",
"[",
"]",
"for",
"idx",
",",
"varBind",
"in",
"enumerate",
"(",
"varBinds",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"if",
"(",
"exval",
".",
"noSuchObject",
".",
"isSameTypeWith",
"(",
"val",
")",
"or",
"exval",
".",
"noSuchInstance",
".",
"isSameTypeWith",
"(",
"val",
")",
")",
":",
"varBindsMap",
"[",
"len",
"(",
"rtrVarBinds",
")",
"]",
"=",
"varBindsMap",
".",
"pop",
"(",
"idx",
",",
"idx",
")",
"rtrVarBinds",
".",
"append",
"(",
"varBind",
")",
"else",
":",
"rspVarBinds",
"[",
"varBindsMap",
".",
"pop",
"(",
"idx",
",",
"idx",
")",
"]",
"=",
"varBind",
"if",
"rtrVarBinds",
":",
"snmpEngine",
"=",
"context",
"[",
"'snmpEngine'",
"]",
"# Need to unwind stack, can't recurse any more",
"def",
"callLater",
"(",
"*",
"args",
")",
":",
"snmpEngine",
".",
"transportDispatcher",
".",
"unregisterTimerCbFun",
"(",
"callLater",
")",
"mgmtFun",
"=",
"context",
"[",
"'mgmtFun'",
"]",
"mgmtFun",
"(",
"*",
"varBinds",
",",
"*",
"*",
"context",
")",
"snmpEngine",
".",
"transportDispatcher",
".",
"registerTimerCbFun",
"(",
"callLater",
",",
"0.01",
")",
"else",
":",
"return",
"rspVarBinds"
] | Iterate over Managed Objects fulfilling SNMP query.
Returns
-------
:py:class:`list` - List of Managed Objects Instances to respond with or
`None` to indicate that not all objects have been gathered
so far. | [
"Iterate",
"over",
"Managed",
"Objects",
"fulfilling",
"SNMP",
"query",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/entity/rfc3413/cmdrsp.py#L339-L375 | train | 232,305 |
etingof/pysnmp | pysnmp/proto/rfc1155.py | NetworkAddress.clone | def clone(self, value=univ.noValue, **kwargs):
"""Clone this instance.
If *value* is specified, use its tag as the component type selector,
and itself as the component value.
:param value: (Optional) the component value.
:type value: :py:obj:`pyasn1.type.base.Asn1ItemBase`
:return: the cloned instance.
:rtype: :py:obj:`pysnmp.proto.rfc1155.NetworkAddress`
:raise: :py:obj:`pysnmp.smi.error.SmiError`:
if the type of *value* is not allowed for this Choice instance.
"""
cloned = univ.Choice.clone(self, **kwargs)
if value is not univ.noValue:
if isinstance(value, NetworkAddress):
value = value.getComponent()
elif not isinstance(value, IpAddress):
# IpAddress is the only supported type, perhaps forever because
# this is SNMPv1.
value = IpAddress(value)
try:
tagSet = value.tagSet
except AttributeError:
raise PyAsn1Error('component value %r has no tag set' % (value,))
cloned.setComponentByType(tagSet, value)
return cloned | python | def clone(self, value=univ.noValue, **kwargs):
"""Clone this instance.
If *value* is specified, use its tag as the component type selector,
and itself as the component value.
:param value: (Optional) the component value.
:type value: :py:obj:`pyasn1.type.base.Asn1ItemBase`
:return: the cloned instance.
:rtype: :py:obj:`pysnmp.proto.rfc1155.NetworkAddress`
:raise: :py:obj:`pysnmp.smi.error.SmiError`:
if the type of *value* is not allowed for this Choice instance.
"""
cloned = univ.Choice.clone(self, **kwargs)
if value is not univ.noValue:
if isinstance(value, NetworkAddress):
value = value.getComponent()
elif not isinstance(value, IpAddress):
# IpAddress is the only supported type, perhaps forever because
# this is SNMPv1.
value = IpAddress(value)
try:
tagSet = value.tagSet
except AttributeError:
raise PyAsn1Error('component value %r has no tag set' % (value,))
cloned.setComponentByType(tagSet, value)
return cloned | [
"def",
"clone",
"(",
"self",
",",
"value",
"=",
"univ",
".",
"noValue",
",",
"*",
"*",
"kwargs",
")",
":",
"cloned",
"=",
"univ",
".",
"Choice",
".",
"clone",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"if",
"value",
"is",
"not",
"univ",
".",
"noValue",
":",
"if",
"isinstance",
"(",
"value",
",",
"NetworkAddress",
")",
":",
"value",
"=",
"value",
".",
"getComponent",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"IpAddress",
")",
":",
"# IpAddress is the only supported type, perhaps forever because",
"# this is SNMPv1.",
"value",
"=",
"IpAddress",
"(",
"value",
")",
"try",
":",
"tagSet",
"=",
"value",
".",
"tagSet",
"except",
"AttributeError",
":",
"raise",
"PyAsn1Error",
"(",
"'component value %r has no tag set'",
"%",
"(",
"value",
",",
")",
")",
"cloned",
".",
"setComponentByType",
"(",
"tagSet",
",",
"value",
")",
"return",
"cloned"
] | Clone this instance.
If *value* is specified, use its tag as the component type selector,
and itself as the component value.
:param value: (Optional) the component value.
:type value: :py:obj:`pyasn1.type.base.Asn1ItemBase`
:return: the cloned instance.
:rtype: :py:obj:`pysnmp.proto.rfc1155.NetworkAddress`
:raise: :py:obj:`pysnmp.smi.error.SmiError`:
if the type of *value* is not allowed for this Choice instance. | [
"Clone",
"this",
"instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1155.py#L63-L95 | train | 232,306 |
etingof/pysnmp | pysnmp/smi/instrum.py | MibInstrumController._defaultErrorHandler | def _defaultErrorHandler(varBinds, **context):
"""Raise exception on any error if user callback is missing"""
errors = context.get('errors')
if errors:
err = errors[-1]
raise err['error'] | python | def _defaultErrorHandler(varBinds, **context):
"""Raise exception on any error if user callback is missing"""
errors = context.get('errors')
if errors:
err = errors[-1]
raise err['error'] | [
"def",
"_defaultErrorHandler",
"(",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"errors",
"=",
"context",
".",
"get",
"(",
"'errors'",
")",
"if",
"errors",
":",
"err",
"=",
"errors",
"[",
"-",
"1",
"]",
"raise",
"err",
"[",
"'error'",
"]"
] | Raise exception on any error if user callback is missing | [
"Raise",
"exception",
"on",
"any",
"error",
"if",
"user",
"callback",
"is",
"missing"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L375-L381 | train | 232,307 |
etingof/pysnmp | pysnmp/smi/instrum.py | MibInstrumController.readMibObjects | def readMibObjects(self, *varBinds, **context):
"""Read Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the referenced Managed Objects Instances.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be either
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated).
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_READ_VAR, *varBinds, **context) | python | def readMibObjects(self, *varBinds, **context):
"""Read Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the referenced Managed Objects Instances.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be either
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated).
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_READ_VAR, *varBinds, **context) | [
"def",
"readMibObjects",
"(",
"self",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"if",
"'cbFun'",
"not",
"in",
"context",
":",
"context",
"[",
"'cbFun'",
"]",
"=",
"self",
".",
"_defaultErrorHandler",
"self",
".",
"flipFlopFsm",
"(",
"self",
".",
"FSM_READ_VAR",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")"
] | Read Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the referenced Managed Objects Instances.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be either
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated). | [
"Read",
"Managed",
"Objects",
"Instances",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L383-L435 | train | 232,308 |
etingof/pysnmp | pysnmp/smi/instrum.py | MibInstrumController.readNextMibObjects | def readNextMibObjects(self, *varBinds, **context):
"""Read Managed Objects Instances next to the given ones.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the Managed Objects Instances next to the referenced ones.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read next to.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated) or :py:class:`EndOfMibView` (when the last Managed Object
Instance has been read).
When :py:class:`NoSuchObject` or :py:class:`NoSuchInstance` values are
returned, the caller is expected to repeat the same call with some
or all `varBinds` returned to progress towards the end of the
implemented MIB.
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_READ_NEXT_VAR, *varBinds, **context) | python | def readNextMibObjects(self, *varBinds, **context):
"""Read Managed Objects Instances next to the given ones.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the Managed Objects Instances next to the referenced ones.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read next to.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated) or :py:class:`EndOfMibView` (when the last Managed Object
Instance has been read).
When :py:class:`NoSuchObject` or :py:class:`NoSuchInstance` values are
returned, the caller is expected to repeat the same call with some
or all `varBinds` returned to progress towards the end of the
implemented MIB.
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_READ_NEXT_VAR, *varBinds, **context) | [
"def",
"readNextMibObjects",
"(",
"self",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"if",
"'cbFun'",
"not",
"in",
"context",
":",
"context",
"[",
"'cbFun'",
"]",
"=",
"self",
".",
"_defaultErrorHandler",
"self",
".",
"flipFlopFsm",
"(",
"self",
".",
"FSM_READ_NEXT_VAR",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")"
] | Read Managed Objects Instances next to the given ones.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the Managed Objects Instances next to the referenced ones.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read next to.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated) or :py:class:`EndOfMibView` (when the last Managed Object
Instance has been read).
When :py:class:`NoSuchObject` or :py:class:`NoSuchInstance` values are
returned, the caller is expected to repeat the same call with some
or all `varBinds` returned to progress towards the end of the
implemented MIB. | [
"Read",
"Managed",
"Objects",
"Instances",
"next",
"to",
"the",
"given",
"ones",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L437-L495 | train | 232,309 |
etingof/pysnmp | pysnmp/smi/instrum.py | MibInstrumController.writeMibObjects | def writeMibObjects(self, *varBinds, **context):
"""Create, destroy or modify Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create,
destroy or modify all or none of the referenced Managed Objects Instances.
If a non-existing Managed Object Instance is written, the new Managed Object
Instance will be created with the value given in the `varBinds`.
If existing Managed Object Instance is being written, its value is changed
to the new one.
Unless it's a :py:class:`RowStatus` object of a SMI table, in which case the
outcome of the *write* operation depends on the :py:class:`RowStatus`
transition. The whole table row could be created or destroyed or brought
on/offline.
When SMI table row is brought online (i.e. into the *active* state), all
columns will be checked for consistency. Error will be reported and write
operation will fail if inconsistency is found.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to modify.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but can't be
modified.
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_WRITE_VAR, *varBinds, **context) | python | def writeMibObjects(self, *varBinds, **context):
"""Create, destroy or modify Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create,
destroy or modify all or none of the referenced Managed Objects Instances.
If a non-existing Managed Object Instance is written, the new Managed Object
Instance will be created with the value given in the `varBinds`.
If existing Managed Object Instance is being written, its value is changed
to the new one.
Unless it's a :py:class:`RowStatus` object of a SMI table, in which case the
outcome of the *write* operation depends on the :py:class:`RowStatus`
transition. The whole table row could be created or destroyed or brought
on/offline.
When SMI table row is brought online (i.e. into the *active* state), all
columns will be checked for consistency. Error will be reported and write
operation will fail if inconsistency is found.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to modify.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but can't be
modified.
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_WRITE_VAR, *varBinds, **context) | [
"def",
"writeMibObjects",
"(",
"self",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"if",
"'cbFun'",
"not",
"in",
"context",
":",
"context",
"[",
"'cbFun'",
"]",
"=",
"self",
".",
"_defaultErrorHandler",
"self",
".",
"flipFlopFsm",
"(",
"self",
".",
"FSM_WRITE_VAR",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")"
] | Create, destroy or modify Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create,
destroy or modify all or none of the referenced Managed Objects Instances.
If a non-existing Managed Object Instance is written, the new Managed Object
Instance will be created with the value given in the `varBinds`.
If existing Managed Object Instance is being written, its value is changed
to the new one.
Unless it's a :py:class:`RowStatus` object of a SMI table, in which case the
outcome of the *write* operation depends on the :py:class:`RowStatus`
transition. The whole table row could be created or destroyed or brought
on/offline.
When SMI table row is brought online (i.e. into the *active* state), all
columns will be checked for consistency. Error will be reported and write
operation will fail if inconsistency is found.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to modify.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but can't be
modified. | [
"Create",
"destroy",
"or",
"modify",
"Managed",
"Objects",
"Instances",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L497-L564 | train | 232,310 |
etingof/pysnmp | pysnmp/hlapi/v1arch/asyncore/cmdgen.py | bulkCmd | def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
"""Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher`
Class instance representing SNMP dispatcher.
authData: :py:class:`~pysnmp.hlapi.v1arch.CommunityData` or :py:class:`~pysnmp.hlapi.v1arch.UsmUserData`
Class instance representing SNMP credentials.
transportTarget: :py:class:`~pysnmp.hlapi.v1arch.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.v1arch.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer
address.
nonRepeaters: int
One MIB variable is requested in response for the first
`nonRepeaters` MIB variables in request.
maxRepetitions: int
`maxRepetitions` MIB variables are requested in response for each
of the remaining MIB variables in the request (e.g. excluding
`nonRepeaters`). Remote SNMP dispatcher may choose lesser value than
requested.
\*varBinds: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `cbFun` (callable) - user-supplied callable that is invoked
to pass SNMP response data or error to user at a later point
of time. Default is `None`.
* `cbCtx` (object) - user-supplied object passing additional
parameters to/from `cbFun`. Default is `None`.
Notes
-----
User-supplied `cbFun` callable must have the following call
signature:
* snmpDispatcher (:py:class:`~pysnmp.hlapi.v1arch.snmpDispatcher`):
Class instance representing SNMP dispatcher.
* stateHandle (int): Unique request identifier. Can be used
for matching multiple ongoing requests with received responses.
* errorIndication (str): True value indicates SNMP dispatcher error.
* errorStatus (str): True value indicates SNMP PDU error.
* errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]`
* varBindTable (tuple): A sequence of sequences (e.g. 2-D array) of
variable-bindings represented as :class:`tuple` or
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response, with
up to ``maxRepetitions`` rows, i.e. ``len(varBindTable) <= maxRepetitions``.
For ``0 <= i < len(varBindTable)`` and ``0 <= j < len(varBinds)``,
``varBindTable[i][j]`` represents:
- For non-repeaters (``j < nonRepeaters``), the first lexicographic
successor of ``varBinds[j]``, regardless the value of ``i``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists;
- For repeaters (``j >= nonRepeaters``), the ``i``-th lexicographic
successor of ``varBinds[j]``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists.
See :rfc:`3416#section-4.2.3` for details on the underlying
``GetBulkRequest-PDU`` and the associated ``GetResponse-PDU``, such as
specific conditions under which the server may truncate the response,
causing ``varBindTable`` to have less than ``maxRepetitions`` rows.
* `cbCtx` (object): Original user-supplied object.
Returns
-------
stateHandle : int
Unique request identifier. Can be used for matching received
responses with ongoing requests.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Examples
--------
>>> from pysnmp.hlapi.v1arch.asyncore import *
>>>
>>> def cbFun(snmpDispatcher, stateHandle, errorIndication,
>>> errorStatus, errorIndex, varBinds, cbCtx):
>>> print(errorIndication, errorStatus, errorIndex, varBinds)
>>>
>>> snmpDispatcher = snmpDispatcher()
>>>
>>> stateHandle = bulkCmd(
>>> snmpDispatcher,
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> 0, 2,
>>> ('1.3.6.1.2.1.1', None),
>>> cbFun=cbFun
>>> )
>>>
>>> snmpDispatcher.transportDispatcher.runDispatcher()
"""
def _cbFun(snmpDispatcher, stateHandle, errorIndication, rspPdu, _cbCtx):
if not cbFun:
return
if errorIndication:
cbFun(errorIndication, pMod.Integer(0), pMod.Integer(0), None,
cbCtx=cbCtx, snmpDispatcher=snmpDispatcher, stateHandle=stateHandle)
return
errorStatus = pMod.apiBulkPDU.getErrorStatus(rspPdu)
errorIndex = pMod.apiBulkPDU.getErrorIndex(rspPdu)
varBindTable = pMod.apiBulkPDU.getVarBindTable(reqPdu, rspPdu)
errorIndication, nextVarBinds = pMod.apiBulkPDU.getNextVarBinds(
varBindTable[-1], errorIndex=errorIndex
)
if options.get('lookupMib'):
varBindTable = [
VB_PROCESSOR.unmakeVarBinds(snmpDispatcher.cache, vbs) for vbs in varBindTable
]
nextStateHandle = pMod.getNextRequestID()
nextVarBinds = cbFun(errorIndication, errorStatus, errorIndex, varBindTable,
cbCtx=cbCtx,
snmpDispatcher=snmpDispatcher,
stateHandle=stateHandle,
nextStateHandle=nextStateHandle,
nextVarBinds=nextVarBinds)
if not nextVarBinds:
return
pMod.apiBulkPDU.setRequestID(reqPdu, nextStateHandle)
pMod.apiBulkPDU.setVarBinds(reqPdu, nextVarBinds)
return snmpDispatcher.sendPdu(authData, transportTarget, reqPdu, cbFun=_cbFun)
if authData.mpModel < 1:
raise error.PySnmpError('GETBULK PDU is only supported in SNMPv2c and SNMPv3')
lookupMib, cbFun, cbCtx = [options.get(x) for x in ('lookupMib', 'cbFun', 'cbCtx')]
if lookupMib:
varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqPdu = pMod.GetBulkRequestPDU()
pMod.apiBulkPDU.setDefaults(reqPdu)
pMod.apiBulkPDU.setNonRepeaters(reqPdu, nonRepeaters)
pMod.apiBulkPDU.setMaxRepetitions(reqPdu, maxRepetitions)
pMod.apiBulkPDU.setVarBinds(reqPdu, varBinds)
return snmpDispatcher.sendPdu(authData, transportTarget, reqPdu, cbFun=_cbFun) | python | def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
"""Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher`
Class instance representing SNMP dispatcher.
authData: :py:class:`~pysnmp.hlapi.v1arch.CommunityData` or :py:class:`~pysnmp.hlapi.v1arch.UsmUserData`
Class instance representing SNMP credentials.
transportTarget: :py:class:`~pysnmp.hlapi.v1arch.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.v1arch.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer
address.
nonRepeaters: int
One MIB variable is requested in response for the first
`nonRepeaters` MIB variables in request.
maxRepetitions: int
`maxRepetitions` MIB variables are requested in response for each
of the remaining MIB variables in the request (e.g. excluding
`nonRepeaters`). Remote SNMP dispatcher may choose lesser value than
requested.
\*varBinds: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `cbFun` (callable) - user-supplied callable that is invoked
to pass SNMP response data or error to user at a later point
of time. Default is `None`.
* `cbCtx` (object) - user-supplied object passing additional
parameters to/from `cbFun`. Default is `None`.
Notes
-----
User-supplied `cbFun` callable must have the following call
signature:
* snmpDispatcher (:py:class:`~pysnmp.hlapi.v1arch.snmpDispatcher`):
Class instance representing SNMP dispatcher.
* stateHandle (int): Unique request identifier. Can be used
for matching multiple ongoing requests with received responses.
* errorIndication (str): True value indicates SNMP dispatcher error.
* errorStatus (str): True value indicates SNMP PDU error.
* errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]`
* varBindTable (tuple): A sequence of sequences (e.g. 2-D array) of
variable-bindings represented as :class:`tuple` or
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response, with
up to ``maxRepetitions`` rows, i.e. ``len(varBindTable) <= maxRepetitions``.
For ``0 <= i < len(varBindTable)`` and ``0 <= j < len(varBinds)``,
``varBindTable[i][j]`` represents:
- For non-repeaters (``j < nonRepeaters``), the first lexicographic
successor of ``varBinds[j]``, regardless the value of ``i``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists;
- For repeaters (``j >= nonRepeaters``), the ``i``-th lexicographic
successor of ``varBinds[j]``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists.
See :rfc:`3416#section-4.2.3` for details on the underlying
``GetBulkRequest-PDU`` and the associated ``GetResponse-PDU``, such as
specific conditions under which the server may truncate the response,
causing ``varBindTable`` to have less than ``maxRepetitions`` rows.
* `cbCtx` (object): Original user-supplied object.
Returns
-------
stateHandle : int
Unique request identifier. Can be used for matching received
responses with ongoing requests.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Examples
--------
>>> from pysnmp.hlapi.v1arch.asyncore import *
>>>
>>> def cbFun(snmpDispatcher, stateHandle, errorIndication,
>>> errorStatus, errorIndex, varBinds, cbCtx):
>>> print(errorIndication, errorStatus, errorIndex, varBinds)
>>>
>>> snmpDispatcher = snmpDispatcher()
>>>
>>> stateHandle = bulkCmd(
>>> snmpDispatcher,
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> 0, 2,
>>> ('1.3.6.1.2.1.1', None),
>>> cbFun=cbFun
>>> )
>>>
>>> snmpDispatcher.transportDispatcher.runDispatcher()
"""
def _cbFun(snmpDispatcher, stateHandle, errorIndication, rspPdu, _cbCtx):
if not cbFun:
return
if errorIndication:
cbFun(errorIndication, pMod.Integer(0), pMod.Integer(0), None,
cbCtx=cbCtx, snmpDispatcher=snmpDispatcher, stateHandle=stateHandle)
return
errorStatus = pMod.apiBulkPDU.getErrorStatus(rspPdu)
errorIndex = pMod.apiBulkPDU.getErrorIndex(rspPdu)
varBindTable = pMod.apiBulkPDU.getVarBindTable(reqPdu, rspPdu)
errorIndication, nextVarBinds = pMod.apiBulkPDU.getNextVarBinds(
varBindTable[-1], errorIndex=errorIndex
)
if options.get('lookupMib'):
varBindTable = [
VB_PROCESSOR.unmakeVarBinds(snmpDispatcher.cache, vbs) for vbs in varBindTable
]
nextStateHandle = pMod.getNextRequestID()
nextVarBinds = cbFun(errorIndication, errorStatus, errorIndex, varBindTable,
cbCtx=cbCtx,
snmpDispatcher=snmpDispatcher,
stateHandle=stateHandle,
nextStateHandle=nextStateHandle,
nextVarBinds=nextVarBinds)
if not nextVarBinds:
return
pMod.apiBulkPDU.setRequestID(reqPdu, nextStateHandle)
pMod.apiBulkPDU.setVarBinds(reqPdu, nextVarBinds)
return snmpDispatcher.sendPdu(authData, transportTarget, reqPdu, cbFun=_cbFun)
if authData.mpModel < 1:
raise error.PySnmpError('GETBULK PDU is only supported in SNMPv2c and SNMPv3')
lookupMib, cbFun, cbCtx = [options.get(x) for x in ('lookupMib', 'cbFun', 'cbCtx')]
if lookupMib:
varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqPdu = pMod.GetBulkRequestPDU()
pMod.apiBulkPDU.setDefaults(reqPdu)
pMod.apiBulkPDU.setNonRepeaters(reqPdu, nonRepeaters)
pMod.apiBulkPDU.setMaxRepetitions(reqPdu, maxRepetitions)
pMod.apiBulkPDU.setVarBinds(reqPdu, varBinds)
return snmpDispatcher.sendPdu(authData, transportTarget, reqPdu, cbFun=_cbFun) | [
"def",
"bulkCmd",
"(",
"snmpDispatcher",
",",
"authData",
",",
"transportTarget",
",",
"nonRepeaters",
",",
"maxRepetitions",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"_cbFun",
"(",
"snmpDispatcher",
",",
"stateHandle",
",",
"errorIndication",
",",
"rspPdu",
",",
"_cbCtx",
")",
":",
"if",
"not",
"cbFun",
":",
"return",
"if",
"errorIndication",
":",
"cbFun",
"(",
"errorIndication",
",",
"pMod",
".",
"Integer",
"(",
"0",
")",
",",
"pMod",
".",
"Integer",
"(",
"0",
")",
",",
"None",
",",
"cbCtx",
"=",
"cbCtx",
",",
"snmpDispatcher",
"=",
"snmpDispatcher",
",",
"stateHandle",
"=",
"stateHandle",
")",
"return",
"errorStatus",
"=",
"pMod",
".",
"apiBulkPDU",
".",
"getErrorStatus",
"(",
"rspPdu",
")",
"errorIndex",
"=",
"pMod",
".",
"apiBulkPDU",
".",
"getErrorIndex",
"(",
"rspPdu",
")",
"varBindTable",
"=",
"pMod",
".",
"apiBulkPDU",
".",
"getVarBindTable",
"(",
"reqPdu",
",",
"rspPdu",
")",
"errorIndication",
",",
"nextVarBinds",
"=",
"pMod",
".",
"apiBulkPDU",
".",
"getNextVarBinds",
"(",
"varBindTable",
"[",
"-",
"1",
"]",
",",
"errorIndex",
"=",
"errorIndex",
")",
"if",
"options",
".",
"get",
"(",
"'lookupMib'",
")",
":",
"varBindTable",
"=",
"[",
"VB_PROCESSOR",
".",
"unmakeVarBinds",
"(",
"snmpDispatcher",
".",
"cache",
",",
"vbs",
")",
"for",
"vbs",
"in",
"varBindTable",
"]",
"nextStateHandle",
"=",
"pMod",
".",
"getNextRequestID",
"(",
")",
"nextVarBinds",
"=",
"cbFun",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
",",
"cbCtx",
"=",
"cbCtx",
",",
"snmpDispatcher",
"=",
"snmpDispatcher",
",",
"stateHandle",
"=",
"stateHandle",
",",
"nextStateHandle",
"=",
"nextStateHandle",
",",
"nextVarBinds",
"=",
"nextVarBinds",
")",
"if",
"not",
"nextVarBinds",
":",
"return",
"pMod",
".",
"apiBulkPDU",
".",
"setRequestID",
"(",
"reqPdu",
",",
"nextStateHandle",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setVarBinds",
"(",
"reqPdu",
",",
"nextVarBinds",
")",
"return",
"snmpDispatcher",
".",
"sendPdu",
"(",
"authData",
",",
"transportTarget",
",",
"reqPdu",
",",
"cbFun",
"=",
"_cbFun",
")",
"if",
"authData",
".",
"mpModel",
"<",
"1",
":",
"raise",
"error",
".",
"PySnmpError",
"(",
"'GETBULK PDU is only supported in SNMPv2c and SNMPv3'",
")",
"lookupMib",
",",
"cbFun",
",",
"cbCtx",
"=",
"[",
"options",
".",
"get",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"'lookupMib'",
",",
"'cbFun'",
",",
"'cbCtx'",
")",
"]",
"if",
"lookupMib",
":",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpDispatcher",
".",
"cache",
",",
"varBinds",
")",
"pMod",
"=",
"api",
".",
"PROTOCOL_MODULES",
"[",
"authData",
".",
"mpModel",
"]",
"reqPdu",
"=",
"pMod",
".",
"GetBulkRequestPDU",
"(",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setDefaults",
"(",
"reqPdu",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setNonRepeaters",
"(",
"reqPdu",
",",
"nonRepeaters",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setMaxRepetitions",
"(",
"reqPdu",
",",
"maxRepetitions",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setVarBinds",
"(",
"reqPdu",
",",
"varBinds",
")",
"return",
"snmpDispatcher",
".",
"sendPdu",
"(",
"authData",
",",
"transportTarget",
",",
"reqPdu",
",",
"cbFun",
"=",
"_cbFun",
")"
] | Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher`
Class instance representing SNMP dispatcher.
authData: :py:class:`~pysnmp.hlapi.v1arch.CommunityData` or :py:class:`~pysnmp.hlapi.v1arch.UsmUserData`
Class instance representing SNMP credentials.
transportTarget: :py:class:`~pysnmp.hlapi.v1arch.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.v1arch.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer
address.
nonRepeaters: int
One MIB variable is requested in response for the first
`nonRepeaters` MIB variables in request.
maxRepetitions: int
`maxRepetitions` MIB variables are requested in response for each
of the remaining MIB variables in the request (e.g. excluding
`nonRepeaters`). Remote SNMP dispatcher may choose lesser value than
requested.
\*varBinds: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `cbFun` (callable) - user-supplied callable that is invoked
to pass SNMP response data or error to user at a later point
of time. Default is `None`.
* `cbCtx` (object) - user-supplied object passing additional
parameters to/from `cbFun`. Default is `None`.
Notes
-----
User-supplied `cbFun` callable must have the following call
signature:
* snmpDispatcher (:py:class:`~pysnmp.hlapi.v1arch.snmpDispatcher`):
Class instance representing SNMP dispatcher.
* stateHandle (int): Unique request identifier. Can be used
for matching multiple ongoing requests with received responses.
* errorIndication (str): True value indicates SNMP dispatcher error.
* errorStatus (str): True value indicates SNMP PDU error.
* errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]`
* varBindTable (tuple): A sequence of sequences (e.g. 2-D array) of
variable-bindings represented as :class:`tuple` or
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response, with
up to ``maxRepetitions`` rows, i.e. ``len(varBindTable) <= maxRepetitions``.
For ``0 <= i < len(varBindTable)`` and ``0 <= j < len(varBinds)``,
``varBindTable[i][j]`` represents:
- For non-repeaters (``j < nonRepeaters``), the first lexicographic
successor of ``varBinds[j]``, regardless the value of ``i``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists;
- For repeaters (``j >= nonRepeaters``), the ``i``-th lexicographic
successor of ``varBinds[j]``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists.
See :rfc:`3416#section-4.2.3` for details on the underlying
``GetBulkRequest-PDU`` and the associated ``GetResponse-PDU``, such as
specific conditions under which the server may truncate the response,
causing ``varBindTable`` to have less than ``maxRepetitions`` rows.
* `cbCtx` (object): Original user-supplied object.
Returns
-------
stateHandle : int
Unique request identifier. Can be used for matching received
responses with ongoing requests.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Examples
--------
>>> from pysnmp.hlapi.v1arch.asyncore import *
>>>
>>> def cbFun(snmpDispatcher, stateHandle, errorIndication,
>>> errorStatus, errorIndex, varBinds, cbCtx):
>>> print(errorIndication, errorStatus, errorIndex, varBinds)
>>>
>>> snmpDispatcher = snmpDispatcher()
>>>
>>> stateHandle = bulkCmd(
>>> snmpDispatcher,
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> 0, 2,
>>> ('1.3.6.1.2.1.1', None),
>>> cbFun=cbFun
>>> )
>>>
>>> snmpDispatcher.transportDispatcher.runDispatcher() | [
"Initiate",
"SNMP",
"GETBULK",
"query",
"over",
"SNMPv2c",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v1arch/asyncore/cmdgen.py#L451-L626 | train | 232,311 |
markreidvfx/pyaaf2 | aaf2/file.py | AAFFile.save | def save(self):
"""
Writes current changes to disk and flushes modified objects in the
AAFObjectManager
"""
if self.mode in ("wb+", 'rb+'):
if not self.is_open:
raise IOError("file closed")
self.write_reference_properties()
self.manager.write_objects() | python | def save(self):
"""
Writes current changes to disk and flushes modified objects in the
AAFObjectManager
"""
if self.mode in ("wb+", 'rb+'):
if not self.is_open:
raise IOError("file closed")
self.write_reference_properties()
self.manager.write_objects() | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"in",
"(",
"\"wb+\"",
",",
"'rb+'",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"IOError",
"(",
"\"file closed\"",
")",
"self",
".",
"write_reference_properties",
"(",
")",
"self",
".",
"manager",
".",
"write_objects",
"(",
")"
] | Writes current changes to disk and flushes modified objects in the
AAFObjectManager | [
"Writes",
"current",
"changes",
"to",
"disk",
"and",
"flushes",
"modified",
"objects",
"in",
"the",
"AAFObjectManager"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/file.py#L339-L348 | train | 232,312 |
markreidvfx/pyaaf2 | aaf2/file.py | AAFFile.close | def close(self):
"""
Close the file. A closed file cannot be read or written any more.
"""
self.save()
self.manager.remove_temp()
self.cfb.close()
self.is_open = False
self.f.close() | python | def close(self):
"""
Close the file. A closed file cannot be read or written any more.
"""
self.save()
self.manager.remove_temp()
self.cfb.close()
self.is_open = False
self.f.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"save",
"(",
")",
"self",
".",
"manager",
".",
"remove_temp",
"(",
")",
"self",
".",
"cfb",
".",
"close",
"(",
")",
"self",
".",
"is_open",
"=",
"False",
"self",
".",
"f",
".",
"close",
"(",
")"
] | Close the file. A closed file cannot be read or written any more. | [
"Close",
"the",
"file",
".",
"A",
"closed",
"file",
"cannot",
"be",
"read",
"or",
"written",
"any",
"more",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/file.py#L350-L358 | train | 232,313 |
markreidvfx/pyaaf2 | docs/source/conf.py | run_apidoc | def run_apidoc(_):
"""This method is required by the setup method below."""
import os
dirname = os.path.dirname(__file__)
ignore_paths = [os.path.join(dirname, '../../aaf2/model'),]
# https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py
argv = [
'--force',
'--no-toc',
'--separate',
'--module-first',
'--output-dir',
os.path.join(dirname, 'api'),
os.path.join(dirname, '../../aaf2'),
] + ignore_paths
from sphinx.ext import apidoc
apidoc.main(argv) | python | def run_apidoc(_):
"""This method is required by the setup method below."""
import os
dirname = os.path.dirname(__file__)
ignore_paths = [os.path.join(dirname, '../../aaf2/model'),]
# https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py
argv = [
'--force',
'--no-toc',
'--separate',
'--module-first',
'--output-dir',
os.path.join(dirname, 'api'),
os.path.join(dirname, '../../aaf2'),
] + ignore_paths
from sphinx.ext import apidoc
apidoc.main(argv) | [
"def",
"run_apidoc",
"(",
"_",
")",
":",
"import",
"os",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"ignore_paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'../../aaf2/model'",
")",
",",
"]",
"# https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py",
"argv",
"=",
"[",
"'--force'",
",",
"'--no-toc'",
",",
"'--separate'",
",",
"'--module-first'",
",",
"'--output-dir'",
",",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'api'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'../../aaf2'",
")",
",",
"]",
"+",
"ignore_paths",
"from",
"sphinx",
".",
"ext",
"import",
"apidoc",
"apidoc",
".",
"main",
"(",
"argv",
")"
] | This method is required by the setup method below. | [
"This",
"method",
"is",
"required",
"by",
"the",
"setup",
"method",
"below",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/docs/source/conf.py#L182-L199 | train | 232,314 |
markreidvfx/pyaaf2 | aaf2/mobid.py | MobID.from_dict | def from_dict(self, d):
"""
Set MobID from a dict
"""
self.length = d.get("length", 0)
self.instanceHigh = d.get("instanceHigh", 0)
self.instanceMid = d.get("instanceMid", 0)
self.instanceLow = d.get("instanceLow", 0)
material = d.get("material", {'Data1':0, 'Data2':0, 'Data3':0, 'Data4': [0 for i in range(8)]})
self.Data1 = material.get('Data1', 0)
self.Data2 = material.get('Data2', 0)
self.Data3 = material.get('Data3', 0)
self.Data4 = material.get("Data4", [0 for i in range(8)])
self.SMPTELabel = d.get("SMPTELabel", [0 for i in range(12)]) | python | def from_dict(self, d):
"""
Set MobID from a dict
"""
self.length = d.get("length", 0)
self.instanceHigh = d.get("instanceHigh", 0)
self.instanceMid = d.get("instanceMid", 0)
self.instanceLow = d.get("instanceLow", 0)
material = d.get("material", {'Data1':0, 'Data2':0, 'Data3':0, 'Data4': [0 for i in range(8)]})
self.Data1 = material.get('Data1', 0)
self.Data2 = material.get('Data2', 0)
self.Data3 = material.get('Data3', 0)
self.Data4 = material.get("Data4", [0 for i in range(8)])
self.SMPTELabel = d.get("SMPTELabel", [0 for i in range(12)]) | [
"def",
"from_dict",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"length",
"=",
"d",
".",
"get",
"(",
"\"length\"",
",",
"0",
")",
"self",
".",
"instanceHigh",
"=",
"d",
".",
"get",
"(",
"\"instanceHigh\"",
",",
"0",
")",
"self",
".",
"instanceMid",
"=",
"d",
".",
"get",
"(",
"\"instanceMid\"",
",",
"0",
")",
"self",
".",
"instanceLow",
"=",
"d",
".",
"get",
"(",
"\"instanceLow\"",
",",
"0",
")",
"material",
"=",
"d",
".",
"get",
"(",
"\"material\"",
",",
"{",
"'Data1'",
":",
"0",
",",
"'Data2'",
":",
"0",
",",
"'Data3'",
":",
"0",
",",
"'Data4'",
":",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"8",
")",
"]",
"}",
")",
"self",
".",
"Data1",
"=",
"material",
".",
"get",
"(",
"'Data1'",
",",
"0",
")",
"self",
".",
"Data2",
"=",
"material",
".",
"get",
"(",
"'Data2'",
",",
"0",
")",
"self",
".",
"Data3",
"=",
"material",
".",
"get",
"(",
"'Data3'",
",",
"0",
")",
"self",
".",
"Data4",
"=",
"material",
".",
"get",
"(",
"\"Data4\"",
",",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"8",
")",
"]",
")",
"self",
".",
"SMPTELabel",
"=",
"d",
".",
"get",
"(",
"\"SMPTELabel\"",
",",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"12",
")",
"]",
")"
] | Set MobID from a dict | [
"Set",
"MobID",
"from",
"a",
"dict"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L280-L296 | train | 232,315 |
markreidvfx/pyaaf2 | aaf2/mobid.py | MobID.to_dict | def to_dict(self):
"""
MobID representation as dict
"""
material = {'Data1': self.Data1,
'Data2': self.Data2,
'Data3': self.Data3,
'Data4': list(self.Data4)
}
return {'material':material,
'length': self.length,
'instanceHigh': self.instanceHigh,
'instanceMid': self.instanceMid,
'instanceLow': self.instanceLow,
'SMPTELabel': list(self.SMPTELabel)
} | python | def to_dict(self):
"""
MobID representation as dict
"""
material = {'Data1': self.Data1,
'Data2': self.Data2,
'Data3': self.Data3,
'Data4': list(self.Data4)
}
return {'material':material,
'length': self.length,
'instanceHigh': self.instanceHigh,
'instanceMid': self.instanceMid,
'instanceLow': self.instanceLow,
'SMPTELabel': list(self.SMPTELabel)
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"material",
"=",
"{",
"'Data1'",
":",
"self",
".",
"Data1",
",",
"'Data2'",
":",
"self",
".",
"Data2",
",",
"'Data3'",
":",
"self",
".",
"Data3",
",",
"'Data4'",
":",
"list",
"(",
"self",
".",
"Data4",
")",
"}",
"return",
"{",
"'material'",
":",
"material",
",",
"'length'",
":",
"self",
".",
"length",
",",
"'instanceHigh'",
":",
"self",
".",
"instanceHigh",
",",
"'instanceMid'",
":",
"self",
".",
"instanceMid",
",",
"'instanceLow'",
":",
"self",
".",
"instanceLow",
",",
"'SMPTELabel'",
":",
"list",
"(",
"self",
".",
"SMPTELabel",
")",
"}"
] | MobID representation as dict | [
"MobID",
"representation",
"as",
"dict"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L298-L315 | train | 232,316 |
markreidvfx/pyaaf2 | aaf2/ama.py | wave_infochunk | def wave_infochunk(path):
"""
Returns a bytearray of the WAVE RIFF header and fmt
chunk for a `WAVEDescriptor` `Summary`
"""
with open(path,'rb') as file:
if file.read(4) != b"RIFF":
return None
data_size = file.read(4) # container size
if file.read(4) != b"WAVE":
return None
while True:
chunkid = file.read(4)
sizebuf = file.read(4)
if len(sizebuf) < 4 or len(chunkid) < 4:
return None
size = struct.unpack(b'<L', sizebuf )[0]
if chunkid[0:3] != b"fmt":
if size % 2 == 1:
seek = size + 1
else:
seek = size
file.seek(size,1)
else:
return bytearray(b"RIFF" + data_size + b"WAVE" + chunkid + sizebuf + file.read(size)) | python | def wave_infochunk(path):
"""
Returns a bytearray of the WAVE RIFF header and fmt
chunk for a `WAVEDescriptor` `Summary`
"""
with open(path,'rb') as file:
if file.read(4) != b"RIFF":
return None
data_size = file.read(4) # container size
if file.read(4) != b"WAVE":
return None
while True:
chunkid = file.read(4)
sizebuf = file.read(4)
if len(sizebuf) < 4 or len(chunkid) < 4:
return None
size = struct.unpack(b'<L', sizebuf )[0]
if chunkid[0:3] != b"fmt":
if size % 2 == 1:
seek = size + 1
else:
seek = size
file.seek(size,1)
else:
return bytearray(b"RIFF" + data_size + b"WAVE" + chunkid + sizebuf + file.read(size)) | [
"def",
"wave_infochunk",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"file",
":",
"if",
"file",
".",
"read",
"(",
"4",
")",
"!=",
"b\"RIFF\"",
":",
"return",
"None",
"data_size",
"=",
"file",
".",
"read",
"(",
"4",
")",
"# container size",
"if",
"file",
".",
"read",
"(",
"4",
")",
"!=",
"b\"WAVE\"",
":",
"return",
"None",
"while",
"True",
":",
"chunkid",
"=",
"file",
".",
"read",
"(",
"4",
")",
"sizebuf",
"=",
"file",
".",
"read",
"(",
"4",
")",
"if",
"len",
"(",
"sizebuf",
")",
"<",
"4",
"or",
"len",
"(",
"chunkid",
")",
"<",
"4",
":",
"return",
"None",
"size",
"=",
"struct",
".",
"unpack",
"(",
"b'<L'",
",",
"sizebuf",
")",
"[",
"0",
"]",
"if",
"chunkid",
"[",
"0",
":",
"3",
"]",
"!=",
"b\"fmt\"",
":",
"if",
"size",
"%",
"2",
"==",
"1",
":",
"seek",
"=",
"size",
"+",
"1",
"else",
":",
"seek",
"=",
"size",
"file",
".",
"seek",
"(",
"size",
",",
"1",
")",
"else",
":",
"return",
"bytearray",
"(",
"b\"RIFF\"",
"+",
"data_size",
"+",
"b\"WAVE\"",
"+",
"chunkid",
"+",
"sizebuf",
"+",
"file",
".",
"read",
"(",
"size",
")",
")"
] | Returns a bytearray of the WAVE RIFF header and fmt
chunk for a `WAVEDescriptor` `Summary` | [
"Returns",
"a",
"bytearray",
"of",
"the",
"WAVE",
"RIFF",
"header",
"and",
"fmt",
"chunk",
"for",
"a",
"WAVEDescriptor",
"Summary"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/ama.py#L329-L353 | train | 232,317 |
markreidvfx/pyaaf2 | aaf2/cfb.py | DirEntry.pop | def pop(self):
"""
remove self from binary search tree
"""
entry = self
parent = self.parent
root = parent.child()
dir_per_sector = self.storage.sector_size // 128
max_dirs_entries = self.storage.dir_sector_count * dir_per_sector
count = 0
if root.dir_id == entry.dir_id:
parent.child_id = None
else:
# find dir entry pointing to self
while True:
if count > max_dirs_entries:
raise CompoundFileBinaryError("max dir entries limit reached")
if entry < root:
if root.left_id == entry.dir_id:
root.left_id = None
break
root = root.left()
else:
if root.right_id == entry.dir_id:
# root right is pointing to self
root.right_id = None
break
root = root.right()
count += 1
left = entry.left()
right = entry.right()
# clear from cache
if parent.dir_id in self.storage.children_cache:
del self.storage.children_cache[parent.dir_id][entry.name]
if left:
del self.storage.children_cache[parent.dir_id][left.name]
if right:
del self.storage.children_cache[parent.dir_id][right.name]
if left is not None:
parent.add_child(left)
if right is not None:
parent.add_child(right)
# clear parent and left and right
self.left_id = None
self.right_id = None
self.parent = None | python | def pop(self):
"""
remove self from binary search tree
"""
entry = self
parent = self.parent
root = parent.child()
dir_per_sector = self.storage.sector_size // 128
max_dirs_entries = self.storage.dir_sector_count * dir_per_sector
count = 0
if root.dir_id == entry.dir_id:
parent.child_id = None
else:
# find dir entry pointing to self
while True:
if count > max_dirs_entries:
raise CompoundFileBinaryError("max dir entries limit reached")
if entry < root:
if root.left_id == entry.dir_id:
root.left_id = None
break
root = root.left()
else:
if root.right_id == entry.dir_id:
# root right is pointing to self
root.right_id = None
break
root = root.right()
count += 1
left = entry.left()
right = entry.right()
# clear from cache
if parent.dir_id in self.storage.children_cache:
del self.storage.children_cache[parent.dir_id][entry.name]
if left:
del self.storage.children_cache[parent.dir_id][left.name]
if right:
del self.storage.children_cache[parent.dir_id][right.name]
if left is not None:
parent.add_child(left)
if right is not None:
parent.add_child(right)
# clear parent and left and right
self.left_id = None
self.right_id = None
self.parent = None | [
"def",
"pop",
"(",
"self",
")",
":",
"entry",
"=",
"self",
"parent",
"=",
"self",
".",
"parent",
"root",
"=",
"parent",
".",
"child",
"(",
")",
"dir_per_sector",
"=",
"self",
".",
"storage",
".",
"sector_size",
"//",
"128",
"max_dirs_entries",
"=",
"self",
".",
"storage",
".",
"dir_sector_count",
"*",
"dir_per_sector",
"count",
"=",
"0",
"if",
"root",
".",
"dir_id",
"==",
"entry",
".",
"dir_id",
":",
"parent",
".",
"child_id",
"=",
"None",
"else",
":",
"# find dir entry pointing to self",
"while",
"True",
":",
"if",
"count",
">",
"max_dirs_entries",
":",
"raise",
"CompoundFileBinaryError",
"(",
"\"max dir entries limit reached\"",
")",
"if",
"entry",
"<",
"root",
":",
"if",
"root",
".",
"left_id",
"==",
"entry",
".",
"dir_id",
":",
"root",
".",
"left_id",
"=",
"None",
"break",
"root",
"=",
"root",
".",
"left",
"(",
")",
"else",
":",
"if",
"root",
".",
"right_id",
"==",
"entry",
".",
"dir_id",
":",
"# root right is pointing to self",
"root",
".",
"right_id",
"=",
"None",
"break",
"root",
"=",
"root",
".",
"right",
"(",
")",
"count",
"+=",
"1",
"left",
"=",
"entry",
".",
"left",
"(",
")",
"right",
"=",
"entry",
".",
"right",
"(",
")",
"# clear from cache",
"if",
"parent",
".",
"dir_id",
"in",
"self",
".",
"storage",
".",
"children_cache",
":",
"del",
"self",
".",
"storage",
".",
"children_cache",
"[",
"parent",
".",
"dir_id",
"]",
"[",
"entry",
".",
"name",
"]",
"if",
"left",
":",
"del",
"self",
".",
"storage",
".",
"children_cache",
"[",
"parent",
".",
"dir_id",
"]",
"[",
"left",
".",
"name",
"]",
"if",
"right",
":",
"del",
"self",
".",
"storage",
".",
"children_cache",
"[",
"parent",
".",
"dir_id",
"]",
"[",
"right",
".",
"name",
"]",
"if",
"left",
"is",
"not",
"None",
":",
"parent",
".",
"add_child",
"(",
"left",
")",
"if",
"right",
"is",
"not",
"None",
":",
"parent",
".",
"add_child",
"(",
"right",
")",
"# clear parent and left and right",
"self",
".",
"left_id",
"=",
"None",
"self",
".",
"right_id",
"=",
"None",
"self",
".",
"parent",
"=",
"None"
] | remove self from binary search tree | [
"remove",
"self",
"from",
"binary",
"search",
"tree"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L609-L664 | train | 232,318 |
markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.remove | def remove(self, path):
"""
Removes both streams and storage DirEntry types from file.
storage type entries need to be empty dirs.
"""
entry = self.find(path)
if not entry:
raise ValueError("%s does not exists" % path)
if entry.type == 'root storage':
raise ValueError("can no remove root entry")
if entry.type == "storage" and not entry.child_id is None:
raise ValueError("storage contains children")
entry.pop()
# remove stream data
if entry.type == "stream":
self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)
self.free_dir_entry(entry) | python | def remove(self, path):
"""
Removes both streams and storage DirEntry types from file.
storage type entries need to be empty dirs.
"""
entry = self.find(path)
if not entry:
raise ValueError("%s does not exists" % path)
if entry.type == 'root storage':
raise ValueError("can no remove root entry")
if entry.type == "storage" and not entry.child_id is None:
raise ValueError("storage contains children")
entry.pop()
# remove stream data
if entry.type == "stream":
self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)
self.free_dir_entry(entry) | [
"def",
"remove",
"(",
"self",
",",
"path",
")",
":",
"entry",
"=",
"self",
".",
"find",
"(",
"path",
")",
"if",
"not",
"entry",
":",
"raise",
"ValueError",
"(",
"\"%s does not exists\"",
"%",
"path",
")",
"if",
"entry",
".",
"type",
"==",
"'root storage'",
":",
"raise",
"ValueError",
"(",
"\"can no remove root entry\"",
")",
"if",
"entry",
".",
"type",
"==",
"\"storage\"",
"and",
"not",
"entry",
".",
"child_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"storage contains children\"",
")",
"entry",
".",
"pop",
"(",
")",
"# remove stream data",
"if",
"entry",
".",
"type",
"==",
"\"stream\"",
":",
"self",
".",
"free_fat_chain",
"(",
"entry",
".",
"sector_id",
",",
"entry",
".",
"byte_size",
"<",
"self",
".",
"min_stream_max_size",
")",
"self",
".",
"free_dir_entry",
"(",
"entry",
")"
] | Removes both streams and storage DirEntry types from file.
storage type entries need to be empty dirs. | [
"Removes",
"both",
"streams",
"and",
"storage",
"DirEntry",
"types",
"from",
"file",
".",
"storage",
"type",
"entries",
"need",
"to",
"be",
"empty",
"dirs",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1606-L1629 | train | 232,319 |
markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.rmtree | def rmtree(self, path):
"""
Removes directory structure, similar to shutil.rmtree.
"""
for root, storage, streams in self.walk(path, topdown=False):
for item in streams:
self.free_fat_chain(item.sector_id, item.byte_size < self.min_stream_max_size)
self.free_dir_entry(item)
for item in storage:
self.free_dir_entry(item)
root.child_id = None
# remove root item
self.remove(path) | python | def rmtree(self, path):
"""
Removes directory structure, similar to shutil.rmtree.
"""
for root, storage, streams in self.walk(path, topdown=False):
for item in streams:
self.free_fat_chain(item.sector_id, item.byte_size < self.min_stream_max_size)
self.free_dir_entry(item)
for item in storage:
self.free_dir_entry(item)
root.child_id = None
# remove root item
self.remove(path) | [
"def",
"rmtree",
"(",
"self",
",",
"path",
")",
":",
"for",
"root",
",",
"storage",
",",
"streams",
"in",
"self",
".",
"walk",
"(",
"path",
",",
"topdown",
"=",
"False",
")",
":",
"for",
"item",
"in",
"streams",
":",
"self",
".",
"free_fat_chain",
"(",
"item",
".",
"sector_id",
",",
"item",
".",
"byte_size",
"<",
"self",
".",
"min_stream_max_size",
")",
"self",
".",
"free_dir_entry",
"(",
"item",
")",
"for",
"item",
"in",
"storage",
":",
"self",
".",
"free_dir_entry",
"(",
"item",
")",
"root",
".",
"child_id",
"=",
"None",
"# remove root item",
"self",
".",
"remove",
"(",
"path",
")"
] | Removes directory structure, similar to shutil.rmtree. | [
"Removes",
"directory",
"structure",
"similar",
"to",
"shutil",
".",
"rmtree",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1632-L1648 | train | 232,320 |
markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.listdir_dict | def listdir_dict(self, path = None):
"""
Return a dict containing the ``DirEntry`` objects in the directory
given by path with name of the dir as key.
"""
if path is None:
path = self.root
root = self.find(path)
if root is None:
raise ValueError("unable to find dir: %s" % str(path))
if not root.isdir():
raise ValueError("can only list storage types")
children = self.children_cache.get(root.dir_id, None)
if children is not None:
return children
child = root.child()
result = {}
if not child:
self.children_cache[root.dir_id] = result
return result
dir_per_sector = self.sector_size // 128
max_dirs_entries = self.dir_sector_count * dir_per_sector
stack = deque([child])
count = 0
while stack:
current = stack.pop()
result[current.name] = current
count += 1
if count > max_dirs_entries:
raise CompoundFileBinaryError("corrupt folder structure")
left = current.left()
if left:
stack.append(left)
right = current.right()
if right:
stack.append(right)
self.children_cache[root.dir_id] = result
return result | python | def listdir_dict(self, path = None):
"""
Return a dict containing the ``DirEntry`` objects in the directory
given by path with name of the dir as key.
"""
if path is None:
path = self.root
root = self.find(path)
if root is None:
raise ValueError("unable to find dir: %s" % str(path))
if not root.isdir():
raise ValueError("can only list storage types")
children = self.children_cache.get(root.dir_id, None)
if children is not None:
return children
child = root.child()
result = {}
if not child:
self.children_cache[root.dir_id] = result
return result
dir_per_sector = self.sector_size // 128
max_dirs_entries = self.dir_sector_count * dir_per_sector
stack = deque([child])
count = 0
while stack:
current = stack.pop()
result[current.name] = current
count += 1
if count > max_dirs_entries:
raise CompoundFileBinaryError("corrupt folder structure")
left = current.left()
if left:
stack.append(left)
right = current.right()
if right:
stack.append(right)
self.children_cache[root.dir_id] = result
return result | [
"def",
"listdir_dict",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"root",
"root",
"=",
"self",
".",
"find",
"(",
"path",
")",
"if",
"root",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"unable to find dir: %s\"",
"%",
"str",
"(",
"path",
")",
")",
"if",
"not",
"root",
".",
"isdir",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"can only list storage types\"",
")",
"children",
"=",
"self",
".",
"children_cache",
".",
"get",
"(",
"root",
".",
"dir_id",
",",
"None",
")",
"if",
"children",
"is",
"not",
"None",
":",
"return",
"children",
"child",
"=",
"root",
".",
"child",
"(",
")",
"result",
"=",
"{",
"}",
"if",
"not",
"child",
":",
"self",
".",
"children_cache",
"[",
"root",
".",
"dir_id",
"]",
"=",
"result",
"return",
"result",
"dir_per_sector",
"=",
"self",
".",
"sector_size",
"//",
"128",
"max_dirs_entries",
"=",
"self",
".",
"dir_sector_count",
"*",
"dir_per_sector",
"stack",
"=",
"deque",
"(",
"[",
"child",
"]",
")",
"count",
"=",
"0",
"while",
"stack",
":",
"current",
"=",
"stack",
".",
"pop",
"(",
")",
"result",
"[",
"current",
".",
"name",
"]",
"=",
"current",
"count",
"+=",
"1",
"if",
"count",
">",
"max_dirs_entries",
":",
"raise",
"CompoundFileBinaryError",
"(",
"\"corrupt folder structure\"",
")",
"left",
"=",
"current",
".",
"left",
"(",
")",
"if",
"left",
":",
"stack",
".",
"append",
"(",
"left",
")",
"right",
"=",
"current",
".",
"right",
"(",
")",
"if",
"right",
":",
"stack",
".",
"append",
"(",
"right",
")",
"self",
".",
"children_cache",
"[",
"root",
".",
"dir_id",
"]",
"=",
"result",
"return",
"result"
] | Return a dict containing the ``DirEntry`` objects in the directory
given by path with name of the dir as key. | [
"Return",
"a",
"dict",
"containing",
"the",
"DirEntry",
"objects",
"in",
"the",
"directory",
"given",
"by",
"path",
"with",
"name",
"of",
"the",
"dir",
"as",
"key",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1660-L1709 | train | 232,321 |
markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.makedir | def makedir(self, path, class_id=None):
"""
Create a storage DirEntry name path
"""
return self.create_dir_entry(path, dir_type='storage', class_id=class_id) | python | def makedir(self, path, class_id=None):
"""
Create a storage DirEntry name path
"""
return self.create_dir_entry(path, dir_type='storage', class_id=class_id) | [
"def",
"makedir",
"(",
"self",
",",
"path",
",",
"class_id",
"=",
"None",
")",
":",
"return",
"self",
".",
"create_dir_entry",
"(",
"path",
",",
"dir_type",
"=",
"'storage'",
",",
"class_id",
"=",
"class_id",
")"
] | Create a storage DirEntry name path | [
"Create",
"a",
"storage",
"DirEntry",
"name",
"path"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1800-L1804 | train | 232,322 |
markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.makedirs | def makedirs(self, path):
"""
Recursive storage DirEntry creation function.
"""
root = ""
assert path.startswith('/')
p = path.strip('/')
for item in p.split('/'):
root += "/" + item
if not self.exists(root):
self.makedir(root)
return self.find(path) | python | def makedirs(self, path):
"""
Recursive storage DirEntry creation function.
"""
root = ""
assert path.startswith('/')
p = path.strip('/')
for item in p.split('/'):
root += "/" + item
if not self.exists(root):
self.makedir(root)
return self.find(path) | [
"def",
"makedirs",
"(",
"self",
",",
"path",
")",
":",
"root",
"=",
"\"\"",
"assert",
"path",
".",
"startswith",
"(",
"'/'",
")",
"p",
"=",
"path",
".",
"strip",
"(",
"'/'",
")",
"for",
"item",
"in",
"p",
".",
"split",
"(",
"'/'",
")",
":",
"root",
"+=",
"\"/\"",
"+",
"item",
"if",
"not",
"self",
".",
"exists",
"(",
"root",
")",
":",
"self",
".",
"makedir",
"(",
"root",
")",
"return",
"self",
".",
"find",
"(",
"path",
")"
] | Recursive storage DirEntry creation function. | [
"Recursive",
"storage",
"DirEntry",
"creation",
"function",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1806-L1819 | train | 232,323 |
markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.move | def move(self, src, dst):
"""
Moves ``DirEntry`` from src to dst
"""
src_entry = self.find(src)
if src_entry is None:
raise ValueError("src path does not exist: %s" % src)
if dst.endswith('/'):
dst += src_entry.name
if self.exists(dst):
raise ValueError("dst path already exist: %s" % dst)
if dst == '/' or src == '/':
raise ValueError("cannot overwrite root dir")
split_path = dst.strip('/').split('/')
dst_basename = split_path[-1]
dst_dirname = '/' + '/'.join(split_path[:-1])
# print(dst)
# print(dst_basename, dst_dirname)
dst_entry = self.find(dst_dirname)
if dst_entry is None:
raise ValueError("src path does not exist: %s" % dst_dirname)
if not dst_entry.isdir():
raise ValueError("dst dirname cannot be stream: %s" % dst_dirname)
# src_entry.parent.remove_child(src_entry)
src_entry.pop()
src_entry.parent = None
src_entry.name = dst_basename
dst_entry.add_child(src_entry)
self.children_cache[dst_entry.dir_id][src_entry.name] = src_entry
return src_entry | python | def move(self, src, dst):
"""
Moves ``DirEntry`` from src to dst
"""
src_entry = self.find(src)
if src_entry is None:
raise ValueError("src path does not exist: %s" % src)
if dst.endswith('/'):
dst += src_entry.name
if self.exists(dst):
raise ValueError("dst path already exist: %s" % dst)
if dst == '/' or src == '/':
raise ValueError("cannot overwrite root dir")
split_path = dst.strip('/').split('/')
dst_basename = split_path[-1]
dst_dirname = '/' + '/'.join(split_path[:-1])
# print(dst)
# print(dst_basename, dst_dirname)
dst_entry = self.find(dst_dirname)
if dst_entry is None:
raise ValueError("src path does not exist: %s" % dst_dirname)
if not dst_entry.isdir():
raise ValueError("dst dirname cannot be stream: %s" % dst_dirname)
# src_entry.parent.remove_child(src_entry)
src_entry.pop()
src_entry.parent = None
src_entry.name = dst_basename
dst_entry.add_child(src_entry)
self.children_cache[dst_entry.dir_id][src_entry.name] = src_entry
return src_entry | [
"def",
"move",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"src_entry",
"=",
"self",
".",
"find",
"(",
"src",
")",
"if",
"src_entry",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"src path does not exist: %s\"",
"%",
"src",
")",
"if",
"dst",
".",
"endswith",
"(",
"'/'",
")",
":",
"dst",
"+=",
"src_entry",
".",
"name",
"if",
"self",
".",
"exists",
"(",
"dst",
")",
":",
"raise",
"ValueError",
"(",
"\"dst path already exist: %s\"",
"%",
"dst",
")",
"if",
"dst",
"==",
"'/'",
"or",
"src",
"==",
"'/'",
":",
"raise",
"ValueError",
"(",
"\"cannot overwrite root dir\"",
")",
"split_path",
"=",
"dst",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"dst_basename",
"=",
"split_path",
"[",
"-",
"1",
"]",
"dst_dirname",
"=",
"'/'",
"+",
"'/'",
".",
"join",
"(",
"split_path",
"[",
":",
"-",
"1",
"]",
")",
"# print(dst)",
"# print(dst_basename, dst_dirname)",
"dst_entry",
"=",
"self",
".",
"find",
"(",
"dst_dirname",
")",
"if",
"dst_entry",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"src path does not exist: %s\"",
"%",
"dst_dirname",
")",
"if",
"not",
"dst_entry",
".",
"isdir",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"dst dirname cannot be stream: %s\"",
"%",
"dst_dirname",
")",
"# src_entry.parent.remove_child(src_entry)",
"src_entry",
".",
"pop",
"(",
")",
"src_entry",
".",
"parent",
"=",
"None",
"src_entry",
".",
"name",
"=",
"dst_basename",
"dst_entry",
".",
"add_child",
"(",
"src_entry",
")",
"self",
".",
"children_cache",
"[",
"dst_entry",
".",
"dir_id",
"]",
"[",
"src_entry",
".",
"name",
"]",
"=",
"src_entry",
"return",
"src_entry"
] | Moves ``DirEntry`` from src to dst | [
"Moves",
"DirEntry",
"from",
"src",
"to",
"dst"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1821-L1862 | train | 232,324 |
markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.open | def open(self, path, mode='r'):
"""Open stream, returning ``Stream`` object"""
entry = self.find(path)
if entry is None:
if mode == 'r':
raise ValueError("stream does not exists: %s" % path)
entry = self.create_dir_entry(path, 'stream', None)
else:
if not entry.isfile():
raise ValueError("can only open stream type DirEntry's")
if mode == 'w':
logging.debug("stream: %s exists, overwriting" % path)
self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)
entry.sector_id = None
entry.byte_size = 0
entry.class_id = None
elif mode == 'rw':
pass
s = Stream(self, entry, mode)
return s | python | def open(self, path, mode='r'):
"""Open stream, returning ``Stream`` object"""
entry = self.find(path)
if entry is None:
if mode == 'r':
raise ValueError("stream does not exists: %s" % path)
entry = self.create_dir_entry(path, 'stream', None)
else:
if not entry.isfile():
raise ValueError("can only open stream type DirEntry's")
if mode == 'w':
logging.debug("stream: %s exists, overwriting" % path)
self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)
entry.sector_id = None
entry.byte_size = 0
entry.class_id = None
elif mode == 'rw':
pass
s = Stream(self, entry, mode)
return s | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"'r'",
")",
":",
"entry",
"=",
"self",
".",
"find",
"(",
"path",
")",
"if",
"entry",
"is",
"None",
":",
"if",
"mode",
"==",
"'r'",
":",
"raise",
"ValueError",
"(",
"\"stream does not exists: %s\"",
"%",
"path",
")",
"entry",
"=",
"self",
".",
"create_dir_entry",
"(",
"path",
",",
"'stream'",
",",
"None",
")",
"else",
":",
"if",
"not",
"entry",
".",
"isfile",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"can only open stream type DirEntry's\"",
")",
"if",
"mode",
"==",
"'w'",
":",
"logging",
".",
"debug",
"(",
"\"stream: %s exists, overwriting\"",
"%",
"path",
")",
"self",
".",
"free_fat_chain",
"(",
"entry",
".",
"sector_id",
",",
"entry",
".",
"byte_size",
"<",
"self",
".",
"min_stream_max_size",
")",
"entry",
".",
"sector_id",
"=",
"None",
"entry",
".",
"byte_size",
"=",
"0",
"entry",
".",
"class_id",
"=",
"None",
"elif",
"mode",
"==",
"'rw'",
":",
"pass",
"s",
"=",
"Stream",
"(",
"self",
",",
"entry",
",",
"mode",
")",
"return",
"s"
] | Open stream, returning ``Stream`` object | [
"Open",
"stream",
"returning",
"Stream",
"object"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1864-L1887 | train | 232,325 |
markreidvfx/pyaaf2 | aaf2/properties.py | add2set | def add2set(self, pid, key, value):
"""low level add to StrongRefSetProperty"""
prop = self.property_entries[pid]
current = prop.objects.get(key, None)
current_local_key = prop.references.get(key, None)
if current and current is not value:
current.detach()
if current_local_key is None:
prop.references[key] = prop.next_free_key
prop.next_free_key += 1
prop.objects[key] = value
if prop.parent.dir:
ref = prop.index_ref_name(key)
dir_entry = prop.parent.dir.get(ref)
if dir_entry is None:
dir_entry = prop.parent.dir.makedir(ref)
if value.dir != dir_entry:
value.attach(dir_entry)
prop.mark_modified() | python | def add2set(self, pid, key, value):
"""low level add to StrongRefSetProperty"""
prop = self.property_entries[pid]
current = prop.objects.get(key, None)
current_local_key = prop.references.get(key, None)
if current and current is not value:
current.detach()
if current_local_key is None:
prop.references[key] = prop.next_free_key
prop.next_free_key += 1
prop.objects[key] = value
if prop.parent.dir:
ref = prop.index_ref_name(key)
dir_entry = prop.parent.dir.get(ref)
if dir_entry is None:
dir_entry = prop.parent.dir.makedir(ref)
if value.dir != dir_entry:
value.attach(dir_entry)
prop.mark_modified() | [
"def",
"add2set",
"(",
"self",
",",
"pid",
",",
"key",
",",
"value",
")",
":",
"prop",
"=",
"self",
".",
"property_entries",
"[",
"pid",
"]",
"current",
"=",
"prop",
".",
"objects",
".",
"get",
"(",
"key",
",",
"None",
")",
"current_local_key",
"=",
"prop",
".",
"references",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"current",
"and",
"current",
"is",
"not",
"value",
":",
"current",
".",
"detach",
"(",
")",
"if",
"current_local_key",
"is",
"None",
":",
"prop",
".",
"references",
"[",
"key",
"]",
"=",
"prop",
".",
"next_free_key",
"prop",
".",
"next_free_key",
"+=",
"1",
"prop",
".",
"objects",
"[",
"key",
"]",
"=",
"value",
"if",
"prop",
".",
"parent",
".",
"dir",
":",
"ref",
"=",
"prop",
".",
"index_ref_name",
"(",
"key",
")",
"dir_entry",
"=",
"prop",
".",
"parent",
".",
"dir",
".",
"get",
"(",
"ref",
")",
"if",
"dir_entry",
"is",
"None",
":",
"dir_entry",
"=",
"prop",
".",
"parent",
".",
"dir",
".",
"makedir",
"(",
"ref",
")",
"if",
"value",
".",
"dir",
"!=",
"dir_entry",
":",
"value",
".",
"attach",
"(",
"dir_entry",
")",
"prop",
".",
"mark_modified",
"(",
")"
] | low level add to StrongRefSetProperty | [
"low",
"level",
"add",
"to",
"StrongRefSetProperty"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/properties.py#L1313-L1336 | train | 232,326 |
MillionIntegrals/vel | vel/rl/modules/q_distributional_head.py | QDistributionalHead.histogram_info | def histogram_info(self) -> dict:
""" Return extra information about histogram """
return {
'support_atoms': self.support_atoms,
'atom_delta': self.atom_delta,
'vmin': self.vmin,
'vmax': self.vmax,
'num_atoms': self.atoms
} | python | def histogram_info(self) -> dict:
""" Return extra information about histogram """
return {
'support_atoms': self.support_atoms,
'atom_delta': self.atom_delta,
'vmin': self.vmin,
'vmax': self.vmax,
'num_atoms': self.atoms
} | [
"def",
"histogram_info",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"'support_atoms'",
":",
"self",
".",
"support_atoms",
",",
"'atom_delta'",
":",
"self",
".",
"atom_delta",
",",
"'vmin'",
":",
"self",
".",
"vmin",
",",
"'vmax'",
":",
"self",
".",
"vmax",
",",
"'num_atoms'",
":",
"self",
".",
"atoms",
"}"
] | Return extra information about histogram | [
"Return",
"extra",
"information",
"about",
"histogram"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/q_distributional_head.py#L31-L39 | train | 232,327 |
MillionIntegrals/vel | vel/rl/modules/q_distributional_head.py | QDistributionalHead.sample | def sample(self, histogram_logits):
""" Sample from a greedy strategy with given q-value histogram """
histogram_probs = histogram_logits.exp() # Batch size * actions * atoms
atoms = self.support_atoms.view(1, 1, self.atoms) # Need to introduce two new dimensions
return (histogram_probs * atoms).sum(dim=-1).argmax(dim=1) | python | def sample(self, histogram_logits):
""" Sample from a greedy strategy with given q-value histogram """
histogram_probs = histogram_logits.exp() # Batch size * actions * atoms
atoms = self.support_atoms.view(1, 1, self.atoms) # Need to introduce two new dimensions
return (histogram_probs * atoms).sum(dim=-1).argmax(dim=1) | [
"def",
"sample",
"(",
"self",
",",
"histogram_logits",
")",
":",
"histogram_probs",
"=",
"histogram_logits",
".",
"exp",
"(",
")",
"# Batch size * actions * atoms",
"atoms",
"=",
"self",
".",
"support_atoms",
".",
"view",
"(",
"1",
",",
"1",
",",
"self",
".",
"atoms",
")",
"# Need to introduce two new dimensions",
"return",
"(",
"histogram_probs",
"*",
"atoms",
")",
".",
"sum",
"(",
"dim",
"=",
"-",
"1",
")",
".",
"argmax",
"(",
"dim",
"=",
"1",
")"
] | Sample from a greedy strategy with given q-value histogram | [
"Sample",
"from",
"a",
"greedy",
"strategy",
"with",
"given",
"q",
"-",
"value",
"histogram"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/q_distributional_head.py#L52-L56 | train | 232,328 |
MillionIntegrals/vel | vel/sources/nlp/text_url.py | TextUrlSource.download | def download(self):
""" Make sure data file is downloaded and stored properly """
if not os.path.exists(self.data_path):
# Create if it doesn't exist
pathlib.Path(self.data_path).mkdir(parents=True, exist_ok=True)
if not os.path.exists(self.text_path):
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
with open(self.text_path, 'wt') as fp:
request = http.request('GET', self.url)
content = request.data.decode('utf8')
fp.write(content)
if not os.path.exists(self.processed_path):
with open(self.text_path, 'rt') as fp:
content = fp.read()
alphabet = sorted(set(content))
index_to_character = {idx: c for idx, c in enumerate(alphabet, 1)}
character_to_index = {c: idx for idx, c in enumerate(alphabet, 1)}
content_encoded = np.array([character_to_index[c] for c in content], dtype=np.uint8)
data_dict = {
'alphabet': alphabet,
'index_to_character': index_to_character,
'character_to_index': character_to_index,
'content_encoded': content_encoded
}
with open(self.processed_path, 'wb') as fp:
torch.save(data_dict, fp)
else:
with open(self.processed_path, 'rb') as fp:
data_dict = torch.load(fp)
return data_dict | python | def download(self):
""" Make sure data file is downloaded and stored properly """
if not os.path.exists(self.data_path):
# Create if it doesn't exist
pathlib.Path(self.data_path).mkdir(parents=True, exist_ok=True)
if not os.path.exists(self.text_path):
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
with open(self.text_path, 'wt') as fp:
request = http.request('GET', self.url)
content = request.data.decode('utf8')
fp.write(content)
if not os.path.exists(self.processed_path):
with open(self.text_path, 'rt') as fp:
content = fp.read()
alphabet = sorted(set(content))
index_to_character = {idx: c for idx, c in enumerate(alphabet, 1)}
character_to_index = {c: idx for idx, c in enumerate(alphabet, 1)}
content_encoded = np.array([character_to_index[c] for c in content], dtype=np.uint8)
data_dict = {
'alphabet': alphabet,
'index_to_character': index_to_character,
'character_to_index': character_to_index,
'content_encoded': content_encoded
}
with open(self.processed_path, 'wb') as fp:
torch.save(data_dict, fp)
else:
with open(self.processed_path, 'rb') as fp:
data_dict = torch.load(fp)
return data_dict | [
"def",
"download",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"data_path",
")",
":",
"# Create if it doesn't exist",
"pathlib",
".",
"Path",
"(",
"self",
".",
"data_path",
")",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"text_path",
")",
":",
"http",
"=",
"urllib3",
".",
"PoolManager",
"(",
"cert_reqs",
"=",
"'CERT_REQUIRED'",
",",
"ca_certs",
"=",
"certifi",
".",
"where",
"(",
")",
")",
"with",
"open",
"(",
"self",
".",
"text_path",
",",
"'wt'",
")",
"as",
"fp",
":",
"request",
"=",
"http",
".",
"request",
"(",
"'GET'",
",",
"self",
".",
"url",
")",
"content",
"=",
"request",
".",
"data",
".",
"decode",
"(",
"'utf8'",
")",
"fp",
".",
"write",
"(",
"content",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"processed_path",
")",
":",
"with",
"open",
"(",
"self",
".",
"text_path",
",",
"'rt'",
")",
"as",
"fp",
":",
"content",
"=",
"fp",
".",
"read",
"(",
")",
"alphabet",
"=",
"sorted",
"(",
"set",
"(",
"content",
")",
")",
"index_to_character",
"=",
"{",
"idx",
":",
"c",
"for",
"idx",
",",
"c",
"in",
"enumerate",
"(",
"alphabet",
",",
"1",
")",
"}",
"character_to_index",
"=",
"{",
"c",
":",
"idx",
"for",
"idx",
",",
"c",
"in",
"enumerate",
"(",
"alphabet",
",",
"1",
")",
"}",
"content_encoded",
"=",
"np",
".",
"array",
"(",
"[",
"character_to_index",
"[",
"c",
"]",
"for",
"c",
"in",
"content",
"]",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"data_dict",
"=",
"{",
"'alphabet'",
":",
"alphabet",
",",
"'index_to_character'",
":",
"index_to_character",
",",
"'character_to_index'",
":",
"character_to_index",
",",
"'content_encoded'",
":",
"content_encoded",
"}",
"with",
"open",
"(",
"self",
".",
"processed_path",
",",
"'wb'",
")",
"as",
"fp",
":",
"torch",
".",
"save",
"(",
"data_dict",
",",
"fp",
")",
"else",
":",
"with",
"open",
"(",
"self",
".",
"processed_path",
",",
"'rb'",
")",
"as",
"fp",
":",
"data_dict",
"=",
"torch",
".",
"load",
"(",
"fp",
")",
"return",
"data_dict"
] | Make sure data file is downloaded and stored properly | [
"Make",
"sure",
"data",
"file",
"is",
"downloaded",
"and",
"stored",
"properly"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/nlp/text_url.py#L148-L186 | train | 232,329 |
MillionIntegrals/vel | vel/math/functions.py | explained_variance | def explained_variance(returns, values):
""" Calculate how much variance in returns do the values explain """
exp_var = 1 - torch.var(returns - values) / torch.var(returns)
return exp_var.item() | python | def explained_variance(returns, values):
""" Calculate how much variance in returns do the values explain """
exp_var = 1 - torch.var(returns - values) / torch.var(returns)
return exp_var.item() | [
"def",
"explained_variance",
"(",
"returns",
",",
"values",
")",
":",
"exp_var",
"=",
"1",
"-",
"torch",
".",
"var",
"(",
"returns",
"-",
"values",
")",
"/",
"torch",
".",
"var",
"(",
"returns",
")",
"return",
"exp_var",
".",
"item",
"(",
")"
] | Calculate how much variance in returns do the values explain | [
"Calculate",
"how",
"much",
"variance",
"in",
"returns",
"do",
"the",
"values",
"explain"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/math/functions.py#L4-L7 | train | 232,330 |
MillionIntegrals/vel | vel/sources/img_dir_source.py | create | def create(model_config, path, num_workers, batch_size, augmentations=None, tta=None):
""" Create an ImageDirSource with supplied arguments """
if not os.path.isabs(path):
path = model_config.project_top_dir(path)
train_path = os.path.join(path, 'train')
valid_path = os.path.join(path, 'valid')
train_ds = ImageDirSource(train_path)
val_ds = ImageDirSource(valid_path)
return TrainingData(
train_ds,
val_ds,
num_workers=num_workers,
batch_size=batch_size,
augmentations=augmentations,
# test_time_augmentation=tta
) | python | def create(model_config, path, num_workers, batch_size, augmentations=None, tta=None):
""" Create an ImageDirSource with supplied arguments """
if not os.path.isabs(path):
path = model_config.project_top_dir(path)
train_path = os.path.join(path, 'train')
valid_path = os.path.join(path, 'valid')
train_ds = ImageDirSource(train_path)
val_ds = ImageDirSource(valid_path)
return TrainingData(
train_ds,
val_ds,
num_workers=num_workers,
batch_size=batch_size,
augmentations=augmentations,
# test_time_augmentation=tta
) | [
"def",
"create",
"(",
"model_config",
",",
"path",
",",
"num_workers",
",",
"batch_size",
",",
"augmentations",
"=",
"None",
",",
"tta",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"path",
"=",
"model_config",
".",
"project_top_dir",
"(",
"path",
")",
"train_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'train'",
")",
"valid_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'valid'",
")",
"train_ds",
"=",
"ImageDirSource",
"(",
"train_path",
")",
"val_ds",
"=",
"ImageDirSource",
"(",
"valid_path",
")",
"return",
"TrainingData",
"(",
"train_ds",
",",
"val_ds",
",",
"num_workers",
"=",
"num_workers",
",",
"batch_size",
"=",
"batch_size",
",",
"augmentations",
"=",
"augmentations",
",",
"# test_time_augmentation=tta",
")"
] | Create an ImageDirSource with supplied arguments | [
"Create",
"an",
"ImageDirSource",
"with",
"supplied",
"arguments"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/img_dir_source.py#L12-L30 | train | 232,331 |
MillionIntegrals/vel | vel/rl/models/q_model.py | QModel.reset_weights | def reset_weights(self):
""" Initialize weights to reasonable defaults """
self.input_block.reset_weights()
self.backbone.reset_weights()
self.q_head.reset_weights() | python | def reset_weights(self):
""" Initialize weights to reasonable defaults """
self.input_block.reset_weights()
self.backbone.reset_weights()
self.q_head.reset_weights() | [
"def",
"reset_weights",
"(",
"self",
")",
":",
"self",
".",
"input_block",
".",
"reset_weights",
"(",
")",
"self",
".",
"backbone",
".",
"reset_weights",
"(",
")",
"self",
".",
"q_head",
".",
"reset_weights",
"(",
")"
] | Initialize weights to reasonable defaults | [
"Initialize",
"weights",
"to",
"reasonable",
"defaults"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/models/q_model.py#L50-L54 | train | 232,332 |
MillionIntegrals/vel | vel/util/tensor_accumulator.py | TensorAccumulator.result | def result(self):
""" Concatenate accumulated tensors """
return {k: torch.stack(v) for k, v in self.accumulants.items()} | python | def result(self):
""" Concatenate accumulated tensors """
return {k: torch.stack(v) for k, v in self.accumulants.items()} | [
"def",
"result",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"torch",
".",
"stack",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"accumulants",
".",
"items",
"(",
")",
"}"
] | Concatenate accumulated tensors | [
"Concatenate",
"accumulated",
"tensors"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/tensor_accumulator.py#L14-L16 | train | 232,333 |
MillionIntegrals/vel | vel/internals/provider.py | Provider.resolve_parameters | def resolve_parameters(self, func, extra_env=None):
""" Resolve parameter dictionary for the supplied function """
parameter_list = [
(k, v.default == inspect.Parameter.empty) for k, v in inspect.signature(func).parameters.items()
]
extra_env = extra_env if extra_env is not None else {}
kwargs = {}
for parameter_name, is_required in parameter_list:
# extra_env is a 'local' object data defined in-place
if parameter_name in extra_env:
kwargs[parameter_name] = self.instantiate_from_data(extra_env[parameter_name])
continue
if parameter_name in self.instances:
kwargs[parameter_name] = self.instances[parameter_name]
continue
if parameter_name in self.environment:
kwargs[parameter_name] = self.instantiate_by_name(parameter_name)
continue
if is_required:
funcname = f"{inspect.getmodule(func).__name__}.{func.__name__}"
raise RuntimeError("Required argument '{}' cannot be resolved for function '{}'".format(
parameter_name, funcname
))
return kwargs | python | def resolve_parameters(self, func, extra_env=None):
""" Resolve parameter dictionary for the supplied function """
parameter_list = [
(k, v.default == inspect.Parameter.empty) for k, v in inspect.signature(func).parameters.items()
]
extra_env = extra_env if extra_env is not None else {}
kwargs = {}
for parameter_name, is_required in parameter_list:
# extra_env is a 'local' object data defined in-place
if parameter_name in extra_env:
kwargs[parameter_name] = self.instantiate_from_data(extra_env[parameter_name])
continue
if parameter_name in self.instances:
kwargs[parameter_name] = self.instances[parameter_name]
continue
if parameter_name in self.environment:
kwargs[parameter_name] = self.instantiate_by_name(parameter_name)
continue
if is_required:
funcname = f"{inspect.getmodule(func).__name__}.{func.__name__}"
raise RuntimeError("Required argument '{}' cannot be resolved for function '{}'".format(
parameter_name, funcname
))
return kwargs | [
"def",
"resolve_parameters",
"(",
"self",
",",
"func",
",",
"extra_env",
"=",
"None",
")",
":",
"parameter_list",
"=",
"[",
"(",
"k",
",",
"v",
".",
"default",
"==",
"inspect",
".",
"Parameter",
".",
"empty",
")",
"for",
"k",
",",
"v",
"in",
"inspect",
".",
"signature",
"(",
"func",
")",
".",
"parameters",
".",
"items",
"(",
")",
"]",
"extra_env",
"=",
"extra_env",
"if",
"extra_env",
"is",
"not",
"None",
"else",
"{",
"}",
"kwargs",
"=",
"{",
"}",
"for",
"parameter_name",
",",
"is_required",
"in",
"parameter_list",
":",
"# extra_env is a 'local' object data defined in-place",
"if",
"parameter_name",
"in",
"extra_env",
":",
"kwargs",
"[",
"parameter_name",
"]",
"=",
"self",
".",
"instantiate_from_data",
"(",
"extra_env",
"[",
"parameter_name",
"]",
")",
"continue",
"if",
"parameter_name",
"in",
"self",
".",
"instances",
":",
"kwargs",
"[",
"parameter_name",
"]",
"=",
"self",
".",
"instances",
"[",
"parameter_name",
"]",
"continue",
"if",
"parameter_name",
"in",
"self",
".",
"environment",
":",
"kwargs",
"[",
"parameter_name",
"]",
"=",
"self",
".",
"instantiate_by_name",
"(",
"parameter_name",
")",
"continue",
"if",
"is_required",
":",
"funcname",
"=",
"f\"{inspect.getmodule(func).__name__}.{func.__name__}\"",
"raise",
"RuntimeError",
"(",
"\"Required argument '{}' cannot be resolved for function '{}'\"",
".",
"format",
"(",
"parameter_name",
",",
"funcname",
")",
")",
"return",
"kwargs"
] | Resolve parameter dictionary for the supplied function | [
"Resolve",
"parameter",
"dictionary",
"for",
"the",
"supplied",
"function"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L24-L52 | train | 232,334 |
MillionIntegrals/vel | vel/internals/provider.py | Provider.resolve_and_call | def resolve_and_call(self, func, extra_env=None):
""" Resolve function arguments and call them, possibily filling from the environment """
kwargs = self.resolve_parameters(func, extra_env=extra_env)
return func(**kwargs) | python | def resolve_and_call(self, func, extra_env=None):
""" Resolve function arguments and call them, possibily filling from the environment """
kwargs = self.resolve_parameters(func, extra_env=extra_env)
return func(**kwargs) | [
"def",
"resolve_and_call",
"(",
"self",
",",
"func",
",",
"extra_env",
"=",
"None",
")",
":",
"kwargs",
"=",
"self",
".",
"resolve_parameters",
"(",
"func",
",",
"extra_env",
"=",
"extra_env",
")",
"return",
"func",
"(",
"*",
"*",
"kwargs",
")"
] | Resolve function arguments and call them, possibily filling from the environment | [
"Resolve",
"function",
"arguments",
"and",
"call",
"them",
"possibily",
"filling",
"from",
"the",
"environment"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L54-L57 | train | 232,335 |
MillionIntegrals/vel | vel/internals/provider.py | Provider.instantiate_from_data | def instantiate_from_data(self, object_data):
""" Instantiate object from the supplied data, additional args may come from the environment """
if isinstance(object_data, dict) and 'name' in object_data:
name = object_data['name']
module = importlib.import_module(name)
return self.resolve_and_call(module.create, extra_env=object_data)
if isinstance(object_data, dict) and 'factory' in object_data:
factory = object_data['factory']
module = importlib.import_module(factory)
params = self.resolve_parameters(module.create, extra_env=object_data)
return GenericFactory(module.create, params)
elif isinstance(object_data, dict):
return {k: self.instantiate_from_data(v) for k, v in object_data.items()}
elif isinstance(object_data, list):
return [self.instantiate_from_data(x) for x in object_data]
elif isinstance(object_data, Variable):
return object_data.resolve(self.parameters)
else:
return object_data | python | def instantiate_from_data(self, object_data):
""" Instantiate object from the supplied data, additional args may come from the environment """
if isinstance(object_data, dict) and 'name' in object_data:
name = object_data['name']
module = importlib.import_module(name)
return self.resolve_and_call(module.create, extra_env=object_data)
if isinstance(object_data, dict) and 'factory' in object_data:
factory = object_data['factory']
module = importlib.import_module(factory)
params = self.resolve_parameters(module.create, extra_env=object_data)
return GenericFactory(module.create, params)
elif isinstance(object_data, dict):
return {k: self.instantiate_from_data(v) for k, v in object_data.items()}
elif isinstance(object_data, list):
return [self.instantiate_from_data(x) for x in object_data]
elif isinstance(object_data, Variable):
return object_data.resolve(self.parameters)
else:
return object_data | [
"def",
"instantiate_from_data",
"(",
"self",
",",
"object_data",
")",
":",
"if",
"isinstance",
"(",
"object_data",
",",
"dict",
")",
"and",
"'name'",
"in",
"object_data",
":",
"name",
"=",
"object_data",
"[",
"'name'",
"]",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"name",
")",
"return",
"self",
".",
"resolve_and_call",
"(",
"module",
".",
"create",
",",
"extra_env",
"=",
"object_data",
")",
"if",
"isinstance",
"(",
"object_data",
",",
"dict",
")",
"and",
"'factory'",
"in",
"object_data",
":",
"factory",
"=",
"object_data",
"[",
"'factory'",
"]",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"factory",
")",
"params",
"=",
"self",
".",
"resolve_parameters",
"(",
"module",
".",
"create",
",",
"extra_env",
"=",
"object_data",
")",
"return",
"GenericFactory",
"(",
"module",
".",
"create",
",",
"params",
")",
"elif",
"isinstance",
"(",
"object_data",
",",
"dict",
")",
":",
"return",
"{",
"k",
":",
"self",
".",
"instantiate_from_data",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"object_data",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"object_data",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"instantiate_from_data",
"(",
"x",
")",
"for",
"x",
"in",
"object_data",
"]",
"elif",
"isinstance",
"(",
"object_data",
",",
"Variable",
")",
":",
"return",
"object_data",
".",
"resolve",
"(",
"self",
".",
"parameters",
")",
"else",
":",
"return",
"object_data"
] | Instantiate object from the supplied data, additional args may come from the environment | [
"Instantiate",
"object",
"from",
"the",
"supplied",
"data",
"additional",
"args",
"may",
"come",
"from",
"the",
"environment"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L59-L77 | train | 232,336 |
MillionIntegrals/vel | vel/internals/provider.py | Provider.render_configuration | def render_configuration(self, configuration=None):
""" Render variables in configuration object but don't instantiate anything """
if configuration is None:
configuration = self.environment
if isinstance(configuration, dict):
return {k: self.render_configuration(v) for k, v in configuration.items()}
elif isinstance(configuration, list):
return [self.render_configuration(x) for x in configuration]
elif isinstance(configuration, Variable):
return configuration.resolve(self.parameters)
else:
return configuration | python | def render_configuration(self, configuration=None):
""" Render variables in configuration object but don't instantiate anything """
if configuration is None:
configuration = self.environment
if isinstance(configuration, dict):
return {k: self.render_configuration(v) for k, v in configuration.items()}
elif isinstance(configuration, list):
return [self.render_configuration(x) for x in configuration]
elif isinstance(configuration, Variable):
return configuration.resolve(self.parameters)
else:
return configuration | [
"def",
"render_configuration",
"(",
"self",
",",
"configuration",
"=",
"None",
")",
":",
"if",
"configuration",
"is",
"None",
":",
"configuration",
"=",
"self",
".",
"environment",
"if",
"isinstance",
"(",
"configuration",
",",
"dict",
")",
":",
"return",
"{",
"k",
":",
"self",
".",
"render_configuration",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"configuration",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"configuration",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"render_configuration",
"(",
"x",
")",
"for",
"x",
"in",
"configuration",
"]",
"elif",
"isinstance",
"(",
"configuration",
",",
"Variable",
")",
":",
"return",
"configuration",
".",
"resolve",
"(",
"self",
".",
"parameters",
")",
"else",
":",
"return",
"configuration"
] | Render variables in configuration object but don't instantiate anything | [
"Render",
"variables",
"in",
"configuration",
"object",
"but",
"don",
"t",
"instantiate",
"anything"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L79-L91 | train | 232,337 |
MillionIntegrals/vel | vel/rl/api/evaluator.py | Evaluator.is_provided | def is_provided(self, name):
""" Capability check if evaluator provides given value """
if name in self._storage:
return True
elif name in self._providers:
return True
elif name.startswith('rollout:'):
rollout_name = name[8:]
else:
return False | python | def is_provided(self, name):
""" Capability check if evaluator provides given value """
if name in self._storage:
return True
elif name in self._providers:
return True
elif name.startswith('rollout:'):
rollout_name = name[8:]
else:
return False | [
"def",
"is_provided",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_storage",
":",
"return",
"True",
"elif",
"name",
"in",
"self",
".",
"_providers",
":",
"return",
"True",
"elif",
"name",
".",
"startswith",
"(",
"'rollout:'",
")",
":",
"rollout_name",
"=",
"name",
"[",
"8",
":",
"]",
"else",
":",
"return",
"False"
] | Capability check if evaluator provides given value | [
"Capability",
"check",
"if",
"evaluator",
"provides",
"given",
"value"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/evaluator.py#L103-L112 | train | 232,338 |
MillionIntegrals/vel | vel/rl/api/evaluator.py | Evaluator.get | def get(self, name):
"""
Return a value from this evaluator.
Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times
with and without no_grad() context.
It is advised in such cases to not use no_grad and stick to .detach()
"""
if name in self._storage:
return self._storage[name]
elif name in self._providers:
value = self._storage[name] = self._providers[name](self)
return value
elif name.startswith('rollout:'):
rollout_name = name[8:]
value = self._storage[name] = self.rollout.batch_tensor(rollout_name)
return value
else:
raise RuntimeError(f"Key {name} is not provided by this evaluator") | python | def get(self, name):
"""
Return a value from this evaluator.
Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times
with and without no_grad() context.
It is advised in such cases to not use no_grad and stick to .detach()
"""
if name in self._storage:
return self._storage[name]
elif name in self._providers:
value = self._storage[name] = self._providers[name](self)
return value
elif name.startswith('rollout:'):
rollout_name = name[8:]
value = self._storage[name] = self.rollout.batch_tensor(rollout_name)
return value
else:
raise RuntimeError(f"Key {name} is not provided by this evaluator") | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_storage",
":",
"return",
"self",
".",
"_storage",
"[",
"name",
"]",
"elif",
"name",
"in",
"self",
".",
"_providers",
":",
"value",
"=",
"self",
".",
"_storage",
"[",
"name",
"]",
"=",
"self",
".",
"_providers",
"[",
"name",
"]",
"(",
"self",
")",
"return",
"value",
"elif",
"name",
".",
"startswith",
"(",
"'rollout:'",
")",
":",
"rollout_name",
"=",
"name",
"[",
"8",
":",
"]",
"value",
"=",
"self",
".",
"_storage",
"[",
"name",
"]",
"=",
"self",
".",
"rollout",
".",
"batch_tensor",
"(",
"rollout_name",
")",
"return",
"value",
"else",
":",
"raise",
"RuntimeError",
"(",
"f\"Key {name} is not provided by this evaluator\"",
")"
] | Return a value from this evaluator.
Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times
with and without no_grad() context.
It is advised in such cases to not use no_grad and stick to .detach() | [
"Return",
"a",
"value",
"from",
"this",
"evaluator",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/evaluator.py#L114-L133 | train | 232,339 |
MillionIntegrals/vel | vel/sources/vision/mnist.py | create | def create(model_config, batch_size, normalize=True, num_workers=0, augmentations=None):
""" Create a MNIST dataset, normalized """
path = model_config.data_dir('mnist')
train_dataset = datasets.MNIST(path, train=True, download=True)
test_dataset = datasets.MNIST(path, train=False, download=True)
augmentations = [ToArray()] + (augmentations if augmentations is not None else [])
if normalize:
train_data = train_dataset.train_data
mean_value = (train_data.double() / 255).mean().item()
std_value = (train_data.double() / 255).std().item()
augmentations.append(Normalize(mean=mean_value, std=std_value, tags=['train', 'val']))
augmentations.append(ToTensor())
return TrainingData(
train_dataset,
test_dataset,
num_workers=num_workers,
batch_size=batch_size,
augmentations=augmentations
) | python | def create(model_config, batch_size, normalize=True, num_workers=0, augmentations=None):
""" Create a MNIST dataset, normalized """
path = model_config.data_dir('mnist')
train_dataset = datasets.MNIST(path, train=True, download=True)
test_dataset = datasets.MNIST(path, train=False, download=True)
augmentations = [ToArray()] + (augmentations if augmentations is not None else [])
if normalize:
train_data = train_dataset.train_data
mean_value = (train_data.double() / 255).mean().item()
std_value = (train_data.double() / 255).std().item()
augmentations.append(Normalize(mean=mean_value, std=std_value, tags=['train', 'val']))
augmentations.append(ToTensor())
return TrainingData(
train_dataset,
test_dataset,
num_workers=num_workers,
batch_size=batch_size,
augmentations=augmentations
) | [
"def",
"create",
"(",
"model_config",
",",
"batch_size",
",",
"normalize",
"=",
"True",
",",
"num_workers",
"=",
"0",
",",
"augmentations",
"=",
"None",
")",
":",
"path",
"=",
"model_config",
".",
"data_dir",
"(",
"'mnist'",
")",
"train_dataset",
"=",
"datasets",
".",
"MNIST",
"(",
"path",
",",
"train",
"=",
"True",
",",
"download",
"=",
"True",
")",
"test_dataset",
"=",
"datasets",
".",
"MNIST",
"(",
"path",
",",
"train",
"=",
"False",
",",
"download",
"=",
"True",
")",
"augmentations",
"=",
"[",
"ToArray",
"(",
")",
"]",
"+",
"(",
"augmentations",
"if",
"augmentations",
"is",
"not",
"None",
"else",
"[",
"]",
")",
"if",
"normalize",
":",
"train_data",
"=",
"train_dataset",
".",
"train_data",
"mean_value",
"=",
"(",
"train_data",
".",
"double",
"(",
")",
"/",
"255",
")",
".",
"mean",
"(",
")",
".",
"item",
"(",
")",
"std_value",
"=",
"(",
"train_data",
".",
"double",
"(",
")",
"/",
"255",
")",
".",
"std",
"(",
")",
".",
"item",
"(",
")",
"augmentations",
".",
"append",
"(",
"Normalize",
"(",
"mean",
"=",
"mean_value",
",",
"std",
"=",
"std_value",
",",
"tags",
"=",
"[",
"'train'",
",",
"'val'",
"]",
")",
")",
"augmentations",
".",
"append",
"(",
"ToTensor",
"(",
")",
")",
"return",
"TrainingData",
"(",
"train_dataset",
",",
"test_dataset",
",",
"num_workers",
"=",
"num_workers",
",",
"batch_size",
"=",
"batch_size",
",",
"augmentations",
"=",
"augmentations",
")"
] | Create a MNIST dataset, normalized | [
"Create",
"a",
"MNIST",
"dataset",
"normalized"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/vision/mnist.py#L11-L35 | train | 232,340 |
MillionIntegrals/vel | vel/storage/classic.py | ClassicStorage.reset | def reset(self, configuration: dict) -> None:
"""
Whenever there was anything stored in the database or not, purge previous state and start
new training process from scratch.
"""
self.clean(0)
self.backend.store_config(configuration) | python | def reset(self, configuration: dict) -> None:
"""
Whenever there was anything stored in the database or not, purge previous state and start
new training process from scratch.
"""
self.clean(0)
self.backend.store_config(configuration) | [
"def",
"reset",
"(",
"self",
",",
"configuration",
":",
"dict",
")",
"->",
"None",
":",
"self",
".",
"clean",
"(",
"0",
")",
"self",
".",
"backend",
".",
"store_config",
"(",
"configuration",
")"
] | Whenever there was anything stored in the database or not, purge previous state and start
new training process from scratch. | [
"Whenever",
"there",
"was",
"anything",
"stored",
"in",
"the",
"database",
"or",
"not",
"purge",
"previous",
"state",
"and",
"start",
"new",
"training",
"process",
"from",
"scratch",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L26-L32 | train | 232,341 |
MillionIntegrals/vel | vel/storage/classic.py | ClassicStorage.load | def load(self, train_info: TrainingInfo) -> (dict, dict):
"""
Resume learning process and return loaded hidden state dictionary
"""
last_epoch = train_info.start_epoch_idx
model_state = torch.load(self.checkpoint_filename(last_epoch))
hidden_state = torch.load(self.checkpoint_hidden_filename(last_epoch))
self.checkpoint_strategy.restore(hidden_state)
train_info.restore(hidden_state)
return model_state, hidden_state | python | def load(self, train_info: TrainingInfo) -> (dict, dict):
"""
Resume learning process and return loaded hidden state dictionary
"""
last_epoch = train_info.start_epoch_idx
model_state = torch.load(self.checkpoint_filename(last_epoch))
hidden_state = torch.load(self.checkpoint_hidden_filename(last_epoch))
self.checkpoint_strategy.restore(hidden_state)
train_info.restore(hidden_state)
return model_state, hidden_state | [
"def",
"load",
"(",
"self",
",",
"train_info",
":",
"TrainingInfo",
")",
"->",
"(",
"dict",
",",
"dict",
")",
":",
"last_epoch",
"=",
"train_info",
".",
"start_epoch_idx",
"model_state",
"=",
"torch",
".",
"load",
"(",
"self",
".",
"checkpoint_filename",
"(",
"last_epoch",
")",
")",
"hidden_state",
"=",
"torch",
".",
"load",
"(",
"self",
".",
"checkpoint_hidden_filename",
"(",
"last_epoch",
")",
")",
"self",
".",
"checkpoint_strategy",
".",
"restore",
"(",
"hidden_state",
")",
"train_info",
".",
"restore",
"(",
"hidden_state",
")",
"return",
"model_state",
",",
"hidden_state"
] | Resume learning process and return loaded hidden state dictionary | [
"Resume",
"learning",
"process",
"and",
"return",
"loaded",
"hidden",
"state",
"dictionary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L34-L46 | train | 232,342 |
MillionIntegrals/vel | vel/storage/classic.py | ClassicStorage.clean | def clean(self, global_epoch_idx):
""" Clean old checkpoints """
if self.cleaned:
return
self.cleaned = True
self.backend.clean(global_epoch_idx)
self._make_sure_dir_exists()
for x in os.listdir(self.model_config.checkpoint_dir()):
match = re.match('checkpoint_(\\d+)\\.data', x)
if match:
idx = int(match[1])
if idx > global_epoch_idx:
os.remove(os.path.join(self.model_config.checkpoint_dir(), x))
match = re.match('checkpoint_hidden_(\\d+)\\.data', x)
if match:
idx = int(match[1])
if idx > global_epoch_idx:
os.remove(os.path.join(self.model_config.checkpoint_dir(), x))
match = re.match('checkpoint_best_(\\d+)\\.data', x)
if match:
idx = int(match[1])
if idx > global_epoch_idx:
os.remove(os.path.join(self.model_config.checkpoint_dir(), x)) | python | def clean(self, global_epoch_idx):
""" Clean old checkpoints """
if self.cleaned:
return
self.cleaned = True
self.backend.clean(global_epoch_idx)
self._make_sure_dir_exists()
for x in os.listdir(self.model_config.checkpoint_dir()):
match = re.match('checkpoint_(\\d+)\\.data', x)
if match:
idx = int(match[1])
if idx > global_epoch_idx:
os.remove(os.path.join(self.model_config.checkpoint_dir(), x))
match = re.match('checkpoint_hidden_(\\d+)\\.data', x)
if match:
idx = int(match[1])
if idx > global_epoch_idx:
os.remove(os.path.join(self.model_config.checkpoint_dir(), x))
match = re.match('checkpoint_best_(\\d+)\\.data', x)
if match:
idx = int(match[1])
if idx > global_epoch_idx:
os.remove(os.path.join(self.model_config.checkpoint_dir(), x)) | [
"def",
"clean",
"(",
"self",
",",
"global_epoch_idx",
")",
":",
"if",
"self",
".",
"cleaned",
":",
"return",
"self",
".",
"cleaned",
"=",
"True",
"self",
".",
"backend",
".",
"clean",
"(",
"global_epoch_idx",
")",
"self",
".",
"_make_sure_dir_exists",
"(",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"model_config",
".",
"checkpoint_dir",
"(",
")",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"'checkpoint_(\\\\d+)\\\\.data'",
",",
"x",
")",
"if",
"match",
":",
"idx",
"=",
"int",
"(",
"match",
"[",
"1",
"]",
")",
"if",
"idx",
">",
"global_epoch_idx",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"model_config",
".",
"checkpoint_dir",
"(",
")",
",",
"x",
")",
")",
"match",
"=",
"re",
".",
"match",
"(",
"'checkpoint_hidden_(\\\\d+)\\\\.data'",
",",
"x",
")",
"if",
"match",
":",
"idx",
"=",
"int",
"(",
"match",
"[",
"1",
"]",
")",
"if",
"idx",
">",
"global_epoch_idx",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"model_config",
".",
"checkpoint_dir",
"(",
")",
",",
"x",
")",
")",
"match",
"=",
"re",
".",
"match",
"(",
"'checkpoint_best_(\\\\d+)\\\\.data'",
",",
"x",
")",
"if",
"match",
":",
"idx",
"=",
"int",
"(",
"match",
"[",
"1",
"]",
")",
"if",
"idx",
">",
"global_epoch_idx",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"model_config",
".",
"checkpoint_dir",
"(",
")",
",",
"x",
")",
")"
] | Clean old checkpoints | [
"Clean",
"old",
"checkpoints"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L52-L85 | train | 232,343 |
MillionIntegrals/vel | vel/storage/classic.py | ClassicStorage.checkpoint | def checkpoint(self, epoch_info: EpochInfo, model: Model):
""" When epoch is done, we persist the training state """
self.clean(epoch_info.global_epoch_idx - 1)
self._make_sure_dir_exists()
# Checkpoint latest
torch.save(model.state_dict(), self.checkpoint_filename(epoch_info.global_epoch_idx))
hidden_state = epoch_info.state_dict()
self.checkpoint_strategy.write_state_dict(hidden_state)
torch.save(hidden_state, self.checkpoint_hidden_filename(epoch_info.global_epoch_idx))
if epoch_info.global_epoch_idx > 1 and self.checkpoint_strategy.should_delete_previous_checkpoint(
epoch_info.global_epoch_idx):
prev_epoch_idx = epoch_info.global_epoch_idx - 1
os.remove(self.checkpoint_filename(prev_epoch_idx))
os.remove(self.checkpoint_hidden_filename(prev_epoch_idx))
if self.checkpoint_strategy.should_store_best_checkpoint(epoch_info.global_epoch_idx, epoch_info.result):
best_checkpoint_idx = self.checkpoint_strategy.current_best_checkpoint_idx
if best_checkpoint_idx is not None:
os.remove(self.checkpoint_best_filename(best_checkpoint_idx))
torch.save(model.state_dict(), self.checkpoint_best_filename(epoch_info.global_epoch_idx))
self.checkpoint_strategy.store_best_checkpoint_idx(epoch_info.global_epoch_idx)
self.backend.store(epoch_info.result) | python | def checkpoint(self, epoch_info: EpochInfo, model: Model):
""" When epoch is done, we persist the training state """
self.clean(epoch_info.global_epoch_idx - 1)
self._make_sure_dir_exists()
# Checkpoint latest
torch.save(model.state_dict(), self.checkpoint_filename(epoch_info.global_epoch_idx))
hidden_state = epoch_info.state_dict()
self.checkpoint_strategy.write_state_dict(hidden_state)
torch.save(hidden_state, self.checkpoint_hidden_filename(epoch_info.global_epoch_idx))
if epoch_info.global_epoch_idx > 1 and self.checkpoint_strategy.should_delete_previous_checkpoint(
epoch_info.global_epoch_idx):
prev_epoch_idx = epoch_info.global_epoch_idx - 1
os.remove(self.checkpoint_filename(prev_epoch_idx))
os.remove(self.checkpoint_hidden_filename(prev_epoch_idx))
if self.checkpoint_strategy.should_store_best_checkpoint(epoch_info.global_epoch_idx, epoch_info.result):
best_checkpoint_idx = self.checkpoint_strategy.current_best_checkpoint_idx
if best_checkpoint_idx is not None:
os.remove(self.checkpoint_best_filename(best_checkpoint_idx))
torch.save(model.state_dict(), self.checkpoint_best_filename(epoch_info.global_epoch_idx))
self.checkpoint_strategy.store_best_checkpoint_idx(epoch_info.global_epoch_idx)
self.backend.store(epoch_info.result) | [
"def",
"checkpoint",
"(",
"self",
",",
"epoch_info",
":",
"EpochInfo",
",",
"model",
":",
"Model",
")",
":",
"self",
".",
"clean",
"(",
"epoch_info",
".",
"global_epoch_idx",
"-",
"1",
")",
"self",
".",
"_make_sure_dir_exists",
"(",
")",
"# Checkpoint latest",
"torch",
".",
"save",
"(",
"model",
".",
"state_dict",
"(",
")",
",",
"self",
".",
"checkpoint_filename",
"(",
"epoch_info",
".",
"global_epoch_idx",
")",
")",
"hidden_state",
"=",
"epoch_info",
".",
"state_dict",
"(",
")",
"self",
".",
"checkpoint_strategy",
".",
"write_state_dict",
"(",
"hidden_state",
")",
"torch",
".",
"save",
"(",
"hidden_state",
",",
"self",
".",
"checkpoint_hidden_filename",
"(",
"epoch_info",
".",
"global_epoch_idx",
")",
")",
"if",
"epoch_info",
".",
"global_epoch_idx",
">",
"1",
"and",
"self",
".",
"checkpoint_strategy",
".",
"should_delete_previous_checkpoint",
"(",
"epoch_info",
".",
"global_epoch_idx",
")",
":",
"prev_epoch_idx",
"=",
"epoch_info",
".",
"global_epoch_idx",
"-",
"1",
"os",
".",
"remove",
"(",
"self",
".",
"checkpoint_filename",
"(",
"prev_epoch_idx",
")",
")",
"os",
".",
"remove",
"(",
"self",
".",
"checkpoint_hidden_filename",
"(",
"prev_epoch_idx",
")",
")",
"if",
"self",
".",
"checkpoint_strategy",
".",
"should_store_best_checkpoint",
"(",
"epoch_info",
".",
"global_epoch_idx",
",",
"epoch_info",
".",
"result",
")",
":",
"best_checkpoint_idx",
"=",
"self",
".",
"checkpoint_strategy",
".",
"current_best_checkpoint_idx",
"if",
"best_checkpoint_idx",
"is",
"not",
"None",
":",
"os",
".",
"remove",
"(",
"self",
".",
"checkpoint_best_filename",
"(",
"best_checkpoint_idx",
")",
")",
"torch",
".",
"save",
"(",
"model",
".",
"state_dict",
"(",
")",
",",
"self",
".",
"checkpoint_best_filename",
"(",
"epoch_info",
".",
"global_epoch_idx",
")",
")",
"self",
".",
"checkpoint_strategy",
".",
"store_best_checkpoint_idx",
"(",
"epoch_info",
".",
"global_epoch_idx",
")",
"self",
".",
"backend",
".",
"store",
"(",
"epoch_info",
".",
"result",
")"
] | When epoch is done, we persist the training state | [
"When",
"epoch",
"is",
"done",
"we",
"persist",
"the",
"training",
"state"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L87-L118 | train | 232,344 |
MillionIntegrals/vel | vel/storage/classic.py | ClassicStorage._persisted_last_epoch | def _persisted_last_epoch(self) -> int:
""" Return number of last epoch already calculated """
epoch_number = 0
self._make_sure_dir_exists()
for x in os.listdir(self.model_config.checkpoint_dir()):
match = re.match('checkpoint_(\\d+)\\.data', x)
if match:
idx = int(match[1])
if idx > epoch_number:
epoch_number = idx
return epoch_number | python | def _persisted_last_epoch(self) -> int:
""" Return number of last epoch already calculated """
epoch_number = 0
self._make_sure_dir_exists()
for x in os.listdir(self.model_config.checkpoint_dir()):
match = re.match('checkpoint_(\\d+)\\.data', x)
if match:
idx = int(match[1])
if idx > epoch_number:
epoch_number = idx
return epoch_number | [
"def",
"_persisted_last_epoch",
"(",
"self",
")",
"->",
"int",
":",
"epoch_number",
"=",
"0",
"self",
".",
"_make_sure_dir_exists",
"(",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"model_config",
".",
"checkpoint_dir",
"(",
")",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"'checkpoint_(\\\\d+)\\\\.data'",
",",
"x",
")",
"if",
"match",
":",
"idx",
"=",
"int",
"(",
"match",
"[",
"1",
"]",
")",
"if",
"idx",
">",
"epoch_number",
":",
"epoch_number",
"=",
"idx",
"return",
"epoch_number"
] | Return number of last epoch already calculated | [
"Return",
"number",
"of",
"last",
"epoch",
"already",
"calculated"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L140-L153 | train | 232,345 |
MillionIntegrals/vel | vel/storage/classic.py | ClassicStorage._make_sure_dir_exists | def _make_sure_dir_exists(self):
""" Make sure directory exists """
filename = self.model_config.checkpoint_dir()
pathlib.Path(filename).mkdir(parents=True, exist_ok=True) | python | def _make_sure_dir_exists(self):
""" Make sure directory exists """
filename = self.model_config.checkpoint_dir()
pathlib.Path(filename).mkdir(parents=True, exist_ok=True) | [
"def",
"_make_sure_dir_exists",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"model_config",
".",
"checkpoint_dir",
"(",
")",
"pathlib",
".",
"Path",
"(",
"filename",
")",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")"
] | Make sure directory exists | [
"Make",
"sure",
"directory",
"exists"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L155-L158 | train | 232,346 |
MillionIntegrals/vel | vel/rl/api/algo_base.py | clip_gradients | def clip_gradients(batch_result, model, max_grad_norm):
""" Clip gradients to a given maximum length """
if max_grad_norm is not None:
grad_norm = torch.nn.utils.clip_grad_norm_(
filter(lambda p: p.requires_grad, model.parameters()),
max_norm=max_grad_norm
)
else:
grad_norm = 0.0
batch_result['grad_norm'] = grad_norm | python | def clip_gradients(batch_result, model, max_grad_norm):
""" Clip gradients to a given maximum length """
if max_grad_norm is not None:
grad_norm = torch.nn.utils.clip_grad_norm_(
filter(lambda p: p.requires_grad, model.parameters()),
max_norm=max_grad_norm
)
else:
grad_norm = 0.0
batch_result['grad_norm'] = grad_norm | [
"def",
"clip_gradients",
"(",
"batch_result",
",",
"model",
",",
"max_grad_norm",
")",
":",
"if",
"max_grad_norm",
"is",
"not",
"None",
":",
"grad_norm",
"=",
"torch",
".",
"nn",
".",
"utils",
".",
"clip_grad_norm_",
"(",
"filter",
"(",
"lambda",
"p",
":",
"p",
".",
"requires_grad",
",",
"model",
".",
"parameters",
"(",
")",
")",
",",
"max_norm",
"=",
"max_grad_norm",
")",
"else",
":",
"grad_norm",
"=",
"0.0",
"batch_result",
"[",
"'grad_norm'",
"]",
"=",
"grad_norm"
] | Clip gradients to a given maximum length | [
"Clip",
"gradients",
"to",
"a",
"given",
"maximum",
"length"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/algo_base.py#L4-L14 | train | 232,347 |
MillionIntegrals/vel | vel/rl/buffers/circular_replay_buffer.py | CircularReplayBuffer.sample_trajectories | def sample_trajectories(self, rollout_length, batch_info) -> Trajectories:
""" Sample batch of trajectories and return them """
indexes = self.backend.sample_batch_trajectories(rollout_length)
transition_tensors = self.backend.get_trajectories(indexes, rollout_length)
return Trajectories(
num_steps=rollout_length,
num_envs=self.backend.num_envs,
environment_information=None,
transition_tensors={k: torch.from_numpy(v) for k, v in transition_tensors.items()},
rollout_tensors={}
) | python | def sample_trajectories(self, rollout_length, batch_info) -> Trajectories:
""" Sample batch of trajectories and return them """
indexes = self.backend.sample_batch_trajectories(rollout_length)
transition_tensors = self.backend.get_trajectories(indexes, rollout_length)
return Trajectories(
num_steps=rollout_length,
num_envs=self.backend.num_envs,
environment_information=None,
transition_tensors={k: torch.from_numpy(v) for k, v in transition_tensors.items()},
rollout_tensors={}
) | [
"def",
"sample_trajectories",
"(",
"self",
",",
"rollout_length",
",",
"batch_info",
")",
"->",
"Trajectories",
":",
"indexes",
"=",
"self",
".",
"backend",
".",
"sample_batch_trajectories",
"(",
"rollout_length",
")",
"transition_tensors",
"=",
"self",
".",
"backend",
".",
"get_trajectories",
"(",
"indexes",
",",
"rollout_length",
")",
"return",
"Trajectories",
"(",
"num_steps",
"=",
"rollout_length",
",",
"num_envs",
"=",
"self",
".",
"backend",
".",
"num_envs",
",",
"environment_information",
"=",
"None",
",",
"transition_tensors",
"=",
"{",
"k",
":",
"torch",
".",
"from_numpy",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"transition_tensors",
".",
"items",
"(",
")",
"}",
",",
"rollout_tensors",
"=",
"{",
"}",
")"
] | Sample batch of trajectories and return them | [
"Sample",
"batch",
"of",
"trajectories",
"and",
"return",
"them"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/circular_replay_buffer.py#L52-L63 | train | 232,348 |
MillionIntegrals/vel | vel/rl/algo/policy_gradient/trpo.py | conjugate_gradient_method | def conjugate_gradient_method(matrix_vector_operator, loss_gradient, nsteps, rdotr_tol=1e-10):
""" Conjugate gradient algorithm """
x = torch.zeros_like(loss_gradient)
r = loss_gradient.clone()
p = loss_gradient.clone()
rdotr = torch.dot(r, r)
for i in range(nsteps):
Avp = matrix_vector_operator(p)
alpha = rdotr / torch.dot(p, Avp)
x += alpha * p
r -= alpha * Avp
new_rdotr = torch.dot(r, r)
betta = new_rdotr / rdotr
p = r + betta * p
rdotr = new_rdotr
if rdotr < rdotr_tol:
break
return x | python | def conjugate_gradient_method(matrix_vector_operator, loss_gradient, nsteps, rdotr_tol=1e-10):
""" Conjugate gradient algorithm """
x = torch.zeros_like(loss_gradient)
r = loss_gradient.clone()
p = loss_gradient.clone()
rdotr = torch.dot(r, r)
for i in range(nsteps):
Avp = matrix_vector_operator(p)
alpha = rdotr / torch.dot(p, Avp)
x += alpha * p
r -= alpha * Avp
new_rdotr = torch.dot(r, r)
betta = new_rdotr / rdotr
p = r + betta * p
rdotr = new_rdotr
if rdotr < rdotr_tol:
break
return x | [
"def",
"conjugate_gradient_method",
"(",
"matrix_vector_operator",
",",
"loss_gradient",
",",
"nsteps",
",",
"rdotr_tol",
"=",
"1e-10",
")",
":",
"x",
"=",
"torch",
".",
"zeros_like",
"(",
"loss_gradient",
")",
"r",
"=",
"loss_gradient",
".",
"clone",
"(",
")",
"p",
"=",
"loss_gradient",
".",
"clone",
"(",
")",
"rdotr",
"=",
"torch",
".",
"dot",
"(",
"r",
",",
"r",
")",
"for",
"i",
"in",
"range",
"(",
"nsteps",
")",
":",
"Avp",
"=",
"matrix_vector_operator",
"(",
"p",
")",
"alpha",
"=",
"rdotr",
"/",
"torch",
".",
"dot",
"(",
"p",
",",
"Avp",
")",
"x",
"+=",
"alpha",
"*",
"p",
"r",
"-=",
"alpha",
"*",
"Avp",
"new_rdotr",
"=",
"torch",
".",
"dot",
"(",
"r",
",",
"r",
")",
"betta",
"=",
"new_rdotr",
"/",
"rdotr",
"p",
"=",
"r",
"+",
"betta",
"*",
"p",
"rdotr",
"=",
"new_rdotr",
"if",
"rdotr",
"<",
"rdotr_tol",
":",
"break",
"return",
"x"
] | Conjugate gradient algorithm | [
"Conjugate",
"gradient",
"algorithm"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L23-L47 | train | 232,349 |
MillionIntegrals/vel | vel/rl/algo/policy_gradient/trpo.py | TrpoPolicyGradient.line_search | def line_search(self, model, rollout, original_policy_loss, original_policy_params, original_parameter_vec,
full_step, expected_improvement_full):
""" Find the right stepsize to make sure policy improves """
current_parameter_vec = original_parameter_vec.clone()
for idx in range(self.line_search_iters):
stepsize = 0.5 ** idx
new_parameter_vec = current_parameter_vec + stepsize * full_step
# Update model parameters
v2p(new_parameter_vec, model.policy_parameters())
# Calculate new loss
with torch.no_grad():
policy_params = model.policy(rollout.batch_tensor('observations'))
policy_entropy = torch.mean(model.entropy(policy_params))
kl_divergence = torch.mean(model.kl_divergence(original_policy_params, policy_params))
new_loss = self.calc_policy_loss(model, policy_params, policy_entropy, rollout)
actual_improvement = original_policy_loss - new_loss
expected_improvement = expected_improvement_full * stepsize
ratio = actual_improvement / expected_improvement
if kl_divergence.item() > self.mak_kl * 1.5:
# KL divergence bound exceeded
continue
elif ratio < expected_improvement:
# Not enough loss improvement
continue
else:
# Optimization successful
return True, ratio, actual_improvement, new_loss, kl_divergence
# Optimization failed, revert to initial parameters
v2p(original_parameter_vec, model.policy_parameters())
return False, torch.tensor(0.0), torch.tensor(0.0), torch.tensor(0.0), torch.tensor(0.0) | python | def line_search(self, model, rollout, original_policy_loss, original_policy_params, original_parameter_vec,
full_step, expected_improvement_full):
""" Find the right stepsize to make sure policy improves """
current_parameter_vec = original_parameter_vec.clone()
for idx in range(self.line_search_iters):
stepsize = 0.5 ** idx
new_parameter_vec = current_parameter_vec + stepsize * full_step
# Update model parameters
v2p(new_parameter_vec, model.policy_parameters())
# Calculate new loss
with torch.no_grad():
policy_params = model.policy(rollout.batch_tensor('observations'))
policy_entropy = torch.mean(model.entropy(policy_params))
kl_divergence = torch.mean(model.kl_divergence(original_policy_params, policy_params))
new_loss = self.calc_policy_loss(model, policy_params, policy_entropy, rollout)
actual_improvement = original_policy_loss - new_loss
expected_improvement = expected_improvement_full * stepsize
ratio = actual_improvement / expected_improvement
if kl_divergence.item() > self.mak_kl * 1.5:
# KL divergence bound exceeded
continue
elif ratio < expected_improvement:
# Not enough loss improvement
continue
else:
# Optimization successful
return True, ratio, actual_improvement, new_loss, kl_divergence
# Optimization failed, revert to initial parameters
v2p(original_parameter_vec, model.policy_parameters())
return False, torch.tensor(0.0), torch.tensor(0.0), torch.tensor(0.0), torch.tensor(0.0) | [
"def",
"line_search",
"(",
"self",
",",
"model",
",",
"rollout",
",",
"original_policy_loss",
",",
"original_policy_params",
",",
"original_parameter_vec",
",",
"full_step",
",",
"expected_improvement_full",
")",
":",
"current_parameter_vec",
"=",
"original_parameter_vec",
".",
"clone",
"(",
")",
"for",
"idx",
"in",
"range",
"(",
"self",
".",
"line_search_iters",
")",
":",
"stepsize",
"=",
"0.5",
"**",
"idx",
"new_parameter_vec",
"=",
"current_parameter_vec",
"+",
"stepsize",
"*",
"full_step",
"# Update model parameters",
"v2p",
"(",
"new_parameter_vec",
",",
"model",
".",
"policy_parameters",
"(",
")",
")",
"# Calculate new loss",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"policy_params",
"=",
"model",
".",
"policy",
"(",
"rollout",
".",
"batch_tensor",
"(",
"'observations'",
")",
")",
"policy_entropy",
"=",
"torch",
".",
"mean",
"(",
"model",
".",
"entropy",
"(",
"policy_params",
")",
")",
"kl_divergence",
"=",
"torch",
".",
"mean",
"(",
"model",
".",
"kl_divergence",
"(",
"original_policy_params",
",",
"policy_params",
")",
")",
"new_loss",
"=",
"self",
".",
"calc_policy_loss",
"(",
"model",
",",
"policy_params",
",",
"policy_entropy",
",",
"rollout",
")",
"actual_improvement",
"=",
"original_policy_loss",
"-",
"new_loss",
"expected_improvement",
"=",
"expected_improvement_full",
"*",
"stepsize",
"ratio",
"=",
"actual_improvement",
"/",
"expected_improvement",
"if",
"kl_divergence",
".",
"item",
"(",
")",
">",
"self",
".",
"mak_kl",
"*",
"1.5",
":",
"# KL divergence bound exceeded",
"continue",
"elif",
"ratio",
"<",
"expected_improvement",
":",
"# Not enough loss improvement",
"continue",
"else",
":",
"# Optimization successful",
"return",
"True",
",",
"ratio",
",",
"actual_improvement",
",",
"new_loss",
",",
"kl_divergence",
"# Optimization failed, revert to initial parameters",
"v2p",
"(",
"original_parameter_vec",
",",
"model",
".",
"policy_parameters",
"(",
")",
")",
"return",
"False",
",",
"torch",
".",
"tensor",
"(",
"0.0",
")",
",",
"torch",
".",
"tensor",
"(",
"0.0",
")",
",",
"torch",
".",
"tensor",
"(",
"0.0",
")",
",",
"torch",
".",
"tensor",
"(",
"0.0",
")"
] | Find the right stepsize to make sure policy improves | [
"Find",
"the",
"right",
"stepsize",
"to",
"make",
"sure",
"policy",
"improves"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L167-L205 | train | 232,350 |
MillionIntegrals/vel | vel/rl/algo/policy_gradient/trpo.py | TrpoPolicyGradient.fisher_vector_product | def fisher_vector_product(self, vector, kl_divergence_gradient, model):
""" Calculate product Hessian @ vector """
assert not vector.requires_grad, "Vector must not propagate gradient"
dot_product = vector @ kl_divergence_gradient
# at least one dimension spans across two contiguous subspaces
double_gradient = torch.autograd.grad(dot_product, model.policy_parameters(), retain_graph=True)
fvp = p2v(x.contiguous() for x in double_gradient)
return fvp + vector * self.cg_damping | python | def fisher_vector_product(self, vector, kl_divergence_gradient, model):
""" Calculate product Hessian @ vector """
assert not vector.requires_grad, "Vector must not propagate gradient"
dot_product = vector @ kl_divergence_gradient
# at least one dimension spans across two contiguous subspaces
double_gradient = torch.autograd.grad(dot_product, model.policy_parameters(), retain_graph=True)
fvp = p2v(x.contiguous() for x in double_gradient)
return fvp + vector * self.cg_damping | [
"def",
"fisher_vector_product",
"(",
"self",
",",
"vector",
",",
"kl_divergence_gradient",
",",
"model",
")",
":",
"assert",
"not",
"vector",
".",
"requires_grad",
",",
"\"Vector must not propagate gradient\"",
"dot_product",
"=",
"vector",
"@",
"kl_divergence_gradient",
"# at least one dimension spans across two contiguous subspaces",
"double_gradient",
"=",
"torch",
".",
"autograd",
".",
"grad",
"(",
"dot_product",
",",
"model",
".",
"policy_parameters",
"(",
")",
",",
"retain_graph",
"=",
"True",
")",
"fvp",
"=",
"p2v",
"(",
"x",
".",
"contiguous",
"(",
")",
"for",
"x",
"in",
"double_gradient",
")",
"return",
"fvp",
"+",
"vector",
"*",
"self",
".",
"cg_damping"
] | Calculate product Hessian @ vector | [
"Calculate",
"product",
"Hessian"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L207-L216 | train | 232,351 |
MillionIntegrals/vel | vel/rl/algo/policy_gradient/trpo.py | TrpoPolicyGradient.value_loss | def value_loss(self, model, observations, discounted_rewards):
""" Loss of value estimator """
value_outputs = model.value(observations)
value_loss = 0.5 * F.mse_loss(value_outputs, discounted_rewards)
return value_loss | python | def value_loss(self, model, observations, discounted_rewards):
""" Loss of value estimator """
value_outputs = model.value(observations)
value_loss = 0.5 * F.mse_loss(value_outputs, discounted_rewards)
return value_loss | [
"def",
"value_loss",
"(",
"self",
",",
"model",
",",
"observations",
",",
"discounted_rewards",
")",
":",
"value_outputs",
"=",
"model",
".",
"value",
"(",
"observations",
")",
"value_loss",
"=",
"0.5",
"*",
"F",
".",
"mse_loss",
"(",
"value_outputs",
",",
"discounted_rewards",
")",
"return",
"value_loss"
] | Loss of value estimator | [
"Loss",
"of",
"value",
"estimator"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L218-L222 | train | 232,352 |
MillionIntegrals/vel | vel/rl/algo/policy_gradient/trpo.py | TrpoPolicyGradient.calc_policy_loss | def calc_policy_loss(self, model, policy_params, policy_entropy, rollout):
"""
Policy gradient loss - calculate from probability distribution
Calculate surrogate loss - advantage * policy_probability / fixed_initial_policy_probability
Because we operate with logarithm of -probability (neglogp) we do
- advantage * exp(fixed_neglogps - model_neglogps)
"""
actions = rollout.batch_tensor('actions')
advantages = rollout.batch_tensor('advantages')
fixed_logprobs = rollout.batch_tensor('action:logprobs')
model_logprobs = model.logprob(actions, policy_params)
# Normalize advantages
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
# We put - in front because we want to maximize the surrogate objective
policy_loss = -advantages * torch.exp(model_logprobs - fixed_logprobs)
return policy_loss.mean() - policy_entropy * self.entropy_coef | python | def calc_policy_loss(self, model, policy_params, policy_entropy, rollout):
"""
Policy gradient loss - calculate from probability distribution
Calculate surrogate loss - advantage * policy_probability / fixed_initial_policy_probability
Because we operate with logarithm of -probability (neglogp) we do
- advantage * exp(fixed_neglogps - model_neglogps)
"""
actions = rollout.batch_tensor('actions')
advantages = rollout.batch_tensor('advantages')
fixed_logprobs = rollout.batch_tensor('action:logprobs')
model_logprobs = model.logprob(actions, policy_params)
# Normalize advantages
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
# We put - in front because we want to maximize the surrogate objective
policy_loss = -advantages * torch.exp(model_logprobs - fixed_logprobs)
return policy_loss.mean() - policy_entropy * self.entropy_coef | [
"def",
"calc_policy_loss",
"(",
"self",
",",
"model",
",",
"policy_params",
",",
"policy_entropy",
",",
"rollout",
")",
":",
"actions",
"=",
"rollout",
".",
"batch_tensor",
"(",
"'actions'",
")",
"advantages",
"=",
"rollout",
".",
"batch_tensor",
"(",
"'advantages'",
")",
"fixed_logprobs",
"=",
"rollout",
".",
"batch_tensor",
"(",
"'action:logprobs'",
")",
"model_logprobs",
"=",
"model",
".",
"logprob",
"(",
"actions",
",",
"policy_params",
")",
"# Normalize advantages",
"advantages",
"=",
"(",
"advantages",
"-",
"advantages",
".",
"mean",
"(",
")",
")",
"/",
"(",
"advantages",
".",
"std",
"(",
")",
"+",
"1e-8",
")",
"# We put - in front because we want to maximize the surrogate objective",
"policy_loss",
"=",
"-",
"advantages",
"*",
"torch",
".",
"exp",
"(",
"model_logprobs",
"-",
"fixed_logprobs",
")",
"return",
"policy_loss",
".",
"mean",
"(",
")",
"-",
"policy_entropy",
"*",
"self",
".",
"entropy_coef"
] | Policy gradient loss - calculate from probability distribution
Calculate surrogate loss - advantage * policy_probability / fixed_initial_policy_probability
Because we operate with logarithm of -probability (neglogp) we do
- advantage * exp(fixed_neglogps - model_neglogps) | [
"Policy",
"gradient",
"loss",
"-",
"calculate",
"from",
"probability",
"distribution"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L224-L245 | train | 232,353 |
MillionIntegrals/vel | vel/rl/api/rollout.py | Transitions.shuffled_batches | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data """
if batch_size >= self.size:
yield self
else:
batch_splits = math_util.divide_ceiling(self.size, batch_size)
indices = list(range(self.size))
np.random.shuffle(indices)
for sub_indices in np.array_split(indices, batch_splits):
yield Transitions(
size=len(sub_indices),
environment_information=None,
# Dont use it in batches for a moment, can be uncommented later if needed
# environment_information=[info[sub_indices.tolist()] for info in self.environment_information]
transition_tensors={k: v[sub_indices] for k, v in self.transition_tensors.items()}
# extra_data does not go into batches
) | python | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data """
if batch_size >= self.size:
yield self
else:
batch_splits = math_util.divide_ceiling(self.size, batch_size)
indices = list(range(self.size))
np.random.shuffle(indices)
for sub_indices in np.array_split(indices, batch_splits):
yield Transitions(
size=len(sub_indices),
environment_information=None,
# Dont use it in batches for a moment, can be uncommented later if needed
# environment_information=[info[sub_indices.tolist()] for info in self.environment_information]
transition_tensors={k: v[sub_indices] for k, v in self.transition_tensors.items()}
# extra_data does not go into batches
) | [
"def",
"shuffled_batches",
"(",
"self",
",",
"batch_size",
")",
":",
"if",
"batch_size",
">=",
"self",
".",
"size",
":",
"yield",
"self",
"else",
":",
"batch_splits",
"=",
"math_util",
".",
"divide_ceiling",
"(",
"self",
".",
"size",
",",
"batch_size",
")",
"indices",
"=",
"list",
"(",
"range",
"(",
"self",
".",
"size",
")",
")",
"np",
".",
"random",
".",
"shuffle",
"(",
"indices",
")",
"for",
"sub_indices",
"in",
"np",
".",
"array_split",
"(",
"indices",
",",
"batch_splits",
")",
":",
"yield",
"Transitions",
"(",
"size",
"=",
"len",
"(",
"sub_indices",
")",
",",
"environment_information",
"=",
"None",
",",
"# Dont use it in batches for a moment, can be uncommented later if needed",
"# environment_information=[info[sub_indices.tolist()] for info in self.environment_information]",
"transition_tensors",
"=",
"{",
"k",
":",
"v",
"[",
"sub_indices",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"transition_tensors",
".",
"items",
"(",
")",
"}",
"# extra_data does not go into batches",
")"
] | Generate randomized batches of data | [
"Generate",
"randomized",
"batches",
"of",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L59-L76 | train | 232,354 |
MillionIntegrals/vel | vel/rl/api/rollout.py | Trajectories.to_transitions | def to_transitions(self) -> 'Transitions':
""" Convert given rollout to Transitions """
# No need to propagate 'rollout_tensors' as they won't mean anything
return Transitions(
size=self.num_steps * self.num_envs,
environment_information=
[ei for l in self.environment_information for ei in l]
if self.environment_information is not None else None,
transition_tensors={
name: tensor_util.merge_first_two_dims(t) for name, t in self.transition_tensors.items()
},
extra_data=self.extra_data
) | python | def to_transitions(self) -> 'Transitions':
""" Convert given rollout to Transitions """
# No need to propagate 'rollout_tensors' as they won't mean anything
return Transitions(
size=self.num_steps * self.num_envs,
environment_information=
[ei for l in self.environment_information for ei in l]
if self.environment_information is not None else None,
transition_tensors={
name: tensor_util.merge_first_two_dims(t) for name, t in self.transition_tensors.items()
},
extra_data=self.extra_data
) | [
"def",
"to_transitions",
"(",
"self",
")",
"->",
"'Transitions'",
":",
"# No need to propagate 'rollout_tensors' as they won't mean anything",
"return",
"Transitions",
"(",
"size",
"=",
"self",
".",
"num_steps",
"*",
"self",
".",
"num_envs",
",",
"environment_information",
"=",
"[",
"ei",
"for",
"l",
"in",
"self",
".",
"environment_information",
"for",
"ei",
"in",
"l",
"]",
"if",
"self",
".",
"environment_information",
"is",
"not",
"None",
"else",
"None",
",",
"transition_tensors",
"=",
"{",
"name",
":",
"tensor_util",
".",
"merge_first_two_dims",
"(",
"t",
")",
"for",
"name",
",",
"t",
"in",
"self",
".",
"transition_tensors",
".",
"items",
"(",
")",
"}",
",",
"extra_data",
"=",
"self",
".",
"extra_data",
")"
] | Convert given rollout to Transitions | [
"Convert",
"given",
"rollout",
"to",
"Transitions"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L111-L123 | train | 232,355 |
MillionIntegrals/vel | vel/rl/api/rollout.py | Trajectories.shuffled_batches | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data - only sample whole trajectories """
if batch_size >= self.num_envs * self.num_steps:
yield self
else:
rollouts_in_batch = batch_size // self.num_steps
batch_splits = math_util.divide_ceiling(self.num_envs, rollouts_in_batch)
indices = list(range(self.num_envs))
np.random.shuffle(indices)
for sub_indices in np.array_split(indices, batch_splits):
yield Trajectories(
num_steps=self.num_steps,
num_envs=len(sub_indices),
# Dont use it in batches for a moment, can be uncommented later if needed
# environment_information=[x[sub_indices.tolist()] for x in self.environment_information],
environment_information=None,
transition_tensors={k: x[:, sub_indices] for k, x in self.transition_tensors.items()},
rollout_tensors={k: x[sub_indices] for k, x in self.rollout_tensors.items()},
# extra_data does not go into batches
) | python | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data - only sample whole trajectories """
if batch_size >= self.num_envs * self.num_steps:
yield self
else:
rollouts_in_batch = batch_size // self.num_steps
batch_splits = math_util.divide_ceiling(self.num_envs, rollouts_in_batch)
indices = list(range(self.num_envs))
np.random.shuffle(indices)
for sub_indices in np.array_split(indices, batch_splits):
yield Trajectories(
num_steps=self.num_steps,
num_envs=len(sub_indices),
# Dont use it in batches for a moment, can be uncommented later if needed
# environment_information=[x[sub_indices.tolist()] for x in self.environment_information],
environment_information=None,
transition_tensors={k: x[:, sub_indices] for k, x in self.transition_tensors.items()},
rollout_tensors={k: x[sub_indices] for k, x in self.rollout_tensors.items()},
# extra_data does not go into batches
) | [
"def",
"shuffled_batches",
"(",
"self",
",",
"batch_size",
")",
":",
"if",
"batch_size",
">=",
"self",
".",
"num_envs",
"*",
"self",
".",
"num_steps",
":",
"yield",
"self",
"else",
":",
"rollouts_in_batch",
"=",
"batch_size",
"//",
"self",
".",
"num_steps",
"batch_splits",
"=",
"math_util",
".",
"divide_ceiling",
"(",
"self",
".",
"num_envs",
",",
"rollouts_in_batch",
")",
"indices",
"=",
"list",
"(",
"range",
"(",
"self",
".",
"num_envs",
")",
")",
"np",
".",
"random",
".",
"shuffle",
"(",
"indices",
")",
"for",
"sub_indices",
"in",
"np",
".",
"array_split",
"(",
"indices",
",",
"batch_splits",
")",
":",
"yield",
"Trajectories",
"(",
"num_steps",
"=",
"self",
".",
"num_steps",
",",
"num_envs",
"=",
"len",
"(",
"sub_indices",
")",
",",
"# Dont use it in batches for a moment, can be uncommented later if needed",
"# environment_information=[x[sub_indices.tolist()] for x in self.environment_information],",
"environment_information",
"=",
"None",
",",
"transition_tensors",
"=",
"{",
"k",
":",
"x",
"[",
":",
",",
"sub_indices",
"]",
"for",
"k",
",",
"x",
"in",
"self",
".",
"transition_tensors",
".",
"items",
"(",
")",
"}",
",",
"rollout_tensors",
"=",
"{",
"k",
":",
"x",
"[",
"sub_indices",
"]",
"for",
"k",
",",
"x",
"in",
"self",
".",
"rollout_tensors",
".",
"items",
"(",
")",
"}",
",",
"# extra_data does not go into batches",
")"
] | Generate randomized batches of data - only sample whole trajectories | [
"Generate",
"randomized",
"batches",
"of",
"data",
"-",
"only",
"sample",
"whole",
"trajectories"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L125-L147 | train | 232,356 |
MillionIntegrals/vel | vel/rl/api/rollout.py | Trajectories.episode_information | def episode_information(self):
""" List of information about finished episodes """
return [
info.get('episode') for infolist in self.environment_information for info in infolist if 'episode' in info
] | python | def episode_information(self):
""" List of information about finished episodes """
return [
info.get('episode') for infolist in self.environment_information for info in infolist if 'episode' in info
] | [
"def",
"episode_information",
"(",
"self",
")",
":",
"return",
"[",
"info",
".",
"get",
"(",
"'episode'",
")",
"for",
"infolist",
"in",
"self",
".",
"environment_information",
"for",
"info",
"in",
"infolist",
"if",
"'episode'",
"in",
"info",
"]"
] | List of information about finished episodes | [
"List",
"of",
"information",
"about",
"finished",
"episodes"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L164-L168 | train | 232,357 |
MillionIntegrals/vel | vel/models/rnn/multilayer_rnn_sequence_model.py | MultilayerRnnSequenceModel.forward_state | def forward_state(self, sequence, state=None):
""" Forward propagate a sequence through the network accounting for the state """
if state is None:
state = self.zero_state(sequence.size(0))
data = self.input_block(sequence)
state_outputs = []
# for layer_length, layer in zip(self.hidden_layers, self.recurrent_layers):
for idx in range(len(self.recurrent_layers)):
layer_length = self.recurrent_layers[idx].state_dim
# Partition hidden state, for each layer we have layer_length of h state and layer_length of c state
current_state = state[:, :, :layer_length]
state = state[:, :, layer_length:]
# Propagate through the GRU state
data, new_h = self.recurrent_layers[idx](data, current_state)
if self.dropout_layers:
data = self.dropout_layers[idx](data)
state_outputs.append(new_h)
output_data = self.output_activation(self.output_layer(data))
concatenated_hidden_output = torch.cat(state_outputs, dim=2)
return output_data, concatenated_hidden_output | python | def forward_state(self, sequence, state=None):
""" Forward propagate a sequence through the network accounting for the state """
if state is None:
state = self.zero_state(sequence.size(0))
data = self.input_block(sequence)
state_outputs = []
# for layer_length, layer in zip(self.hidden_layers, self.recurrent_layers):
for idx in range(len(self.recurrent_layers)):
layer_length = self.recurrent_layers[idx].state_dim
# Partition hidden state, for each layer we have layer_length of h state and layer_length of c state
current_state = state[:, :, :layer_length]
state = state[:, :, layer_length:]
# Propagate through the GRU state
data, new_h = self.recurrent_layers[idx](data, current_state)
if self.dropout_layers:
data = self.dropout_layers[idx](data)
state_outputs.append(new_h)
output_data = self.output_activation(self.output_layer(data))
concatenated_hidden_output = torch.cat(state_outputs, dim=2)
return output_data, concatenated_hidden_output | [
"def",
"forward_state",
"(",
"self",
",",
"sequence",
",",
"state",
"=",
"None",
")",
":",
"if",
"state",
"is",
"None",
":",
"state",
"=",
"self",
".",
"zero_state",
"(",
"sequence",
".",
"size",
"(",
"0",
")",
")",
"data",
"=",
"self",
".",
"input_block",
"(",
"sequence",
")",
"state_outputs",
"=",
"[",
"]",
"# for layer_length, layer in zip(self.hidden_layers, self.recurrent_layers):",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"recurrent_layers",
")",
")",
":",
"layer_length",
"=",
"self",
".",
"recurrent_layers",
"[",
"idx",
"]",
".",
"state_dim",
"# Partition hidden state, for each layer we have layer_length of h state and layer_length of c state",
"current_state",
"=",
"state",
"[",
":",
",",
":",
",",
":",
"layer_length",
"]",
"state",
"=",
"state",
"[",
":",
",",
":",
",",
"layer_length",
":",
"]",
"# Propagate through the GRU state",
"data",
",",
"new_h",
"=",
"self",
".",
"recurrent_layers",
"[",
"idx",
"]",
"(",
"data",
",",
"current_state",
")",
"if",
"self",
".",
"dropout_layers",
":",
"data",
"=",
"self",
".",
"dropout_layers",
"[",
"idx",
"]",
"(",
"data",
")",
"state_outputs",
".",
"append",
"(",
"new_h",
")",
"output_data",
"=",
"self",
".",
"output_activation",
"(",
"self",
".",
"output_layer",
"(",
"data",
")",
")",
"concatenated_hidden_output",
"=",
"torch",
".",
"cat",
"(",
"state_outputs",
",",
"dim",
"=",
"2",
")",
"return",
"output_data",
",",
"concatenated_hidden_output"
] | Forward propagate a sequence through the network accounting for the state | [
"Forward",
"propagate",
"a",
"sequence",
"through",
"the",
"network",
"accounting",
"for",
"the",
"state"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/rnn/multilayer_rnn_sequence_model.py#L66-L95 | train | 232,358 |
MillionIntegrals/vel | vel/models/rnn/multilayer_rnn_sequence_model.py | MultilayerRnnSequenceModel.loss_value | def loss_value(self, x_data, y_true, y_pred):
""" Calculate a value of loss function """
y_pred = y_pred.view(-1, y_pred.size(2))
y_true = y_true.view(-1).to(torch.long)
return F.nll_loss(y_pred, y_true) | python | def loss_value(self, x_data, y_true, y_pred):
""" Calculate a value of loss function """
y_pred = y_pred.view(-1, y_pred.size(2))
y_true = y_true.view(-1).to(torch.long)
return F.nll_loss(y_pred, y_true) | [
"def",
"loss_value",
"(",
"self",
",",
"x_data",
",",
"y_true",
",",
"y_pred",
")",
":",
"y_pred",
"=",
"y_pred",
".",
"view",
"(",
"-",
"1",
",",
"y_pred",
".",
"size",
"(",
"2",
")",
")",
"y_true",
"=",
"y_true",
".",
"view",
"(",
"-",
"1",
")",
".",
"to",
"(",
"torch",
".",
"long",
")",
"return",
"F",
".",
"nll_loss",
"(",
"y_pred",
",",
"y_true",
")"
] | Calculate a value of loss function | [
"Calculate",
"a",
"value",
"of",
"loss",
"function"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/rnn/multilayer_rnn_sequence_model.py#L106-L110 | train | 232,359 |
MillionIntegrals/vel | vel/api/learner.py | Learner.initialize_training | def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare for training """
if model_state is None:
self.model.reset_weights()
else:
self.model.load_state_dict(model_state) | python | def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare for training """
if model_state is None:
self.model.reset_weights()
else:
self.model.load_state_dict(model_state) | [
"def",
"initialize_training",
"(",
"self",
",",
"training_info",
":",
"TrainingInfo",
",",
"model_state",
"=",
"None",
",",
"hidden_state",
"=",
"None",
")",
":",
"if",
"model_state",
"is",
"None",
":",
"self",
".",
"model",
".",
"reset_weights",
"(",
")",
"else",
":",
"self",
".",
"model",
".",
"load_state_dict",
"(",
"model_state",
")"
] | Prepare for training | [
"Prepare",
"for",
"training"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L36-L41 | train | 232,360 |
MillionIntegrals/vel | vel/api/learner.py | Learner.run_epoch | def run_epoch(self, epoch_info: EpochInfo, source: 'vel.api.Source'):
""" Run full epoch of learning """
epoch_info.on_epoch_begin()
lr = epoch_info.optimizer.param_groups[-1]['lr']
print("|-------- Epoch {:06} Lr={:.6f} ----------|".format(epoch_info.global_epoch_idx, lr))
self.train_epoch(epoch_info, source)
epoch_info.result_accumulator.freeze_results('train')
self.validation_epoch(epoch_info, source)
epoch_info.result_accumulator.freeze_results('val')
epoch_info.on_epoch_end() | python | def run_epoch(self, epoch_info: EpochInfo, source: 'vel.api.Source'):
""" Run full epoch of learning """
epoch_info.on_epoch_begin()
lr = epoch_info.optimizer.param_groups[-1]['lr']
print("|-------- Epoch {:06} Lr={:.6f} ----------|".format(epoch_info.global_epoch_idx, lr))
self.train_epoch(epoch_info, source)
epoch_info.result_accumulator.freeze_results('train')
self.validation_epoch(epoch_info, source)
epoch_info.result_accumulator.freeze_results('val')
epoch_info.on_epoch_end() | [
"def",
"run_epoch",
"(",
"self",
",",
"epoch_info",
":",
"EpochInfo",
",",
"source",
":",
"'vel.api.Source'",
")",
":",
"epoch_info",
".",
"on_epoch_begin",
"(",
")",
"lr",
"=",
"epoch_info",
".",
"optimizer",
".",
"param_groups",
"[",
"-",
"1",
"]",
"[",
"'lr'",
"]",
"print",
"(",
"\"|-------- Epoch {:06} Lr={:.6f} ----------|\"",
".",
"format",
"(",
"epoch_info",
".",
"global_epoch_idx",
",",
"lr",
")",
")",
"self",
".",
"train_epoch",
"(",
"epoch_info",
",",
"source",
")",
"epoch_info",
".",
"result_accumulator",
".",
"freeze_results",
"(",
"'train'",
")",
"self",
".",
"validation_epoch",
"(",
"epoch_info",
",",
"source",
")",
"epoch_info",
".",
"result_accumulator",
".",
"freeze_results",
"(",
"'val'",
")",
"epoch_info",
".",
"on_epoch_end",
"(",
")"
] | Run full epoch of learning | [
"Run",
"full",
"epoch",
"of",
"learning"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L43-L56 | train | 232,361 |
MillionIntegrals/vel | vel/api/learner.py | Learner.train_epoch | def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True):
""" Run a single training epoch """
self.train()
if interactive:
iterator = tqdm.tqdm(source.train_loader(), desc="Training", unit="iter", file=sys.stdout)
else:
iterator = source.train_loader()
for batch_idx, (data, target) in enumerate(iterator):
batch_info = BatchInfo(epoch_info, batch_idx)
batch_info.on_batch_begin()
self.train_batch(batch_info, data, target)
batch_info.on_batch_end()
iterator.set_postfix(loss=epoch_info.result_accumulator.intermediate_value('loss')) | python | def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True):
""" Run a single training epoch """
self.train()
if interactive:
iterator = tqdm.tqdm(source.train_loader(), desc="Training", unit="iter", file=sys.stdout)
else:
iterator = source.train_loader()
for batch_idx, (data, target) in enumerate(iterator):
batch_info = BatchInfo(epoch_info, batch_idx)
batch_info.on_batch_begin()
self.train_batch(batch_info, data, target)
batch_info.on_batch_end()
iterator.set_postfix(loss=epoch_info.result_accumulator.intermediate_value('loss')) | [
"def",
"train_epoch",
"(",
"self",
",",
"epoch_info",
",",
"source",
":",
"'vel.api.Source'",
",",
"interactive",
"=",
"True",
")",
":",
"self",
".",
"train",
"(",
")",
"if",
"interactive",
":",
"iterator",
"=",
"tqdm",
".",
"tqdm",
"(",
"source",
".",
"train_loader",
"(",
")",
",",
"desc",
"=",
"\"Training\"",
",",
"unit",
"=",
"\"iter\"",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
"else",
":",
"iterator",
"=",
"source",
".",
"train_loader",
"(",
")",
"for",
"batch_idx",
",",
"(",
"data",
",",
"target",
")",
"in",
"enumerate",
"(",
"iterator",
")",
":",
"batch_info",
"=",
"BatchInfo",
"(",
"epoch_info",
",",
"batch_idx",
")",
"batch_info",
".",
"on_batch_begin",
"(",
")",
"self",
".",
"train_batch",
"(",
"batch_info",
",",
"data",
",",
"target",
")",
"batch_info",
".",
"on_batch_end",
"(",
")",
"iterator",
".",
"set_postfix",
"(",
"loss",
"=",
"epoch_info",
".",
"result_accumulator",
".",
"intermediate_value",
"(",
"'loss'",
")",
")"
] | Run a single training epoch | [
"Run",
"a",
"single",
"training",
"epoch"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L58-L74 | train | 232,362 |
MillionIntegrals/vel | vel/api/learner.py | Learner.validation_epoch | def validation_epoch(self, epoch_info, source: 'vel.api.Source'):
""" Run a single evaluation epoch """
self.eval()
iterator = tqdm.tqdm(source.val_loader(), desc="Validation", unit="iter", file=sys.stdout)
with torch.no_grad():
for batch_idx, (data, target) in enumerate(iterator):
batch_info = BatchInfo(epoch_info, batch_idx)
batch_info.on_validation_batch_begin()
self.feed_batch(batch_info, data, target)
batch_info.on_validation_batch_end() | python | def validation_epoch(self, epoch_info, source: 'vel.api.Source'):
""" Run a single evaluation epoch """
self.eval()
iterator = tqdm.tqdm(source.val_loader(), desc="Validation", unit="iter", file=sys.stdout)
with torch.no_grad():
for batch_idx, (data, target) in enumerate(iterator):
batch_info = BatchInfo(epoch_info, batch_idx)
batch_info.on_validation_batch_begin()
self.feed_batch(batch_info, data, target)
batch_info.on_validation_batch_end() | [
"def",
"validation_epoch",
"(",
"self",
",",
"epoch_info",
",",
"source",
":",
"'vel.api.Source'",
")",
":",
"self",
".",
"eval",
"(",
")",
"iterator",
"=",
"tqdm",
".",
"tqdm",
"(",
"source",
".",
"val_loader",
"(",
")",
",",
"desc",
"=",
"\"Validation\"",
",",
"unit",
"=",
"\"iter\"",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"for",
"batch_idx",
",",
"(",
"data",
",",
"target",
")",
"in",
"enumerate",
"(",
"iterator",
")",
":",
"batch_info",
"=",
"BatchInfo",
"(",
"epoch_info",
",",
"batch_idx",
")",
"batch_info",
".",
"on_validation_batch_begin",
"(",
")",
"self",
".",
"feed_batch",
"(",
"batch_info",
",",
"data",
",",
"target",
")",
"batch_info",
".",
"on_validation_batch_end",
"(",
")"
] | Run a single evaluation epoch | [
"Run",
"a",
"single",
"evaluation",
"epoch"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L76-L88 | train | 232,363 |
MillionIntegrals/vel | vel/api/learner.py | Learner.feed_batch | def feed_batch(self, batch_info, data, target):
""" Run single batch of data """
data, target = data.to(self.device), target.to(self.device)
output, loss = self.model.loss(data, target)
# Store extra batch information for calculation of the statistics
batch_info['data'] = data
batch_info['target'] = target
batch_info['output'] = output
batch_info['loss'] = loss
return loss | python | def feed_batch(self, batch_info, data, target):
""" Run single batch of data """
data, target = data.to(self.device), target.to(self.device)
output, loss = self.model.loss(data, target)
# Store extra batch information for calculation of the statistics
batch_info['data'] = data
batch_info['target'] = target
batch_info['output'] = output
batch_info['loss'] = loss
return loss | [
"def",
"feed_batch",
"(",
"self",
",",
"batch_info",
",",
"data",
",",
"target",
")",
":",
"data",
",",
"target",
"=",
"data",
".",
"to",
"(",
"self",
".",
"device",
")",
",",
"target",
".",
"to",
"(",
"self",
".",
"device",
")",
"output",
",",
"loss",
"=",
"self",
".",
"model",
".",
"loss",
"(",
"data",
",",
"target",
")",
"# Store extra batch information for calculation of the statistics",
"batch_info",
"[",
"'data'",
"]",
"=",
"data",
"batch_info",
"[",
"'target'",
"]",
"=",
"target",
"batch_info",
"[",
"'output'",
"]",
"=",
"output",
"batch_info",
"[",
"'loss'",
"]",
"=",
"loss",
"return",
"loss"
] | Run single batch of data | [
"Run",
"single",
"batch",
"of",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L90-L101 | train | 232,364 |
MillionIntegrals/vel | vel/api/learner.py | Learner.train_batch | def train_batch(self, batch_info, data, target):
""" Train single batch of data """
batch_info.optimizer.zero_grad()
loss = self.feed_batch(batch_info, data, target)
loss.backward()
if self.max_grad_norm is not None:
batch_info['grad_norm'] = torch.nn.utils.clip_grad_norm_(
filter(lambda p: p.requires_grad, self.model.parameters()),
max_norm=self.max_grad_norm
)
batch_info.optimizer.step() | python | def train_batch(self, batch_info, data, target):
""" Train single batch of data """
batch_info.optimizer.zero_grad()
loss = self.feed_batch(batch_info, data, target)
loss.backward()
if self.max_grad_norm is not None:
batch_info['grad_norm'] = torch.nn.utils.clip_grad_norm_(
filter(lambda p: p.requires_grad, self.model.parameters()),
max_norm=self.max_grad_norm
)
batch_info.optimizer.step() | [
"def",
"train_batch",
"(",
"self",
",",
"batch_info",
",",
"data",
",",
"target",
")",
":",
"batch_info",
".",
"optimizer",
".",
"zero_grad",
"(",
")",
"loss",
"=",
"self",
".",
"feed_batch",
"(",
"batch_info",
",",
"data",
",",
"target",
")",
"loss",
".",
"backward",
"(",
")",
"if",
"self",
".",
"max_grad_norm",
"is",
"not",
"None",
":",
"batch_info",
"[",
"'grad_norm'",
"]",
"=",
"torch",
".",
"nn",
".",
"utils",
".",
"clip_grad_norm_",
"(",
"filter",
"(",
"lambda",
"p",
":",
"p",
".",
"requires_grad",
",",
"self",
".",
"model",
".",
"parameters",
"(",
")",
")",
",",
"max_norm",
"=",
"self",
".",
"max_grad_norm",
")",
"batch_info",
".",
"optimizer",
".",
"step",
"(",
")"
] | Train single batch of data | [
"Train",
"single",
"batch",
"of",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L103-L115 | train | 232,365 |
MillionIntegrals/vel | vel/util/situational.py | process_environment_settings | def process_environment_settings(default_dictionary: dict, settings: typing.Optional[dict]=None,
presets: typing.Optional[dict]=None):
""" Process a dictionary of env settings """
settings = settings if settings is not None else {}
presets = presets if presets is not None else {}
env_keys = sorted(set(default_dictionary.keys()) | set(presets.keys()))
result_dict = {}
for key in env_keys:
if key in default_dictionary:
new_dict = default_dictionary[key].copy()
else:
new_dict = {}
new_dict.update(settings)
if key in presets:
new_dict.update(presets[key])
result_dict[key] = new_dict
return result_dict | python | def process_environment_settings(default_dictionary: dict, settings: typing.Optional[dict]=None,
presets: typing.Optional[dict]=None):
""" Process a dictionary of env settings """
settings = settings if settings is not None else {}
presets = presets if presets is not None else {}
env_keys = sorted(set(default_dictionary.keys()) | set(presets.keys()))
result_dict = {}
for key in env_keys:
if key in default_dictionary:
new_dict = default_dictionary[key].copy()
else:
new_dict = {}
new_dict.update(settings)
if key in presets:
new_dict.update(presets[key])
result_dict[key] = new_dict
return result_dict | [
"def",
"process_environment_settings",
"(",
"default_dictionary",
":",
"dict",
",",
"settings",
":",
"typing",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"presets",
":",
"typing",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
")",
":",
"settings",
"=",
"settings",
"if",
"settings",
"is",
"not",
"None",
"else",
"{",
"}",
"presets",
"=",
"presets",
"if",
"presets",
"is",
"not",
"None",
"else",
"{",
"}",
"env_keys",
"=",
"sorted",
"(",
"set",
"(",
"default_dictionary",
".",
"keys",
"(",
")",
")",
"|",
"set",
"(",
"presets",
".",
"keys",
"(",
")",
")",
")",
"result_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"env_keys",
":",
"if",
"key",
"in",
"default_dictionary",
":",
"new_dict",
"=",
"default_dictionary",
"[",
"key",
"]",
".",
"copy",
"(",
")",
"else",
":",
"new_dict",
"=",
"{",
"}",
"new_dict",
".",
"update",
"(",
"settings",
")",
"if",
"key",
"in",
"presets",
":",
"new_dict",
".",
"update",
"(",
"presets",
"[",
"key",
"]",
")",
"result_dict",
"[",
"key",
"]",
"=",
"new_dict",
"return",
"result_dict"
] | Process a dictionary of env settings | [
"Process",
"a",
"dictionary",
"of",
"env",
"settings"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/situational.py#L4-L27 | train | 232,366 |
MillionIntegrals/vel | vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py | BufferedOffPolicyIterationReinforcer.roll_out_and_store | def roll_out_and_store(self, batch_info):
""" Roll out environment and store result in the replay buffer """
self.model.train()
if self.env_roller.is_ready_for_sampling():
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device)
# Store some information about the rollout, no training phase
batch_info['frames'] = rollout.frames()
batch_info['episode_infos'] = rollout.episode_information()
else:
frames = 0
episode_infos = []
with tqdm.tqdm(desc="Populating memory", total=self.env_roller.initial_memory_size_hint()) as pbar:
while not self.env_roller.is_ready_for_sampling():
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device)
new_frames = rollout.frames()
frames += new_frames
episode_infos.extend(rollout.episode_information())
pbar.update(new_frames)
# Store some information about the rollout, no training phase
batch_info['frames'] = frames
batch_info['episode_infos'] = episode_infos | python | def roll_out_and_store(self, batch_info):
""" Roll out environment and store result in the replay buffer """
self.model.train()
if self.env_roller.is_ready_for_sampling():
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device)
# Store some information about the rollout, no training phase
batch_info['frames'] = rollout.frames()
batch_info['episode_infos'] = rollout.episode_information()
else:
frames = 0
episode_infos = []
with tqdm.tqdm(desc="Populating memory", total=self.env_roller.initial_memory_size_hint()) as pbar:
while not self.env_roller.is_ready_for_sampling():
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device)
new_frames = rollout.frames()
frames += new_frames
episode_infos.extend(rollout.episode_information())
pbar.update(new_frames)
# Store some information about the rollout, no training phase
batch_info['frames'] = frames
batch_info['episode_infos'] = episode_infos | [
"def",
"roll_out_and_store",
"(",
"self",
",",
"batch_info",
")",
":",
"self",
".",
"model",
".",
"train",
"(",
")",
"if",
"self",
".",
"env_roller",
".",
"is_ready_for_sampling",
"(",
")",
":",
"rollout",
"=",
"self",
".",
"env_roller",
".",
"rollout",
"(",
"batch_info",
",",
"self",
".",
"model",
",",
"self",
".",
"settings",
".",
"rollout_steps",
")",
".",
"to_device",
"(",
"self",
".",
"device",
")",
"# Store some information about the rollout, no training phase",
"batch_info",
"[",
"'frames'",
"]",
"=",
"rollout",
".",
"frames",
"(",
")",
"batch_info",
"[",
"'episode_infos'",
"]",
"=",
"rollout",
".",
"episode_information",
"(",
")",
"else",
":",
"frames",
"=",
"0",
"episode_infos",
"=",
"[",
"]",
"with",
"tqdm",
".",
"tqdm",
"(",
"desc",
"=",
"\"Populating memory\"",
",",
"total",
"=",
"self",
".",
"env_roller",
".",
"initial_memory_size_hint",
"(",
")",
")",
"as",
"pbar",
":",
"while",
"not",
"self",
".",
"env_roller",
".",
"is_ready_for_sampling",
"(",
")",
":",
"rollout",
"=",
"self",
".",
"env_roller",
".",
"rollout",
"(",
"batch_info",
",",
"self",
".",
"model",
",",
"self",
".",
"settings",
".",
"rollout_steps",
")",
".",
"to_device",
"(",
"self",
".",
"device",
")",
"new_frames",
"=",
"rollout",
".",
"frames",
"(",
")",
"frames",
"+=",
"new_frames",
"episode_infos",
".",
"extend",
"(",
"rollout",
".",
"episode_information",
"(",
")",
")",
"pbar",
".",
"update",
"(",
"new_frames",
")",
"# Store some information about the rollout, no training phase",
"batch_info",
"[",
"'frames'",
"]",
"=",
"frames",
"batch_info",
"[",
"'episode_infos'",
"]",
"=",
"episode_infos"
] | Roll out environment and store result in the replay buffer | [
"Roll",
"out",
"environment",
"and",
"store",
"result",
"in",
"the",
"replay",
"buffer"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py#L109-L135 | train | 232,367 |
MillionIntegrals/vel | vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py | BufferedOffPolicyIterationReinforcer.train_on_replay_memory | def train_on_replay_memory(self, batch_info):
""" Train agent on a memory gotten from replay buffer """
self.model.train()
# Algo will aggregate data into this list:
batch_info['sub_batch_data'] = []
for i in range(self.settings.training_rounds):
sampled_rollout = self.env_roller.sample(batch_info, self.model, self.settings.training_steps)
batch_result = self.algo.optimizer_step(
batch_info=batch_info,
device=self.device,
model=self.model,
rollout=sampled_rollout.to_device(self.device)
)
self.env_roller.update(rollout=sampled_rollout, batch_info=batch_result)
batch_info['sub_batch_data'].append(batch_result)
batch_info.aggregate_key('sub_batch_data') | python | def train_on_replay_memory(self, batch_info):
""" Train agent on a memory gotten from replay buffer """
self.model.train()
# Algo will aggregate data into this list:
batch_info['sub_batch_data'] = []
for i in range(self.settings.training_rounds):
sampled_rollout = self.env_roller.sample(batch_info, self.model, self.settings.training_steps)
batch_result = self.algo.optimizer_step(
batch_info=batch_info,
device=self.device,
model=self.model,
rollout=sampled_rollout.to_device(self.device)
)
self.env_roller.update(rollout=sampled_rollout, batch_info=batch_result)
batch_info['sub_batch_data'].append(batch_result)
batch_info.aggregate_key('sub_batch_data') | [
"def",
"train_on_replay_memory",
"(",
"self",
",",
"batch_info",
")",
":",
"self",
".",
"model",
".",
"train",
"(",
")",
"# Algo will aggregate data into this list:",
"batch_info",
"[",
"'sub_batch_data'",
"]",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"settings",
".",
"training_rounds",
")",
":",
"sampled_rollout",
"=",
"self",
".",
"env_roller",
".",
"sample",
"(",
"batch_info",
",",
"self",
".",
"model",
",",
"self",
".",
"settings",
".",
"training_steps",
")",
"batch_result",
"=",
"self",
".",
"algo",
".",
"optimizer_step",
"(",
"batch_info",
"=",
"batch_info",
",",
"device",
"=",
"self",
".",
"device",
",",
"model",
"=",
"self",
".",
"model",
",",
"rollout",
"=",
"sampled_rollout",
".",
"to_device",
"(",
"self",
".",
"device",
")",
")",
"self",
".",
"env_roller",
".",
"update",
"(",
"rollout",
"=",
"sampled_rollout",
",",
"batch_info",
"=",
"batch_result",
")",
"batch_info",
"[",
"'sub_batch_data'",
"]",
".",
"append",
"(",
"batch_result",
")",
"batch_info",
".",
"aggregate_key",
"(",
"'sub_batch_data'",
")"
] | Train agent on a memory gotten from replay buffer | [
"Train",
"agent",
"on",
"a",
"memory",
"gotten",
"from",
"replay",
"buffer"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py#L137-L158 | train | 232,368 |
MillionIntegrals/vel | vel/modules/resnet_v1.py | conv3x3 | def conv3x3(in_channels, out_channels, stride=1):
"""
3x3 convolution with padding.
Original code has had bias turned off, because Batch Norm would remove the bias either way
"""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False) | python | def conv3x3(in_channels, out_channels, stride=1):
"""
3x3 convolution with padding.
Original code has had bias turned off, because Batch Norm would remove the bias either way
"""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False) | [
"def",
"conv3x3",
"(",
"in_channels",
",",
"out_channels",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_channels",
",",
"out_channels",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"bias",
"=",
"False",
")"
] | 3x3 convolution with padding.
Original code has had bias turned off, because Batch Norm would remove the bias either way | [
"3x3",
"convolution",
"with",
"padding",
".",
"Original",
"code",
"has",
"had",
"bias",
"turned",
"off",
"because",
"Batch",
"Norm",
"would",
"remove",
"the",
"bias",
"either",
"way"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/modules/resnet_v1.py#L10-L15 | train | 232,369 |
MillionIntegrals/vel | vel/notebook/loader.py | load | def load(config_path, run_number=0, device='cuda:0'):
""" Load a ModelConfig from filename """
model_config = ModelConfig.from_file(config_path, run_number, device=device)
return model_config | python | def load(config_path, run_number=0, device='cuda:0'):
""" Load a ModelConfig from filename """
model_config = ModelConfig.from_file(config_path, run_number, device=device)
return model_config | [
"def",
"load",
"(",
"config_path",
",",
"run_number",
"=",
"0",
",",
"device",
"=",
"'cuda:0'",
")",
":",
"model_config",
"=",
"ModelConfig",
".",
"from_file",
"(",
"config_path",
",",
"run_number",
",",
"device",
"=",
"device",
")",
"return",
"model_config"
] | Load a ModelConfig from filename | [
"Load",
"a",
"ModelConfig",
"from",
"filename"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/notebook/loader.py#L4-L8 | train | 232,370 |
MillionIntegrals/vel | vel/api/info.py | TrainingInfo.restore | def restore(self, hidden_state):
""" Restore any state from checkpoint - currently not implemented but possible to do so in the future """
for callback in self.callbacks:
callback.load_state_dict(self, hidden_state)
if 'optimizer' in hidden_state:
self.optimizer_initial_state = hidden_state['optimizer'] | python | def restore(self, hidden_state):
""" Restore any state from checkpoint - currently not implemented but possible to do so in the future """
for callback in self.callbacks:
callback.load_state_dict(self, hidden_state)
if 'optimizer' in hidden_state:
self.optimizer_initial_state = hidden_state['optimizer'] | [
"def",
"restore",
"(",
"self",
",",
"hidden_state",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"callback",
".",
"load_state_dict",
"(",
"self",
",",
"hidden_state",
")",
"if",
"'optimizer'",
"in",
"hidden_state",
":",
"self",
".",
"optimizer_initial_state",
"=",
"hidden_state",
"[",
"'optimizer'",
"]"
] | Restore any state from checkpoint - currently not implemented but possible to do so in the future | [
"Restore",
"any",
"state",
"from",
"checkpoint",
"-",
"currently",
"not",
"implemented",
"but",
"possible",
"to",
"do",
"so",
"in",
"the",
"future"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L47-L53 | train | 232,371 |
MillionIntegrals/vel | vel/api/info.py | EpochResultAccumulator.result | def result(self):
""" Return the epoch result """
final_result = {'epoch_idx': self.global_epoch_idx}
for key, value in self.frozen_results.items():
final_result[key] = value
return final_result | python | def result(self):
""" Return the epoch result """
final_result = {'epoch_idx': self.global_epoch_idx}
for key, value in self.frozen_results.items():
final_result[key] = value
return final_result | [
"def",
"result",
"(",
"self",
")",
":",
"final_result",
"=",
"{",
"'epoch_idx'",
":",
"self",
".",
"global_epoch_idx",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"frozen_results",
".",
"items",
"(",
")",
":",
"final_result",
"[",
"key",
"]",
"=",
"value",
"return",
"final_result"
] | Return the epoch result | [
"Return",
"the",
"epoch",
"result"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L144-L151 | train | 232,372 |
MillionIntegrals/vel | vel/api/info.py | EpochInfo.state_dict | def state_dict(self) -> dict:
""" Calculate hidden state dictionary """
hidden_state = {}
if self.optimizer is not None:
hidden_state['optimizer'] = self.optimizer.state_dict()
for callback in self.callbacks:
callback.write_state_dict(self.training_info, hidden_state)
return hidden_state | python | def state_dict(self) -> dict:
""" Calculate hidden state dictionary """
hidden_state = {}
if self.optimizer is not None:
hidden_state['optimizer'] = self.optimizer.state_dict()
for callback in self.callbacks:
callback.write_state_dict(self.training_info, hidden_state)
return hidden_state | [
"def",
"state_dict",
"(",
"self",
")",
"->",
"dict",
":",
"hidden_state",
"=",
"{",
"}",
"if",
"self",
".",
"optimizer",
"is",
"not",
"None",
":",
"hidden_state",
"[",
"'optimizer'",
"]",
"=",
"self",
".",
"optimizer",
".",
"state_dict",
"(",
")",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"callback",
".",
"write_state_dict",
"(",
"self",
".",
"training_info",
",",
"hidden_state",
")",
"return",
"hidden_state"
] | Calculate hidden state dictionary | [
"Calculate",
"hidden",
"state",
"dictionary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L186-L196 | train | 232,373 |
MillionIntegrals/vel | vel/api/info.py | EpochInfo.on_epoch_end | def on_epoch_end(self):
""" Finish epoch processing """
self.freeze_epoch_result()
for callback in self.callbacks:
callback.on_epoch_end(self)
self.training_info.history.add(self.result) | python | def on_epoch_end(self):
""" Finish epoch processing """
self.freeze_epoch_result()
for callback in self.callbacks:
callback.on_epoch_end(self)
self.training_info.history.add(self.result) | [
"def",
"on_epoch_end",
"(",
"self",
")",
":",
"self",
".",
"freeze_epoch_result",
"(",
")",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"callback",
".",
"on_epoch_end",
"(",
"self",
")",
"self",
".",
"training_info",
".",
"history",
".",
"add",
"(",
"self",
".",
"result",
")"
] | Finish epoch processing | [
"Finish",
"epoch",
"processing"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L203-L210 | train | 232,374 |
MillionIntegrals/vel | vel/api/info.py | BatchInfo.aggregate_key | def aggregate_key(self, aggregate_key):
""" Aggregate values from key and put them into the top-level dictionary """
aggregation = self.data_dict[aggregate_key] # List of dictionaries of numpy arrays/scalars
# Aggregate sub batch data
data_dict_keys = {y for x in aggregation for y in x.keys()}
for key in data_dict_keys:
# Just average all the statistics from the loss function
stacked = np.stack([d[key] for d in aggregation], axis=0)
self.data_dict[key] = np.mean(stacked, axis=0) | python | def aggregate_key(self, aggregate_key):
""" Aggregate values from key and put them into the top-level dictionary """
aggregation = self.data_dict[aggregate_key] # List of dictionaries of numpy arrays/scalars
# Aggregate sub batch data
data_dict_keys = {y for x in aggregation for y in x.keys()}
for key in data_dict_keys:
# Just average all the statistics from the loss function
stacked = np.stack([d[key] for d in aggregation], axis=0)
self.data_dict[key] = np.mean(stacked, axis=0) | [
"def",
"aggregate_key",
"(",
"self",
",",
"aggregate_key",
")",
":",
"aggregation",
"=",
"self",
".",
"data_dict",
"[",
"aggregate_key",
"]",
"# List of dictionaries of numpy arrays/scalars",
"# Aggregate sub batch data",
"data_dict_keys",
"=",
"{",
"y",
"for",
"x",
"in",
"aggregation",
"for",
"y",
"in",
"x",
".",
"keys",
"(",
")",
"}",
"for",
"key",
"in",
"data_dict_keys",
":",
"# Just average all the statistics from the loss function",
"stacked",
"=",
"np",
".",
"stack",
"(",
"[",
"d",
"[",
"key",
"]",
"for",
"d",
"in",
"aggregation",
"]",
",",
"axis",
"=",
"0",
")",
"self",
".",
"data_dict",
"[",
"key",
"]",
"=",
"np",
".",
"mean",
"(",
"stacked",
",",
"axis",
"=",
"0",
")"
] | Aggregate values from key and put them into the top-level dictionary | [
"Aggregate",
"values",
"from",
"key",
"and",
"put",
"them",
"into",
"the",
"top",
"-",
"level",
"dictionary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L316-L326 | train | 232,375 |
MillionIntegrals/vel | vel/rl/commands/rl_train_command.py | RlTrainCommand.run | def run(self):
""" Run reinforcement learning algorithm """
device = self.model_config.torch_device()
# Reinforcer is the learner for the reinforcement learning model
reinforcer = self.reinforcer.instantiate(device)
optimizer = self.optimizer_factory.instantiate(reinforcer.model)
# All callbacks used for learning
callbacks = self.gather_callbacks(optimizer)
# Metrics to track through this training
metrics = reinforcer.metrics()
training_info = self.resume_training(reinforcer, callbacks, metrics)
reinforcer.initialize_training(training_info)
training_info.on_train_begin()
if training_info.optimizer_initial_state:
optimizer.load_state_dict(training_info.optimizer_initial_state)
global_epoch_idx = training_info.start_epoch_idx + 1
while training_info['frames'] < self.total_frames:
epoch_info = EpochInfo(
training_info,
global_epoch_idx=global_epoch_idx,
batches_per_epoch=self.batches_per_epoch,
optimizer=optimizer,
)
reinforcer.train_epoch(epoch_info)
if self.openai_logging:
self._openai_logging(epoch_info.result)
self.storage.checkpoint(epoch_info, reinforcer.model)
global_epoch_idx += 1
training_info.on_train_end()
return training_info | python | def run(self):
""" Run reinforcement learning algorithm """
device = self.model_config.torch_device()
# Reinforcer is the learner for the reinforcement learning model
reinforcer = self.reinforcer.instantiate(device)
optimizer = self.optimizer_factory.instantiate(reinforcer.model)
# All callbacks used for learning
callbacks = self.gather_callbacks(optimizer)
# Metrics to track through this training
metrics = reinforcer.metrics()
training_info = self.resume_training(reinforcer, callbacks, metrics)
reinforcer.initialize_training(training_info)
training_info.on_train_begin()
if training_info.optimizer_initial_state:
optimizer.load_state_dict(training_info.optimizer_initial_state)
global_epoch_idx = training_info.start_epoch_idx + 1
while training_info['frames'] < self.total_frames:
epoch_info = EpochInfo(
training_info,
global_epoch_idx=global_epoch_idx,
batches_per_epoch=self.batches_per_epoch,
optimizer=optimizer,
)
reinforcer.train_epoch(epoch_info)
if self.openai_logging:
self._openai_logging(epoch_info.result)
self.storage.checkpoint(epoch_info, reinforcer.model)
global_epoch_idx += 1
training_info.on_train_end()
return training_info | [
"def",
"run",
"(",
"self",
")",
":",
"device",
"=",
"self",
".",
"model_config",
".",
"torch_device",
"(",
")",
"# Reinforcer is the learner for the reinforcement learning model",
"reinforcer",
"=",
"self",
".",
"reinforcer",
".",
"instantiate",
"(",
"device",
")",
"optimizer",
"=",
"self",
".",
"optimizer_factory",
".",
"instantiate",
"(",
"reinforcer",
".",
"model",
")",
"# All callbacks used for learning",
"callbacks",
"=",
"self",
".",
"gather_callbacks",
"(",
"optimizer",
")",
"# Metrics to track through this training",
"metrics",
"=",
"reinforcer",
".",
"metrics",
"(",
")",
"training_info",
"=",
"self",
".",
"resume_training",
"(",
"reinforcer",
",",
"callbacks",
",",
"metrics",
")",
"reinforcer",
".",
"initialize_training",
"(",
"training_info",
")",
"training_info",
".",
"on_train_begin",
"(",
")",
"if",
"training_info",
".",
"optimizer_initial_state",
":",
"optimizer",
".",
"load_state_dict",
"(",
"training_info",
".",
"optimizer_initial_state",
")",
"global_epoch_idx",
"=",
"training_info",
".",
"start_epoch_idx",
"+",
"1",
"while",
"training_info",
"[",
"'frames'",
"]",
"<",
"self",
".",
"total_frames",
":",
"epoch_info",
"=",
"EpochInfo",
"(",
"training_info",
",",
"global_epoch_idx",
"=",
"global_epoch_idx",
",",
"batches_per_epoch",
"=",
"self",
".",
"batches_per_epoch",
",",
"optimizer",
"=",
"optimizer",
",",
")",
"reinforcer",
".",
"train_epoch",
"(",
"epoch_info",
")",
"if",
"self",
".",
"openai_logging",
":",
"self",
".",
"_openai_logging",
"(",
"epoch_info",
".",
"result",
")",
"self",
".",
"storage",
".",
"checkpoint",
"(",
"epoch_info",
",",
"reinforcer",
".",
"model",
")",
"global_epoch_idx",
"+=",
"1",
"training_info",
".",
"on_train_end",
"(",
")",
"return",
"training_info"
] | Run reinforcement learning algorithm | [
"Run",
"reinforcement",
"learning",
"algorithm"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L62-L104 | train | 232,376 |
MillionIntegrals/vel | vel/rl/commands/rl_train_command.py | RlTrainCommand.resume_training | def resume_training(self, reinforcer, callbacks, metrics) -> TrainingInfo:
""" Possibly resume training from a saved state from the storage """
if self.model_config.continue_training:
start_epoch = self.storage.last_epoch_idx()
else:
start_epoch = 0
training_info = TrainingInfo(
start_epoch_idx=start_epoch,
run_name=self.model_config.run_name,
metrics=metrics, callbacks=callbacks
)
if start_epoch == 0:
self.storage.reset(self.model_config.render_configuration())
training_info.initialize()
reinforcer.initialize_training(training_info)
else:
model_state, hidden_state = self.storage.load(training_info)
reinforcer.initialize_training(training_info, model_state, hidden_state)
return training_info | python | def resume_training(self, reinforcer, callbacks, metrics) -> TrainingInfo:
""" Possibly resume training from a saved state from the storage """
if self.model_config.continue_training:
start_epoch = self.storage.last_epoch_idx()
else:
start_epoch = 0
training_info = TrainingInfo(
start_epoch_idx=start_epoch,
run_name=self.model_config.run_name,
metrics=metrics, callbacks=callbacks
)
if start_epoch == 0:
self.storage.reset(self.model_config.render_configuration())
training_info.initialize()
reinforcer.initialize_training(training_info)
else:
model_state, hidden_state = self.storage.load(training_info)
reinforcer.initialize_training(training_info, model_state, hidden_state)
return training_info | [
"def",
"resume_training",
"(",
"self",
",",
"reinforcer",
",",
"callbacks",
",",
"metrics",
")",
"->",
"TrainingInfo",
":",
"if",
"self",
".",
"model_config",
".",
"continue_training",
":",
"start_epoch",
"=",
"self",
".",
"storage",
".",
"last_epoch_idx",
"(",
")",
"else",
":",
"start_epoch",
"=",
"0",
"training_info",
"=",
"TrainingInfo",
"(",
"start_epoch_idx",
"=",
"start_epoch",
",",
"run_name",
"=",
"self",
".",
"model_config",
".",
"run_name",
",",
"metrics",
"=",
"metrics",
",",
"callbacks",
"=",
"callbacks",
")",
"if",
"start_epoch",
"==",
"0",
":",
"self",
".",
"storage",
".",
"reset",
"(",
"self",
".",
"model_config",
".",
"render_configuration",
"(",
")",
")",
"training_info",
".",
"initialize",
"(",
")",
"reinforcer",
".",
"initialize_training",
"(",
"training_info",
")",
"else",
":",
"model_state",
",",
"hidden_state",
"=",
"self",
".",
"storage",
".",
"load",
"(",
"training_info",
")",
"reinforcer",
".",
"initialize_training",
"(",
"training_info",
",",
"model_state",
",",
"hidden_state",
")",
"return",
"training_info"
] | Possibly resume training from a saved state from the storage | [
"Possibly",
"resume",
"training",
"from",
"a",
"saved",
"state",
"from",
"the",
"storage"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L118-L139 | train | 232,377 |
MillionIntegrals/vel | vel/rl/commands/rl_train_command.py | RlTrainCommand._openai_logging | def _openai_logging(self, epoch_result):
""" Use OpenAI logging facilities for the same type of logging """
for key in sorted(epoch_result.keys()):
if key == 'fps':
# Not super elegant, but I like nicer display of FPS
openai_logger.record_tabular(key, int(epoch_result[key]))
else:
openai_logger.record_tabular(key, epoch_result[key])
openai_logger.dump_tabular() | python | def _openai_logging(self, epoch_result):
""" Use OpenAI logging facilities for the same type of logging """
for key in sorted(epoch_result.keys()):
if key == 'fps':
# Not super elegant, but I like nicer display of FPS
openai_logger.record_tabular(key, int(epoch_result[key]))
else:
openai_logger.record_tabular(key, epoch_result[key])
openai_logger.dump_tabular() | [
"def",
"_openai_logging",
"(",
"self",
",",
"epoch_result",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"epoch_result",
".",
"keys",
"(",
")",
")",
":",
"if",
"key",
"==",
"'fps'",
":",
"# Not super elegant, but I like nicer display of FPS",
"openai_logger",
".",
"record_tabular",
"(",
"key",
",",
"int",
"(",
"epoch_result",
"[",
"key",
"]",
")",
")",
"else",
":",
"openai_logger",
".",
"record_tabular",
"(",
"key",
",",
"epoch_result",
"[",
"key",
"]",
")",
"openai_logger",
".",
"dump_tabular",
"(",
")"
] | Use OpenAI logging facilities for the same type of logging | [
"Use",
"OpenAI",
"logging",
"facilities",
"for",
"the",
"same",
"type",
"of",
"logging"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L141-L150 | train | 232,378 |
MillionIntegrals/vel | vel/util/module_util.py | module_broadcast | def module_broadcast(m, broadcast_fn, *args, **kwargs):
""" Call given function in all submodules with given parameters """
apply_leaf(m, lambda x: module_apply_broadcast(x, broadcast_fn, args, kwargs)) | python | def module_broadcast(m, broadcast_fn, *args, **kwargs):
""" Call given function in all submodules with given parameters """
apply_leaf(m, lambda x: module_apply_broadcast(x, broadcast_fn, args, kwargs)) | [
"def",
"module_broadcast",
"(",
"m",
",",
"broadcast_fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"apply_leaf",
"(",
"m",
",",
"lambda",
"x",
":",
"module_apply_broadcast",
"(",
"x",
",",
"broadcast_fn",
",",
"args",
",",
"kwargs",
")",
")"
] | Call given function in all submodules with given parameters | [
"Call",
"given",
"function",
"in",
"all",
"submodules",
"with",
"given",
"parameters"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/module_util.py#L34-L36 | train | 232,379 |
MillionIntegrals/vel | vel/commands/phase_train_command.py | PhaseTrainCommand._select_phase_left_bound | def _select_phase_left_bound(self, epoch_number):
"""
Return number of current phase.
Return index of first phase not done after all up to epoch_number were done.
"""
idx = bisect.bisect_left(self.ladder, epoch_number)
if idx >= len(self.ladder):
return len(self.ladder) - 1
elif self.ladder[idx] > epoch_number:
return idx - 1
else:
return idx | python | def _select_phase_left_bound(self, epoch_number):
"""
Return number of current phase.
Return index of first phase not done after all up to epoch_number were done.
"""
idx = bisect.bisect_left(self.ladder, epoch_number)
if idx >= len(self.ladder):
return len(self.ladder) - 1
elif self.ladder[idx] > epoch_number:
return idx - 1
else:
return idx | [
"def",
"_select_phase_left_bound",
"(",
"self",
",",
"epoch_number",
")",
":",
"idx",
"=",
"bisect",
".",
"bisect_left",
"(",
"self",
".",
"ladder",
",",
"epoch_number",
")",
"if",
"idx",
">=",
"len",
"(",
"self",
".",
"ladder",
")",
":",
"return",
"len",
"(",
"self",
".",
"ladder",
")",
"-",
"1",
"elif",
"self",
".",
"ladder",
"[",
"idx",
"]",
">",
"epoch_number",
":",
"return",
"idx",
"-",
"1",
"else",
":",
"return",
"idx"
] | Return number of current phase.
Return index of first phase not done after all up to epoch_number were done. | [
"Return",
"number",
"of",
"current",
"phase",
".",
"Return",
"index",
"of",
"first",
"phase",
"not",
"done",
"after",
"all",
"up",
"to",
"epoch_number",
"were",
"done",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/phase_train_command.py#L29-L41 | train | 232,380 |
MillionIntegrals/vel | vel/rl/env/classic_atari.py | wrapped_env_maker | def wrapped_env_maker(environment_id, seed, serial_id, disable_reward_clipping=False, disable_episodic_life=False,
monitor=False, allow_early_resets=False, scale_float_frames=False,
max_episode_frames=10000, frame_stack=None):
""" Wrap atari environment so that it's nicer to learn RL algorithms """
env = env_maker(environment_id)
env.seed(seed + serial_id)
if max_episode_frames is not None:
env = ClipEpisodeLengthWrapper(env, max_episode_length=max_episode_frames)
# Monitoring the env
if monitor:
logdir = logger.get_dir() and os.path.join(logger.get_dir(), str(serial_id))
else:
logdir = None
env = Monitor(env, logdir, allow_early_resets=allow_early_resets)
if not disable_episodic_life:
# Make end-of-life == end-of-episode, but only reset on true game over.
# Done by DeepMind for the DQN and co. since it helps value estimation.
env = EpisodicLifeEnv(env)
if 'FIRE' in env.unwrapped.get_action_meanings():
# Take action on reset for environments that are fixed until firing.
if disable_episodic_life:
env = FireEpisodicLifeEnv(env)
else:
env = FireResetEnv(env)
# Warp frames to 84x84 as done in the Nature paper and later work.
env = WarpFrame(env)
if scale_float_frames:
env = ScaledFloatFrame(env)
if not disable_reward_clipping:
# Bin reward to {+1, 0, -1} by its sign.
env = ClipRewardEnv(env)
if frame_stack is not None:
env = FrameStack(env, frame_stack)
return env | python | def wrapped_env_maker(environment_id, seed, serial_id, disable_reward_clipping=False, disable_episodic_life=False,
monitor=False, allow_early_resets=False, scale_float_frames=False,
max_episode_frames=10000, frame_stack=None):
""" Wrap atari environment so that it's nicer to learn RL algorithms """
env = env_maker(environment_id)
env.seed(seed + serial_id)
if max_episode_frames is not None:
env = ClipEpisodeLengthWrapper(env, max_episode_length=max_episode_frames)
# Monitoring the env
if monitor:
logdir = logger.get_dir() and os.path.join(logger.get_dir(), str(serial_id))
else:
logdir = None
env = Monitor(env, logdir, allow_early_resets=allow_early_resets)
if not disable_episodic_life:
# Make end-of-life == end-of-episode, but only reset on true game over.
# Done by DeepMind for the DQN and co. since it helps value estimation.
env = EpisodicLifeEnv(env)
if 'FIRE' in env.unwrapped.get_action_meanings():
# Take action on reset for environments that are fixed until firing.
if disable_episodic_life:
env = FireEpisodicLifeEnv(env)
else:
env = FireResetEnv(env)
# Warp frames to 84x84 as done in the Nature paper and later work.
env = WarpFrame(env)
if scale_float_frames:
env = ScaledFloatFrame(env)
if not disable_reward_clipping:
# Bin reward to {+1, 0, -1} by its sign.
env = ClipRewardEnv(env)
if frame_stack is not None:
env = FrameStack(env, frame_stack)
return env | [
"def",
"wrapped_env_maker",
"(",
"environment_id",
",",
"seed",
",",
"serial_id",
",",
"disable_reward_clipping",
"=",
"False",
",",
"disable_episodic_life",
"=",
"False",
",",
"monitor",
"=",
"False",
",",
"allow_early_resets",
"=",
"False",
",",
"scale_float_frames",
"=",
"False",
",",
"max_episode_frames",
"=",
"10000",
",",
"frame_stack",
"=",
"None",
")",
":",
"env",
"=",
"env_maker",
"(",
"environment_id",
")",
"env",
".",
"seed",
"(",
"seed",
"+",
"serial_id",
")",
"if",
"max_episode_frames",
"is",
"not",
"None",
":",
"env",
"=",
"ClipEpisodeLengthWrapper",
"(",
"env",
",",
"max_episode_length",
"=",
"max_episode_frames",
")",
"# Monitoring the env",
"if",
"monitor",
":",
"logdir",
"=",
"logger",
".",
"get_dir",
"(",
")",
"and",
"os",
".",
"path",
".",
"join",
"(",
"logger",
".",
"get_dir",
"(",
")",
",",
"str",
"(",
"serial_id",
")",
")",
"else",
":",
"logdir",
"=",
"None",
"env",
"=",
"Monitor",
"(",
"env",
",",
"logdir",
",",
"allow_early_resets",
"=",
"allow_early_resets",
")",
"if",
"not",
"disable_episodic_life",
":",
"# Make end-of-life == end-of-episode, but only reset on true game over.",
"# Done by DeepMind for the DQN and co. since it helps value estimation.",
"env",
"=",
"EpisodicLifeEnv",
"(",
"env",
")",
"if",
"'FIRE'",
"in",
"env",
".",
"unwrapped",
".",
"get_action_meanings",
"(",
")",
":",
"# Take action on reset for environments that are fixed until firing.",
"if",
"disable_episodic_life",
":",
"env",
"=",
"FireEpisodicLifeEnv",
"(",
"env",
")",
"else",
":",
"env",
"=",
"FireResetEnv",
"(",
"env",
")",
"# Warp frames to 84x84 as done in the Nature paper and later work.",
"env",
"=",
"WarpFrame",
"(",
"env",
")",
"if",
"scale_float_frames",
":",
"env",
"=",
"ScaledFloatFrame",
"(",
"env",
")",
"if",
"not",
"disable_reward_clipping",
":",
"# Bin reward to {+1, 0, -1} by its sign.",
"env",
"=",
"ClipRewardEnv",
"(",
"env",
")",
"if",
"frame_stack",
"is",
"not",
"None",
":",
"env",
"=",
"FrameStack",
"(",
"env",
",",
"frame_stack",
")",
"return",
"env"
] | Wrap atari environment so that it's nicer to learn RL algorithms | [
"Wrap",
"atari",
"environment",
"so",
"that",
"it",
"s",
"nicer",
"to",
"learn",
"RL",
"algorithms"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_atari.py#L55-L98 | train | 232,381 |
MillionIntegrals/vel | vel/rl/env/classic_atari.py | ClassicAtariEnv.instantiate | def instantiate(self, seed=0, serial_id=0, preset='default', extra_args=None) -> gym.Env:
""" Make a single environment compatible with the experiments """
settings = self.get_preset(preset)
return wrapped_env_maker(self.envname, seed, serial_id, **settings) | python | def instantiate(self, seed=0, serial_id=0, preset='default', extra_args=None) -> gym.Env:
""" Make a single environment compatible with the experiments """
settings = self.get_preset(preset)
return wrapped_env_maker(self.envname, seed, serial_id, **settings) | [
"def",
"instantiate",
"(",
"self",
",",
"seed",
"=",
"0",
",",
"serial_id",
"=",
"0",
",",
"preset",
"=",
"'default'",
",",
"extra_args",
"=",
"None",
")",
"->",
"gym",
".",
"Env",
":",
"settings",
"=",
"self",
".",
"get_preset",
"(",
"preset",
")",
"return",
"wrapped_env_maker",
"(",
"self",
".",
"envname",
",",
"seed",
",",
"serial_id",
",",
"*",
"*",
"settings",
")"
] | Make a single environment compatible with the experiments | [
"Make",
"a",
"single",
"environment",
"compatible",
"with",
"the",
"experiments"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_atari.py#L115-L118 | train | 232,382 |
MillionIntegrals/vel | vel/util/visdom.py | visdom_send_metrics | def visdom_send_metrics(vis, metrics, update='replace'):
""" Send set of metrics to visdom """
visited = {}
sorted_metrics = sorted(metrics.columns, key=_column_original_name)
for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name):
metric_list = list(metric_list)
for metric in metric_list:
if vis.win_exists(metric_basename) and (not visited.get(metric, False)):
update = update
elif not vis.win_exists(metric_basename):
update = None
else:
update = 'append'
vis.line(
metrics[metric].values,
metrics.index.values,
win=metric_basename,
name=metric,
opts={
'title': metric_basename,
'showlegend': True
},
update=update
)
if metric_basename != metric and len(metric_list) > 1:
if vis.win_exists(metric):
update = update
else:
update = None
vis.line(
metrics[metric].values,
metrics.index.values,
win=metric,
name=metric,
opts={
'title': metric,
'showlegend': True
},
update=update
) | python | def visdom_send_metrics(vis, metrics, update='replace'):
""" Send set of metrics to visdom """
visited = {}
sorted_metrics = sorted(metrics.columns, key=_column_original_name)
for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name):
metric_list = list(metric_list)
for metric in metric_list:
if vis.win_exists(metric_basename) and (not visited.get(metric, False)):
update = update
elif not vis.win_exists(metric_basename):
update = None
else:
update = 'append'
vis.line(
metrics[metric].values,
metrics.index.values,
win=metric_basename,
name=metric,
opts={
'title': metric_basename,
'showlegend': True
},
update=update
)
if metric_basename != metric and len(metric_list) > 1:
if vis.win_exists(metric):
update = update
else:
update = None
vis.line(
metrics[metric].values,
metrics.index.values,
win=metric,
name=metric,
opts={
'title': metric,
'showlegend': True
},
update=update
) | [
"def",
"visdom_send_metrics",
"(",
"vis",
",",
"metrics",
",",
"update",
"=",
"'replace'",
")",
":",
"visited",
"=",
"{",
"}",
"sorted_metrics",
"=",
"sorted",
"(",
"metrics",
".",
"columns",
",",
"key",
"=",
"_column_original_name",
")",
"for",
"metric_basename",
",",
"metric_list",
"in",
"it",
".",
"groupby",
"(",
"sorted_metrics",
",",
"key",
"=",
"_column_original_name",
")",
":",
"metric_list",
"=",
"list",
"(",
"metric_list",
")",
"for",
"metric",
"in",
"metric_list",
":",
"if",
"vis",
".",
"win_exists",
"(",
"metric_basename",
")",
"and",
"(",
"not",
"visited",
".",
"get",
"(",
"metric",
",",
"False",
")",
")",
":",
"update",
"=",
"update",
"elif",
"not",
"vis",
".",
"win_exists",
"(",
"metric_basename",
")",
":",
"update",
"=",
"None",
"else",
":",
"update",
"=",
"'append'",
"vis",
".",
"line",
"(",
"metrics",
"[",
"metric",
"]",
".",
"values",
",",
"metrics",
".",
"index",
".",
"values",
",",
"win",
"=",
"metric_basename",
",",
"name",
"=",
"metric",
",",
"opts",
"=",
"{",
"'title'",
":",
"metric_basename",
",",
"'showlegend'",
":",
"True",
"}",
",",
"update",
"=",
"update",
")",
"if",
"metric_basename",
"!=",
"metric",
"and",
"len",
"(",
"metric_list",
")",
">",
"1",
":",
"if",
"vis",
".",
"win_exists",
"(",
"metric",
")",
":",
"update",
"=",
"update",
"else",
":",
"update",
"=",
"None",
"vis",
".",
"line",
"(",
"metrics",
"[",
"metric",
"]",
".",
"values",
",",
"metrics",
".",
"index",
".",
"values",
",",
"win",
"=",
"metric",
",",
"name",
"=",
"metric",
",",
"opts",
"=",
"{",
"'title'",
":",
"metric",
",",
"'showlegend'",
":",
"True",
"}",
",",
"update",
"=",
"update",
")"
] | Send set of metrics to visdom | [
"Send",
"set",
"of",
"metrics",
"to",
"visdom"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/visdom.py#L27-L71 | train | 232,383 |
MillionIntegrals/vel | vel/api/train_phase.py | TrainPhase.restore | def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict):
"""
Restore learning from intermediate state.
"""
pass | python | def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict):
"""
Restore learning from intermediate state.
"""
pass | [
"def",
"restore",
"(",
"self",
",",
"training_info",
":",
"TrainingInfo",
",",
"local_batch_idx",
":",
"int",
",",
"model",
":",
"Model",
",",
"hidden_state",
":",
"dict",
")",
":",
"pass"
] | Restore learning from intermediate state. | [
"Restore",
"learning",
"from",
"intermediate",
"state",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/train_phase.py#L18-L22 | train | 232,384 |
MillionIntegrals/vel | vel/rl/buffers/backend/prioritized_vec_buffer_backend.py | PrioritizedCircularVecEnvBufferBackend.update_priority | def update_priority(self, tree_idx_list, priority_list):
""" Update priorities of the elements in the tree """
for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees):
segment_tree.update(tree_idx, priority) | python | def update_priority(self, tree_idx_list, priority_list):
""" Update priorities of the elements in the tree """
for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees):
segment_tree.update(tree_idx, priority) | [
"def",
"update_priority",
"(",
"self",
",",
"tree_idx_list",
",",
"priority_list",
")",
":",
"for",
"tree_idx",
",",
"priority",
",",
"segment_tree",
"in",
"zip",
"(",
"tree_idx_list",
",",
"priority_list",
",",
"self",
".",
"segment_trees",
")",
":",
"segment_tree",
".",
"update",
"(",
"tree_idx",
",",
"priority",
")"
] | Update priorities of the elements in the tree | [
"Update",
"priorities",
"of",
"the",
"elements",
"in",
"the",
"tree"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/prioritized_vec_buffer_backend.py#L72-L75 | train | 232,385 |
MillionIntegrals/vel | vel/rl/buffers/backend/prioritized_vec_buffer_backend.py | PrioritizedCircularVecEnvBufferBackend._sample_batch_prioritized | def _sample_batch_prioritized(self, segment_tree, batch_size, history, forward_steps=1):
""" Return indexes of the next sample in from prioritized distribution """
p_total = segment_tree.total()
segment = p_total / batch_size
# Get batch of valid samples
batch = [
self._get_sample_from_segment(segment_tree, segment, i, history, forward_steps)
for i in range(batch_size)
]
probs, idxs, tree_idxs = zip(*batch)
return np.array(probs), np.array(idxs), np.array(tree_idxs) | python | def _sample_batch_prioritized(self, segment_tree, batch_size, history, forward_steps=1):
""" Return indexes of the next sample in from prioritized distribution """
p_total = segment_tree.total()
segment = p_total / batch_size
# Get batch of valid samples
batch = [
self._get_sample_from_segment(segment_tree, segment, i, history, forward_steps)
for i in range(batch_size)
]
probs, idxs, tree_idxs = zip(*batch)
return np.array(probs), np.array(idxs), np.array(tree_idxs) | [
"def",
"_sample_batch_prioritized",
"(",
"self",
",",
"segment_tree",
",",
"batch_size",
",",
"history",
",",
"forward_steps",
"=",
"1",
")",
":",
"p_total",
"=",
"segment_tree",
".",
"total",
"(",
")",
"segment",
"=",
"p_total",
"/",
"batch_size",
"# Get batch of valid samples",
"batch",
"=",
"[",
"self",
".",
"_get_sample_from_segment",
"(",
"segment_tree",
",",
"segment",
",",
"i",
",",
"history",
",",
"forward_steps",
")",
"for",
"i",
"in",
"range",
"(",
"batch_size",
")",
"]",
"probs",
",",
"idxs",
",",
"tree_idxs",
"=",
"zip",
"(",
"*",
"batch",
")",
"return",
"np",
".",
"array",
"(",
"probs",
")",
",",
"np",
".",
"array",
"(",
"idxs",
")",
",",
"np",
".",
"array",
"(",
"tree_idxs",
")"
] | Return indexes of the next sample in from prioritized distribution | [
"Return",
"indexes",
"of",
"the",
"next",
"sample",
"in",
"from",
"prioritized",
"distribution"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/prioritized_vec_buffer_backend.py#L87-L99 | train | 232,386 |
MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | take_along_axis | def take_along_axis(large_array, indexes):
""" Take along axis """
# Reshape indexes into the right shape
if len(large_array.shape) > len(indexes.shape):
indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.shape) - len(indexes.shape))))
return np.take_along_axis(large_array, indexes, axis=0) | python | def take_along_axis(large_array, indexes):
""" Take along axis """
# Reshape indexes into the right shape
if len(large_array.shape) > len(indexes.shape):
indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.shape) - len(indexes.shape))))
return np.take_along_axis(large_array, indexes, axis=0) | [
"def",
"take_along_axis",
"(",
"large_array",
",",
"indexes",
")",
":",
"# Reshape indexes into the right shape",
"if",
"len",
"(",
"large_array",
".",
"shape",
")",
">",
"len",
"(",
"indexes",
".",
"shape",
")",
":",
"indexes",
"=",
"indexes",
".",
"reshape",
"(",
"indexes",
".",
"shape",
"+",
"tuple",
"(",
"[",
"1",
"]",
"*",
"(",
"len",
"(",
"large_array",
".",
"shape",
")",
"-",
"len",
"(",
"indexes",
".",
"shape",
")",
")",
")",
")",
"return",
"np",
".",
"take_along_axis",
"(",
"large_array",
",",
"indexes",
",",
"axis",
"=",
"0",
")"
] | Take along axis | [
"Take",
"along",
"axis"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L7-L13 | train | 232,387 |
MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | CircularVecEnvBufferBackend.get_transition | def get_transition(self, frame_idx, env_idx):
""" Single transition with given index """
past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx)
data_dict = {
'observations': past_frame,
'observations_next': future_frame,
'actions': self.action_buffer[frame_idx, env_idx],
'rewards': self.reward_buffer[frame_idx, env_idx],
'dones': self.dones_buffer[frame_idx, env_idx],
}
for name in self.extra_data:
data_dict[name] = self.extra_data[name][frame_idx, env_idx]
return data_dict | python | def get_transition(self, frame_idx, env_idx):
""" Single transition with given index """
past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx)
data_dict = {
'observations': past_frame,
'observations_next': future_frame,
'actions': self.action_buffer[frame_idx, env_idx],
'rewards': self.reward_buffer[frame_idx, env_idx],
'dones': self.dones_buffer[frame_idx, env_idx],
}
for name in self.extra_data:
data_dict[name] = self.extra_data[name][frame_idx, env_idx]
return data_dict | [
"def",
"get_transition",
"(",
"self",
",",
"frame_idx",
",",
"env_idx",
")",
":",
"past_frame",
",",
"future_frame",
"=",
"self",
".",
"get_frame_with_future",
"(",
"frame_idx",
",",
"env_idx",
")",
"data_dict",
"=",
"{",
"'observations'",
":",
"past_frame",
",",
"'observations_next'",
":",
"future_frame",
",",
"'actions'",
":",
"self",
".",
"action_buffer",
"[",
"frame_idx",
",",
"env_idx",
"]",
",",
"'rewards'",
":",
"self",
".",
"reward_buffer",
"[",
"frame_idx",
",",
"env_idx",
"]",
",",
"'dones'",
":",
"self",
".",
"dones_buffer",
"[",
"frame_idx",
",",
"env_idx",
"]",
",",
"}",
"for",
"name",
"in",
"self",
".",
"extra_data",
":",
"data_dict",
"[",
"name",
"]",
"=",
"self",
".",
"extra_data",
"[",
"name",
"]",
"[",
"frame_idx",
",",
"env_idx",
"]",
"return",
"data_dict"
] | Single transition with given index | [
"Single",
"transition",
"with",
"given",
"index"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L190-L205 | train | 232,388 |
MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | CircularVecEnvBufferBackend.get_transitions_forward_steps | def get_transitions_forward_steps(self, indexes, forward_steps, discount_factor):
"""
Get dictionary of a transition data - where the target of a transition is
n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor,
and the process stops when trajectory is done.
"""
frame_batch_shape = (
[indexes.shape[0], indexes.shape[1]]
+ list(self.state_buffer.shape[2:-1])
+ [self.state_buffer.shape[-1] * self.frame_history]
)
simple_batch_shape = [indexes.shape[0], indexes.shape[1]]
past_frame_buffer = np.zeros(frame_batch_shape, dtype=self.state_buffer.dtype)
future_frame_buffer = np.zeros(frame_batch_shape, dtype=self.state_buffer.dtype)
reward_buffer = np.zeros(simple_batch_shape, dtype=np.float32)
dones_buffer = np.zeros(simple_batch_shape, dtype=bool)
for buffer_idx, frame_row in enumerate(indexes):
for env_idx, frame_idx in enumerate(frame_row):
past_frame, future_frame, reward, done = self.get_frame_with_future_forward_steps(
frame_idx, env_idx, forward_steps=forward_steps, discount_factor=discount_factor
)
past_frame_buffer[buffer_idx, env_idx] = past_frame
future_frame_buffer[buffer_idx, env_idx] = future_frame
reward_buffer[buffer_idx, env_idx] = reward
dones_buffer[buffer_idx, env_idx] = done
actions = take_along_axis(self.action_buffer, indexes)
transition_tensors = {
'observations': past_frame_buffer,
'actions': actions,
'rewards': reward_buffer,
'observations_next': future_frame_buffer,
'dones': dones_buffer.astype(np.float32),
}
for name in self.extra_data:
transition_tensors[name] = take_along_axis(self.extra_data[name], indexes)
return transition_tensors | python | def get_transitions_forward_steps(self, indexes, forward_steps, discount_factor):
"""
Get dictionary of a transition data - where the target of a transition is
n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor,
and the process stops when trajectory is done.
"""
frame_batch_shape = (
[indexes.shape[0], indexes.shape[1]]
+ list(self.state_buffer.shape[2:-1])
+ [self.state_buffer.shape[-1] * self.frame_history]
)
simple_batch_shape = [indexes.shape[0], indexes.shape[1]]
past_frame_buffer = np.zeros(frame_batch_shape, dtype=self.state_buffer.dtype)
future_frame_buffer = np.zeros(frame_batch_shape, dtype=self.state_buffer.dtype)
reward_buffer = np.zeros(simple_batch_shape, dtype=np.float32)
dones_buffer = np.zeros(simple_batch_shape, dtype=bool)
for buffer_idx, frame_row in enumerate(indexes):
for env_idx, frame_idx in enumerate(frame_row):
past_frame, future_frame, reward, done = self.get_frame_with_future_forward_steps(
frame_idx, env_idx, forward_steps=forward_steps, discount_factor=discount_factor
)
past_frame_buffer[buffer_idx, env_idx] = past_frame
future_frame_buffer[buffer_idx, env_idx] = future_frame
reward_buffer[buffer_idx, env_idx] = reward
dones_buffer[buffer_idx, env_idx] = done
actions = take_along_axis(self.action_buffer, indexes)
transition_tensors = {
'observations': past_frame_buffer,
'actions': actions,
'rewards': reward_buffer,
'observations_next': future_frame_buffer,
'dones': dones_buffer.astype(np.float32),
}
for name in self.extra_data:
transition_tensors[name] = take_along_axis(self.extra_data[name], indexes)
return transition_tensors | [
"def",
"get_transitions_forward_steps",
"(",
"self",
",",
"indexes",
",",
"forward_steps",
",",
"discount_factor",
")",
":",
"frame_batch_shape",
"=",
"(",
"[",
"indexes",
".",
"shape",
"[",
"0",
"]",
",",
"indexes",
".",
"shape",
"[",
"1",
"]",
"]",
"+",
"list",
"(",
"self",
".",
"state_buffer",
".",
"shape",
"[",
"2",
":",
"-",
"1",
"]",
")",
"+",
"[",
"self",
".",
"state_buffer",
".",
"shape",
"[",
"-",
"1",
"]",
"*",
"self",
".",
"frame_history",
"]",
")",
"simple_batch_shape",
"=",
"[",
"indexes",
".",
"shape",
"[",
"0",
"]",
",",
"indexes",
".",
"shape",
"[",
"1",
"]",
"]",
"past_frame_buffer",
"=",
"np",
".",
"zeros",
"(",
"frame_batch_shape",
",",
"dtype",
"=",
"self",
".",
"state_buffer",
".",
"dtype",
")",
"future_frame_buffer",
"=",
"np",
".",
"zeros",
"(",
"frame_batch_shape",
",",
"dtype",
"=",
"self",
".",
"state_buffer",
".",
"dtype",
")",
"reward_buffer",
"=",
"np",
".",
"zeros",
"(",
"simple_batch_shape",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"dones_buffer",
"=",
"np",
".",
"zeros",
"(",
"simple_batch_shape",
",",
"dtype",
"=",
"bool",
")",
"for",
"buffer_idx",
",",
"frame_row",
"in",
"enumerate",
"(",
"indexes",
")",
":",
"for",
"env_idx",
",",
"frame_idx",
"in",
"enumerate",
"(",
"frame_row",
")",
":",
"past_frame",
",",
"future_frame",
",",
"reward",
",",
"done",
"=",
"self",
".",
"get_frame_with_future_forward_steps",
"(",
"frame_idx",
",",
"env_idx",
",",
"forward_steps",
"=",
"forward_steps",
",",
"discount_factor",
"=",
"discount_factor",
")",
"past_frame_buffer",
"[",
"buffer_idx",
",",
"env_idx",
"]",
"=",
"past_frame",
"future_frame_buffer",
"[",
"buffer_idx",
",",
"env_idx",
"]",
"=",
"future_frame",
"reward_buffer",
"[",
"buffer_idx",
",",
"env_idx",
"]",
"=",
"reward",
"dones_buffer",
"[",
"buffer_idx",
",",
"env_idx",
"]",
"=",
"done",
"actions",
"=",
"take_along_axis",
"(",
"self",
".",
"action_buffer",
",",
"indexes",
")",
"transition_tensors",
"=",
"{",
"'observations'",
":",
"past_frame_buffer",
",",
"'actions'",
":",
"actions",
",",
"'rewards'",
":",
"reward_buffer",
",",
"'observations_next'",
":",
"future_frame_buffer",
",",
"'dones'",
":",
"dones_buffer",
".",
"astype",
"(",
"np",
".",
"float32",
")",
",",
"}",
"for",
"name",
"in",
"self",
".",
"extra_data",
":",
"transition_tensors",
"[",
"name",
"]",
"=",
"take_along_axis",
"(",
"self",
".",
"extra_data",
"[",
"name",
"]",
",",
"indexes",
")",
"return",
"transition_tensors"
] | Get dictionary of a transition data - where the target of a transition is
n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor,
and the process stops when trajectory is done. | [
"Get",
"dictionary",
"of",
"a",
"transition",
"data",
"-",
"where",
"the",
"target",
"of",
"a",
"transition",
"is",
"n",
"steps",
"forward",
"along",
"the",
"trajectory",
".",
"Rewards",
"are",
"properly",
"aggregated",
"according",
"to",
"the",
"discount",
"factor",
"and",
"the",
"process",
"stops",
"when",
"trajectory",
"is",
"done",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L244-L288 | train | 232,389 |
MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | CircularVecEnvBufferBackend.sample_batch_trajectories | def sample_batch_trajectories(self, rollout_length):
""" Return indexes of next random rollout """
results = []
for i in range(self.num_envs):
results.append(self.sample_rollout_single_env(rollout_length))
return np.stack(results, axis=-1) | python | def sample_batch_trajectories(self, rollout_length):
""" Return indexes of next random rollout """
results = []
for i in range(self.num_envs):
results.append(self.sample_rollout_single_env(rollout_length))
return np.stack(results, axis=-1) | [
"def",
"sample_batch_trajectories",
"(",
"self",
",",
"rollout_length",
")",
":",
"results",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_envs",
")",
":",
"results",
".",
"append",
"(",
"self",
".",
"sample_rollout_single_env",
"(",
"rollout_length",
")",
")",
"return",
"np",
".",
"stack",
"(",
"results",
",",
"axis",
"=",
"-",
"1",
")"
] | Return indexes of next random rollout | [
"Return",
"indexes",
"of",
"next",
"random",
"rollout"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L310-L317 | train | 232,390 |
MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | CircularVecEnvBufferBackend.sample_frame_single_env | def sample_frame_single_env(self, batch_size, forward_steps=1):
""" Return an in index of a random set of frames from a buffer, that have enough history and future """
# Whole idea of this function is to make sure that sample we take is far away from the point which we are
# currently writing to the buffer, which is 'discontinuous'
if self.current_size < self.buffer_capacity:
# Sample from up to total size of the buffer
# -1 because we cannot take the last one
return np.random.choice(self.current_size - forward_steps, batch_size, replace=False)
else:
candidate = np.random.choice(self.buffer_capacity, batch_size, replace=False)
forbidden_ones = (
np.arange(self.current_idx - forward_steps + 1, self.current_idx + self.frame_history)
% self.buffer_capacity
)
# Exclude these frames for learning as they may have some part of history overwritten
while any(x in candidate for x in forbidden_ones):
candidate = np.random.choice(self.buffer_capacity, batch_size, replace=False)
return candidate | python | def sample_frame_single_env(self, batch_size, forward_steps=1):
""" Return an in index of a random set of frames from a buffer, that have enough history and future """
# Whole idea of this function is to make sure that sample we take is far away from the point which we are
# currently writing to the buffer, which is 'discontinuous'
if self.current_size < self.buffer_capacity:
# Sample from up to total size of the buffer
# -1 because we cannot take the last one
return np.random.choice(self.current_size - forward_steps, batch_size, replace=False)
else:
candidate = np.random.choice(self.buffer_capacity, batch_size, replace=False)
forbidden_ones = (
np.arange(self.current_idx - forward_steps + 1, self.current_idx + self.frame_history)
% self.buffer_capacity
)
# Exclude these frames for learning as they may have some part of history overwritten
while any(x in candidate for x in forbidden_ones):
candidate = np.random.choice(self.buffer_capacity, batch_size, replace=False)
return candidate | [
"def",
"sample_frame_single_env",
"(",
"self",
",",
"batch_size",
",",
"forward_steps",
"=",
"1",
")",
":",
"# Whole idea of this function is to make sure that sample we take is far away from the point which we are",
"# currently writing to the buffer, which is 'discontinuous'",
"if",
"self",
".",
"current_size",
"<",
"self",
".",
"buffer_capacity",
":",
"# Sample from up to total size of the buffer",
"# -1 because we cannot take the last one",
"return",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"current_size",
"-",
"forward_steps",
",",
"batch_size",
",",
"replace",
"=",
"False",
")",
"else",
":",
"candidate",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"buffer_capacity",
",",
"batch_size",
",",
"replace",
"=",
"False",
")",
"forbidden_ones",
"=",
"(",
"np",
".",
"arange",
"(",
"self",
".",
"current_idx",
"-",
"forward_steps",
"+",
"1",
",",
"self",
".",
"current_idx",
"+",
"self",
".",
"frame_history",
")",
"%",
"self",
".",
"buffer_capacity",
")",
"# Exclude these frames for learning as they may have some part of history overwritten",
"while",
"any",
"(",
"x",
"in",
"candidate",
"for",
"x",
"in",
"forbidden_ones",
")",
":",
"candidate",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"buffer_capacity",
",",
"batch_size",
",",
"replace",
"=",
"False",
")",
"return",
"candidate"
] | Return an in index of a random set of frames from a buffer, that have enough history and future | [
"Return",
"an",
"in",
"index",
"of",
"a",
"random",
"set",
"of",
"frames",
"from",
"a",
"buffer",
"that",
"have",
"enough",
"history",
"and",
"future"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L346-L367 | train | 232,391 |
MillionIntegrals/vel | vel/rl/commands/record_movie_command.py | RecordMovieCommand.record_take | def record_take(self, model, env_instance, device, take_number):
""" Record a single movie and store it on hard drive """
frames = []
observation = env_instance.reset()
if model.is_recurrent:
hidden_state = model.zero_state(1).to(device)
frames.append(env_instance.render('rgb_array'))
print("Evaluating environment...")
while True:
observation_array = np.expand_dims(np.array(observation), axis=0)
observation_tensor = torch.from_numpy(observation_array).to(device)
if model.is_recurrent:
output = model.step(observation_tensor, hidden_state, **self.sample_args)
hidden_state = output['state']
actions = output['actions']
else:
actions = model.step(observation_tensor, **self.sample_args)['actions']
actions = actions.detach().cpu().numpy()
observation, reward, done, epinfo = env_instance.step(actions[0])
frames.append(env_instance.render('rgb_array'))
if 'episode' in epinfo:
# End of an episode
break
takename = self.model_config.output_dir('videos', self.model_config.run_name, self.videoname.format(take_number))
pathlib.Path(os.path.dirname(takename)).mkdir(parents=True, exist_ok=True)
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
video = cv2.VideoWriter(takename, fourcc, self.fps, (frames[0].shape[1], frames[0].shape[0]))
for i in tqdm.trange(len(frames), file=sys.stdout):
video.write(cv2.cvtColor(frames[i], cv2.COLOR_RGB2BGR))
video.release()
print("Written {}".format(takename)) | python | def record_take(self, model, env_instance, device, take_number):
""" Record a single movie and store it on hard drive """
frames = []
observation = env_instance.reset()
if model.is_recurrent:
hidden_state = model.zero_state(1).to(device)
frames.append(env_instance.render('rgb_array'))
print("Evaluating environment...")
while True:
observation_array = np.expand_dims(np.array(observation), axis=0)
observation_tensor = torch.from_numpy(observation_array).to(device)
if model.is_recurrent:
output = model.step(observation_tensor, hidden_state, **self.sample_args)
hidden_state = output['state']
actions = output['actions']
else:
actions = model.step(observation_tensor, **self.sample_args)['actions']
actions = actions.detach().cpu().numpy()
observation, reward, done, epinfo = env_instance.step(actions[0])
frames.append(env_instance.render('rgb_array'))
if 'episode' in epinfo:
# End of an episode
break
takename = self.model_config.output_dir('videos', self.model_config.run_name, self.videoname.format(take_number))
pathlib.Path(os.path.dirname(takename)).mkdir(parents=True, exist_ok=True)
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
video = cv2.VideoWriter(takename, fourcc, self.fps, (frames[0].shape[1], frames[0].shape[0]))
for i in tqdm.trange(len(frames), file=sys.stdout):
video.write(cv2.cvtColor(frames[i], cv2.COLOR_RGB2BGR))
video.release()
print("Written {}".format(takename)) | [
"def",
"record_take",
"(",
"self",
",",
"model",
",",
"env_instance",
",",
"device",
",",
"take_number",
")",
":",
"frames",
"=",
"[",
"]",
"observation",
"=",
"env_instance",
".",
"reset",
"(",
")",
"if",
"model",
".",
"is_recurrent",
":",
"hidden_state",
"=",
"model",
".",
"zero_state",
"(",
"1",
")",
".",
"to",
"(",
"device",
")",
"frames",
".",
"append",
"(",
"env_instance",
".",
"render",
"(",
"'rgb_array'",
")",
")",
"print",
"(",
"\"Evaluating environment...\"",
")",
"while",
"True",
":",
"observation_array",
"=",
"np",
".",
"expand_dims",
"(",
"np",
".",
"array",
"(",
"observation",
")",
",",
"axis",
"=",
"0",
")",
"observation_tensor",
"=",
"torch",
".",
"from_numpy",
"(",
"observation_array",
")",
".",
"to",
"(",
"device",
")",
"if",
"model",
".",
"is_recurrent",
":",
"output",
"=",
"model",
".",
"step",
"(",
"observation_tensor",
",",
"hidden_state",
",",
"*",
"*",
"self",
".",
"sample_args",
")",
"hidden_state",
"=",
"output",
"[",
"'state'",
"]",
"actions",
"=",
"output",
"[",
"'actions'",
"]",
"else",
":",
"actions",
"=",
"model",
".",
"step",
"(",
"observation_tensor",
",",
"*",
"*",
"self",
".",
"sample_args",
")",
"[",
"'actions'",
"]",
"actions",
"=",
"actions",
".",
"detach",
"(",
")",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
"observation",
",",
"reward",
",",
"done",
",",
"epinfo",
"=",
"env_instance",
".",
"step",
"(",
"actions",
"[",
"0",
"]",
")",
"frames",
".",
"append",
"(",
"env_instance",
".",
"render",
"(",
"'rgb_array'",
")",
")",
"if",
"'episode'",
"in",
"epinfo",
":",
"# End of an episode",
"break",
"takename",
"=",
"self",
".",
"model_config",
".",
"output_dir",
"(",
"'videos'",
",",
"self",
".",
"model_config",
".",
"run_name",
",",
"self",
".",
"videoname",
".",
"format",
"(",
"take_number",
")",
")",
"pathlib",
".",
"Path",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"takename",
")",
")",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"fourcc",
"=",
"cv2",
".",
"VideoWriter_fourcc",
"(",
"'M'",
",",
"'J'",
",",
"'P'",
",",
"'G'",
")",
"video",
"=",
"cv2",
".",
"VideoWriter",
"(",
"takename",
",",
"fourcc",
",",
"self",
".",
"fps",
",",
"(",
"frames",
"[",
"0",
"]",
".",
"shape",
"[",
"1",
"]",
",",
"frames",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
")",
")",
"for",
"i",
"in",
"tqdm",
".",
"trange",
"(",
"len",
"(",
"frames",
")",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"video",
".",
"write",
"(",
"cv2",
".",
"cvtColor",
"(",
"frames",
"[",
"i",
"]",
",",
"cv2",
".",
"COLOR_RGB2BGR",
")",
")",
"video",
".",
"release",
"(",
")",
"print",
"(",
"\"Written {}\"",
".",
"format",
"(",
"takename",
")",
")"
] | Record a single movie and store it on hard drive | [
"Record",
"a",
"single",
"movie",
"and",
"store",
"it",
"on",
"hard",
"drive"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/record_movie_command.py#L47-L91 | train | 232,392 |
MillionIntegrals/vel | vel/rl/modules/noise/ou_noise.py | OuNoise.reset_training_state | def reset_training_state(self, dones, batch_info):
""" A hook for a model to react when during training episode is finished """
for idx, done in enumerate(dones):
if done > 0.5:
self.processes[idx].reset() | python | def reset_training_state(self, dones, batch_info):
""" A hook for a model to react when during training episode is finished """
for idx, done in enumerate(dones):
if done > 0.5:
self.processes[idx].reset() | [
"def",
"reset_training_state",
"(",
"self",
",",
"dones",
",",
"batch_info",
")",
":",
"for",
"idx",
",",
"done",
"in",
"enumerate",
"(",
"dones",
")",
":",
"if",
"done",
">",
"0.5",
":",
"self",
".",
"processes",
"[",
"idx",
"]",
".",
"reset",
"(",
")"
] | A hook for a model to react when during training episode is finished | [
"A",
"hook",
"for",
"a",
"model",
"to",
"react",
"when",
"during",
"training",
"episode",
"is",
"finished"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/noise/ou_noise.py#L22-L26 | train | 232,393 |
MillionIntegrals/vel | vel/rl/modules/noise/ou_noise.py | OuNoise.forward | def forward(self, actions, batch_info):
""" Return model step after applying noise """
while len(self.processes) < actions.shape[0]:
len_action_space = self.action_space.shape[-1]
self.processes.append(
OrnsteinUhlenbeckNoiseProcess(
np.zeros(len_action_space), float(self.std_dev) * np.ones(len_action_space)
)
)
noise = torch.from_numpy(np.stack([x() for x in self.processes])).float().to(actions.device)
return torch.min(torch.max(actions + noise, self.low_tensor), self.high_tensor) | python | def forward(self, actions, batch_info):
""" Return model step after applying noise """
while len(self.processes) < actions.shape[0]:
len_action_space = self.action_space.shape[-1]
self.processes.append(
OrnsteinUhlenbeckNoiseProcess(
np.zeros(len_action_space), float(self.std_dev) * np.ones(len_action_space)
)
)
noise = torch.from_numpy(np.stack([x() for x in self.processes])).float().to(actions.device)
return torch.min(torch.max(actions + noise, self.low_tensor), self.high_tensor) | [
"def",
"forward",
"(",
"self",
",",
"actions",
",",
"batch_info",
")",
":",
"while",
"len",
"(",
"self",
".",
"processes",
")",
"<",
"actions",
".",
"shape",
"[",
"0",
"]",
":",
"len_action_space",
"=",
"self",
".",
"action_space",
".",
"shape",
"[",
"-",
"1",
"]",
"self",
".",
"processes",
".",
"append",
"(",
"OrnsteinUhlenbeckNoiseProcess",
"(",
"np",
".",
"zeros",
"(",
"len_action_space",
")",
",",
"float",
"(",
"self",
".",
"std_dev",
")",
"*",
"np",
".",
"ones",
"(",
"len_action_space",
")",
")",
")",
"noise",
"=",
"torch",
".",
"from_numpy",
"(",
"np",
".",
"stack",
"(",
"[",
"x",
"(",
")",
"for",
"x",
"in",
"self",
".",
"processes",
"]",
")",
")",
".",
"float",
"(",
")",
".",
"to",
"(",
"actions",
".",
"device",
")",
"return",
"torch",
".",
"min",
"(",
"torch",
".",
"max",
"(",
"actions",
"+",
"noise",
",",
"self",
".",
"low_tensor",
")",
",",
"self",
".",
"high_tensor",
")"
] | Return model step after applying noise | [
"Return",
"model",
"step",
"after",
"applying",
"noise"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/noise/ou_noise.py#L28-L41 | train | 232,394 |
MillionIntegrals/vel | vel/util/intepolate.py | interpolate_logscale | def interpolate_logscale(start, end, steps):
""" Interpolate series between start and end in given number of steps - logscale interpolation """
if start <= 0.0:
warnings.warn("Start of logscale interpolation must be positive!")
start = 1e-5
return np.logspace(np.log10(float(start)), np.log10(float(end)), steps) | python | def interpolate_logscale(start, end, steps):
""" Interpolate series between start and end in given number of steps - logscale interpolation """
if start <= 0.0:
warnings.warn("Start of logscale interpolation must be positive!")
start = 1e-5
return np.logspace(np.log10(float(start)), np.log10(float(end)), steps) | [
"def",
"interpolate_logscale",
"(",
"start",
",",
"end",
",",
"steps",
")",
":",
"if",
"start",
"<=",
"0.0",
":",
"warnings",
".",
"warn",
"(",
"\"Start of logscale interpolation must be positive!\"",
")",
"start",
"=",
"1e-5",
"return",
"np",
".",
"logspace",
"(",
"np",
".",
"log10",
"(",
"float",
"(",
"start",
")",
")",
",",
"np",
".",
"log10",
"(",
"float",
"(",
"end",
")",
")",
",",
"steps",
")"
] | Interpolate series between start and end in given number of steps - logscale interpolation | [
"Interpolate",
"series",
"between",
"start",
"and",
"end",
"in",
"given",
"number",
"of",
"steps",
"-",
"logscale",
"interpolation"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L10-L16 | train | 232,395 |
MillionIntegrals/vel | vel/util/intepolate.py | interpolate_series | def interpolate_series(start, end, steps, how='linear'):
""" Interpolate series between start and end in given number of steps """
return INTERP_DICT[how](start, end, steps) | python | def interpolate_series(start, end, steps, how='linear'):
""" Interpolate series between start and end in given number of steps """
return INTERP_DICT[how](start, end, steps) | [
"def",
"interpolate_series",
"(",
"start",
",",
"end",
",",
"steps",
",",
"how",
"=",
"'linear'",
")",
":",
"return",
"INTERP_DICT",
"[",
"how",
"]",
"(",
"start",
",",
"end",
",",
"steps",
")"
] | Interpolate series between start and end in given number of steps | [
"Interpolate",
"series",
"between",
"start",
"and",
"end",
"in",
"given",
"number",
"of",
"steps"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L48-L50 | train | 232,396 |
MillionIntegrals/vel | vel/util/intepolate.py | interpolate_single | def interpolate_single(start, end, coefficient, how='linear'):
""" Interpolate single value between start and end in given number of steps """
return INTERP_SINGLE_DICT[how](start, end, coefficient) | python | def interpolate_single(start, end, coefficient, how='linear'):
""" Interpolate single value between start and end in given number of steps """
return INTERP_SINGLE_DICT[how](start, end, coefficient) | [
"def",
"interpolate_single",
"(",
"start",
",",
"end",
",",
"coefficient",
",",
"how",
"=",
"'linear'",
")",
":",
"return",
"INTERP_SINGLE_DICT",
"[",
"how",
"]",
"(",
"start",
",",
"end",
",",
"coefficient",
")"
] | Interpolate single value between start and end in given number of steps | [
"Interpolate",
"single",
"value",
"between",
"start",
"and",
"end",
"in",
"given",
"number",
"of",
"steps"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L53-L55 | train | 232,397 |
MillionIntegrals/vel | vel/commands/summary_command.py | ModelSummary.run | def run(self, *args):
""" Print model summary """
if self.source is None:
self.model.summary()
else:
x_data, y_data = next(iter(self.source.train_loader()))
self.model.summary(input_size=x_data.shape[1:]) | python | def run(self, *args):
""" Print model summary """
if self.source is None:
self.model.summary()
else:
x_data, y_data = next(iter(self.source.train_loader()))
self.model.summary(input_size=x_data.shape[1:]) | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"source",
"is",
"None",
":",
"self",
".",
"model",
".",
"summary",
"(",
")",
"else",
":",
"x_data",
",",
"y_data",
"=",
"next",
"(",
"iter",
"(",
"self",
".",
"source",
".",
"train_loader",
"(",
")",
")",
")",
"self",
".",
"model",
".",
"summary",
"(",
"input_size",
"=",
"x_data",
".",
"shape",
"[",
"1",
":",
"]",
")"
] | Print model summary | [
"Print",
"model",
"summary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/summary_command.py#L10-L16 | train | 232,398 |
MillionIntegrals/vel | vel/rl/reinforcers/on_policy_iteration_reinforcer.py | OnPolicyIterationReinforcer.initialize_training | def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare models for training """
if model_state is not None:
self.model.load_state_dict(model_state)
else:
self.model.reset_weights()
self.algo.initialize(
training_info=training_info, model=self.model, environment=self.env_roller.environment, device=self.device
) | python | def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare models for training """
if model_state is not None:
self.model.load_state_dict(model_state)
else:
self.model.reset_weights()
self.algo.initialize(
training_info=training_info, model=self.model, environment=self.env_roller.environment, device=self.device
) | [
"def",
"initialize_training",
"(",
"self",
",",
"training_info",
":",
"TrainingInfo",
",",
"model_state",
"=",
"None",
",",
"hidden_state",
"=",
"None",
")",
":",
"if",
"model_state",
"is",
"not",
"None",
":",
"self",
".",
"model",
".",
"load_state_dict",
"(",
"model_state",
")",
"else",
":",
"self",
".",
"model",
".",
"reset_weights",
"(",
")",
"self",
".",
"algo",
".",
"initialize",
"(",
"training_info",
"=",
"training_info",
",",
"model",
"=",
"self",
".",
"model",
",",
"environment",
"=",
"self",
".",
"env_roller",
".",
"environment",
",",
"device",
"=",
"self",
".",
"device",
")"
] | Prepare models for training | [
"Prepare",
"models",
"for",
"training"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/on_policy_iteration_reinforcer.py#L63-L72 | train | 232,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.