id
int32 0
252k
| 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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,900 | faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | GsmTerm._cursorLeft | def _cursorLeft(self):
""" Handles "cursor left" events """
if self.cursorPos > 0:
self.cursorPos -= 1
sys.stdout.write(console.CURSOR_LEFT)
sys.stdout.flush() | python | def _cursorLeft(self):
""" Handles "cursor left" events """
if self.cursorPos > 0:
self.cursorPos -= 1
sys.stdout.write(console.CURSOR_LEFT)
sys.stdout.flush() | [
"def",
"_cursorLeft",
"(",
"self",
")",
":",
"if",
"self",
".",
"cursorPos",
">",
"0",
":",
"self",
".",
"cursorPos",
"-=",
"1",
"sys",
".",
"stdout",
".",
"write",
"(",
"console",
".",
"CURSOR_LEFT",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | Handles "cursor left" events | [
"Handles",
"cursor",
"left",
"events"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L311-L316 |
5,901 | faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | GsmTerm._cursorRight | def _cursorRight(self):
""" Handles "cursor right" events """
if self.cursorPos < len(self.inputBuffer):
self.cursorPos += 1
sys.stdout.write(console.CURSOR_RIGHT)
sys.stdout.flush() | python | def _cursorRight(self):
""" Handles "cursor right" events """
if self.cursorPos < len(self.inputBuffer):
self.cursorPos += 1
sys.stdout.write(console.CURSOR_RIGHT)
sys.stdout.flush() | [
"def",
"_cursorRight",
"(",
"self",
")",
":",
"if",
"self",
".",
"cursorPos",
"<",
"len",
"(",
"self",
".",
"inputBuffer",
")",
":",
"self",
".",
"cursorPos",
"+=",
"1",
"sys",
".",
"stdout",
".",
"write",
"(",
"console",
".",
"CURSOR_RIGHT",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | Handles "cursor right" events | [
"Handles",
"cursor",
"right",
"events"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L318-L323 |
5,902 | faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | GsmTerm._cursorUp | def _cursorUp(self):
""" Handles "cursor up" events """
if self.historyPos > 0:
self.historyPos -= 1
clearLen = len(self.inputBuffer)
self.inputBuffer = list(self.history[self.historyPos])
self.cursorPos = len(self.inputBuffer)
self._refreshInputPrompt(clearLen) | python | def _cursorUp(self):
""" Handles "cursor up" events """
if self.historyPos > 0:
self.historyPos -= 1
clearLen = len(self.inputBuffer)
self.inputBuffer = list(self.history[self.historyPos])
self.cursorPos = len(self.inputBuffer)
self._refreshInputPrompt(clearLen) | [
"def",
"_cursorUp",
"(",
"self",
")",
":",
"if",
"self",
".",
"historyPos",
">",
"0",
":",
"self",
".",
"historyPos",
"-=",
"1",
"clearLen",
"=",
"len",
"(",
"self",
".",
"inputBuffer",
")",
"self",
".",
"inputBuffer",
"=",
"list",
"(",
"self",
".",
"history",
"[",
"self",
".",
"historyPos",
"]",
")",
"self",
".",
"cursorPos",
"=",
"len",
"(",
"self",
".",
"inputBuffer",
")",
"self",
".",
"_refreshInputPrompt",
"(",
"clearLen",
")"
] | Handles "cursor up" events | [
"Handles",
"cursor",
"up",
"events"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L325-L332 |
5,903 | faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | GsmTerm._handleBackspace | def _handleBackspace(self):
""" Handles backspace characters """
if self.cursorPos > 0:
#print( 'cp:',self.cursorPos,'was:', self.inputBuffer)
self.inputBuffer = self.inputBuffer[0:self.cursorPos-1] + self.inputBuffer[self.cursorPos:]
self.cursorPos -= 1
#print ('cp:', self.cursorPos,'is:', self.inputBuffer)
self._refreshInputPrompt(len(self.inputBuffer)+1) | python | def _handleBackspace(self):
""" Handles backspace characters """
if self.cursorPos > 0:
#print( 'cp:',self.cursorPos,'was:', self.inputBuffer)
self.inputBuffer = self.inputBuffer[0:self.cursorPos-1] + self.inputBuffer[self.cursorPos:]
self.cursorPos -= 1
#print ('cp:', self.cursorPos,'is:', self.inputBuffer)
self._refreshInputPrompt(len(self.inputBuffer)+1) | [
"def",
"_handleBackspace",
"(",
"self",
")",
":",
"if",
"self",
".",
"cursorPos",
">",
"0",
":",
"#print( 'cp:',self.cursorPos,'was:', self.inputBuffer)",
"self",
".",
"inputBuffer",
"=",
"self",
".",
"inputBuffer",
"[",
"0",
":",
"self",
".",
"cursorPos",
"-",
"1",
"]",
"+",
"self",
".",
"inputBuffer",
"[",
"self",
".",
"cursorPos",
":",
"]",
"self",
".",
"cursorPos",
"-=",
"1",
"#print ('cp:', self.cursorPos,'is:', self.inputBuffer) ",
"self",
".",
"_refreshInputPrompt",
"(",
"len",
"(",
"self",
".",
"inputBuffer",
")",
"+",
"1",
")"
] | Handles backspace characters | [
"Handles",
"backspace",
"characters"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L343-L350 |
5,904 | faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | GsmTerm._handleDelete | def _handleDelete(self):
""" Handles "delete" characters """
if self.cursorPos < len(self.inputBuffer):
self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[self.cursorPos+1:]
self._refreshInputPrompt(len(self.inputBuffer)+1) | python | def _handleDelete(self):
""" Handles "delete" characters """
if self.cursorPos < len(self.inputBuffer):
self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[self.cursorPos+1:]
self._refreshInputPrompt(len(self.inputBuffer)+1) | [
"def",
"_handleDelete",
"(",
"self",
")",
":",
"if",
"self",
".",
"cursorPos",
"<",
"len",
"(",
"self",
".",
"inputBuffer",
")",
":",
"self",
".",
"inputBuffer",
"=",
"self",
".",
"inputBuffer",
"[",
"0",
":",
"self",
".",
"cursorPos",
"]",
"+",
"self",
".",
"inputBuffer",
"[",
"self",
".",
"cursorPos",
"+",
"1",
":",
"]",
"self",
".",
"_refreshInputPrompt",
"(",
"len",
"(",
"self",
".",
"inputBuffer",
")",
"+",
"1",
")"
] | Handles "delete" characters | [
"Handles",
"delete",
"characters"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L352-L356 |
5,905 | faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | GsmTerm._handleEnd | def _handleEnd(self):
""" Handles "end" character """
self.cursorPos = len(self.inputBuffer)
self._refreshInputPrompt(len(self.inputBuffer)) | python | def _handleEnd(self):
""" Handles "end" character """
self.cursorPos = len(self.inputBuffer)
self._refreshInputPrompt(len(self.inputBuffer)) | [
"def",
"_handleEnd",
"(",
"self",
")",
":",
"self",
".",
"cursorPos",
"=",
"len",
"(",
"self",
".",
"inputBuffer",
")",
"self",
".",
"_refreshInputPrompt",
"(",
"len",
"(",
"self",
".",
"inputBuffer",
")",
")"
] | Handles "end" character | [
"Handles",
"end",
"character"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L363-L366 |
5,906 | faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | GsmTerm._doCommandCompletion | def _doCommandCompletion(self):
""" Command-completion method """
prefix = ''.join(self.inputBuffer).strip().upper()
matches = self.completion.keys(prefix)
matchLen = len(matches)
if matchLen == 0 and prefix[-1] == '=':
try:
command = prefix[:-1]
except KeyError:
pass
else:
self.__printCommandSyntax(command)
elif matchLen > 0:
if matchLen == 1:
if matches[0] == prefix:
# User has already entered command - show command syntax
self.__printCommandSyntax(prefix)
else:
# Complete only possible command
self.inputBuffer = list(matches[0])
self.cursorPos = len(self.inputBuffer)
self._refreshInputPrompt(len(self.inputBuffer))
return
else:
commonPrefix = self.completion.longestCommonPrefix(''.join(self.inputBuffer))
self.inputBuffer = list(commonPrefix)
self.cursorPos = len(self.inputBuffer)
if matchLen > 20:
matches = matches[:20]
matches.append('... ({0} more)'.format(matchLen - 20))
sys.stdout.write('\n')
for match in matches:
sys.stdout.write(' {0} '.format(match))
sys.stdout.write('\n')
sys.stdout.flush()
self._refreshInputPrompt(len(self.inputBuffer)) | python | def _doCommandCompletion(self):
""" Command-completion method """
prefix = ''.join(self.inputBuffer).strip().upper()
matches = self.completion.keys(prefix)
matchLen = len(matches)
if matchLen == 0 and prefix[-1] == '=':
try:
command = prefix[:-1]
except KeyError:
pass
else:
self.__printCommandSyntax(command)
elif matchLen > 0:
if matchLen == 1:
if matches[0] == prefix:
# User has already entered command - show command syntax
self.__printCommandSyntax(prefix)
else:
# Complete only possible command
self.inputBuffer = list(matches[0])
self.cursorPos = len(self.inputBuffer)
self._refreshInputPrompt(len(self.inputBuffer))
return
else:
commonPrefix = self.completion.longestCommonPrefix(''.join(self.inputBuffer))
self.inputBuffer = list(commonPrefix)
self.cursorPos = len(self.inputBuffer)
if matchLen > 20:
matches = matches[:20]
matches.append('... ({0} more)'.format(matchLen - 20))
sys.stdout.write('\n')
for match in matches:
sys.stdout.write(' {0} '.format(match))
sys.stdout.write('\n')
sys.stdout.flush()
self._refreshInputPrompt(len(self.inputBuffer)) | [
"def",
"_doCommandCompletion",
"(",
"self",
")",
":",
"prefix",
"=",
"''",
".",
"join",
"(",
"self",
".",
"inputBuffer",
")",
".",
"strip",
"(",
")",
".",
"upper",
"(",
")",
"matches",
"=",
"self",
".",
"completion",
".",
"keys",
"(",
"prefix",
")",
"matchLen",
"=",
"len",
"(",
"matches",
")",
"if",
"matchLen",
"==",
"0",
"and",
"prefix",
"[",
"-",
"1",
"]",
"==",
"'='",
":",
"try",
":",
"command",
"=",
"prefix",
"[",
":",
"-",
"1",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"self",
".",
"__printCommandSyntax",
"(",
"command",
")",
"elif",
"matchLen",
">",
"0",
":",
"if",
"matchLen",
"==",
"1",
":",
"if",
"matches",
"[",
"0",
"]",
"==",
"prefix",
":",
"# User has already entered command - show command syntax",
"self",
".",
"__printCommandSyntax",
"(",
"prefix",
")",
"else",
":",
"# Complete only possible command",
"self",
".",
"inputBuffer",
"=",
"list",
"(",
"matches",
"[",
"0",
"]",
")",
"self",
".",
"cursorPos",
"=",
"len",
"(",
"self",
".",
"inputBuffer",
")",
"self",
".",
"_refreshInputPrompt",
"(",
"len",
"(",
"self",
".",
"inputBuffer",
")",
")",
"return",
"else",
":",
"commonPrefix",
"=",
"self",
".",
"completion",
".",
"longestCommonPrefix",
"(",
"''",
".",
"join",
"(",
"self",
".",
"inputBuffer",
")",
")",
"self",
".",
"inputBuffer",
"=",
"list",
"(",
"commonPrefix",
")",
"self",
".",
"cursorPos",
"=",
"len",
"(",
"self",
".",
"inputBuffer",
")",
"if",
"matchLen",
">",
"20",
":",
"matches",
"=",
"matches",
"[",
":",
"20",
"]",
"matches",
".",
"append",
"(",
"'... ({0} more)'",
".",
"format",
"(",
"matchLen",
"-",
"20",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"for",
"match",
"in",
"matches",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"' {0} '",
".",
"format",
"(",
"match",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"self",
".",
"_refreshInputPrompt",
"(",
"len",
"(",
"self",
".",
"inputBuffer",
")",
")"
] | Command-completion method | [
"Command",
"-",
"completion",
"method"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L533-L568 |
5,907 | faucamp/python-gsmmodem | gsmmodem/serial_comms.py | SerialComms.connect | def connect(self):
""" Connects to the device and starts the read thread """
self.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout)
# Start read thread
self.alive = True
self.rxThread = threading.Thread(target=self._readLoop)
self.rxThread.daemon = True
self.rxThread.start() | python | def connect(self):
""" Connects to the device and starts the read thread """
self.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout)
# Start read thread
self.alive = True
self.rxThread = threading.Thread(target=self._readLoop)
self.rxThread.daemon = True
self.rxThread.start() | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"serial",
"=",
"serial",
".",
"Serial",
"(",
"port",
"=",
"self",
".",
"port",
",",
"baudrate",
"=",
"self",
".",
"baudrate",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"# Start read thread",
"self",
".",
"alive",
"=",
"True",
"self",
".",
"rxThread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_readLoop",
")",
"self",
".",
"rxThread",
".",
"daemon",
"=",
"True",
"self",
".",
"rxThread",
".",
"start",
"(",
")"
] | Connects to the device and starts the read thread | [
"Connects",
"to",
"the",
"device",
"and",
"starts",
"the",
"read",
"thread"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/serial_comms.py#L45-L52 |
5,908 | faucamp/python-gsmmodem | gsmmodem/serial_comms.py | SerialComms.close | def close(self):
""" Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """
self.alive = False
self.rxThread.join()
self.serial.close() | python | def close(self):
""" Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """
self.alive = False
self.rxThread.join()
self.serial.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"alive",
"=",
"False",
"self",
".",
"rxThread",
".",
"join",
"(",
")",
"self",
".",
"serial",
".",
"close",
"(",
")"
] | Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port | [
"Stops",
"the",
"read",
"thread",
"waits",
"for",
"it",
"to",
"exit",
"cleanly",
"then",
"closes",
"the",
"underlying",
"serial",
"port"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/serial_comms.py#L54-L58 |
5,909 | faucamp/python-gsmmodem | gsmmodem/serial_comms.py | SerialComms._readLoop | def _readLoop(self):
""" Read thread main loop
Reads lines from the connected device
"""
try:
readTermSeq = list(self.RX_EOL_SEQ)
readTermLen = len(readTermSeq)
rxBuffer = []
while self.alive:
data = self.serial.read(1)
if data != '': # check for timeout
#print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data))
rxBuffer.append(data)
if rxBuffer[-readTermLen:] == readTermSeq:
# A line (or other logical segment) has been read
line = ''.join(rxBuffer[:-readTermLen])
rxBuffer = []
if len(line) > 0:
#print 'calling handler'
self._handleLineRead(line)
elif self._expectResponseTermSeq:
if rxBuffer[-len(self._expectResponseTermSeq):] == self._expectResponseTermSeq:
line = ''.join(rxBuffer)
rxBuffer = []
self._handleLineRead(line, checkForResponseTerm=False)
#else:
#' <RX timeout>'
except serial.SerialException as e:
self.alive = False
try:
self.serial.close()
except Exception: #pragma: no cover
pass
# Notify the fatal error handler
self.fatalErrorCallback(e) | python | def _readLoop(self):
""" Read thread main loop
Reads lines from the connected device
"""
try:
readTermSeq = list(self.RX_EOL_SEQ)
readTermLen = len(readTermSeq)
rxBuffer = []
while self.alive:
data = self.serial.read(1)
if data != '': # check for timeout
#print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data))
rxBuffer.append(data)
if rxBuffer[-readTermLen:] == readTermSeq:
# A line (or other logical segment) has been read
line = ''.join(rxBuffer[:-readTermLen])
rxBuffer = []
if len(line) > 0:
#print 'calling handler'
self._handleLineRead(line)
elif self._expectResponseTermSeq:
if rxBuffer[-len(self._expectResponseTermSeq):] == self._expectResponseTermSeq:
line = ''.join(rxBuffer)
rxBuffer = []
self._handleLineRead(line, checkForResponseTerm=False)
#else:
#' <RX timeout>'
except serial.SerialException as e:
self.alive = False
try:
self.serial.close()
except Exception: #pragma: no cover
pass
# Notify the fatal error handler
self.fatalErrorCallback(e) | [
"def",
"_readLoop",
"(",
"self",
")",
":",
"try",
":",
"readTermSeq",
"=",
"list",
"(",
"self",
".",
"RX_EOL_SEQ",
")",
"readTermLen",
"=",
"len",
"(",
"readTermSeq",
")",
"rxBuffer",
"=",
"[",
"]",
"while",
"self",
".",
"alive",
":",
"data",
"=",
"self",
".",
"serial",
".",
"read",
"(",
"1",
")",
"if",
"data",
"!=",
"''",
":",
"# check for timeout",
"#print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data))",
"rxBuffer",
".",
"append",
"(",
"data",
")",
"if",
"rxBuffer",
"[",
"-",
"readTermLen",
":",
"]",
"==",
"readTermSeq",
":",
"# A line (or other logical segment) has been read",
"line",
"=",
"''",
".",
"join",
"(",
"rxBuffer",
"[",
":",
"-",
"readTermLen",
"]",
")",
"rxBuffer",
"=",
"[",
"]",
"if",
"len",
"(",
"line",
")",
">",
"0",
":",
"#print 'calling handler' ",
"self",
".",
"_handleLineRead",
"(",
"line",
")",
"elif",
"self",
".",
"_expectResponseTermSeq",
":",
"if",
"rxBuffer",
"[",
"-",
"len",
"(",
"self",
".",
"_expectResponseTermSeq",
")",
":",
"]",
"==",
"self",
".",
"_expectResponseTermSeq",
":",
"line",
"=",
"''",
".",
"join",
"(",
"rxBuffer",
")",
"rxBuffer",
"=",
"[",
"]",
"self",
".",
"_handleLineRead",
"(",
"line",
",",
"checkForResponseTerm",
"=",
"False",
")",
"#else:",
"#' <RX timeout>'",
"except",
"serial",
".",
"SerialException",
"as",
"e",
":",
"self",
".",
"alive",
"=",
"False",
"try",
":",
"self",
".",
"serial",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"#pragma: no cover",
"pass",
"# Notify the fatal error handler",
"self",
".",
"fatalErrorCallback",
"(",
"e",
")"
] | Read thread main loop
Reads lines from the connected device | [
"Read",
"thread",
"main",
"loop",
"Reads",
"lines",
"from",
"the",
"connected",
"device"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/serial_comms.py#L83-L118 |
5,910 | faucamp/python-gsmmodem | gsmmodem/pdu.py | _decodeTimestamp | def _decodeTimestamp(byteIter):
""" Decodes a 7-octet timestamp """
dateStr = decodeSemiOctets(byteIter, 7)
timeZoneStr = dateStr[-2:]
return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr)) | python | def _decodeTimestamp(byteIter):
""" Decodes a 7-octet timestamp """
dateStr = decodeSemiOctets(byteIter, 7)
timeZoneStr = dateStr[-2:]
return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr)) | [
"def",
"_decodeTimestamp",
"(",
"byteIter",
")",
":",
"dateStr",
"=",
"decodeSemiOctets",
"(",
"byteIter",
",",
"7",
")",
"timeZoneStr",
"=",
"dateStr",
"[",
"-",
"2",
":",
"]",
"return",
"datetime",
".",
"strptime",
"(",
"dateStr",
"[",
":",
"-",
"2",
"]",
",",
"'%y%m%d%H%M%S'",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"SmsPduTzInfo",
"(",
"timeZoneStr",
")",
")"
] | Decodes a 7-octet timestamp | [
"Decodes",
"a",
"7",
"-",
"octet",
"timestamp"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L494-L498 |
5,911 | faucamp/python-gsmmodem | gsmmodem/pdu.py | decodeUcs2 | def decodeUcs2(byteIter, numBytes):
""" Decodes UCS2-encoded text from the specified byte iterator, up to a maximum of numBytes """
userData = []
i = 0
try:
while i < numBytes:
userData.append(unichr((next(byteIter) << 8) | next(byteIter)))
i += 2
except StopIteration:
# Not enough bytes in iterator to reach numBytes; return what we have
pass
return ''.join(userData) | python | def decodeUcs2(byteIter, numBytes):
""" Decodes UCS2-encoded text from the specified byte iterator, up to a maximum of numBytes """
userData = []
i = 0
try:
while i < numBytes:
userData.append(unichr((next(byteIter) << 8) | next(byteIter)))
i += 2
except StopIteration:
# Not enough bytes in iterator to reach numBytes; return what we have
pass
return ''.join(userData) | [
"def",
"decodeUcs2",
"(",
"byteIter",
",",
"numBytes",
")",
":",
"userData",
"=",
"[",
"]",
"i",
"=",
"0",
"try",
":",
"while",
"i",
"<",
"numBytes",
":",
"userData",
".",
"append",
"(",
"unichr",
"(",
"(",
"next",
"(",
"byteIter",
")",
"<<",
"8",
")",
"|",
"next",
"(",
"byteIter",
")",
")",
")",
"i",
"+=",
"2",
"except",
"StopIteration",
":",
"# Not enough bytes in iterator to reach numBytes; return what we have",
"pass",
"return",
"''",
".",
"join",
"(",
"userData",
")"
] | Decodes UCS2-encoded text from the specified byte iterator, up to a maximum of numBytes | [
"Decodes",
"UCS2",
"-",
"encoded",
"text",
"from",
"the",
"specified",
"byte",
"iterator",
"up",
"to",
"a",
"maximum",
"of",
"numBytes"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L795-L806 |
5,912 | faucamp/python-gsmmodem | gsmmodem/pdu.py | InformationElement.encode | def encode(self):
""" Encodes this IE and returns the resulting bytes """
result = bytearray()
result.append(self.id)
result.append(self.dataLength)
result.extend(self.data)
return result | python | def encode(self):
""" Encodes this IE and returns the resulting bytes """
result = bytearray()
result.append(self.id)
result.append(self.dataLength)
result.extend(self.data)
return result | [
"def",
"encode",
"(",
"self",
")",
":",
"result",
"=",
"bytearray",
"(",
")",
"result",
".",
"append",
"(",
"self",
".",
"id",
")",
"result",
".",
"append",
"(",
"self",
".",
"dataLength",
")",
"result",
".",
"extend",
"(",
"self",
".",
"data",
")",
"return",
"result"
] | Encodes this IE and returns the resulting bytes | [
"Encodes",
"this",
"IE",
"and",
"returns",
"the",
"resulting",
"bytes"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L123-L129 |
5,913 | faucamp/python-gsmmodem | tools/sendsms.py | parseArgsPy26 | def parseArgsPy26():
""" Argument parser for Python 2.6 """
from gsmtermlib.posoptparse import PosOptionParser, Option
parser = PosOptionParser(description='Simple script for sending SMS messages')
parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.')
parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate')
parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN')
parser.add_option('-d', '--deliver', action='store_true', help='wait for SMS delivery report')
parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number'))
options, args = parser.parse_args()
if len(args) != 1:
parser.error('Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'.format(sys.argv[0]))
else:
options.destination = args[0]
return options | python | def parseArgsPy26():
""" Argument parser for Python 2.6 """
from gsmtermlib.posoptparse import PosOptionParser, Option
parser = PosOptionParser(description='Simple script for sending SMS messages')
parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.')
parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate')
parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN')
parser.add_option('-d', '--deliver', action='store_true', help='wait for SMS delivery report')
parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number'))
options, args = parser.parse_args()
if len(args) != 1:
parser.error('Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'.format(sys.argv[0]))
else:
options.destination = args[0]
return options | [
"def",
"parseArgsPy26",
"(",
")",
":",
"from",
"gsmtermlib",
".",
"posoptparse",
"import",
"PosOptionParser",
",",
"Option",
"parser",
"=",
"PosOptionParser",
"(",
"description",
"=",
"'Simple script for sending SMS messages'",
")",
"parser",
".",
"add_option",
"(",
"'-i'",
",",
"'--port'",
",",
"metavar",
"=",
"'PORT'",
",",
"help",
"=",
"'port to which the GSM modem is connected; a number or a device name.'",
")",
"parser",
".",
"add_option",
"(",
"'-b'",
",",
"'--baud'",
",",
"metavar",
"=",
"'BAUDRATE'",
",",
"default",
"=",
"115200",
",",
"help",
"=",
"'set baud rate'",
")",
"parser",
".",
"add_option",
"(",
"'-p'",
",",
"'--pin'",
",",
"metavar",
"=",
"'PIN'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'SIM card PIN'",
")",
"parser",
".",
"add_option",
"(",
"'-d'",
",",
"'--deliver'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'wait for SMS delivery report'",
")",
"parser",
".",
"add_positional_argument",
"(",
"Option",
"(",
"'--destination'",
",",
"metavar",
"=",
"'DESTINATION'",
",",
"help",
"=",
"'destination mobile number'",
")",
")",
"options",
",",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"parser",
".",
"error",
"(",
"'Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'",
".",
"format",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"else",
":",
"options",
".",
"destination",
"=",
"args",
"[",
"0",
"]",
"return",
"options"
] | Argument parser for Python 2.6 | [
"Argument",
"parser",
"for",
"Python",
"2",
".",
"6"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/sendsms.py#L26-L40 |
5,914 | faucamp/python-gsmmodem | gsmmodem/util.py | lineMatching | def lineMatching(regexStr, lines):
""" Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified regex string, or None if no match was found
Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() instead
:type regexStr: Regular expression string to use
:type lines: List of lines to search
:return: the regular expression match for the first line that matches the specified regex, or None if no match was found
:rtype: re.Match
"""
regex = re.compile(regexStr)
for line in lines:
m = regex.match(line)
if m:
return m
else:
return None | python | def lineMatching(regexStr, lines):
""" Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified regex string, or None if no match was found
Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() instead
:type regexStr: Regular expression string to use
:type lines: List of lines to search
:return: the regular expression match for the first line that matches the specified regex, or None if no match was found
:rtype: re.Match
"""
regex = re.compile(regexStr)
for line in lines:
m = regex.match(line)
if m:
return m
else:
return None | [
"def",
"lineMatching",
"(",
"regexStr",
",",
"lines",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"regexStr",
")",
"for",
"line",
"in",
"lines",
":",
"m",
"=",
"regex",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"return",
"m",
"else",
":",
"return",
"None"
] | Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified regex string, or None if no match was found
Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() instead
:type regexStr: Regular expression string to use
:type lines: List of lines to search
:return: the regular expression match for the first line that matches the specified regex, or None if no match was found
:rtype: re.Match | [
"Searches",
"through",
"the",
"specified",
"list",
"of",
"strings",
"and",
"returns",
"the",
"regular",
"expression",
"match",
"for",
"the",
"first",
"line",
"that",
"matches",
"the",
"specified",
"regex",
"string",
"or",
"None",
"if",
"no",
"match",
"was",
"found"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/util.py#L57-L75 |
5,915 | faucamp/python-gsmmodem | gsmmodem/util.py | lineMatchingPattern | def lineMatchingPattern(pattern, lines):
""" Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found
Note: if you are using a regex pattern string (i.e. not already compiled), use lineMatching() instead
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: the regular expression match for the first line that matches the specified regex, or None if no match was found
:rtype: re.Match
"""
for line in lines:
m = pattern.match(line)
if m:
return m
else:
return None | python | def lineMatchingPattern(pattern, lines):
""" Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found
Note: if you are using a regex pattern string (i.e. not already compiled), use lineMatching() instead
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: the regular expression match for the first line that matches the specified regex, or None if no match was found
:rtype: re.Match
"""
for line in lines:
m = pattern.match(line)
if m:
return m
else:
return None | [
"def",
"lineMatchingPattern",
"(",
"pattern",
",",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"m",
"=",
"pattern",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"return",
"m",
"else",
":",
"return",
"None"
] | Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found
Note: if you are using a regex pattern string (i.e. not already compiled), use lineMatching() instead
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: the regular expression match for the first line that matches the specified regex, or None if no match was found
:rtype: re.Match | [
"Searches",
"through",
"the",
"specified",
"list",
"of",
"strings",
"and",
"returns",
"the",
"regular",
"expression",
"match",
"for",
"the",
"first",
"line",
"that",
"matches",
"the",
"specified",
"pre",
"-",
"compiled",
"regex",
"pattern",
"or",
"None",
"if",
"no",
"match",
"was",
"found"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/util.py#L77-L94 |
5,916 | faucamp/python-gsmmodem | gsmmodem/util.py | allLinesMatchingPattern | def allLinesMatchingPattern(pattern, lines):
""" Like lineMatchingPattern, but returns all lines that match the specified pattern
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: list of re.Match objects for each line matched, or an empty list if none matched
:rtype: list
"""
result = []
for line in lines:
m = pattern.match(line)
if m:
result.append(m)
return result | python | def allLinesMatchingPattern(pattern, lines):
""" Like lineMatchingPattern, but returns all lines that match the specified pattern
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: list of re.Match objects for each line matched, or an empty list if none matched
:rtype: list
"""
result = []
for line in lines:
m = pattern.match(line)
if m:
result.append(m)
return result | [
"def",
"allLinesMatchingPattern",
"(",
"pattern",
",",
"lines",
")",
":",
"result",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"m",
"=",
"pattern",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"result",
".",
"append",
"(",
"m",
")",
"return",
"result"
] | Like lineMatchingPattern, but returns all lines that match the specified pattern
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: list of re.Match objects for each line matched, or an empty list if none matched
:rtype: list | [
"Like",
"lineMatchingPattern",
"but",
"returns",
"all",
"lines",
"that",
"match",
"the",
"specified",
"pattern"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/util.py#L96-L110 |
5,917 | n8henrie/pycookiecheat | src/pycookiecheat/pycookiecheat.py | clean | def clean(decrypted: bytes) -> str:
r"""Strip padding from decrypted value.
Remove number indicated by padding
e.g. if last is '\x0e' then ord('\x0e') == 14, so take off 14.
Args:
decrypted: decrypted value
Returns:
Decrypted stripped of junk padding
"""
last = decrypted[-1]
if isinstance(last, int):
return decrypted[:-last].decode('utf8')
return decrypted[:-ord(last)].decode('utf8') | python | def clean(decrypted: bytes) -> str:
r"""Strip padding from decrypted value.
Remove number indicated by padding
e.g. if last is '\x0e' then ord('\x0e') == 14, so take off 14.
Args:
decrypted: decrypted value
Returns:
Decrypted stripped of junk padding
"""
last = decrypted[-1]
if isinstance(last, int):
return decrypted[:-last].decode('utf8')
return decrypted[:-ord(last)].decode('utf8') | [
"def",
"clean",
"(",
"decrypted",
":",
"bytes",
")",
"->",
"str",
":",
"last",
"=",
"decrypted",
"[",
"-",
"1",
"]",
"if",
"isinstance",
"(",
"last",
",",
"int",
")",
":",
"return",
"decrypted",
"[",
":",
"-",
"last",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"return",
"decrypted",
"[",
":",
"-",
"ord",
"(",
"last",
")",
"]",
".",
"decode",
"(",
"'utf8'",
")"
] | r"""Strip padding from decrypted value.
Remove number indicated by padding
e.g. if last is '\x0e' then ord('\x0e') == 14, so take off 14.
Args:
decrypted: decrypted value
Returns:
Decrypted stripped of junk padding | [
"r",
"Strip",
"padding",
"from",
"decrypted",
"value",
"."
] | 1e0ba783da31689f5b37f9706205ff366d72f03d | https://github.com/n8henrie/pycookiecheat/blob/1e0ba783da31689f5b37f9706205ff366d72f03d/src/pycookiecheat/pycookiecheat.py#L26-L41 |
5,918 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.set_pattern_step_setpoint | def set_pattern_step_setpoint(self, patternnumber, stepnumber, setpointvalue):
"""Set the setpoint value for a step.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
* setpointvalue (float): Setpoint value
"""
_checkPatternNumber(patternnumber)
_checkStepNumber(stepnumber)
_checkSetpointValue(setpointvalue, self.setpoint_max)
address = _calculateRegisterAddress('setpoint', patternnumber, stepnumber)
self.write_register(address, setpointvalue, 1) | python | def set_pattern_step_setpoint(self, patternnumber, stepnumber, setpointvalue):
"""Set the setpoint value for a step.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
* setpointvalue (float): Setpoint value
"""
_checkPatternNumber(patternnumber)
_checkStepNumber(stepnumber)
_checkSetpointValue(setpointvalue, self.setpoint_max)
address = _calculateRegisterAddress('setpoint', patternnumber, stepnumber)
self.write_register(address, setpointvalue, 1) | [
"def",
"set_pattern_step_setpoint",
"(",
"self",
",",
"patternnumber",
",",
"stepnumber",
",",
"setpointvalue",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"_checkStepNumber",
"(",
"stepnumber",
")",
"_checkSetpointValue",
"(",
"setpointvalue",
",",
"self",
".",
"setpoint_max",
")",
"address",
"=",
"_calculateRegisterAddress",
"(",
"'setpoint'",
",",
"patternnumber",
",",
"stepnumber",
")",
"self",
".",
"write_register",
"(",
"address",
",",
"setpointvalue",
",",
"1",
")"
] | Set the setpoint value for a step.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
* setpointvalue (float): Setpoint value | [
"Set",
"the",
"setpoint",
"value",
"for",
"a",
"step",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L237-L250 |
5,919 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.get_pattern_step_time | def get_pattern_step_time(self, patternnumber, stepnumber):
"""Get the step time.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
Returns:
The step time (int??).
"""
_checkPatternNumber(patternnumber)
_checkStepNumber(stepnumber)
address = _calculateRegisterAddress('time', patternnumber, stepnumber)
return self.read_register(address, 0) | python | def get_pattern_step_time(self, patternnumber, stepnumber):
"""Get the step time.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
Returns:
The step time (int??).
"""
_checkPatternNumber(patternnumber)
_checkStepNumber(stepnumber)
address = _calculateRegisterAddress('time', patternnumber, stepnumber)
return self.read_register(address, 0) | [
"def",
"get_pattern_step_time",
"(",
"self",
",",
"patternnumber",
",",
"stepnumber",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"_checkStepNumber",
"(",
"stepnumber",
")",
"address",
"=",
"_calculateRegisterAddress",
"(",
"'time'",
",",
"patternnumber",
",",
"stepnumber",
")",
"return",
"self",
".",
"read_register",
"(",
"address",
",",
"0",
")"
] | Get the step time.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
Returns:
The step time (int??). | [
"Get",
"the",
"step",
"time",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L253-L268 |
5,920 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.set_pattern_step_time | def set_pattern_step_time(self, patternnumber, stepnumber, timevalue):
"""Set the step time.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
* timevalue (integer??): 0-900
"""
_checkPatternNumber(patternnumber)
_checkStepNumber(stepnumber)
_checkTimeValue(timevalue, self.time_max)
address = _calculateRegisterAddress('time', patternnumber, stepnumber)
self.write_register(address, timevalue, 0) | python | def set_pattern_step_time(self, patternnumber, stepnumber, timevalue):
"""Set the step time.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
* timevalue (integer??): 0-900
"""
_checkPatternNumber(patternnumber)
_checkStepNumber(stepnumber)
_checkTimeValue(timevalue, self.time_max)
address = _calculateRegisterAddress('time', patternnumber, stepnumber)
self.write_register(address, timevalue, 0) | [
"def",
"set_pattern_step_time",
"(",
"self",
",",
"patternnumber",
",",
"stepnumber",
",",
"timevalue",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"_checkStepNumber",
"(",
"stepnumber",
")",
"_checkTimeValue",
"(",
"timevalue",
",",
"self",
".",
"time_max",
")",
"address",
"=",
"_calculateRegisterAddress",
"(",
"'time'",
",",
"patternnumber",
",",
"stepnumber",
")",
"self",
".",
"write_register",
"(",
"address",
",",
"timevalue",
",",
"0",
")"
] | Set the step time.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
* timevalue (integer??): 0-900 | [
"Set",
"the",
"step",
"time",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L271-L284 |
5,921 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.get_pattern_actual_step | def get_pattern_actual_step(self, patternnumber):
"""Get the 'actual step' parameter for a given pattern.
Args:
patternnumber (integer): 0-7
Returns:
The 'actual step' parameter (int).
"""
_checkPatternNumber(patternnumber)
address = _calculateRegisterAddress('actualstep', patternnumber)
return self.read_register(address, 0) | python | def get_pattern_actual_step(self, patternnumber):
"""Get the 'actual step' parameter for a given pattern.
Args:
patternnumber (integer): 0-7
Returns:
The 'actual step' parameter (int).
"""
_checkPatternNumber(patternnumber)
address = _calculateRegisterAddress('actualstep', patternnumber)
return self.read_register(address, 0) | [
"def",
"get_pattern_actual_step",
"(",
"self",
",",
"patternnumber",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"address",
"=",
"_calculateRegisterAddress",
"(",
"'actualstep'",
",",
"patternnumber",
")",
"return",
"self",
".",
"read_register",
"(",
"address",
",",
"0",
")"
] | Get the 'actual step' parameter for a given pattern.
Args:
patternnumber (integer): 0-7
Returns:
The 'actual step' parameter (int). | [
"Get",
"the",
"actual",
"step",
"parameter",
"for",
"a",
"given",
"pattern",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L287-L300 |
5,922 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.set_pattern_actual_step | def set_pattern_actual_step(self, patternnumber, value):
"""Set the 'actual step' parameter for a given pattern.
Args:
* patternnumber (integer): 0-7
* value (integer): 0-7
"""
_checkPatternNumber(patternnumber)
_checkStepNumber(value)
address = _calculateRegisterAddress('actualstep', patternnumber)
self.write_register(address, value, 0) | python | def set_pattern_actual_step(self, patternnumber, value):
"""Set the 'actual step' parameter for a given pattern.
Args:
* patternnumber (integer): 0-7
* value (integer): 0-7
"""
_checkPatternNumber(patternnumber)
_checkStepNumber(value)
address = _calculateRegisterAddress('actualstep', patternnumber)
self.write_register(address, value, 0) | [
"def",
"set_pattern_actual_step",
"(",
"self",
",",
"patternnumber",
",",
"value",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"_checkStepNumber",
"(",
"value",
")",
"address",
"=",
"_calculateRegisterAddress",
"(",
"'actualstep'",
",",
"patternnumber",
")",
"self",
".",
"write_register",
"(",
"address",
",",
"value",
",",
"0",
")"
] | Set the 'actual step' parameter for a given pattern.
Args:
* patternnumber (integer): 0-7
* value (integer): 0-7 | [
"Set",
"the",
"actual",
"step",
"parameter",
"for",
"a",
"given",
"pattern",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L303-L314 |
5,923 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.get_pattern_additional_cycles | def get_pattern_additional_cycles(self, patternnumber):
"""Get the number of additional cycles for a given pattern.
Args:
patternnumber (integer): 0-7
Returns:
The number of additional cycles (int).
"""
_checkPatternNumber(patternnumber)
address = _calculateRegisterAddress('cycles', patternnumber)
return self.read_register(address) | python | def get_pattern_additional_cycles(self, patternnumber):
"""Get the number of additional cycles for a given pattern.
Args:
patternnumber (integer): 0-7
Returns:
The number of additional cycles (int).
"""
_checkPatternNumber(patternnumber)
address = _calculateRegisterAddress('cycles', patternnumber)
return self.read_register(address) | [
"def",
"get_pattern_additional_cycles",
"(",
"self",
",",
"patternnumber",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"address",
"=",
"_calculateRegisterAddress",
"(",
"'cycles'",
",",
"patternnumber",
")",
"return",
"self",
".",
"read_register",
"(",
"address",
")"
] | Get the number of additional cycles for a given pattern.
Args:
patternnumber (integer): 0-7
Returns:
The number of additional cycles (int). | [
"Get",
"the",
"number",
"of",
"additional",
"cycles",
"for",
"a",
"given",
"pattern",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L317-L330 |
5,924 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.set_pattern_additional_cycles | def set_pattern_additional_cycles(self, patternnumber, value):
"""Set the number of additional cycles for a given pattern.
Args:
* patternnumber (integer): 0-7
* value (integer): 0-99
"""
_checkPatternNumber(patternnumber)
minimalmodbus._checkInt(value, minvalue=0, maxvalue=99, description='number of additional cycles')
address = _calculateRegisterAddress('cycles', patternnumber)
self.write_register(address, value, 0) | python | def set_pattern_additional_cycles(self, patternnumber, value):
"""Set the number of additional cycles for a given pattern.
Args:
* patternnumber (integer): 0-7
* value (integer): 0-99
"""
_checkPatternNumber(patternnumber)
minimalmodbus._checkInt(value, minvalue=0, maxvalue=99, description='number of additional cycles')
address = _calculateRegisterAddress('cycles', patternnumber)
self.write_register(address, value, 0) | [
"def",
"set_pattern_additional_cycles",
"(",
"self",
",",
"patternnumber",
",",
"value",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"minimalmodbus",
".",
"_checkInt",
"(",
"value",
",",
"minvalue",
"=",
"0",
",",
"maxvalue",
"=",
"99",
",",
"description",
"=",
"'number of additional cycles'",
")",
"address",
"=",
"_calculateRegisterAddress",
"(",
"'cycles'",
",",
"patternnumber",
")",
"self",
".",
"write_register",
"(",
"address",
",",
"value",
",",
"0",
")"
] | Set the number of additional cycles for a given pattern.
Args:
* patternnumber (integer): 0-7
* value (integer): 0-99 | [
"Set",
"the",
"number",
"of",
"additional",
"cycles",
"for",
"a",
"given",
"pattern",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L333-L344 |
5,925 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.get_pattern_link_topattern | def get_pattern_link_topattern(self, patternnumber):
"""Get the 'linked pattern' value for a given pattern.
Args:
patternnumber (integer): From 0-7
Returns:
The 'linked pattern' value (int).
"""
_checkPatternNumber(patternnumber)
address = _calculateRegisterAddress('linkpattern', patternnumber)
return self.read_register(address) | python | def get_pattern_link_topattern(self, patternnumber):
"""Get the 'linked pattern' value for a given pattern.
Args:
patternnumber (integer): From 0-7
Returns:
The 'linked pattern' value (int).
"""
_checkPatternNumber(patternnumber)
address = _calculateRegisterAddress('linkpattern', patternnumber)
return self.read_register(address) | [
"def",
"get_pattern_link_topattern",
"(",
"self",
",",
"patternnumber",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"address",
"=",
"_calculateRegisterAddress",
"(",
"'linkpattern'",
",",
"patternnumber",
")",
"return",
"self",
".",
"read_register",
"(",
"address",
")"
] | Get the 'linked pattern' value for a given pattern.
Args:
patternnumber (integer): From 0-7
Returns:
The 'linked pattern' value (int). | [
"Get",
"the",
"linked",
"pattern",
"value",
"for",
"a",
"given",
"pattern",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L347-L359 |
5,926 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.get_all_pattern_variables | def get_all_pattern_variables(self, patternnumber):
"""Get all variables for a given pattern at one time.
Args:
patternnumber (integer): 0-7
Returns:
A descriptive multiline string.
"""
_checkPatternNumber(patternnumber)
outputstring = ''
for stepnumber in range(8):
outputstring += 'SP{0}: {1} Time{0}: {2}\n'.format(stepnumber, \
self.get_pattern_step_setpoint( patternnumber, stepnumber), \
self.get_pattern_step_time( patternnumber, stepnumber) )
outputstring += 'Actual step: {0}\n'.format(self.get_pattern_actual_step( patternnumber) )
outputstring += 'Additional cycles: {0}\n'.format(self.get_pattern_additional_cycles( patternnumber) )
outputstring += 'Linked pattern: {0}\n'.format(self.get_pattern_link_topattern( patternnumber) )
return outputstring | python | def get_all_pattern_variables(self, patternnumber):
"""Get all variables for a given pattern at one time.
Args:
patternnumber (integer): 0-7
Returns:
A descriptive multiline string.
"""
_checkPatternNumber(patternnumber)
outputstring = ''
for stepnumber in range(8):
outputstring += 'SP{0}: {1} Time{0}: {2}\n'.format(stepnumber, \
self.get_pattern_step_setpoint( patternnumber, stepnumber), \
self.get_pattern_step_time( patternnumber, stepnumber) )
outputstring += 'Actual step: {0}\n'.format(self.get_pattern_actual_step( patternnumber) )
outputstring += 'Additional cycles: {0}\n'.format(self.get_pattern_additional_cycles( patternnumber) )
outputstring += 'Linked pattern: {0}\n'.format(self.get_pattern_link_topattern( patternnumber) )
return outputstring | [
"def",
"get_all_pattern_variables",
"(",
"self",
",",
"patternnumber",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"outputstring",
"=",
"''",
"for",
"stepnumber",
"in",
"range",
"(",
"8",
")",
":",
"outputstring",
"+=",
"'SP{0}: {1} Time{0}: {2}\\n'",
".",
"format",
"(",
"stepnumber",
",",
"self",
".",
"get_pattern_step_setpoint",
"(",
"patternnumber",
",",
"stepnumber",
")",
",",
"self",
".",
"get_pattern_step_time",
"(",
"patternnumber",
",",
"stepnumber",
")",
")",
"outputstring",
"+=",
"'Actual step: {0}\\n'",
".",
"format",
"(",
"self",
".",
"get_pattern_actual_step",
"(",
"patternnumber",
")",
")",
"outputstring",
"+=",
"'Additional cycles: {0}\\n'",
".",
"format",
"(",
"self",
".",
"get_pattern_additional_cycles",
"(",
"patternnumber",
")",
")",
"outputstring",
"+=",
"'Linked pattern: {0}\\n'",
".",
"format",
"(",
"self",
".",
"get_pattern_link_topattern",
"(",
"patternnumber",
")",
")",
"return",
"outputstring"
] | Get all variables for a given pattern at one time.
Args:
patternnumber (integer): 0-7
Returns:
A descriptive multiline string. | [
"Get",
"all",
"variables",
"for",
"a",
"given",
"pattern",
"at",
"one",
"time",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L376-L398 |
5,927 | pyhys/minimalmodbus | omegacn7500.py | OmegaCN7500.set_all_pattern_variables | def set_all_pattern_variables(self, patternnumber, \
sp0, ti0, sp1, ti1, sp2, ti2, sp3, ti3, sp4, ti4, sp5, ti5, sp6, ti6, sp7, ti7, \
actual_step, additional_cycles, link_pattern):
"""Set all variables for a given pattern at one time.
Args:
* patternnumber (integer): 0-7
* sp[*n*] (float): setpoint value for step *n*
* ti[*n*] (integer??): step time for step *n*, 0-900
* actual_step (int): ?
* additional_cycles(int): ?
* link_pattern(int): ?
"""
_checkPatternNumber(patternnumber)
self.set_pattern_step_setpoint(patternnumber, 0, sp0)
self.set_pattern_step_setpoint(patternnumber, 1, sp1)
self.set_pattern_step_setpoint(patternnumber, 2, sp2)
self.set_pattern_step_setpoint(patternnumber, 3, sp3)
self.set_pattern_step_setpoint(patternnumber, 4, sp4)
self.set_pattern_step_setpoint(patternnumber, 5, sp5)
self.set_pattern_step_setpoint(patternnumber, 6, sp6)
self.set_pattern_step_setpoint(patternnumber, 7, sp7)
self.set_pattern_step_time( patternnumber, 0, ti0)
self.set_pattern_step_time( patternnumber, 1, ti1)
self.set_pattern_step_time( patternnumber, 2, ti2)
self.set_pattern_step_time( patternnumber, 3, ti3)
self.set_pattern_step_time( patternnumber, 4, ti4)
self.set_pattern_step_time( patternnumber, 5, ti5)
self.set_pattern_step_time( patternnumber, 6, ti6)
self.set_pattern_step_time( patternnumber, 7, ti7)
self.set_pattern_additional_cycles(patternnumber, additional_cycles)
self.set_pattern_link_topattern( patternnumber, link_pattern)
self.set_pattern_actual_step( patternnumber, actual_step) | python | def set_all_pattern_variables(self, patternnumber, \
sp0, ti0, sp1, ti1, sp2, ti2, sp3, ti3, sp4, ti4, sp5, ti5, sp6, ti6, sp7, ti7, \
actual_step, additional_cycles, link_pattern):
"""Set all variables for a given pattern at one time.
Args:
* patternnumber (integer): 0-7
* sp[*n*] (float): setpoint value for step *n*
* ti[*n*] (integer??): step time for step *n*, 0-900
* actual_step (int): ?
* additional_cycles(int): ?
* link_pattern(int): ?
"""
_checkPatternNumber(patternnumber)
self.set_pattern_step_setpoint(patternnumber, 0, sp0)
self.set_pattern_step_setpoint(patternnumber, 1, sp1)
self.set_pattern_step_setpoint(patternnumber, 2, sp2)
self.set_pattern_step_setpoint(patternnumber, 3, sp3)
self.set_pattern_step_setpoint(patternnumber, 4, sp4)
self.set_pattern_step_setpoint(patternnumber, 5, sp5)
self.set_pattern_step_setpoint(patternnumber, 6, sp6)
self.set_pattern_step_setpoint(patternnumber, 7, sp7)
self.set_pattern_step_time( patternnumber, 0, ti0)
self.set_pattern_step_time( patternnumber, 1, ti1)
self.set_pattern_step_time( patternnumber, 2, ti2)
self.set_pattern_step_time( patternnumber, 3, ti3)
self.set_pattern_step_time( patternnumber, 4, ti4)
self.set_pattern_step_time( patternnumber, 5, ti5)
self.set_pattern_step_time( patternnumber, 6, ti6)
self.set_pattern_step_time( patternnumber, 7, ti7)
self.set_pattern_additional_cycles(patternnumber, additional_cycles)
self.set_pattern_link_topattern( patternnumber, link_pattern)
self.set_pattern_actual_step( patternnumber, actual_step) | [
"def",
"set_all_pattern_variables",
"(",
"self",
",",
"patternnumber",
",",
"sp0",
",",
"ti0",
",",
"sp1",
",",
"ti1",
",",
"sp2",
",",
"ti2",
",",
"sp3",
",",
"ti3",
",",
"sp4",
",",
"ti4",
",",
"sp5",
",",
"ti5",
",",
"sp6",
",",
"ti6",
",",
"sp7",
",",
"ti7",
",",
"actual_step",
",",
"additional_cycles",
",",
"link_pattern",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"self",
".",
"set_pattern_step_setpoint",
"(",
"patternnumber",
",",
"0",
",",
"sp0",
")",
"self",
".",
"set_pattern_step_setpoint",
"(",
"patternnumber",
",",
"1",
",",
"sp1",
")",
"self",
".",
"set_pattern_step_setpoint",
"(",
"patternnumber",
",",
"2",
",",
"sp2",
")",
"self",
".",
"set_pattern_step_setpoint",
"(",
"patternnumber",
",",
"3",
",",
"sp3",
")",
"self",
".",
"set_pattern_step_setpoint",
"(",
"patternnumber",
",",
"4",
",",
"sp4",
")",
"self",
".",
"set_pattern_step_setpoint",
"(",
"patternnumber",
",",
"5",
",",
"sp5",
")",
"self",
".",
"set_pattern_step_setpoint",
"(",
"patternnumber",
",",
"6",
",",
"sp6",
")",
"self",
".",
"set_pattern_step_setpoint",
"(",
"patternnumber",
",",
"7",
",",
"sp7",
")",
"self",
".",
"set_pattern_step_time",
"(",
"patternnumber",
",",
"0",
",",
"ti0",
")",
"self",
".",
"set_pattern_step_time",
"(",
"patternnumber",
",",
"1",
",",
"ti1",
")",
"self",
".",
"set_pattern_step_time",
"(",
"patternnumber",
",",
"2",
",",
"ti2",
")",
"self",
".",
"set_pattern_step_time",
"(",
"patternnumber",
",",
"3",
",",
"ti3",
")",
"self",
".",
"set_pattern_step_time",
"(",
"patternnumber",
",",
"4",
",",
"ti4",
")",
"self",
".",
"set_pattern_step_time",
"(",
"patternnumber",
",",
"5",
",",
"ti5",
")",
"self",
".",
"set_pattern_step_time",
"(",
"patternnumber",
",",
"6",
",",
"ti6",
")",
"self",
".",
"set_pattern_step_time",
"(",
"patternnumber",
",",
"7",
",",
"ti7",
")",
"self",
".",
"set_pattern_additional_cycles",
"(",
"patternnumber",
",",
"additional_cycles",
")",
"self",
".",
"set_pattern_link_topattern",
"(",
"patternnumber",
",",
"link_pattern",
")",
"self",
".",
"set_pattern_actual_step",
"(",
"patternnumber",
",",
"actual_step",
")"
] | Set all variables for a given pattern at one time.
Args:
* patternnumber (integer): 0-7
* sp[*n*] (float): setpoint value for step *n*
* ti[*n*] (integer??): step time for step *n*, 0-900
* actual_step (int): ?
* additional_cycles(int): ?
* link_pattern(int): ? | [
"Set",
"all",
"variables",
"for",
"a",
"given",
"pattern",
"at",
"one",
"time",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L401-L435 |
5,928 | pyhys/minimalmodbus | dummy_serial.py | Serial.close | def close(self):
"""Close a port on dummy_serial."""
if VERBOSE:
_print_out('\nDummy_serial: Closing port\n')
if not self._isOpen:
raise IOError('Dummy_serial: The port is already closed')
self._isOpen = False
self.port = None | python | def close(self):
"""Close a port on dummy_serial."""
if VERBOSE:
_print_out('\nDummy_serial: Closing port\n')
if not self._isOpen:
raise IOError('Dummy_serial: The port is already closed')
self._isOpen = False
self.port = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"VERBOSE",
":",
"_print_out",
"(",
"'\\nDummy_serial: Closing port\\n'",
")",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"IOError",
"(",
"'Dummy_serial: The port is already closed'",
")",
"self",
".",
"_isOpen",
"=",
"False",
"self",
".",
"port",
"=",
"None"
] | Close a port on dummy_serial. | [
"Close",
"a",
"port",
"on",
"dummy_serial",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/dummy_serial.py#L129-L138 |
5,929 | pyhys/minimalmodbus | dummy_serial.py | Serial.write | def write(self, inputdata):
"""Write to a port on dummy_serial.
Args:
inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response
for subsequent read operations.
Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**.
"""
if VERBOSE:
_print_out('\nDummy_serial: Writing to port. Given:' + repr(inputdata) + '\n')
if sys.version_info[0] > 2:
if not type(inputdata) == bytes:
raise TypeError('The input must be type bytes. Given:' + repr(inputdata))
inputstring = str(inputdata, encoding='latin1')
else:
inputstring = inputdata
if not self._isOpen:
raise IOError('Dummy_serial: Trying to write, but the port is not open. Given:' + repr(inputdata))
# Look up which data that should be waiting for subsequent read commands
try:
response = RESPONSES[inputstring]
except:
response = DEFAULT_RESPONSE
self._waiting_data = response | python | def write(self, inputdata):
"""Write to a port on dummy_serial.
Args:
inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response
for subsequent read operations.
Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**.
"""
if VERBOSE:
_print_out('\nDummy_serial: Writing to port. Given:' + repr(inputdata) + '\n')
if sys.version_info[0] > 2:
if not type(inputdata) == bytes:
raise TypeError('The input must be type bytes. Given:' + repr(inputdata))
inputstring = str(inputdata, encoding='latin1')
else:
inputstring = inputdata
if not self._isOpen:
raise IOError('Dummy_serial: Trying to write, but the port is not open. Given:' + repr(inputdata))
# Look up which data that should be waiting for subsequent read commands
try:
response = RESPONSES[inputstring]
except:
response = DEFAULT_RESPONSE
self._waiting_data = response | [
"def",
"write",
"(",
"self",
",",
"inputdata",
")",
":",
"if",
"VERBOSE",
":",
"_print_out",
"(",
"'\\nDummy_serial: Writing to port. Given:'",
"+",
"repr",
"(",
"inputdata",
")",
"+",
"'\\n'",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"if",
"not",
"type",
"(",
"inputdata",
")",
"==",
"bytes",
":",
"raise",
"TypeError",
"(",
"'The input must be type bytes. Given:'",
"+",
"repr",
"(",
"inputdata",
")",
")",
"inputstring",
"=",
"str",
"(",
"inputdata",
",",
"encoding",
"=",
"'latin1'",
")",
"else",
":",
"inputstring",
"=",
"inputdata",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"IOError",
"(",
"'Dummy_serial: Trying to write, but the port is not open. Given:'",
"+",
"repr",
"(",
"inputdata",
")",
")",
"# Look up which data that should be waiting for subsequent read commands",
"try",
":",
"response",
"=",
"RESPONSES",
"[",
"inputstring",
"]",
"except",
":",
"response",
"=",
"DEFAULT_RESPONSE",
"self",
".",
"_waiting_data",
"=",
"response"
] | Write to a port on dummy_serial.
Args:
inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response
for subsequent read operations.
Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**. | [
"Write",
"to",
"a",
"port",
"on",
"dummy_serial",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/dummy_serial.py#L141-L169 |
5,930 | pyhys/minimalmodbus | dummy_serial.py | Serial.read | def read(self, numberOfBytes):
"""Read from a port on dummy_serial.
The response is dependent on what was written last to the port on dummy_serial,
and what is defined in the :data:`RESPONSES` dictionary.
Args:
numberOfBytes (int): For compability with the real function.
Returns a **string** for Python2 and **bytes** for Python3.
If the response is shorter than numberOfBytes, it will sleep for timeout.
If the response is longer than numberOfBytes, it will return only numberOfBytes bytes.
"""
if VERBOSE:
_print_out('\nDummy_serial: Reading from port (max length {!r} bytes)'.format(numberOfBytes))
if numberOfBytes < 0:
raise IOError('Dummy_serial: The numberOfBytes to read must not be negative. Given: {!r}'.format(numberOfBytes))
if not self._isOpen:
raise IOError('Dummy_serial: Trying to read, but the port is not open.')
# Do the actual reading from the waiting data, and simulate the influence of numberOfBytes
if self._waiting_data == DEFAULT_RESPONSE:
returnstring = self._waiting_data
elif numberOfBytes == len(self._waiting_data):
returnstring = self._waiting_data
self._waiting_data = NO_DATA_PRESENT
elif numberOfBytes < len(self._waiting_data):
if VERBOSE:
_print_out('Dummy_serial: The numberOfBytes to read is smaller than the available data. ' + \
'Some bytes will be kept for later. Available data: {!r} (length = {}), numberOfBytes: {}'.format( \
self._waiting_data, len(self._waiting_data), numberOfBytes))
returnstring = self._waiting_data[:numberOfBytes]
self._waiting_data = self._waiting_data[numberOfBytes:]
else: # Wait for timeout, as we have asked for more data than available
if VERBOSE:
_print_out('Dummy_serial: The numberOfBytes to read is larger than the available data. ' + \
'Will sleep until timeout. Available data: {!r} (length = {}), numberOfBytes: {}'.format( \
self._waiting_data, len(self._waiting_data), numberOfBytes))
time.sleep(self.timeout)
returnstring = self._waiting_data
self._waiting_data = NO_DATA_PRESENT
# TODO Adapt the behavior to better mimic the Windows behavior
if VERBOSE:
_print_out('Dummy_serial read return data: {!r} (has length {})\n'.format(returnstring, len(returnstring)))
if sys.version_info[0] > 2: # Convert types to make it python3 compatible
return bytes(returnstring, encoding='latin1')
else:
return returnstring | python | def read(self, numberOfBytes):
"""Read from a port on dummy_serial.
The response is dependent on what was written last to the port on dummy_serial,
and what is defined in the :data:`RESPONSES` dictionary.
Args:
numberOfBytes (int): For compability with the real function.
Returns a **string** for Python2 and **bytes** for Python3.
If the response is shorter than numberOfBytes, it will sleep for timeout.
If the response is longer than numberOfBytes, it will return only numberOfBytes bytes.
"""
if VERBOSE:
_print_out('\nDummy_serial: Reading from port (max length {!r} bytes)'.format(numberOfBytes))
if numberOfBytes < 0:
raise IOError('Dummy_serial: The numberOfBytes to read must not be negative. Given: {!r}'.format(numberOfBytes))
if not self._isOpen:
raise IOError('Dummy_serial: Trying to read, but the port is not open.')
# Do the actual reading from the waiting data, and simulate the influence of numberOfBytes
if self._waiting_data == DEFAULT_RESPONSE:
returnstring = self._waiting_data
elif numberOfBytes == len(self._waiting_data):
returnstring = self._waiting_data
self._waiting_data = NO_DATA_PRESENT
elif numberOfBytes < len(self._waiting_data):
if VERBOSE:
_print_out('Dummy_serial: The numberOfBytes to read is smaller than the available data. ' + \
'Some bytes will be kept for later. Available data: {!r} (length = {}), numberOfBytes: {}'.format( \
self._waiting_data, len(self._waiting_data), numberOfBytes))
returnstring = self._waiting_data[:numberOfBytes]
self._waiting_data = self._waiting_data[numberOfBytes:]
else: # Wait for timeout, as we have asked for more data than available
if VERBOSE:
_print_out('Dummy_serial: The numberOfBytes to read is larger than the available data. ' + \
'Will sleep until timeout. Available data: {!r} (length = {}), numberOfBytes: {}'.format( \
self._waiting_data, len(self._waiting_data), numberOfBytes))
time.sleep(self.timeout)
returnstring = self._waiting_data
self._waiting_data = NO_DATA_PRESENT
# TODO Adapt the behavior to better mimic the Windows behavior
if VERBOSE:
_print_out('Dummy_serial read return data: {!r} (has length {})\n'.format(returnstring, len(returnstring)))
if sys.version_info[0] > 2: # Convert types to make it python3 compatible
return bytes(returnstring, encoding='latin1')
else:
return returnstring | [
"def",
"read",
"(",
"self",
",",
"numberOfBytes",
")",
":",
"if",
"VERBOSE",
":",
"_print_out",
"(",
"'\\nDummy_serial: Reading from port (max length {!r} bytes)'",
".",
"format",
"(",
"numberOfBytes",
")",
")",
"if",
"numberOfBytes",
"<",
"0",
":",
"raise",
"IOError",
"(",
"'Dummy_serial: The numberOfBytes to read must not be negative. Given: {!r}'",
".",
"format",
"(",
"numberOfBytes",
")",
")",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"IOError",
"(",
"'Dummy_serial: Trying to read, but the port is not open.'",
")",
"# Do the actual reading from the waiting data, and simulate the influence of numberOfBytes",
"if",
"self",
".",
"_waiting_data",
"==",
"DEFAULT_RESPONSE",
":",
"returnstring",
"=",
"self",
".",
"_waiting_data",
"elif",
"numberOfBytes",
"==",
"len",
"(",
"self",
".",
"_waiting_data",
")",
":",
"returnstring",
"=",
"self",
".",
"_waiting_data",
"self",
".",
"_waiting_data",
"=",
"NO_DATA_PRESENT",
"elif",
"numberOfBytes",
"<",
"len",
"(",
"self",
".",
"_waiting_data",
")",
":",
"if",
"VERBOSE",
":",
"_print_out",
"(",
"'Dummy_serial: The numberOfBytes to read is smaller than the available data. '",
"+",
"'Some bytes will be kept for later. Available data: {!r} (length = {}), numberOfBytes: {}'",
".",
"format",
"(",
"self",
".",
"_waiting_data",
",",
"len",
"(",
"self",
".",
"_waiting_data",
")",
",",
"numberOfBytes",
")",
")",
"returnstring",
"=",
"self",
".",
"_waiting_data",
"[",
":",
"numberOfBytes",
"]",
"self",
".",
"_waiting_data",
"=",
"self",
".",
"_waiting_data",
"[",
"numberOfBytes",
":",
"]",
"else",
":",
"# Wait for timeout, as we have asked for more data than available",
"if",
"VERBOSE",
":",
"_print_out",
"(",
"'Dummy_serial: The numberOfBytes to read is larger than the available data. '",
"+",
"'Will sleep until timeout. Available data: {!r} (length = {}), numberOfBytes: {}'",
".",
"format",
"(",
"self",
".",
"_waiting_data",
",",
"len",
"(",
"self",
".",
"_waiting_data",
")",
",",
"numberOfBytes",
")",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"timeout",
")",
"returnstring",
"=",
"self",
".",
"_waiting_data",
"self",
".",
"_waiting_data",
"=",
"NO_DATA_PRESENT",
"# TODO Adapt the behavior to better mimic the Windows behavior",
"if",
"VERBOSE",
":",
"_print_out",
"(",
"'Dummy_serial read return data: {!r} (has length {})\\n'",
".",
"format",
"(",
"returnstring",
",",
"len",
"(",
"returnstring",
")",
")",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"# Convert types to make it python3 compatible",
"return",
"bytes",
"(",
"returnstring",
",",
"encoding",
"=",
"'latin1'",
")",
"else",
":",
"return",
"returnstring"
] | Read from a port on dummy_serial.
The response is dependent on what was written last to the port on dummy_serial,
and what is defined in the :data:`RESPONSES` dictionary.
Args:
numberOfBytes (int): For compability with the real function.
Returns a **string** for Python2 and **bytes** for Python3.
If the response is shorter than numberOfBytes, it will sleep for timeout.
If the response is longer than numberOfBytes, it will return only numberOfBytes bytes. | [
"Read",
"from",
"a",
"port",
"on",
"dummy_serial",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/dummy_serial.py#L172-L227 |
5,931 | pyhys/minimalmodbus | minimalmodbus.py | _embedPayload | def _embedPayload(slaveaddress, mode, functioncode, payloaddata):
"""Build a request from the slaveaddress, the function code and the payload data.
Args:
* slaveaddress (int): The address of the slave.
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): The function code for the command to be performed. Can for example be 16 (Write register).
* payloaddata (str): The byte string to be sent to the slave.
Returns:
The built (raw) request string for sending to the slave (including CRC etc).
Raises:
ValueError, TypeError.
The resulting request has the format:
* RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes).
* ASCII Mode: header (:) + slaveaddress (2 characters) + functioncode (2 characters) + payloaddata + LRC (which is two characters) + footer (CRLF)
The LRC or CRC is calculated from the byte string made up of slaveaddress + functioncode + payloaddata.
The header, LRC/CRC, and footer are excluded from the calculation.
"""
_checkSlaveaddress(slaveaddress)
_checkMode(mode)
_checkFunctioncode(functioncode, None)
_checkString(payloaddata, description='payload')
firstPart = _numToOneByteString(slaveaddress) + _numToOneByteString(functioncode) + payloaddata
if mode == MODE_ASCII:
request = _ASCII_HEADER + \
_hexencode(firstPart) + \
_hexencode(_calculateLrcString(firstPart)) + \
_ASCII_FOOTER
else:
request = firstPart + _calculateCrcString(firstPart)
return request | python | def _embedPayload(slaveaddress, mode, functioncode, payloaddata):
"""Build a request from the slaveaddress, the function code and the payload data.
Args:
* slaveaddress (int): The address of the slave.
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): The function code for the command to be performed. Can for example be 16 (Write register).
* payloaddata (str): The byte string to be sent to the slave.
Returns:
The built (raw) request string for sending to the slave (including CRC etc).
Raises:
ValueError, TypeError.
The resulting request has the format:
* RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes).
* ASCII Mode: header (:) + slaveaddress (2 characters) + functioncode (2 characters) + payloaddata + LRC (which is two characters) + footer (CRLF)
The LRC or CRC is calculated from the byte string made up of slaveaddress + functioncode + payloaddata.
The header, LRC/CRC, and footer are excluded from the calculation.
"""
_checkSlaveaddress(slaveaddress)
_checkMode(mode)
_checkFunctioncode(functioncode, None)
_checkString(payloaddata, description='payload')
firstPart = _numToOneByteString(slaveaddress) + _numToOneByteString(functioncode) + payloaddata
if mode == MODE_ASCII:
request = _ASCII_HEADER + \
_hexencode(firstPart) + \
_hexencode(_calculateLrcString(firstPart)) + \
_ASCII_FOOTER
else:
request = firstPart + _calculateCrcString(firstPart)
return request | [
"def",
"_embedPayload",
"(",
"slaveaddress",
",",
"mode",
",",
"functioncode",
",",
"payloaddata",
")",
":",
"_checkSlaveaddress",
"(",
"slaveaddress",
")",
"_checkMode",
"(",
"mode",
")",
"_checkFunctioncode",
"(",
"functioncode",
",",
"None",
")",
"_checkString",
"(",
"payloaddata",
",",
"description",
"=",
"'payload'",
")",
"firstPart",
"=",
"_numToOneByteString",
"(",
"slaveaddress",
")",
"+",
"_numToOneByteString",
"(",
"functioncode",
")",
"+",
"payloaddata",
"if",
"mode",
"==",
"MODE_ASCII",
":",
"request",
"=",
"_ASCII_HEADER",
"+",
"_hexencode",
"(",
"firstPart",
")",
"+",
"_hexencode",
"(",
"_calculateLrcString",
"(",
"firstPart",
")",
")",
"+",
"_ASCII_FOOTER",
"else",
":",
"request",
"=",
"firstPart",
"+",
"_calculateCrcString",
"(",
"firstPart",
")",
"return",
"request"
] | Build a request from the slaveaddress, the function code and the payload data.
Args:
* slaveaddress (int): The address of the slave.
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): The function code for the command to be performed. Can for example be 16 (Write register).
* payloaddata (str): The byte string to be sent to the slave.
Returns:
The built (raw) request string for sending to the slave (including CRC etc).
Raises:
ValueError, TypeError.
The resulting request has the format:
* RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes).
* ASCII Mode: header (:) + slaveaddress (2 characters) + functioncode (2 characters) + payloaddata + LRC (which is two characters) + footer (CRLF)
The LRC or CRC is calculated from the byte string made up of slaveaddress + functioncode + payloaddata.
The header, LRC/CRC, and footer are excluded from the calculation. | [
"Build",
"a",
"request",
"from",
"the",
"slaveaddress",
"the",
"function",
"code",
"and",
"the",
"payload",
"data",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L939-L977 |
5,932 | pyhys/minimalmodbus | minimalmodbus.py | _extractPayload | def _extractPayload(response, slaveaddress, mode, functioncode):
"""Extract the payload data part from the slave's response.
Args:
* response (str): The raw response byte string from the slave.
* slaveaddress (int): The adress of the slave. Used here for error checking only.
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): Used here for error checking only.
Returns:
The payload part of the *response* string.
Raises:
ValueError, TypeError. Raises an exception if there is any problem with the received address, the functioncode or the CRC.
The received response should have the format:
* RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes)
* ASCII Mode: header (:) + slaveaddress byte + functioncode byte + payloaddata + LRC (which is two characters) + footer (CRLF)
For development purposes, this function can also be used to extract the payload from the request sent TO the slave.
"""
BYTEPOSITION_FOR_ASCII_HEADER = 0 # Relative to plain response
BYTEPOSITION_FOR_SLAVEADDRESS = 0 # Relative to (stripped) response
BYTEPOSITION_FOR_FUNCTIONCODE = 1
NUMBER_OF_RESPONSE_STARTBYTES = 2 # Number of bytes before the response payload (in stripped response)
NUMBER_OF_CRC_BYTES = 2
NUMBER_OF_LRC_BYTES = 1
BITNUMBER_FUNCTIONCODE_ERRORINDICATION = 7
MINIMAL_RESPONSE_LENGTH_RTU = NUMBER_OF_RESPONSE_STARTBYTES + NUMBER_OF_CRC_BYTES
MINIMAL_RESPONSE_LENGTH_ASCII = 9
# Argument validity testing
_checkString(response, description='response')
_checkSlaveaddress(slaveaddress)
_checkMode(mode)
_checkFunctioncode(functioncode, None)
plainresponse = response
# Validate response length
if mode == MODE_ASCII:
if len(response) < MINIMAL_RESPONSE_LENGTH_ASCII:
raise ValueError('Too short Modbus ASCII response (minimum length {} bytes). Response: {!r}'.format( \
MINIMAL_RESPONSE_LENGTH_ASCII,
response))
elif len(response) < MINIMAL_RESPONSE_LENGTH_RTU:
raise ValueError('Too short Modbus RTU response (minimum length {} bytes). Response: {!r}'.format( \
MINIMAL_RESPONSE_LENGTH_RTU,
response))
# Validate the ASCII header and footer.
if mode == MODE_ASCII:
if response[BYTEPOSITION_FOR_ASCII_HEADER] != _ASCII_HEADER:
raise ValueError('Did not find header ({!r}) as start of ASCII response. The plain response is: {!r}'.format( \
_ASCII_HEADER,
response))
elif response[-len(_ASCII_FOOTER):] != _ASCII_FOOTER:
raise ValueError('Did not find footer ({!r}) as end of ASCII response. The plain response is: {!r}'.format( \
_ASCII_FOOTER,
response))
# Strip ASCII header and footer
response = response[1:-2]
if len(response) % 2 != 0:
template = 'Stripped ASCII frames should have an even number of bytes, but is {} bytes. ' + \
'The stripped response is: {!r} (plain response: {!r})'
raise ValueError(template.format(len(response), response, plainresponse))
# Convert the ASCII (stripped) response string to RTU-like response string
response = _hexdecode(response)
# Validate response checksum
if mode == MODE_ASCII:
calculateChecksum = _calculateLrcString
numberOfChecksumBytes = NUMBER_OF_LRC_BYTES
else:
calculateChecksum = _calculateCrcString
numberOfChecksumBytes = NUMBER_OF_CRC_BYTES
receivedChecksum = response[-numberOfChecksumBytes:]
responseWithoutChecksum = response[0 : len(response) - numberOfChecksumBytes]
calculatedChecksum = calculateChecksum(responseWithoutChecksum)
if receivedChecksum != calculatedChecksum:
template = 'Checksum error in {} mode: {!r} instead of {!r} . The response is: {!r} (plain response: {!r})'
text = template.format(
mode,
receivedChecksum,
calculatedChecksum,
response, plainresponse)
raise ValueError(text)
# Check slave address
responseaddress = ord(response[BYTEPOSITION_FOR_SLAVEADDRESS])
if responseaddress != slaveaddress:
raise ValueError('Wrong return slave address: {} instead of {}. The response is: {!r}'.format( \
responseaddress, slaveaddress, response))
# Check function code
receivedFunctioncode = ord(response[BYTEPOSITION_FOR_FUNCTIONCODE])
if receivedFunctioncode == _setBitOn(functioncode, BITNUMBER_FUNCTIONCODE_ERRORINDICATION):
raise ValueError('The slave is indicating an error. The response is: {!r}'.format(response))
elif receivedFunctioncode != functioncode:
raise ValueError('Wrong functioncode: {} instead of {}. The response is: {!r}'.format( \
receivedFunctioncode, functioncode, response))
# Read data payload
firstDatabyteNumber = NUMBER_OF_RESPONSE_STARTBYTES
if mode == MODE_ASCII:
lastDatabyteNumber = len(response) - NUMBER_OF_LRC_BYTES
else:
lastDatabyteNumber = len(response) - NUMBER_OF_CRC_BYTES
payload = response[firstDatabyteNumber:lastDatabyteNumber]
return payload | python | def _extractPayload(response, slaveaddress, mode, functioncode):
"""Extract the payload data part from the slave's response.
Args:
* response (str): The raw response byte string from the slave.
* slaveaddress (int): The adress of the slave. Used here for error checking only.
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): Used here for error checking only.
Returns:
The payload part of the *response* string.
Raises:
ValueError, TypeError. Raises an exception if there is any problem with the received address, the functioncode or the CRC.
The received response should have the format:
* RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes)
* ASCII Mode: header (:) + slaveaddress byte + functioncode byte + payloaddata + LRC (which is two characters) + footer (CRLF)
For development purposes, this function can also be used to extract the payload from the request sent TO the slave.
"""
BYTEPOSITION_FOR_ASCII_HEADER = 0 # Relative to plain response
BYTEPOSITION_FOR_SLAVEADDRESS = 0 # Relative to (stripped) response
BYTEPOSITION_FOR_FUNCTIONCODE = 1
NUMBER_OF_RESPONSE_STARTBYTES = 2 # Number of bytes before the response payload (in stripped response)
NUMBER_OF_CRC_BYTES = 2
NUMBER_OF_LRC_BYTES = 1
BITNUMBER_FUNCTIONCODE_ERRORINDICATION = 7
MINIMAL_RESPONSE_LENGTH_RTU = NUMBER_OF_RESPONSE_STARTBYTES + NUMBER_OF_CRC_BYTES
MINIMAL_RESPONSE_LENGTH_ASCII = 9
# Argument validity testing
_checkString(response, description='response')
_checkSlaveaddress(slaveaddress)
_checkMode(mode)
_checkFunctioncode(functioncode, None)
plainresponse = response
# Validate response length
if mode == MODE_ASCII:
if len(response) < MINIMAL_RESPONSE_LENGTH_ASCII:
raise ValueError('Too short Modbus ASCII response (minimum length {} bytes). Response: {!r}'.format( \
MINIMAL_RESPONSE_LENGTH_ASCII,
response))
elif len(response) < MINIMAL_RESPONSE_LENGTH_RTU:
raise ValueError('Too short Modbus RTU response (minimum length {} bytes). Response: {!r}'.format( \
MINIMAL_RESPONSE_LENGTH_RTU,
response))
# Validate the ASCII header and footer.
if mode == MODE_ASCII:
if response[BYTEPOSITION_FOR_ASCII_HEADER] != _ASCII_HEADER:
raise ValueError('Did not find header ({!r}) as start of ASCII response. The plain response is: {!r}'.format( \
_ASCII_HEADER,
response))
elif response[-len(_ASCII_FOOTER):] != _ASCII_FOOTER:
raise ValueError('Did not find footer ({!r}) as end of ASCII response. The plain response is: {!r}'.format( \
_ASCII_FOOTER,
response))
# Strip ASCII header and footer
response = response[1:-2]
if len(response) % 2 != 0:
template = 'Stripped ASCII frames should have an even number of bytes, but is {} bytes. ' + \
'The stripped response is: {!r} (plain response: {!r})'
raise ValueError(template.format(len(response), response, plainresponse))
# Convert the ASCII (stripped) response string to RTU-like response string
response = _hexdecode(response)
# Validate response checksum
if mode == MODE_ASCII:
calculateChecksum = _calculateLrcString
numberOfChecksumBytes = NUMBER_OF_LRC_BYTES
else:
calculateChecksum = _calculateCrcString
numberOfChecksumBytes = NUMBER_OF_CRC_BYTES
receivedChecksum = response[-numberOfChecksumBytes:]
responseWithoutChecksum = response[0 : len(response) - numberOfChecksumBytes]
calculatedChecksum = calculateChecksum(responseWithoutChecksum)
if receivedChecksum != calculatedChecksum:
template = 'Checksum error in {} mode: {!r} instead of {!r} . The response is: {!r} (plain response: {!r})'
text = template.format(
mode,
receivedChecksum,
calculatedChecksum,
response, plainresponse)
raise ValueError(text)
# Check slave address
responseaddress = ord(response[BYTEPOSITION_FOR_SLAVEADDRESS])
if responseaddress != slaveaddress:
raise ValueError('Wrong return slave address: {} instead of {}. The response is: {!r}'.format( \
responseaddress, slaveaddress, response))
# Check function code
receivedFunctioncode = ord(response[BYTEPOSITION_FOR_FUNCTIONCODE])
if receivedFunctioncode == _setBitOn(functioncode, BITNUMBER_FUNCTIONCODE_ERRORINDICATION):
raise ValueError('The slave is indicating an error. The response is: {!r}'.format(response))
elif receivedFunctioncode != functioncode:
raise ValueError('Wrong functioncode: {} instead of {}. The response is: {!r}'.format( \
receivedFunctioncode, functioncode, response))
# Read data payload
firstDatabyteNumber = NUMBER_OF_RESPONSE_STARTBYTES
if mode == MODE_ASCII:
lastDatabyteNumber = len(response) - NUMBER_OF_LRC_BYTES
else:
lastDatabyteNumber = len(response) - NUMBER_OF_CRC_BYTES
payload = response[firstDatabyteNumber:lastDatabyteNumber]
return payload | [
"def",
"_extractPayload",
"(",
"response",
",",
"slaveaddress",
",",
"mode",
",",
"functioncode",
")",
":",
"BYTEPOSITION_FOR_ASCII_HEADER",
"=",
"0",
"# Relative to plain response",
"BYTEPOSITION_FOR_SLAVEADDRESS",
"=",
"0",
"# Relative to (stripped) response",
"BYTEPOSITION_FOR_FUNCTIONCODE",
"=",
"1",
"NUMBER_OF_RESPONSE_STARTBYTES",
"=",
"2",
"# Number of bytes before the response payload (in stripped response)",
"NUMBER_OF_CRC_BYTES",
"=",
"2",
"NUMBER_OF_LRC_BYTES",
"=",
"1",
"BITNUMBER_FUNCTIONCODE_ERRORINDICATION",
"=",
"7",
"MINIMAL_RESPONSE_LENGTH_RTU",
"=",
"NUMBER_OF_RESPONSE_STARTBYTES",
"+",
"NUMBER_OF_CRC_BYTES",
"MINIMAL_RESPONSE_LENGTH_ASCII",
"=",
"9",
"# Argument validity testing",
"_checkString",
"(",
"response",
",",
"description",
"=",
"'response'",
")",
"_checkSlaveaddress",
"(",
"slaveaddress",
")",
"_checkMode",
"(",
"mode",
")",
"_checkFunctioncode",
"(",
"functioncode",
",",
"None",
")",
"plainresponse",
"=",
"response",
"# Validate response length",
"if",
"mode",
"==",
"MODE_ASCII",
":",
"if",
"len",
"(",
"response",
")",
"<",
"MINIMAL_RESPONSE_LENGTH_ASCII",
":",
"raise",
"ValueError",
"(",
"'Too short Modbus ASCII response (minimum length {} bytes). Response: {!r}'",
".",
"format",
"(",
"MINIMAL_RESPONSE_LENGTH_ASCII",
",",
"response",
")",
")",
"elif",
"len",
"(",
"response",
")",
"<",
"MINIMAL_RESPONSE_LENGTH_RTU",
":",
"raise",
"ValueError",
"(",
"'Too short Modbus RTU response (minimum length {} bytes). Response: {!r}'",
".",
"format",
"(",
"MINIMAL_RESPONSE_LENGTH_RTU",
",",
"response",
")",
")",
"# Validate the ASCII header and footer.",
"if",
"mode",
"==",
"MODE_ASCII",
":",
"if",
"response",
"[",
"BYTEPOSITION_FOR_ASCII_HEADER",
"]",
"!=",
"_ASCII_HEADER",
":",
"raise",
"ValueError",
"(",
"'Did not find header ({!r}) as start of ASCII response. The plain response is: {!r}'",
".",
"format",
"(",
"_ASCII_HEADER",
",",
"response",
")",
")",
"elif",
"response",
"[",
"-",
"len",
"(",
"_ASCII_FOOTER",
")",
":",
"]",
"!=",
"_ASCII_FOOTER",
":",
"raise",
"ValueError",
"(",
"'Did not find footer ({!r}) as end of ASCII response. The plain response is: {!r}'",
".",
"format",
"(",
"_ASCII_FOOTER",
",",
"response",
")",
")",
"# Strip ASCII header and footer",
"response",
"=",
"response",
"[",
"1",
":",
"-",
"2",
"]",
"if",
"len",
"(",
"response",
")",
"%",
"2",
"!=",
"0",
":",
"template",
"=",
"'Stripped ASCII frames should have an even number of bytes, but is {} bytes. '",
"+",
"'The stripped response is: {!r} (plain response: {!r})'",
"raise",
"ValueError",
"(",
"template",
".",
"format",
"(",
"len",
"(",
"response",
")",
",",
"response",
",",
"plainresponse",
")",
")",
"# Convert the ASCII (stripped) response string to RTU-like response string",
"response",
"=",
"_hexdecode",
"(",
"response",
")",
"# Validate response checksum",
"if",
"mode",
"==",
"MODE_ASCII",
":",
"calculateChecksum",
"=",
"_calculateLrcString",
"numberOfChecksumBytes",
"=",
"NUMBER_OF_LRC_BYTES",
"else",
":",
"calculateChecksum",
"=",
"_calculateCrcString",
"numberOfChecksumBytes",
"=",
"NUMBER_OF_CRC_BYTES",
"receivedChecksum",
"=",
"response",
"[",
"-",
"numberOfChecksumBytes",
":",
"]",
"responseWithoutChecksum",
"=",
"response",
"[",
"0",
":",
"len",
"(",
"response",
")",
"-",
"numberOfChecksumBytes",
"]",
"calculatedChecksum",
"=",
"calculateChecksum",
"(",
"responseWithoutChecksum",
")",
"if",
"receivedChecksum",
"!=",
"calculatedChecksum",
":",
"template",
"=",
"'Checksum error in {} mode: {!r} instead of {!r} . The response is: {!r} (plain response: {!r})'",
"text",
"=",
"template",
".",
"format",
"(",
"mode",
",",
"receivedChecksum",
",",
"calculatedChecksum",
",",
"response",
",",
"plainresponse",
")",
"raise",
"ValueError",
"(",
"text",
")",
"# Check slave address",
"responseaddress",
"=",
"ord",
"(",
"response",
"[",
"BYTEPOSITION_FOR_SLAVEADDRESS",
"]",
")",
"if",
"responseaddress",
"!=",
"slaveaddress",
":",
"raise",
"ValueError",
"(",
"'Wrong return slave address: {} instead of {}. The response is: {!r}'",
".",
"format",
"(",
"responseaddress",
",",
"slaveaddress",
",",
"response",
")",
")",
"# Check function code",
"receivedFunctioncode",
"=",
"ord",
"(",
"response",
"[",
"BYTEPOSITION_FOR_FUNCTIONCODE",
"]",
")",
"if",
"receivedFunctioncode",
"==",
"_setBitOn",
"(",
"functioncode",
",",
"BITNUMBER_FUNCTIONCODE_ERRORINDICATION",
")",
":",
"raise",
"ValueError",
"(",
"'The slave is indicating an error. The response is: {!r}'",
".",
"format",
"(",
"response",
")",
")",
"elif",
"receivedFunctioncode",
"!=",
"functioncode",
":",
"raise",
"ValueError",
"(",
"'Wrong functioncode: {} instead of {}. The response is: {!r}'",
".",
"format",
"(",
"receivedFunctioncode",
",",
"functioncode",
",",
"response",
")",
")",
"# Read data payload",
"firstDatabyteNumber",
"=",
"NUMBER_OF_RESPONSE_STARTBYTES",
"if",
"mode",
"==",
"MODE_ASCII",
":",
"lastDatabyteNumber",
"=",
"len",
"(",
"response",
")",
"-",
"NUMBER_OF_LRC_BYTES",
"else",
":",
"lastDatabyteNumber",
"=",
"len",
"(",
"response",
")",
"-",
"NUMBER_OF_CRC_BYTES",
"payload",
"=",
"response",
"[",
"firstDatabyteNumber",
":",
"lastDatabyteNumber",
"]",
"return",
"payload"
] | Extract the payload data part from the slave's response.
Args:
* response (str): The raw response byte string from the slave.
* slaveaddress (int): The adress of the slave. Used here for error checking only.
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): Used here for error checking only.
Returns:
The payload part of the *response* string.
Raises:
ValueError, TypeError. Raises an exception if there is any problem with the received address, the functioncode or the CRC.
The received response should have the format:
* RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes)
* ASCII Mode: header (:) + slaveaddress byte + functioncode byte + payloaddata + LRC (which is two characters) + footer (CRLF)
For development purposes, this function can also be used to extract the payload from the request sent TO the slave. | [
"Extract",
"the",
"payload",
"data",
"part",
"from",
"the",
"slave",
"s",
"response",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L980-L1103 |
5,933 | pyhys/minimalmodbus | minimalmodbus.py | _predictResponseSize | def _predictResponseSize(mode, functioncode, payloadToSlave):
"""Calculate the number of bytes that should be received from the slave.
Args:
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): Modbus function code.
* payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string)
Returns:
The preducted number of bytes (int) in the response.
Raises:
ValueError, TypeError.
"""
MIN_PAYLOAD_LENGTH = 4 # For implemented functioncodes here
BYTERANGE_FOR_GIVEN_SIZE = slice(2, 4) # Within the payload
NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION = 4
NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD = 1
RTU_TO_ASCII_PAYLOAD_FACTOR = 2
NUMBER_OF_RTU_RESPONSE_STARTBYTES = 2
NUMBER_OF_RTU_RESPONSE_ENDBYTES = 2
NUMBER_OF_ASCII_RESPONSE_STARTBYTES = 5
NUMBER_OF_ASCII_RESPONSE_ENDBYTES = 4
# Argument validity testing
_checkMode(mode)
_checkFunctioncode(functioncode, None)
_checkString(payloadToSlave, description='payload', minlength=MIN_PAYLOAD_LENGTH)
# Calculate payload size
if functioncode in [5, 6, 15, 16]:
response_payload_size = NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION
elif functioncode in [1, 2, 3, 4]:
given_size = _twoByteStringToNum(payloadToSlave[BYTERANGE_FOR_GIVEN_SIZE])
if functioncode == 1 or functioncode == 2:
# Algorithm from MODBUS APPLICATION PROTOCOL SPECIFICATION V1.1b
number_of_inputs = given_size
response_payload_size = NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD + \
number_of_inputs // 8 + (1 if number_of_inputs % 8 else 0)
elif functioncode == 3 or functioncode == 4:
number_of_registers = given_size
response_payload_size = NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD + \
number_of_registers * _NUMBER_OF_BYTES_PER_REGISTER
else:
raise ValueError('Wrong functioncode: {}. The payload is: {!r}'.format( \
functioncode, payloadToSlave))
# Calculate number of bytes to read
if mode == MODE_ASCII:
return NUMBER_OF_ASCII_RESPONSE_STARTBYTES + \
response_payload_size * RTU_TO_ASCII_PAYLOAD_FACTOR + \
NUMBER_OF_ASCII_RESPONSE_ENDBYTES
else:
return NUMBER_OF_RTU_RESPONSE_STARTBYTES + \
response_payload_size + \
NUMBER_OF_RTU_RESPONSE_ENDBYTES | python | def _predictResponseSize(mode, functioncode, payloadToSlave):
"""Calculate the number of bytes that should be received from the slave.
Args:
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): Modbus function code.
* payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string)
Returns:
The preducted number of bytes (int) in the response.
Raises:
ValueError, TypeError.
"""
MIN_PAYLOAD_LENGTH = 4 # For implemented functioncodes here
BYTERANGE_FOR_GIVEN_SIZE = slice(2, 4) # Within the payload
NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION = 4
NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD = 1
RTU_TO_ASCII_PAYLOAD_FACTOR = 2
NUMBER_OF_RTU_RESPONSE_STARTBYTES = 2
NUMBER_OF_RTU_RESPONSE_ENDBYTES = 2
NUMBER_OF_ASCII_RESPONSE_STARTBYTES = 5
NUMBER_OF_ASCII_RESPONSE_ENDBYTES = 4
# Argument validity testing
_checkMode(mode)
_checkFunctioncode(functioncode, None)
_checkString(payloadToSlave, description='payload', minlength=MIN_PAYLOAD_LENGTH)
# Calculate payload size
if functioncode in [5, 6, 15, 16]:
response_payload_size = NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION
elif functioncode in [1, 2, 3, 4]:
given_size = _twoByteStringToNum(payloadToSlave[BYTERANGE_FOR_GIVEN_SIZE])
if functioncode == 1 or functioncode == 2:
# Algorithm from MODBUS APPLICATION PROTOCOL SPECIFICATION V1.1b
number_of_inputs = given_size
response_payload_size = NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD + \
number_of_inputs // 8 + (1 if number_of_inputs % 8 else 0)
elif functioncode == 3 or functioncode == 4:
number_of_registers = given_size
response_payload_size = NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD + \
number_of_registers * _NUMBER_OF_BYTES_PER_REGISTER
else:
raise ValueError('Wrong functioncode: {}. The payload is: {!r}'.format( \
functioncode, payloadToSlave))
# Calculate number of bytes to read
if mode == MODE_ASCII:
return NUMBER_OF_ASCII_RESPONSE_STARTBYTES + \
response_payload_size * RTU_TO_ASCII_PAYLOAD_FACTOR + \
NUMBER_OF_ASCII_RESPONSE_ENDBYTES
else:
return NUMBER_OF_RTU_RESPONSE_STARTBYTES + \
response_payload_size + \
NUMBER_OF_RTU_RESPONSE_ENDBYTES | [
"def",
"_predictResponseSize",
"(",
"mode",
",",
"functioncode",
",",
"payloadToSlave",
")",
":",
"MIN_PAYLOAD_LENGTH",
"=",
"4",
"# For implemented functioncodes here",
"BYTERANGE_FOR_GIVEN_SIZE",
"=",
"slice",
"(",
"2",
",",
"4",
")",
"# Within the payload",
"NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION",
"=",
"4",
"NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD",
"=",
"1",
"RTU_TO_ASCII_PAYLOAD_FACTOR",
"=",
"2",
"NUMBER_OF_RTU_RESPONSE_STARTBYTES",
"=",
"2",
"NUMBER_OF_RTU_RESPONSE_ENDBYTES",
"=",
"2",
"NUMBER_OF_ASCII_RESPONSE_STARTBYTES",
"=",
"5",
"NUMBER_OF_ASCII_RESPONSE_ENDBYTES",
"=",
"4",
"# Argument validity testing",
"_checkMode",
"(",
"mode",
")",
"_checkFunctioncode",
"(",
"functioncode",
",",
"None",
")",
"_checkString",
"(",
"payloadToSlave",
",",
"description",
"=",
"'payload'",
",",
"minlength",
"=",
"MIN_PAYLOAD_LENGTH",
")",
"# Calculate payload size",
"if",
"functioncode",
"in",
"[",
"5",
",",
"6",
",",
"15",
",",
"16",
"]",
":",
"response_payload_size",
"=",
"NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION",
"elif",
"functioncode",
"in",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
"]",
":",
"given_size",
"=",
"_twoByteStringToNum",
"(",
"payloadToSlave",
"[",
"BYTERANGE_FOR_GIVEN_SIZE",
"]",
")",
"if",
"functioncode",
"==",
"1",
"or",
"functioncode",
"==",
"2",
":",
"# Algorithm from MODBUS APPLICATION PROTOCOL SPECIFICATION V1.1b",
"number_of_inputs",
"=",
"given_size",
"response_payload_size",
"=",
"NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD",
"+",
"number_of_inputs",
"//",
"8",
"+",
"(",
"1",
"if",
"number_of_inputs",
"%",
"8",
"else",
"0",
")",
"elif",
"functioncode",
"==",
"3",
"or",
"functioncode",
"==",
"4",
":",
"number_of_registers",
"=",
"given_size",
"response_payload_size",
"=",
"NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD",
"+",
"number_of_registers",
"*",
"_NUMBER_OF_BYTES_PER_REGISTER",
"else",
":",
"raise",
"ValueError",
"(",
"'Wrong functioncode: {}. The payload is: {!r}'",
".",
"format",
"(",
"functioncode",
",",
"payloadToSlave",
")",
")",
"# Calculate number of bytes to read",
"if",
"mode",
"==",
"MODE_ASCII",
":",
"return",
"NUMBER_OF_ASCII_RESPONSE_STARTBYTES",
"+",
"response_payload_size",
"*",
"RTU_TO_ASCII_PAYLOAD_FACTOR",
"+",
"NUMBER_OF_ASCII_RESPONSE_ENDBYTES",
"else",
":",
"return",
"NUMBER_OF_RTU_RESPONSE_STARTBYTES",
"+",
"response_payload_size",
"+",
"NUMBER_OF_RTU_RESPONSE_ENDBYTES"
] | Calculate the number of bytes that should be received from the slave.
Args:
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): Modbus function code.
* payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string)
Returns:
The preducted number of bytes (int) in the response.
Raises:
ValueError, TypeError. | [
"Calculate",
"the",
"number",
"of",
"bytes",
"that",
"should",
"be",
"received",
"from",
"the",
"slave",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1110-L1172 |
5,934 | pyhys/minimalmodbus | minimalmodbus.py | _calculate_minimum_silent_period | def _calculate_minimum_silent_period(baudrate):
"""Calculate the silent period length to comply with the 3.5 character silence between messages.
Args:
baudrate (numerical): The baudrate for the serial port
Returns:
The number of seconds (float) that should pass between each message on the bus.
Raises:
ValueError, TypeError.
"""
_checkNumerical(baudrate, minvalue=1, description='baudrate') # Avoid division by zero
BITTIMES_PER_CHARACTERTIME = 11
MINIMUM_SILENT_CHARACTERTIMES = 3.5
bittime = 1 / float(baudrate)
return bittime * BITTIMES_PER_CHARACTERTIME * MINIMUM_SILENT_CHARACTERTIMES | python | def _calculate_minimum_silent_period(baudrate):
"""Calculate the silent period length to comply with the 3.5 character silence between messages.
Args:
baudrate (numerical): The baudrate for the serial port
Returns:
The number of seconds (float) that should pass between each message on the bus.
Raises:
ValueError, TypeError.
"""
_checkNumerical(baudrate, minvalue=1, description='baudrate') # Avoid division by zero
BITTIMES_PER_CHARACTERTIME = 11
MINIMUM_SILENT_CHARACTERTIMES = 3.5
bittime = 1 / float(baudrate)
return bittime * BITTIMES_PER_CHARACTERTIME * MINIMUM_SILENT_CHARACTERTIMES | [
"def",
"_calculate_minimum_silent_period",
"(",
"baudrate",
")",
":",
"_checkNumerical",
"(",
"baudrate",
",",
"minvalue",
"=",
"1",
",",
"description",
"=",
"'baudrate'",
")",
"# Avoid division by zero",
"BITTIMES_PER_CHARACTERTIME",
"=",
"11",
"MINIMUM_SILENT_CHARACTERTIMES",
"=",
"3.5",
"bittime",
"=",
"1",
"/",
"float",
"(",
"baudrate",
")",
"return",
"bittime",
"*",
"BITTIMES_PER_CHARACTERTIME",
"*",
"MINIMUM_SILENT_CHARACTERTIMES"
] | Calculate the silent period length to comply with the 3.5 character silence between messages.
Args:
baudrate (numerical): The baudrate for the serial port
Returns:
The number of seconds (float) that should pass between each message on the bus.
Raises:
ValueError, TypeError. | [
"Calculate",
"the",
"silent",
"period",
"length",
"to",
"comply",
"with",
"the",
"3",
".",
"5",
"character",
"silence",
"between",
"messages",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1175-L1194 |
5,935 | pyhys/minimalmodbus | minimalmodbus.py | _numToTwoByteString | def _numToTwoByteString(value, numberOfDecimals=0, LsbFirst=False, signed=False):
"""Convert a numerical value to a two-byte string, possibly scaling it.
Args:
* value (float or int): The numerical value to be converted.
* numberOfDecimals (int): Number of decimals, 0 or more, for scaling.
* LsbFirst (bol): Whether the least significant byte should be first in the resulting string.
* signed (bol): Whether negative values should be accepted.
Returns:
A two-byte string.
Raises:
TypeError, ValueError. Gives DeprecationWarning instead of ValueError
for some values in Python 2.6.
Use ``numberOfDecimals=1`` to multiply ``value`` by 10 before sending it to the slave register.
Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register.
Use the parameter ``signed=True`` if making a bytestring that can hold
negative values. Then negative input will be automatically converted into
upper range data (two's complement).
The byte order is controlled by the ``LsbFirst`` parameter, as seen here:
====================== ============= ====================================
``LsbFirst`` parameter Endianness Description
====================== ============= ====================================
False (default) Big-endian Most significant byte is sent first
True Little-endian Least significant byte is sent first
====================== ============= ====================================
For example:
To store for example value=77.0, use ``numberOfDecimals = 1`` if the register will hold it as 770 internally.
The value 770 (dec) is 0302 (hex), where the most significant byte is 03 (hex) and the
least significant byte is 02 (hex). With ``LsbFirst = False``, the most significant byte is given first
why the resulting string is ``\\x03\\x02``, which has the length 2.
"""
_checkNumerical(value, description='inputvalue')
_checkInt(numberOfDecimals, minvalue=0, description='number of decimals')
_checkBool(LsbFirst, description='LsbFirst')
_checkBool(signed, description='signed parameter')
multiplier = 10 ** numberOfDecimals
integer = int(float(value) * multiplier)
if LsbFirst:
formatcode = '<' # Little-endian
else:
formatcode = '>' # Big-endian
if signed:
formatcode += 'h' # (Signed) short (2 bytes)
else:
formatcode += 'H' # Unsigned short (2 bytes)
outstring = _pack(formatcode, integer)
assert len(outstring) == 2
return outstring | python | def _numToTwoByteString(value, numberOfDecimals=0, LsbFirst=False, signed=False):
"""Convert a numerical value to a two-byte string, possibly scaling it.
Args:
* value (float or int): The numerical value to be converted.
* numberOfDecimals (int): Number of decimals, 0 or more, for scaling.
* LsbFirst (bol): Whether the least significant byte should be first in the resulting string.
* signed (bol): Whether negative values should be accepted.
Returns:
A two-byte string.
Raises:
TypeError, ValueError. Gives DeprecationWarning instead of ValueError
for some values in Python 2.6.
Use ``numberOfDecimals=1`` to multiply ``value`` by 10 before sending it to the slave register.
Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register.
Use the parameter ``signed=True`` if making a bytestring that can hold
negative values. Then negative input will be automatically converted into
upper range data (two's complement).
The byte order is controlled by the ``LsbFirst`` parameter, as seen here:
====================== ============= ====================================
``LsbFirst`` parameter Endianness Description
====================== ============= ====================================
False (default) Big-endian Most significant byte is sent first
True Little-endian Least significant byte is sent first
====================== ============= ====================================
For example:
To store for example value=77.0, use ``numberOfDecimals = 1`` if the register will hold it as 770 internally.
The value 770 (dec) is 0302 (hex), where the most significant byte is 03 (hex) and the
least significant byte is 02 (hex). With ``LsbFirst = False``, the most significant byte is given first
why the resulting string is ``\\x03\\x02``, which has the length 2.
"""
_checkNumerical(value, description='inputvalue')
_checkInt(numberOfDecimals, minvalue=0, description='number of decimals')
_checkBool(LsbFirst, description='LsbFirst')
_checkBool(signed, description='signed parameter')
multiplier = 10 ** numberOfDecimals
integer = int(float(value) * multiplier)
if LsbFirst:
formatcode = '<' # Little-endian
else:
formatcode = '>' # Big-endian
if signed:
formatcode += 'h' # (Signed) short (2 bytes)
else:
formatcode += 'H' # Unsigned short (2 bytes)
outstring = _pack(formatcode, integer)
assert len(outstring) == 2
return outstring | [
"def",
"_numToTwoByteString",
"(",
"value",
",",
"numberOfDecimals",
"=",
"0",
",",
"LsbFirst",
"=",
"False",
",",
"signed",
"=",
"False",
")",
":",
"_checkNumerical",
"(",
"value",
",",
"description",
"=",
"'inputvalue'",
")",
"_checkInt",
"(",
"numberOfDecimals",
",",
"minvalue",
"=",
"0",
",",
"description",
"=",
"'number of decimals'",
")",
"_checkBool",
"(",
"LsbFirst",
",",
"description",
"=",
"'LsbFirst'",
")",
"_checkBool",
"(",
"signed",
",",
"description",
"=",
"'signed parameter'",
")",
"multiplier",
"=",
"10",
"**",
"numberOfDecimals",
"integer",
"=",
"int",
"(",
"float",
"(",
"value",
")",
"*",
"multiplier",
")",
"if",
"LsbFirst",
":",
"formatcode",
"=",
"'<'",
"# Little-endian",
"else",
":",
"formatcode",
"=",
"'>'",
"# Big-endian",
"if",
"signed",
":",
"formatcode",
"+=",
"'h'",
"# (Signed) short (2 bytes)",
"else",
":",
"formatcode",
"+=",
"'H'",
"# Unsigned short (2 bytes)",
"outstring",
"=",
"_pack",
"(",
"formatcode",
",",
"integer",
")",
"assert",
"len",
"(",
"outstring",
")",
"==",
"2",
"return",
"outstring"
] | Convert a numerical value to a two-byte string, possibly scaling it.
Args:
* value (float or int): The numerical value to be converted.
* numberOfDecimals (int): Number of decimals, 0 or more, for scaling.
* LsbFirst (bol): Whether the least significant byte should be first in the resulting string.
* signed (bol): Whether negative values should be accepted.
Returns:
A two-byte string.
Raises:
TypeError, ValueError. Gives DeprecationWarning instead of ValueError
for some values in Python 2.6.
Use ``numberOfDecimals=1`` to multiply ``value`` by 10 before sending it to the slave register.
Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register.
Use the parameter ``signed=True`` if making a bytestring that can hold
negative values. Then negative input will be automatically converted into
upper range data (two's complement).
The byte order is controlled by the ``LsbFirst`` parameter, as seen here:
====================== ============= ====================================
``LsbFirst`` parameter Endianness Description
====================== ============= ====================================
False (default) Big-endian Most significant byte is sent first
True Little-endian Least significant byte is sent first
====================== ============= ====================================
For example:
To store for example value=77.0, use ``numberOfDecimals = 1`` if the register will hold it as 770 internally.
The value 770 (dec) is 0302 (hex), where the most significant byte is 03 (hex) and the
least significant byte is 02 (hex). With ``LsbFirst = False``, the most significant byte is given first
why the resulting string is ``\\x03\\x02``, which has the length 2. | [
"Convert",
"a",
"numerical",
"value",
"to",
"a",
"two",
"-",
"byte",
"string",
"possibly",
"scaling",
"it",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1219-L1277 |
5,936 | pyhys/minimalmodbus | minimalmodbus.py | _twoByteStringToNum | def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False):
"""Convert a two-byte string to a numerical value, possibly scaling it.
Args:
* bytestring (str): A string of length 2.
* numberOfDecimals (int): The number of decimals. Defaults to 0.
* signed (bol): Whether large positive values should be interpreted as negative values.
Returns:
The numerical value (int or float) calculated from the ``bytestring``.
Raises:
TypeError, ValueError
Use the parameter ``signed=True`` if converting a bytestring that can hold
negative values. Then upper range data will be automatically converted into
negative return values (two's complement).
Use ``numberOfDecimals=1`` to divide the received data by 10 before returning the value.
Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value.
The byte order is big-endian, meaning that the most significant byte is sent first.
For example:
A string ``\\x03\\x02`` (which has the length 2) corresponds to 0302 (hex) = 770 (dec). If
``numberOfDecimals = 1``, then this is converted to 77.0 (float).
"""
_checkString(bytestring, minlength=2, maxlength=2, description='bytestring')
_checkInt(numberOfDecimals, minvalue=0, description='number of decimals')
_checkBool(signed, description='signed parameter')
formatcode = '>' # Big-endian
if signed:
formatcode += 'h' # (Signed) short (2 bytes)
else:
formatcode += 'H' # Unsigned short (2 bytes)
fullregister = _unpack(formatcode, bytestring)
if numberOfDecimals == 0:
return fullregister
divisor = 10 ** numberOfDecimals
return fullregister / float(divisor) | python | def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False):
"""Convert a two-byte string to a numerical value, possibly scaling it.
Args:
* bytestring (str): A string of length 2.
* numberOfDecimals (int): The number of decimals. Defaults to 0.
* signed (bol): Whether large positive values should be interpreted as negative values.
Returns:
The numerical value (int or float) calculated from the ``bytestring``.
Raises:
TypeError, ValueError
Use the parameter ``signed=True`` if converting a bytestring that can hold
negative values. Then upper range data will be automatically converted into
negative return values (two's complement).
Use ``numberOfDecimals=1`` to divide the received data by 10 before returning the value.
Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value.
The byte order is big-endian, meaning that the most significant byte is sent first.
For example:
A string ``\\x03\\x02`` (which has the length 2) corresponds to 0302 (hex) = 770 (dec). If
``numberOfDecimals = 1``, then this is converted to 77.0 (float).
"""
_checkString(bytestring, minlength=2, maxlength=2, description='bytestring')
_checkInt(numberOfDecimals, minvalue=0, description='number of decimals')
_checkBool(signed, description='signed parameter')
formatcode = '>' # Big-endian
if signed:
formatcode += 'h' # (Signed) short (2 bytes)
else:
formatcode += 'H' # Unsigned short (2 bytes)
fullregister = _unpack(formatcode, bytestring)
if numberOfDecimals == 0:
return fullregister
divisor = 10 ** numberOfDecimals
return fullregister / float(divisor) | [
"def",
"_twoByteStringToNum",
"(",
"bytestring",
",",
"numberOfDecimals",
"=",
"0",
",",
"signed",
"=",
"False",
")",
":",
"_checkString",
"(",
"bytestring",
",",
"minlength",
"=",
"2",
",",
"maxlength",
"=",
"2",
",",
"description",
"=",
"'bytestring'",
")",
"_checkInt",
"(",
"numberOfDecimals",
",",
"minvalue",
"=",
"0",
",",
"description",
"=",
"'number of decimals'",
")",
"_checkBool",
"(",
"signed",
",",
"description",
"=",
"'signed parameter'",
")",
"formatcode",
"=",
"'>'",
"# Big-endian",
"if",
"signed",
":",
"formatcode",
"+=",
"'h'",
"# (Signed) short (2 bytes)",
"else",
":",
"formatcode",
"+=",
"'H'",
"# Unsigned short (2 bytes)",
"fullregister",
"=",
"_unpack",
"(",
"formatcode",
",",
"bytestring",
")",
"if",
"numberOfDecimals",
"==",
"0",
":",
"return",
"fullregister",
"divisor",
"=",
"10",
"**",
"numberOfDecimals",
"return",
"fullregister",
"/",
"float",
"(",
"divisor",
")"
] | Convert a two-byte string to a numerical value, possibly scaling it.
Args:
* bytestring (str): A string of length 2.
* numberOfDecimals (int): The number of decimals. Defaults to 0.
* signed (bol): Whether large positive values should be interpreted as negative values.
Returns:
The numerical value (int or float) calculated from the ``bytestring``.
Raises:
TypeError, ValueError
Use the parameter ``signed=True`` if converting a bytestring that can hold
negative values. Then upper range data will be automatically converted into
negative return values (two's complement).
Use ``numberOfDecimals=1`` to divide the received data by 10 before returning the value.
Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value.
The byte order is big-endian, meaning that the most significant byte is sent first.
For example:
A string ``\\x03\\x02`` (which has the length 2) corresponds to 0302 (hex) = 770 (dec). If
``numberOfDecimals = 1``, then this is converted to 77.0 (float). | [
"Convert",
"a",
"two",
"-",
"byte",
"string",
"to",
"a",
"numerical",
"value",
"possibly",
"scaling",
"it",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1280-L1323 |
5,937 | pyhys/minimalmodbus | minimalmodbus.py | _pack | def _pack(formatstring, value):
"""Pack a value into a bytestring.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* value (depends on formatstring): The value to be packed
Returns:
A bytestring (str).
Raises:
ValueError
Note that the :mod:`struct` module produces byte buffers for Python3,
but bytestrings for Python2. This is compensated for automatically.
"""
_checkString(formatstring, description='formatstring', minlength=1)
try:
result = struct.pack(formatstring, value)
except:
errortext = 'The value to send is probably out of range, as the num-to-bytestring conversion failed.'
errortext += ' Value: {0!r} Struct format code is: {1}'
raise ValueError(errortext.format(value, formatstring))
if sys.version_info[0] > 2:
return str(result, encoding='latin1') # Convert types to make it Python3 compatible
return result | python | def _pack(formatstring, value):
"""Pack a value into a bytestring.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* value (depends on formatstring): The value to be packed
Returns:
A bytestring (str).
Raises:
ValueError
Note that the :mod:`struct` module produces byte buffers for Python3,
but bytestrings for Python2. This is compensated for automatically.
"""
_checkString(formatstring, description='formatstring', minlength=1)
try:
result = struct.pack(formatstring, value)
except:
errortext = 'The value to send is probably out of range, as the num-to-bytestring conversion failed.'
errortext += ' Value: {0!r} Struct format code is: {1}'
raise ValueError(errortext.format(value, formatstring))
if sys.version_info[0] > 2:
return str(result, encoding='latin1') # Convert types to make it Python3 compatible
return result | [
"def",
"_pack",
"(",
"formatstring",
",",
"value",
")",
":",
"_checkString",
"(",
"formatstring",
",",
"description",
"=",
"'formatstring'",
",",
"minlength",
"=",
"1",
")",
"try",
":",
"result",
"=",
"struct",
".",
"pack",
"(",
"formatstring",
",",
"value",
")",
"except",
":",
"errortext",
"=",
"'The value to send is probably out of range, as the num-to-bytestring conversion failed.'",
"errortext",
"+=",
"' Value: {0!r} Struct format code is: {1}'",
"raise",
"ValueError",
"(",
"errortext",
".",
"format",
"(",
"value",
",",
"formatstring",
")",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"return",
"str",
"(",
"result",
",",
"encoding",
"=",
"'latin1'",
")",
"# Convert types to make it Python3 compatible",
"return",
"result"
] | Pack a value into a bytestring.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* value (depends on formatstring): The value to be packed
Returns:
A bytestring (str).
Raises:
ValueError
Note that the :mod:`struct` module produces byte buffers for Python3,
but bytestrings for Python2. This is compensated for automatically. | [
"Pack",
"a",
"value",
"into",
"a",
"bytestring",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1597-L1627 |
5,938 | pyhys/minimalmodbus | minimalmodbus.py | _unpack | def _unpack(formatstring, packed):
"""Unpack a bytestring into a value.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* packed (str): The bytestring to be unpacked.
Returns:
A value. The type depends on the formatstring.
Raises:
ValueError
Note that the :mod:`struct` module wants byte buffers for Python3,
but bytestrings for Python2. This is compensated for automatically.
"""
_checkString(formatstring, description='formatstring', minlength=1)
_checkString(packed, description='packed string', minlength=1)
if sys.version_info[0] > 2:
packed = bytes(packed, encoding='latin1') # Convert types to make it Python3 compatible
try:
value = struct.unpack(formatstring, packed)[0]
except:
errortext = 'The received bytestring is probably wrong, as the bytestring-to-num conversion failed.'
errortext += ' Bytestring: {0!r} Struct format code is: {1}'
raise ValueError(errortext.format(packed, formatstring))
return value | python | def _unpack(formatstring, packed):
"""Unpack a bytestring into a value.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* packed (str): The bytestring to be unpacked.
Returns:
A value. The type depends on the formatstring.
Raises:
ValueError
Note that the :mod:`struct` module wants byte buffers for Python3,
but bytestrings for Python2. This is compensated for automatically.
"""
_checkString(formatstring, description='formatstring', minlength=1)
_checkString(packed, description='packed string', minlength=1)
if sys.version_info[0] > 2:
packed = bytes(packed, encoding='latin1') # Convert types to make it Python3 compatible
try:
value = struct.unpack(formatstring, packed)[0]
except:
errortext = 'The received bytestring is probably wrong, as the bytestring-to-num conversion failed.'
errortext += ' Bytestring: {0!r} Struct format code is: {1}'
raise ValueError(errortext.format(packed, formatstring))
return value | [
"def",
"_unpack",
"(",
"formatstring",
",",
"packed",
")",
":",
"_checkString",
"(",
"formatstring",
",",
"description",
"=",
"'formatstring'",
",",
"minlength",
"=",
"1",
")",
"_checkString",
"(",
"packed",
",",
"description",
"=",
"'packed string'",
",",
"minlength",
"=",
"1",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"packed",
"=",
"bytes",
"(",
"packed",
",",
"encoding",
"=",
"'latin1'",
")",
"# Convert types to make it Python3 compatible",
"try",
":",
"value",
"=",
"struct",
".",
"unpack",
"(",
"formatstring",
",",
"packed",
")",
"[",
"0",
"]",
"except",
":",
"errortext",
"=",
"'The received bytestring is probably wrong, as the bytestring-to-num conversion failed.'",
"errortext",
"+=",
"' Bytestring: {0!r} Struct format code is: {1}'",
"raise",
"ValueError",
"(",
"errortext",
".",
"format",
"(",
"packed",
",",
"formatstring",
")",
")",
"return",
"value"
] | Unpack a bytestring into a value.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* packed (str): The bytestring to be unpacked.
Returns:
A value. The type depends on the formatstring.
Raises:
ValueError
Note that the :mod:`struct` module wants byte buffers for Python3,
but bytestrings for Python2. This is compensated for automatically. | [
"Unpack",
"a",
"bytestring",
"into",
"a",
"value",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1630-L1662 |
5,939 | pyhys/minimalmodbus | minimalmodbus.py | _hexencode | def _hexencode(bytestring, insert_spaces = False):
"""Convert a byte string to a hex encoded string.
For example 'J' will return '4A', and ``'\\x04'`` will return '04'.
Args:
bytestring (str): Can be for example ``'A\\x01B\\x45'``.
insert_spaces (bool): Insert space characters between pair of characters to increase readability.
Returns:
A string of twice the length, with characters in the range '0' to '9' and 'A' to 'F'.
The string will be longer if spaces are inserted.
Raises:
TypeError, ValueError
"""
_checkString(bytestring, description='byte string')
separator = '' if not insert_spaces else ' '
# Use plain string formatting instead of binhex.hexlify,
# in order to have it Python 2.x and 3.x compatible
byte_representions = []
for c in bytestring:
byte_representions.append( '{0:02X}'.format(ord(c)) )
return separator.join(byte_representions).strip() | python | def _hexencode(bytestring, insert_spaces = False):
"""Convert a byte string to a hex encoded string.
For example 'J' will return '4A', and ``'\\x04'`` will return '04'.
Args:
bytestring (str): Can be for example ``'A\\x01B\\x45'``.
insert_spaces (bool): Insert space characters between pair of characters to increase readability.
Returns:
A string of twice the length, with characters in the range '0' to '9' and 'A' to 'F'.
The string will be longer if spaces are inserted.
Raises:
TypeError, ValueError
"""
_checkString(bytestring, description='byte string')
separator = '' if not insert_spaces else ' '
# Use plain string formatting instead of binhex.hexlify,
# in order to have it Python 2.x and 3.x compatible
byte_representions = []
for c in bytestring:
byte_representions.append( '{0:02X}'.format(ord(c)) )
return separator.join(byte_representions).strip() | [
"def",
"_hexencode",
"(",
"bytestring",
",",
"insert_spaces",
"=",
"False",
")",
":",
"_checkString",
"(",
"bytestring",
",",
"description",
"=",
"'byte string'",
")",
"separator",
"=",
"''",
"if",
"not",
"insert_spaces",
"else",
"' '",
"# Use plain string formatting instead of binhex.hexlify,",
"# in order to have it Python 2.x and 3.x compatible",
"byte_representions",
"=",
"[",
"]",
"for",
"c",
"in",
"bytestring",
":",
"byte_representions",
".",
"append",
"(",
"'{0:02X}'",
".",
"format",
"(",
"ord",
"(",
"c",
")",
")",
")",
"return",
"separator",
".",
"join",
"(",
"byte_representions",
")",
".",
"strip",
"(",
")"
] | Convert a byte string to a hex encoded string.
For example 'J' will return '4A', and ``'\\x04'`` will return '04'.
Args:
bytestring (str): Can be for example ``'A\\x01B\\x45'``.
insert_spaces (bool): Insert space characters between pair of characters to increase readability.
Returns:
A string of twice the length, with characters in the range '0' to '9' and 'A' to 'F'.
The string will be longer if spaces are inserted.
Raises:
TypeError, ValueError | [
"Convert",
"a",
"byte",
"string",
"to",
"a",
"hex",
"encoded",
"string",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1665-L1692 |
5,940 | pyhys/minimalmodbus | minimalmodbus.py | _hexdecode | def _hexdecode(hexstring):
"""Convert a hex encoded string to a byte string.
For example '4A' will return 'J', and '04' will return ``'\\x04'`` (which has length 1).
Args:
hexstring (str): Can be for example 'A3' or 'A3B4'. Must be of even length.
Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space).
Returns:
A string of half the length, with characters corresponding to all 0-255 values for each byte.
Raises:
TypeError, ValueError
"""
# Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err
# but the Python2 interpreter will indicate SyntaxError.
# Thus we need to live with this warning in Python3:
# 'During handling of the above exception, another exception occurred'
_checkString(hexstring, description='hexstring')
if len(hexstring) % 2 != 0:
raise ValueError('The input hexstring must be of even length. Given: {!r}'.format(hexstring))
if sys.version_info[0] > 2:
by = bytes(hexstring, 'latin1')
try:
return str(binascii.unhexlify(by), encoding='latin1')
except binascii.Error as err:
new_error_message = 'Hexdecode reported an error: {!s}. Input hexstring: {}'.format(err.args[0], hexstring)
raise TypeError(new_error_message)
else:
try:
return hexstring.decode('hex')
except TypeError as err:
raise TypeError('Hexdecode reported an error: {}. Input hexstring: {}'.format(err.message, hexstring)) | python | def _hexdecode(hexstring):
"""Convert a hex encoded string to a byte string.
For example '4A' will return 'J', and '04' will return ``'\\x04'`` (which has length 1).
Args:
hexstring (str): Can be for example 'A3' or 'A3B4'. Must be of even length.
Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space).
Returns:
A string of half the length, with characters corresponding to all 0-255 values for each byte.
Raises:
TypeError, ValueError
"""
# Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err
# but the Python2 interpreter will indicate SyntaxError.
# Thus we need to live with this warning in Python3:
# 'During handling of the above exception, another exception occurred'
_checkString(hexstring, description='hexstring')
if len(hexstring) % 2 != 0:
raise ValueError('The input hexstring must be of even length. Given: {!r}'.format(hexstring))
if sys.version_info[0] > 2:
by = bytes(hexstring, 'latin1')
try:
return str(binascii.unhexlify(by), encoding='latin1')
except binascii.Error as err:
new_error_message = 'Hexdecode reported an error: {!s}. Input hexstring: {}'.format(err.args[0], hexstring)
raise TypeError(new_error_message)
else:
try:
return hexstring.decode('hex')
except TypeError as err:
raise TypeError('Hexdecode reported an error: {}. Input hexstring: {}'.format(err.message, hexstring)) | [
"def",
"_hexdecode",
"(",
"hexstring",
")",
":",
"# Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err",
"# but the Python2 interpreter will indicate SyntaxError.",
"# Thus we need to live with this warning in Python3:",
"# 'During handling of the above exception, another exception occurred'",
"_checkString",
"(",
"hexstring",
",",
"description",
"=",
"'hexstring'",
")",
"if",
"len",
"(",
"hexstring",
")",
"%",
"2",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'The input hexstring must be of even length. Given: {!r}'",
".",
"format",
"(",
"hexstring",
")",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"by",
"=",
"bytes",
"(",
"hexstring",
",",
"'latin1'",
")",
"try",
":",
"return",
"str",
"(",
"binascii",
".",
"unhexlify",
"(",
"by",
")",
",",
"encoding",
"=",
"'latin1'",
")",
"except",
"binascii",
".",
"Error",
"as",
"err",
":",
"new_error_message",
"=",
"'Hexdecode reported an error: {!s}. Input hexstring: {}'",
".",
"format",
"(",
"err",
".",
"args",
"[",
"0",
"]",
",",
"hexstring",
")",
"raise",
"TypeError",
"(",
"new_error_message",
")",
"else",
":",
"try",
":",
"return",
"hexstring",
".",
"decode",
"(",
"'hex'",
")",
"except",
"TypeError",
"as",
"err",
":",
"raise",
"TypeError",
"(",
"'Hexdecode reported an error: {}. Input hexstring: {}'",
".",
"format",
"(",
"err",
".",
"message",
",",
"hexstring",
")",
")"
] | Convert a hex encoded string to a byte string.
For example '4A' will return 'J', and '04' will return ``'\\x04'`` (which has length 1).
Args:
hexstring (str): Can be for example 'A3' or 'A3B4'. Must be of even length.
Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space).
Returns:
A string of half the length, with characters corresponding to all 0-255 values for each byte.
Raises:
TypeError, ValueError | [
"Convert",
"a",
"hex",
"encoded",
"string",
"to",
"a",
"byte",
"string",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1695-L1733 |
5,941 | pyhys/minimalmodbus | minimalmodbus.py | _bitResponseToValue | def _bitResponseToValue(bytestring):
"""Convert a response string to a numerical value.
Args:
bytestring (str): A string of length 1. Can be for example ``\\x01``.
Returns:
The converted value (int).
Raises:
TypeError, ValueError
"""
_checkString(bytestring, description='bytestring', minlength=1, maxlength=1)
RESPONSE_ON = '\x01'
RESPONSE_OFF = '\x00'
if bytestring == RESPONSE_ON:
return 1
elif bytestring == RESPONSE_OFF:
return 0
else:
raise ValueError('Could not convert bit response to a value. Input: {0!r}'.format(bytestring)) | python | def _bitResponseToValue(bytestring):
"""Convert a response string to a numerical value.
Args:
bytestring (str): A string of length 1. Can be for example ``\\x01``.
Returns:
The converted value (int).
Raises:
TypeError, ValueError
"""
_checkString(bytestring, description='bytestring', minlength=1, maxlength=1)
RESPONSE_ON = '\x01'
RESPONSE_OFF = '\x00'
if bytestring == RESPONSE_ON:
return 1
elif bytestring == RESPONSE_OFF:
return 0
else:
raise ValueError('Could not convert bit response to a value. Input: {0!r}'.format(bytestring)) | [
"def",
"_bitResponseToValue",
"(",
"bytestring",
")",
":",
"_checkString",
"(",
"bytestring",
",",
"description",
"=",
"'bytestring'",
",",
"minlength",
"=",
"1",
",",
"maxlength",
"=",
"1",
")",
"RESPONSE_ON",
"=",
"'\\x01'",
"RESPONSE_OFF",
"=",
"'\\x00'",
"if",
"bytestring",
"==",
"RESPONSE_ON",
":",
"return",
"1",
"elif",
"bytestring",
"==",
"RESPONSE_OFF",
":",
"return",
"0",
"else",
":",
"raise",
"ValueError",
"(",
"'Could not convert bit response to a value. Input: {0!r}'",
".",
"format",
"(",
"bytestring",
")",
")"
] | Convert a response string to a numerical value.
Args:
bytestring (str): A string of length 1. Can be for example ``\\x01``.
Returns:
The converted value (int).
Raises:
TypeError, ValueError | [
"Convert",
"a",
"response",
"string",
"to",
"a",
"numerical",
"value",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1747-L1770 |
5,942 | pyhys/minimalmodbus | minimalmodbus.py | _createBitpattern | def _createBitpattern(functioncode, value):
"""Create the bit pattern that is used for writing single bits.
This is basically a storage of numerical constants.
Args:
* functioncode (int): can be 5 or 15
* value (int): can be 0 or 1
Returns:
The bit pattern (string).
Raises:
TypeError, ValueError
"""
_checkFunctioncode(functioncode, [5, 15])
_checkInt(value, minvalue=0, maxvalue=1, description='inputvalue')
if functioncode == 5:
if value == 0:
return '\x00\x00'
else:
return '\xff\x00'
elif functioncode == 15:
if value == 0:
return '\x00'
else:
return '\x01' | python | def _createBitpattern(functioncode, value):
"""Create the bit pattern that is used for writing single bits.
This is basically a storage of numerical constants.
Args:
* functioncode (int): can be 5 or 15
* value (int): can be 0 or 1
Returns:
The bit pattern (string).
Raises:
TypeError, ValueError
"""
_checkFunctioncode(functioncode, [5, 15])
_checkInt(value, minvalue=0, maxvalue=1, description='inputvalue')
if functioncode == 5:
if value == 0:
return '\x00\x00'
else:
return '\xff\x00'
elif functioncode == 15:
if value == 0:
return '\x00'
else:
return '\x01' | [
"def",
"_createBitpattern",
"(",
"functioncode",
",",
"value",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"5",
",",
"15",
"]",
")",
"_checkInt",
"(",
"value",
",",
"minvalue",
"=",
"0",
",",
"maxvalue",
"=",
"1",
",",
"description",
"=",
"'inputvalue'",
")",
"if",
"functioncode",
"==",
"5",
":",
"if",
"value",
"==",
"0",
":",
"return",
"'\\x00\\x00'",
"else",
":",
"return",
"'\\xff\\x00'",
"elif",
"functioncode",
"==",
"15",
":",
"if",
"value",
"==",
"0",
":",
"return",
"'\\x00'",
"else",
":",
"return",
"'\\x01'"
] | Create the bit pattern that is used for writing single bits.
This is basically a storage of numerical constants.
Args:
* functioncode (int): can be 5 or 15
* value (int): can be 0 or 1
Returns:
The bit pattern (string).
Raises:
TypeError, ValueError | [
"Create",
"the",
"bit",
"pattern",
"that",
"is",
"used",
"for",
"writing",
"single",
"bits",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1773-L1802 |
5,943 | pyhys/minimalmodbus | minimalmodbus.py | _twosComplement | def _twosComplement(x, bits=16):
"""Calculate the two's complement of an integer.
Then also negative values can be represented by an upper range of positive values.
See https://en.wikipedia.org/wiki/Two%27s_complement
Args:
* x (int): input integer.
* bits (int): number of bits, must be > 0.
Returns:
An int, that represents the two's complement of the input.
Example for bits=8:
==== =======
x returns
==== =======
0 0
1 1
127 127
-128 128
-127 129
-1 255
==== =======
"""
_checkInt(bits, minvalue=0, description='number of bits')
_checkInt(x, description='input')
upperlimit = 2 ** (bits - 1) - 1
lowerlimit = -2 ** (bits - 1)
if x > upperlimit or x < lowerlimit:
raise ValueError('The input value is out of range. Given value is {0}, but allowed range is {1} to {2} when using {3} bits.' \
.format(x, lowerlimit, upperlimit, bits))
# Calculate two'2 complement
if x >= 0:
return x
return x + 2 ** bits | python | def _twosComplement(x, bits=16):
"""Calculate the two's complement of an integer.
Then also negative values can be represented by an upper range of positive values.
See https://en.wikipedia.org/wiki/Two%27s_complement
Args:
* x (int): input integer.
* bits (int): number of bits, must be > 0.
Returns:
An int, that represents the two's complement of the input.
Example for bits=8:
==== =======
x returns
==== =======
0 0
1 1
127 127
-128 128
-127 129
-1 255
==== =======
"""
_checkInt(bits, minvalue=0, description='number of bits')
_checkInt(x, description='input')
upperlimit = 2 ** (bits - 1) - 1
lowerlimit = -2 ** (bits - 1)
if x > upperlimit or x < lowerlimit:
raise ValueError('The input value is out of range. Given value is {0}, but allowed range is {1} to {2} when using {3} bits.' \
.format(x, lowerlimit, upperlimit, bits))
# Calculate two'2 complement
if x >= 0:
return x
return x + 2 ** bits | [
"def",
"_twosComplement",
"(",
"x",
",",
"bits",
"=",
"16",
")",
":",
"_checkInt",
"(",
"bits",
",",
"minvalue",
"=",
"0",
",",
"description",
"=",
"'number of bits'",
")",
"_checkInt",
"(",
"x",
",",
"description",
"=",
"'input'",
")",
"upperlimit",
"=",
"2",
"**",
"(",
"bits",
"-",
"1",
")",
"-",
"1",
"lowerlimit",
"=",
"-",
"2",
"**",
"(",
"bits",
"-",
"1",
")",
"if",
"x",
">",
"upperlimit",
"or",
"x",
"<",
"lowerlimit",
":",
"raise",
"ValueError",
"(",
"'The input value is out of range. Given value is {0}, but allowed range is {1} to {2} when using {3} bits.'",
".",
"format",
"(",
"x",
",",
"lowerlimit",
",",
"upperlimit",
",",
"bits",
")",
")",
"# Calculate two'2 complement",
"if",
"x",
">=",
"0",
":",
"return",
"x",
"return",
"x",
"+",
"2",
"**",
"bits"
] | Calculate the two's complement of an integer.
Then also negative values can be represented by an upper range of positive values.
See https://en.wikipedia.org/wiki/Two%27s_complement
Args:
* x (int): input integer.
* bits (int): number of bits, must be > 0.
Returns:
An int, that represents the two's complement of the input.
Example for bits=8:
==== =======
x returns
==== =======
0 0
1 1
127 127
-128 128
-127 129
-1 255
==== ======= | [
"Calculate",
"the",
"two",
"s",
"complement",
"of",
"an",
"integer",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1809-L1847 |
5,944 | pyhys/minimalmodbus | minimalmodbus.py | _setBitOn | def _setBitOn(x, bitNum):
"""Set bit 'bitNum' to True.
Args:
* x (int): The value before.
* bitNum (int): The bit number that should be set to True.
Returns:
The value after setting the bit. This is an integer.
For example:
For x = 4 (dec) = 0100 (bin), setting bit number 0 results in 0101 (bin) = 5 (dec).
"""
_checkInt(x, minvalue=0, description='input value')
_checkInt(bitNum, minvalue=0, description='bitnumber')
return x | (1 << bitNum) | python | def _setBitOn(x, bitNum):
"""Set bit 'bitNum' to True.
Args:
* x (int): The value before.
* bitNum (int): The bit number that should be set to True.
Returns:
The value after setting the bit. This is an integer.
For example:
For x = 4 (dec) = 0100 (bin), setting bit number 0 results in 0101 (bin) = 5 (dec).
"""
_checkInt(x, minvalue=0, description='input value')
_checkInt(bitNum, minvalue=0, description='bitnumber')
return x | (1 << bitNum) | [
"def",
"_setBitOn",
"(",
"x",
",",
"bitNum",
")",
":",
"_checkInt",
"(",
"x",
",",
"minvalue",
"=",
"0",
",",
"description",
"=",
"'input value'",
")",
"_checkInt",
"(",
"bitNum",
",",
"minvalue",
"=",
"0",
",",
"description",
"=",
"'bitnumber'",
")",
"return",
"x",
"|",
"(",
"1",
"<<",
"bitNum",
")"
] | Set bit 'bitNum' to True.
Args:
* x (int): The value before.
* bitNum (int): The bit number that should be set to True.
Returns:
The value after setting the bit. This is an integer.
For example:
For x = 4 (dec) = 0100 (bin), setting bit number 0 results in 0101 (bin) = 5 (dec). | [
"Set",
"bit",
"bitNum",
"to",
"True",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1893-L1910 |
5,945 | pyhys/minimalmodbus | minimalmodbus.py | _calculateCrcString | def _calculateCrcString(inputstring):
"""Calculate CRC-16 for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the CRC).
Returns:
A two-byte CRC string, where the least significant byte is first.
"""
_checkString(inputstring, description='input CRC string')
# Preload a 16-bit register with ones
register = 0xFFFF
for char in inputstring:
register = (register >> 8) ^ _CRC16TABLE[(register ^ ord(char)) & 0xFF]
return _numToTwoByteString(register, LsbFirst=True) | python | def _calculateCrcString(inputstring):
"""Calculate CRC-16 for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the CRC).
Returns:
A two-byte CRC string, where the least significant byte is first.
"""
_checkString(inputstring, description='input CRC string')
# Preload a 16-bit register with ones
register = 0xFFFF
for char in inputstring:
register = (register >> 8) ^ _CRC16TABLE[(register ^ ord(char)) & 0xFF]
return _numToTwoByteString(register, LsbFirst=True) | [
"def",
"_calculateCrcString",
"(",
"inputstring",
")",
":",
"_checkString",
"(",
"inputstring",
",",
"description",
"=",
"'input CRC string'",
")",
"# Preload a 16-bit register with ones",
"register",
"=",
"0xFFFF",
"for",
"char",
"in",
"inputstring",
":",
"register",
"=",
"(",
"register",
">>",
"8",
")",
"^",
"_CRC16TABLE",
"[",
"(",
"register",
"^",
"ord",
"(",
"char",
")",
")",
"&",
"0xFF",
"]",
"return",
"_numToTwoByteString",
"(",
"register",
",",
"LsbFirst",
"=",
"True",
")"
] | Calculate CRC-16 for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the CRC).
Returns:
A two-byte CRC string, where the least significant byte is first. | [
"Calculate",
"CRC",
"-",
"16",
"for",
"Modbus",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1965-L1983 |
5,946 | pyhys/minimalmodbus | minimalmodbus.py | _calculateLrcString | def _calculateLrcString(inputstring):
"""Calculate LRC for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the beginning
colon and terminating CRLF). It should already be decoded from hex-string.
Returns:
A one-byte LRC bytestring (not encoded to hex-string)
Algorithm from the document 'MODBUS over serial line specification and implementation guide V1.02'.
The LRC is calculated as 8 bits (one byte).
For example a LRC 0110 0001 (bin) = 61 (hex) = 97 (dec) = 'a'. This function will
then return 'a'.
In Modbus ASCII mode, this should be transmitted using two characters. This
example should be transmitted '61', which is a string of length two. This function
does not handle that conversion for transmission.
"""
_checkString(inputstring, description='input LRC string')
register = 0
for character in inputstring:
register += ord(character)
lrc = ((register ^ 0xFF) + 1) & 0xFF
lrcString = _numToOneByteString(lrc)
return lrcString | python | def _calculateLrcString(inputstring):
"""Calculate LRC for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the beginning
colon and terminating CRLF). It should already be decoded from hex-string.
Returns:
A one-byte LRC bytestring (not encoded to hex-string)
Algorithm from the document 'MODBUS over serial line specification and implementation guide V1.02'.
The LRC is calculated as 8 bits (one byte).
For example a LRC 0110 0001 (bin) = 61 (hex) = 97 (dec) = 'a'. This function will
then return 'a'.
In Modbus ASCII mode, this should be transmitted using two characters. This
example should be transmitted '61', which is a string of length two. This function
does not handle that conversion for transmission.
"""
_checkString(inputstring, description='input LRC string')
register = 0
for character in inputstring:
register += ord(character)
lrc = ((register ^ 0xFF) + 1) & 0xFF
lrcString = _numToOneByteString(lrc)
return lrcString | [
"def",
"_calculateLrcString",
"(",
"inputstring",
")",
":",
"_checkString",
"(",
"inputstring",
",",
"description",
"=",
"'input LRC string'",
")",
"register",
"=",
"0",
"for",
"character",
"in",
"inputstring",
":",
"register",
"+=",
"ord",
"(",
"character",
")",
"lrc",
"=",
"(",
"(",
"register",
"^",
"0xFF",
")",
"+",
"1",
")",
"&",
"0xFF",
"lrcString",
"=",
"_numToOneByteString",
"(",
"lrc",
")",
"return",
"lrcString"
] | Calculate LRC for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the beginning
colon and terminating CRLF). It should already be decoded from hex-string.
Returns:
A one-byte LRC bytestring (not encoded to hex-string)
Algorithm from the document 'MODBUS over serial line specification and implementation guide V1.02'.
The LRC is calculated as 8 bits (one byte).
For example a LRC 0110 0001 (bin) = 61 (hex) = 97 (dec) = 'a'. This function will
then return 'a'.
In Modbus ASCII mode, this should be transmitted using two characters. This
example should be transmitted '61', which is a string of length two. This function
does not handle that conversion for transmission. | [
"Calculate",
"LRC",
"for",
"Modbus",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1986-L2016 |
5,947 | pyhys/minimalmodbus | minimalmodbus.py | _checkMode | def _checkMode(mode):
"""Check that the Modbus mode is valie.
Args:
mode (string): The Modbus mode (MODE_RTU or MODE_ASCII)
Raises:
TypeError, ValueError
"""
if not isinstance(mode, str):
raise TypeError('The {0} should be a string. Given: {1!r}'.format("mode", mode))
if mode not in [MODE_RTU, MODE_ASCII]:
raise ValueError("Unreconized Modbus mode given. Must be 'rtu' or 'ascii' but {0!r} was given.".format(mode)) | python | def _checkMode(mode):
"""Check that the Modbus mode is valie.
Args:
mode (string): The Modbus mode (MODE_RTU or MODE_ASCII)
Raises:
TypeError, ValueError
"""
if not isinstance(mode, str):
raise TypeError('The {0} should be a string. Given: {1!r}'.format("mode", mode))
if mode not in [MODE_RTU, MODE_ASCII]:
raise ValueError("Unreconized Modbus mode given. Must be 'rtu' or 'ascii' but {0!r} was given.".format(mode)) | [
"def",
"_checkMode",
"(",
"mode",
")",
":",
"if",
"not",
"isinstance",
"(",
"mode",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'The {0} should be a string. Given: {1!r}'",
".",
"format",
"(",
"\"mode\"",
",",
"mode",
")",
")",
"if",
"mode",
"not",
"in",
"[",
"MODE_RTU",
",",
"MODE_ASCII",
"]",
":",
"raise",
"ValueError",
"(",
"\"Unreconized Modbus mode given. Must be 'rtu' or 'ascii' but {0!r} was given.\"",
".",
"format",
"(",
"mode",
")",
")"
] | Check that the Modbus mode is valie.
Args:
mode (string): The Modbus mode (MODE_RTU or MODE_ASCII)
Raises:
TypeError, ValueError | [
"Check",
"that",
"the",
"Modbus",
"mode",
"is",
"valie",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2019-L2034 |
5,948 | pyhys/minimalmodbus | minimalmodbus.py | _checkFunctioncode | def _checkFunctioncode(functioncode, listOfAllowedValues=[]):
"""Check that the given functioncode is in the listOfAllowedValues.
Also verifies that 1 <= function code <= 127.
Args:
* functioncode (int): The function code
* listOfAllowedValues (list of int): Allowed values. Use *None* to bypass this part of the checking.
Raises:
TypeError, ValueError
"""
FUNCTIONCODE_MIN = 1
FUNCTIONCODE_MAX = 127
_checkInt(functioncode, FUNCTIONCODE_MIN, FUNCTIONCODE_MAX, description='functioncode')
if listOfAllowedValues is None:
return
if not isinstance(listOfAllowedValues, list):
raise TypeError('The listOfAllowedValues should be a list. Given: {0!r}'.format(listOfAllowedValues))
for value in listOfAllowedValues:
_checkInt(value, FUNCTIONCODE_MIN, FUNCTIONCODE_MAX, description='functioncode inside listOfAllowedValues')
if functioncode not in listOfAllowedValues:
raise ValueError('Wrong function code: {0}, allowed values are {1!r}'.format(functioncode, listOfAllowedValues)) | python | def _checkFunctioncode(functioncode, listOfAllowedValues=[]):
"""Check that the given functioncode is in the listOfAllowedValues.
Also verifies that 1 <= function code <= 127.
Args:
* functioncode (int): The function code
* listOfAllowedValues (list of int): Allowed values. Use *None* to bypass this part of the checking.
Raises:
TypeError, ValueError
"""
FUNCTIONCODE_MIN = 1
FUNCTIONCODE_MAX = 127
_checkInt(functioncode, FUNCTIONCODE_MIN, FUNCTIONCODE_MAX, description='functioncode')
if listOfAllowedValues is None:
return
if not isinstance(listOfAllowedValues, list):
raise TypeError('The listOfAllowedValues should be a list. Given: {0!r}'.format(listOfAllowedValues))
for value in listOfAllowedValues:
_checkInt(value, FUNCTIONCODE_MIN, FUNCTIONCODE_MAX, description='functioncode inside listOfAllowedValues')
if functioncode not in listOfAllowedValues:
raise ValueError('Wrong function code: {0}, allowed values are {1!r}'.format(functioncode, listOfAllowedValues)) | [
"def",
"_checkFunctioncode",
"(",
"functioncode",
",",
"listOfAllowedValues",
"=",
"[",
"]",
")",
":",
"FUNCTIONCODE_MIN",
"=",
"1",
"FUNCTIONCODE_MAX",
"=",
"127",
"_checkInt",
"(",
"functioncode",
",",
"FUNCTIONCODE_MIN",
",",
"FUNCTIONCODE_MAX",
",",
"description",
"=",
"'functioncode'",
")",
"if",
"listOfAllowedValues",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"listOfAllowedValues",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'The listOfAllowedValues should be a list. Given: {0!r}'",
".",
"format",
"(",
"listOfAllowedValues",
")",
")",
"for",
"value",
"in",
"listOfAllowedValues",
":",
"_checkInt",
"(",
"value",
",",
"FUNCTIONCODE_MIN",
",",
"FUNCTIONCODE_MAX",
",",
"description",
"=",
"'functioncode inside listOfAllowedValues'",
")",
"if",
"functioncode",
"not",
"in",
"listOfAllowedValues",
":",
"raise",
"ValueError",
"(",
"'Wrong function code: {0}, allowed values are {1!r}'",
".",
"format",
"(",
"functioncode",
",",
"listOfAllowedValues",
")",
")"
] | Check that the given functioncode is in the listOfAllowedValues.
Also verifies that 1 <= function code <= 127.
Args:
* functioncode (int): The function code
* listOfAllowedValues (list of int): Allowed values. Use *None* to bypass this part of the checking.
Raises:
TypeError, ValueError | [
"Check",
"that",
"the",
"given",
"functioncode",
"is",
"in",
"the",
"listOfAllowedValues",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2037-L2065 |
5,949 | pyhys/minimalmodbus | minimalmodbus.py | _checkResponseByteCount | def _checkResponseByteCount(payload):
"""Check that the number of bytes as given in the response is correct.
The first byte in the payload indicates the length of the payload (first byte not counted).
Args:
payload (string): The payload
Raises:
TypeError, ValueError
"""
POSITION_FOR_GIVEN_NUMBER = 0
NUMBER_OF_BYTES_TO_SKIP = 1
_checkString(payload, minlength=1, description='payload')
givenNumberOfDatabytes = ord(payload[POSITION_FOR_GIVEN_NUMBER])
countedNumberOfDatabytes = len(payload) - NUMBER_OF_BYTES_TO_SKIP
if givenNumberOfDatabytes != countedNumberOfDatabytes:
errortemplate = 'Wrong given number of bytes in the response: {0}, but counted is {1} as data payload length is {2}.' + \
' The data payload is: {3!r}'
errortext = errortemplate.format(givenNumberOfDatabytes, countedNumberOfDatabytes, len(payload), payload)
raise ValueError(errortext) | python | def _checkResponseByteCount(payload):
"""Check that the number of bytes as given in the response is correct.
The first byte in the payload indicates the length of the payload (first byte not counted).
Args:
payload (string): The payload
Raises:
TypeError, ValueError
"""
POSITION_FOR_GIVEN_NUMBER = 0
NUMBER_OF_BYTES_TO_SKIP = 1
_checkString(payload, minlength=1, description='payload')
givenNumberOfDatabytes = ord(payload[POSITION_FOR_GIVEN_NUMBER])
countedNumberOfDatabytes = len(payload) - NUMBER_OF_BYTES_TO_SKIP
if givenNumberOfDatabytes != countedNumberOfDatabytes:
errortemplate = 'Wrong given number of bytes in the response: {0}, but counted is {1} as data payload length is {2}.' + \
' The data payload is: {3!r}'
errortext = errortemplate.format(givenNumberOfDatabytes, countedNumberOfDatabytes, len(payload), payload)
raise ValueError(errortext) | [
"def",
"_checkResponseByteCount",
"(",
"payload",
")",
":",
"POSITION_FOR_GIVEN_NUMBER",
"=",
"0",
"NUMBER_OF_BYTES_TO_SKIP",
"=",
"1",
"_checkString",
"(",
"payload",
",",
"minlength",
"=",
"1",
",",
"description",
"=",
"'payload'",
")",
"givenNumberOfDatabytes",
"=",
"ord",
"(",
"payload",
"[",
"POSITION_FOR_GIVEN_NUMBER",
"]",
")",
"countedNumberOfDatabytes",
"=",
"len",
"(",
"payload",
")",
"-",
"NUMBER_OF_BYTES_TO_SKIP",
"if",
"givenNumberOfDatabytes",
"!=",
"countedNumberOfDatabytes",
":",
"errortemplate",
"=",
"'Wrong given number of bytes in the response: {0}, but counted is {1} as data payload length is {2}.'",
"+",
"' The data payload is: {3!r}'",
"errortext",
"=",
"errortemplate",
".",
"format",
"(",
"givenNumberOfDatabytes",
",",
"countedNumberOfDatabytes",
",",
"len",
"(",
"payload",
")",
",",
"payload",
")",
"raise",
"ValueError",
"(",
"errortext",
")"
] | Check that the number of bytes as given in the response is correct.
The first byte in the payload indicates the length of the payload (first byte not counted).
Args:
payload (string): The payload
Raises:
TypeError, ValueError | [
"Check",
"that",
"the",
"number",
"of",
"bytes",
"as",
"given",
"in",
"the",
"response",
"is",
"correct",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2100-L2124 |
5,950 | pyhys/minimalmodbus | minimalmodbus.py | _checkResponseRegisterAddress | def _checkResponseRegisterAddress(payload, registeraddress):
"""Check that the start adress as given in the response is correct.
The first two bytes in the payload holds the address value.
Args:
* payload (string): The payload
* registeraddress (int): The register address (use decimal numbers, not hex).
Raises:
TypeError, ValueError
"""
_checkString(payload, minlength=2, description='payload')
_checkRegisteraddress(registeraddress)
BYTERANGE_FOR_STARTADDRESS = slice(0, 2)
bytesForStartAddress = payload[BYTERANGE_FOR_STARTADDRESS]
receivedStartAddress = _twoByteStringToNum(bytesForStartAddress)
if receivedStartAddress != registeraddress:
raise ValueError('Wrong given write start adress: {0}, but commanded is {1}. The data payload is: {2!r}'.format( \
receivedStartAddress, registeraddress, payload)) | python | def _checkResponseRegisterAddress(payload, registeraddress):
"""Check that the start adress as given in the response is correct.
The first two bytes in the payload holds the address value.
Args:
* payload (string): The payload
* registeraddress (int): The register address (use decimal numbers, not hex).
Raises:
TypeError, ValueError
"""
_checkString(payload, minlength=2, description='payload')
_checkRegisteraddress(registeraddress)
BYTERANGE_FOR_STARTADDRESS = slice(0, 2)
bytesForStartAddress = payload[BYTERANGE_FOR_STARTADDRESS]
receivedStartAddress = _twoByteStringToNum(bytesForStartAddress)
if receivedStartAddress != registeraddress:
raise ValueError('Wrong given write start adress: {0}, but commanded is {1}. The data payload is: {2!r}'.format( \
receivedStartAddress, registeraddress, payload)) | [
"def",
"_checkResponseRegisterAddress",
"(",
"payload",
",",
"registeraddress",
")",
":",
"_checkString",
"(",
"payload",
",",
"minlength",
"=",
"2",
",",
"description",
"=",
"'payload'",
")",
"_checkRegisteraddress",
"(",
"registeraddress",
")",
"BYTERANGE_FOR_STARTADDRESS",
"=",
"slice",
"(",
"0",
",",
"2",
")",
"bytesForStartAddress",
"=",
"payload",
"[",
"BYTERANGE_FOR_STARTADDRESS",
"]",
"receivedStartAddress",
"=",
"_twoByteStringToNum",
"(",
"bytesForStartAddress",
")",
"if",
"receivedStartAddress",
"!=",
"registeraddress",
":",
"raise",
"ValueError",
"(",
"'Wrong given write start adress: {0}, but commanded is {1}. The data payload is: {2!r}'",
".",
"format",
"(",
"receivedStartAddress",
",",
"registeraddress",
",",
"payload",
")",
")"
] | Check that the start adress as given in the response is correct.
The first two bytes in the payload holds the address value.
Args:
* payload (string): The payload
* registeraddress (int): The register address (use decimal numbers, not hex).
Raises:
TypeError, ValueError | [
"Check",
"that",
"the",
"start",
"adress",
"as",
"given",
"in",
"the",
"response",
"is",
"correct",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2127-L2150 |
5,951 | pyhys/minimalmodbus | minimalmodbus.py | _checkResponseNumberOfRegisters | def _checkResponseNumberOfRegisters(payload, numberOfRegisters):
"""Check that the number of written registers as given in the response is correct.
The bytes 2 and 3 (zero based counting) in the payload holds the value.
Args:
* payload (string): The payload
* numberOfRegisters (int): Number of registers that have been written
Raises:
TypeError, ValueError
"""
_checkString(payload, minlength=4, description='payload')
_checkInt(numberOfRegisters, minvalue=1, maxvalue=0xFFFF, description='numberOfRegisters')
BYTERANGE_FOR_NUMBER_OF_REGISTERS = slice(2, 4)
bytesForNumberOfRegisters = payload[BYTERANGE_FOR_NUMBER_OF_REGISTERS]
receivedNumberOfWrittenReisters = _twoByteStringToNum(bytesForNumberOfRegisters)
if receivedNumberOfWrittenReisters != numberOfRegisters:
raise ValueError('Wrong number of registers to write in the response: {0}, but commanded is {1}. The data payload is: {2!r}'.format( \
receivedNumberOfWrittenReisters, numberOfRegisters, payload)) | python | def _checkResponseNumberOfRegisters(payload, numberOfRegisters):
"""Check that the number of written registers as given in the response is correct.
The bytes 2 and 3 (zero based counting) in the payload holds the value.
Args:
* payload (string): The payload
* numberOfRegisters (int): Number of registers that have been written
Raises:
TypeError, ValueError
"""
_checkString(payload, minlength=4, description='payload')
_checkInt(numberOfRegisters, minvalue=1, maxvalue=0xFFFF, description='numberOfRegisters')
BYTERANGE_FOR_NUMBER_OF_REGISTERS = slice(2, 4)
bytesForNumberOfRegisters = payload[BYTERANGE_FOR_NUMBER_OF_REGISTERS]
receivedNumberOfWrittenReisters = _twoByteStringToNum(bytesForNumberOfRegisters)
if receivedNumberOfWrittenReisters != numberOfRegisters:
raise ValueError('Wrong number of registers to write in the response: {0}, but commanded is {1}. The data payload is: {2!r}'.format( \
receivedNumberOfWrittenReisters, numberOfRegisters, payload)) | [
"def",
"_checkResponseNumberOfRegisters",
"(",
"payload",
",",
"numberOfRegisters",
")",
":",
"_checkString",
"(",
"payload",
",",
"minlength",
"=",
"4",
",",
"description",
"=",
"'payload'",
")",
"_checkInt",
"(",
"numberOfRegisters",
",",
"minvalue",
"=",
"1",
",",
"maxvalue",
"=",
"0xFFFF",
",",
"description",
"=",
"'numberOfRegisters'",
")",
"BYTERANGE_FOR_NUMBER_OF_REGISTERS",
"=",
"slice",
"(",
"2",
",",
"4",
")",
"bytesForNumberOfRegisters",
"=",
"payload",
"[",
"BYTERANGE_FOR_NUMBER_OF_REGISTERS",
"]",
"receivedNumberOfWrittenReisters",
"=",
"_twoByteStringToNum",
"(",
"bytesForNumberOfRegisters",
")",
"if",
"receivedNumberOfWrittenReisters",
"!=",
"numberOfRegisters",
":",
"raise",
"ValueError",
"(",
"'Wrong number of registers to write in the response: {0}, but commanded is {1}. The data payload is: {2!r}'",
".",
"format",
"(",
"receivedNumberOfWrittenReisters",
",",
"numberOfRegisters",
",",
"payload",
")",
")"
] | Check that the number of written registers as given in the response is correct.
The bytes 2 and 3 (zero based counting) in the payload holds the value.
Args:
* payload (string): The payload
* numberOfRegisters (int): Number of registers that have been written
Raises:
TypeError, ValueError | [
"Check",
"that",
"the",
"number",
"of",
"written",
"registers",
"as",
"given",
"in",
"the",
"response",
"is",
"correct",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2153-L2176 |
5,952 | pyhys/minimalmodbus | minimalmodbus.py | _checkResponseWriteData | def _checkResponseWriteData(payload, writedata):
"""Check that the write data as given in the response is correct.
The bytes 2 and 3 (zero based counting) in the payload holds the write data.
Args:
* payload (string): The payload
* writedata (string): The data to write, length should be 2 bytes.
Raises:
TypeError, ValueError
"""
_checkString(payload, minlength=4, description='payload')
_checkString(writedata, minlength=2, maxlength=2, description='writedata')
BYTERANGE_FOR_WRITEDATA = slice(2, 4)
receivedWritedata = payload[BYTERANGE_FOR_WRITEDATA]
if receivedWritedata != writedata:
raise ValueError('Wrong write data in the response: {0!r}, but commanded is {1!r}. The data payload is: {2!r}'.format( \
receivedWritedata, writedata, payload)) | python | def _checkResponseWriteData(payload, writedata):
"""Check that the write data as given in the response is correct.
The bytes 2 and 3 (zero based counting) in the payload holds the write data.
Args:
* payload (string): The payload
* writedata (string): The data to write, length should be 2 bytes.
Raises:
TypeError, ValueError
"""
_checkString(payload, minlength=4, description='payload')
_checkString(writedata, minlength=2, maxlength=2, description='writedata')
BYTERANGE_FOR_WRITEDATA = slice(2, 4)
receivedWritedata = payload[BYTERANGE_FOR_WRITEDATA]
if receivedWritedata != writedata:
raise ValueError('Wrong write data in the response: {0!r}, but commanded is {1!r}. The data payload is: {2!r}'.format( \
receivedWritedata, writedata, payload)) | [
"def",
"_checkResponseWriteData",
"(",
"payload",
",",
"writedata",
")",
":",
"_checkString",
"(",
"payload",
",",
"minlength",
"=",
"4",
",",
"description",
"=",
"'payload'",
")",
"_checkString",
"(",
"writedata",
",",
"minlength",
"=",
"2",
",",
"maxlength",
"=",
"2",
",",
"description",
"=",
"'writedata'",
")",
"BYTERANGE_FOR_WRITEDATA",
"=",
"slice",
"(",
"2",
",",
"4",
")",
"receivedWritedata",
"=",
"payload",
"[",
"BYTERANGE_FOR_WRITEDATA",
"]",
"if",
"receivedWritedata",
"!=",
"writedata",
":",
"raise",
"ValueError",
"(",
"'Wrong write data in the response: {0!r}, but commanded is {1!r}. The data payload is: {2!r}'",
".",
"format",
"(",
"receivedWritedata",
",",
"writedata",
",",
"payload",
")",
")"
] | Check that the write data as given in the response is correct.
The bytes 2 and 3 (zero based counting) in the payload holds the write data.
Args:
* payload (string): The payload
* writedata (string): The data to write, length should be 2 bytes.
Raises:
TypeError, ValueError | [
"Check",
"that",
"the",
"write",
"data",
"as",
"given",
"in",
"the",
"response",
"is",
"correct",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2179-L2201 |
5,953 | pyhys/minimalmodbus | minimalmodbus.py | _checkString | def _checkString(inputstring, description, minlength=0, maxlength=None):
"""Check that the given string is valid.
Args:
* inputstring (string): The string to be checked
* description (string): Used in error messages for the checked inputstring
* minlength (int): Minimum length of the string
* maxlength (int or None): Maximum length of the string
Raises:
TypeError, ValueError
Uses the function :func:`_checkInt` internally.
"""
# Type checking
if not isinstance(description, str):
raise TypeError('The description should be a string. Given: {0!r}'.format(description))
if not isinstance(inputstring, str):
raise TypeError('The {0} should be a string. Given: {1!r}'.format(description, inputstring))
if not isinstance(maxlength, (int, type(None))):
raise TypeError('The maxlength must be an integer or None. Given: {0!r}'.format(maxlength))
# Check values
_checkInt(minlength, minvalue=0, maxvalue=None, description='minlength')
if len(inputstring) < minlength:
raise ValueError('The {0} is too short: {1}, but minimum value is {2}. Given: {3!r}'.format( \
description, len(inputstring), minlength, inputstring))
if not maxlength is None:
if maxlength < 0:
raise ValueError('The maxlength must be positive. Given: {0}'.format(maxlength))
if maxlength < minlength:
raise ValueError('The maxlength must not be smaller than minlength. Given: {0} and {1}'.format( \
maxlength, minlength))
if len(inputstring) > maxlength:
raise ValueError('The {0} is too long: {1}, but maximum value is {2}. Given: {3!r}'.format( \
description, len(inputstring), maxlength, inputstring)) | python | def _checkString(inputstring, description, minlength=0, maxlength=None):
"""Check that the given string is valid.
Args:
* inputstring (string): The string to be checked
* description (string): Used in error messages for the checked inputstring
* minlength (int): Minimum length of the string
* maxlength (int or None): Maximum length of the string
Raises:
TypeError, ValueError
Uses the function :func:`_checkInt` internally.
"""
# Type checking
if not isinstance(description, str):
raise TypeError('The description should be a string. Given: {0!r}'.format(description))
if not isinstance(inputstring, str):
raise TypeError('The {0} should be a string. Given: {1!r}'.format(description, inputstring))
if not isinstance(maxlength, (int, type(None))):
raise TypeError('The maxlength must be an integer or None. Given: {0!r}'.format(maxlength))
# Check values
_checkInt(minlength, minvalue=0, maxvalue=None, description='minlength')
if len(inputstring) < minlength:
raise ValueError('The {0} is too short: {1}, but minimum value is {2}. Given: {3!r}'.format( \
description, len(inputstring), minlength, inputstring))
if not maxlength is None:
if maxlength < 0:
raise ValueError('The maxlength must be positive. Given: {0}'.format(maxlength))
if maxlength < minlength:
raise ValueError('The maxlength must not be smaller than minlength. Given: {0} and {1}'.format( \
maxlength, minlength))
if len(inputstring) > maxlength:
raise ValueError('The {0} is too long: {1}, but maximum value is {2}. Given: {3!r}'.format( \
description, len(inputstring), maxlength, inputstring)) | [
"def",
"_checkString",
"(",
"inputstring",
",",
"description",
",",
"minlength",
"=",
"0",
",",
"maxlength",
"=",
"None",
")",
":",
"# Type checking",
"if",
"not",
"isinstance",
"(",
"description",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'The description should be a string. Given: {0!r}'",
".",
"format",
"(",
"description",
")",
")",
"if",
"not",
"isinstance",
"(",
"inputstring",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'The {0} should be a string. Given: {1!r}'",
".",
"format",
"(",
"description",
",",
"inputstring",
")",
")",
"if",
"not",
"isinstance",
"(",
"maxlength",
",",
"(",
"int",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The maxlength must be an integer or None. Given: {0!r}'",
".",
"format",
"(",
"maxlength",
")",
")",
"# Check values",
"_checkInt",
"(",
"minlength",
",",
"minvalue",
"=",
"0",
",",
"maxvalue",
"=",
"None",
",",
"description",
"=",
"'minlength'",
")",
"if",
"len",
"(",
"inputstring",
")",
"<",
"minlength",
":",
"raise",
"ValueError",
"(",
"'The {0} is too short: {1}, but minimum value is {2}. Given: {3!r}'",
".",
"format",
"(",
"description",
",",
"len",
"(",
"inputstring",
")",
",",
"minlength",
",",
"inputstring",
")",
")",
"if",
"not",
"maxlength",
"is",
"None",
":",
"if",
"maxlength",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'The maxlength must be positive. Given: {0}'",
".",
"format",
"(",
"maxlength",
")",
")",
"if",
"maxlength",
"<",
"minlength",
":",
"raise",
"ValueError",
"(",
"'The maxlength must not be smaller than minlength. Given: {0} and {1}'",
".",
"format",
"(",
"maxlength",
",",
"minlength",
")",
")",
"if",
"len",
"(",
"inputstring",
")",
">",
"maxlength",
":",
"raise",
"ValueError",
"(",
"'The {0} is too long: {1}, but maximum value is {2}. Given: {3!r}'",
".",
"format",
"(",
"description",
",",
"len",
"(",
"inputstring",
")",
",",
"maxlength",
",",
"inputstring",
")",
")"
] | Check that the given string is valid.
Args:
* inputstring (string): The string to be checked
* description (string): Used in error messages for the checked inputstring
* minlength (int): Minimum length of the string
* maxlength (int or None): Maximum length of the string
Raises:
TypeError, ValueError
Uses the function :func:`_checkInt` internally. | [
"Check",
"that",
"the",
"given",
"string",
"is",
"valid",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2204-L2246 |
5,954 | pyhys/minimalmodbus | minimalmodbus.py | _checkInt | def _checkInt(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'):
"""Check that the given integer is valid.
Args:
* inputvalue (int or long): The integer to be checked
* minvalue (int or long, or None): Minimum value of the integer
* maxvalue (int or long, or None): Maximum value of the integer
* description (string): Used in error messages for the checked inputvalue
Raises:
TypeError, ValueError
Note: Can not use the function :func:`_checkString`, as that function uses this function internally.
"""
if not isinstance(description, str):
raise TypeError('The description should be a string. Given: {0!r}'.format(description))
if not isinstance(inputvalue, (int, long)):
raise TypeError('The {0} must be an integer. Given: {1!r}'.format(description, inputvalue))
if not isinstance(minvalue, (int, long, type(None))):
raise TypeError('The minvalue must be an integer or None. Given: {0!r}'.format(minvalue))
if not isinstance(maxvalue, (int, long, type(None))):
raise TypeError('The maxvalue must be an integer or None. Given: {0!r}'.format(maxvalue))
_checkNumerical(inputvalue, minvalue, maxvalue, description) | python | def _checkInt(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'):
"""Check that the given integer is valid.
Args:
* inputvalue (int or long): The integer to be checked
* minvalue (int or long, or None): Minimum value of the integer
* maxvalue (int or long, or None): Maximum value of the integer
* description (string): Used in error messages for the checked inputvalue
Raises:
TypeError, ValueError
Note: Can not use the function :func:`_checkString`, as that function uses this function internally.
"""
if not isinstance(description, str):
raise TypeError('The description should be a string. Given: {0!r}'.format(description))
if not isinstance(inputvalue, (int, long)):
raise TypeError('The {0} must be an integer. Given: {1!r}'.format(description, inputvalue))
if not isinstance(minvalue, (int, long, type(None))):
raise TypeError('The minvalue must be an integer or None. Given: {0!r}'.format(minvalue))
if not isinstance(maxvalue, (int, long, type(None))):
raise TypeError('The maxvalue must be an integer or None. Given: {0!r}'.format(maxvalue))
_checkNumerical(inputvalue, minvalue, maxvalue, description) | [
"def",
"_checkInt",
"(",
"inputvalue",
",",
"minvalue",
"=",
"None",
",",
"maxvalue",
"=",
"None",
",",
"description",
"=",
"'inputvalue'",
")",
":",
"if",
"not",
"isinstance",
"(",
"description",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'The description should be a string. Given: {0!r}'",
".",
"format",
"(",
"description",
")",
")",
"if",
"not",
"isinstance",
"(",
"inputvalue",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The {0} must be an integer. Given: {1!r}'",
".",
"format",
"(",
"description",
",",
"inputvalue",
")",
")",
"if",
"not",
"isinstance",
"(",
"minvalue",
",",
"(",
"int",
",",
"long",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The minvalue must be an integer or None. Given: {0!r}'",
".",
"format",
"(",
"minvalue",
")",
")",
"if",
"not",
"isinstance",
"(",
"maxvalue",
",",
"(",
"int",
",",
"long",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The maxvalue must be an integer or None. Given: {0!r}'",
".",
"format",
"(",
"maxvalue",
")",
")",
"_checkNumerical",
"(",
"inputvalue",
",",
"minvalue",
",",
"maxvalue",
",",
"description",
")"
] | Check that the given integer is valid.
Args:
* inputvalue (int or long): The integer to be checked
* minvalue (int or long, or None): Minimum value of the integer
* maxvalue (int or long, or None): Maximum value of the integer
* description (string): Used in error messages for the checked inputvalue
Raises:
TypeError, ValueError
Note: Can not use the function :func:`_checkString`, as that function uses this function internally. | [
"Check",
"that",
"the",
"given",
"integer",
"is",
"valid",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2249-L2276 |
5,955 | pyhys/minimalmodbus | minimalmodbus.py | _checkNumerical | def _checkNumerical(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'):
"""Check that the given numerical value is valid.
Args:
* inputvalue (numerical): The value to be checked.
* minvalue (numerical): Minimum value Use None to skip this part of the test.
* maxvalue (numerical): Maximum value. Use None to skip this part of the test.
* description (string): Used in error messages for the checked inputvalue
Raises:
TypeError, ValueError
Note: Can not use the function :func:`_checkString`, as it uses this function internally.
"""
# Type checking
if not isinstance(description, str):
raise TypeError('The description should be a string. Given: {0!r}'.format(description))
if not isinstance(inputvalue, (int, long, float)):
raise TypeError('The {0} must be numerical. Given: {1!r}'.format(description, inputvalue))
if not isinstance(minvalue, (int, float, long, type(None))):
raise TypeError('The minvalue must be numeric or None. Given: {0!r}'.format(minvalue))
if not isinstance(maxvalue, (int, float, long, type(None))):
raise TypeError('The maxvalue must be numeric or None. Given: {0!r}'.format(maxvalue))
# Consistency checking
if (not minvalue is None) and (not maxvalue is None):
if maxvalue < minvalue:
raise ValueError('The maxvalue must not be smaller than minvalue. Given: {0} and {1}, respectively.'.format( \
maxvalue, minvalue))
# Value checking
if not minvalue is None:
if inputvalue < minvalue:
raise ValueError('The {0} is too small: {1}, but minimum value is {2}.'.format( \
description, inputvalue, minvalue))
if not maxvalue is None:
if inputvalue > maxvalue:
raise ValueError('The {0} is too large: {1}, but maximum value is {2}.'.format( \
description, inputvalue, maxvalue)) | python | def _checkNumerical(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'):
"""Check that the given numerical value is valid.
Args:
* inputvalue (numerical): The value to be checked.
* minvalue (numerical): Minimum value Use None to skip this part of the test.
* maxvalue (numerical): Maximum value. Use None to skip this part of the test.
* description (string): Used in error messages for the checked inputvalue
Raises:
TypeError, ValueError
Note: Can not use the function :func:`_checkString`, as it uses this function internally.
"""
# Type checking
if not isinstance(description, str):
raise TypeError('The description should be a string. Given: {0!r}'.format(description))
if not isinstance(inputvalue, (int, long, float)):
raise TypeError('The {0} must be numerical. Given: {1!r}'.format(description, inputvalue))
if not isinstance(minvalue, (int, float, long, type(None))):
raise TypeError('The minvalue must be numeric or None. Given: {0!r}'.format(minvalue))
if not isinstance(maxvalue, (int, float, long, type(None))):
raise TypeError('The maxvalue must be numeric or None. Given: {0!r}'.format(maxvalue))
# Consistency checking
if (not minvalue is None) and (not maxvalue is None):
if maxvalue < minvalue:
raise ValueError('The maxvalue must not be smaller than minvalue. Given: {0} and {1}, respectively.'.format( \
maxvalue, minvalue))
# Value checking
if not minvalue is None:
if inputvalue < minvalue:
raise ValueError('The {0} is too small: {1}, but minimum value is {2}.'.format( \
description, inputvalue, minvalue))
if not maxvalue is None:
if inputvalue > maxvalue:
raise ValueError('The {0} is too large: {1}, but maximum value is {2}.'.format( \
description, inputvalue, maxvalue)) | [
"def",
"_checkNumerical",
"(",
"inputvalue",
",",
"minvalue",
"=",
"None",
",",
"maxvalue",
"=",
"None",
",",
"description",
"=",
"'inputvalue'",
")",
":",
"# Type checking",
"if",
"not",
"isinstance",
"(",
"description",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'The description should be a string. Given: {0!r}'",
".",
"format",
"(",
"description",
")",
")",
"if",
"not",
"isinstance",
"(",
"inputvalue",
",",
"(",
"int",
",",
"long",
",",
"float",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The {0} must be numerical. Given: {1!r}'",
".",
"format",
"(",
"description",
",",
"inputvalue",
")",
")",
"if",
"not",
"isinstance",
"(",
"minvalue",
",",
"(",
"int",
",",
"float",
",",
"long",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The minvalue must be numeric or None. Given: {0!r}'",
".",
"format",
"(",
"minvalue",
")",
")",
"if",
"not",
"isinstance",
"(",
"maxvalue",
",",
"(",
"int",
",",
"float",
",",
"long",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The maxvalue must be numeric or None. Given: {0!r}'",
".",
"format",
"(",
"maxvalue",
")",
")",
"# Consistency checking",
"if",
"(",
"not",
"minvalue",
"is",
"None",
")",
"and",
"(",
"not",
"maxvalue",
"is",
"None",
")",
":",
"if",
"maxvalue",
"<",
"minvalue",
":",
"raise",
"ValueError",
"(",
"'The maxvalue must not be smaller than minvalue. Given: {0} and {1}, respectively.'",
".",
"format",
"(",
"maxvalue",
",",
"minvalue",
")",
")",
"# Value checking",
"if",
"not",
"minvalue",
"is",
"None",
":",
"if",
"inputvalue",
"<",
"minvalue",
":",
"raise",
"ValueError",
"(",
"'The {0} is too small: {1}, but minimum value is {2}.'",
".",
"format",
"(",
"description",
",",
"inputvalue",
",",
"minvalue",
")",
")",
"if",
"not",
"maxvalue",
"is",
"None",
":",
"if",
"inputvalue",
">",
"maxvalue",
":",
"raise",
"ValueError",
"(",
"'The {0} is too large: {1}, but maximum value is {2}.'",
".",
"format",
"(",
"description",
",",
"inputvalue",
",",
"maxvalue",
")",
")"
] | Check that the given numerical value is valid.
Args:
* inputvalue (numerical): The value to be checked.
* minvalue (numerical): Minimum value Use None to skip this part of the test.
* maxvalue (numerical): Maximum value. Use None to skip this part of the test.
* description (string): Used in error messages for the checked inputvalue
Raises:
TypeError, ValueError
Note: Can not use the function :func:`_checkString`, as it uses this function internally. | [
"Check",
"that",
"the",
"given",
"numerical",
"value",
"is",
"valid",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2279-L2322 |
5,956 | pyhys/minimalmodbus | minimalmodbus.py | _checkBool | def _checkBool(inputvalue, description='inputvalue'):
"""Check that the given inputvalue is a boolean.
Args:
* inputvalue (boolean): The value to be checked.
* description (string): Used in error messages for the checked inputvalue.
Raises:
TypeError, ValueError
"""
_checkString(description, minlength=1, description='description string')
if not isinstance(inputvalue, bool):
raise TypeError('The {0} must be boolean. Given: {1!r}'.format(description, inputvalue)) | python | def _checkBool(inputvalue, description='inputvalue'):
"""Check that the given inputvalue is a boolean.
Args:
* inputvalue (boolean): The value to be checked.
* description (string): Used in error messages for the checked inputvalue.
Raises:
TypeError, ValueError
"""
_checkString(description, minlength=1, description='description string')
if not isinstance(inputvalue, bool):
raise TypeError('The {0} must be boolean. Given: {1!r}'.format(description, inputvalue)) | [
"def",
"_checkBool",
"(",
"inputvalue",
",",
"description",
"=",
"'inputvalue'",
")",
":",
"_checkString",
"(",
"description",
",",
"minlength",
"=",
"1",
",",
"description",
"=",
"'description string'",
")",
"if",
"not",
"isinstance",
"(",
"inputvalue",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"'The {0} must be boolean. Given: {1!r}'",
".",
"format",
"(",
"description",
",",
"inputvalue",
")",
")"
] | Check that the given inputvalue is a boolean.
Args:
* inputvalue (boolean): The value to be checked.
* description (string): Used in error messages for the checked inputvalue.
Raises:
TypeError, ValueError | [
"Check",
"that",
"the",
"given",
"inputvalue",
"is",
"a",
"boolean",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2325-L2338 |
5,957 | pyhys/minimalmodbus | minimalmodbus.py | _getDiagnosticString | def _getDiagnosticString():
"""Generate a diagnostic string, showing the module version, the platform, current directory etc.
Returns:
A descriptive string.
"""
text = '\n## Diagnostic output from minimalmodbus ## \n\n'
text += 'Minimalmodbus version: ' + __version__ + '\n'
text += 'Minimalmodbus status: ' + __status__ + '\n'
text += 'File name (with relative path): ' + __file__ + '\n'
text += 'Full file path: ' + os.path.abspath(__file__) + '\n\n'
text += 'pySerial version: ' + serial.VERSION + '\n'
text += 'pySerial full file path: ' + os.path.abspath(serial.__file__) + '\n\n'
text += 'Platform: ' + sys.platform + '\n'
text += 'Filesystem encoding: ' + repr(sys.getfilesystemencoding()) + '\n'
text += 'Byteorder: ' + sys.byteorder + '\n'
text += 'Python version: ' + sys.version + '\n'
text += 'Python version info: ' + repr(sys.version_info) + '\n'
text += 'Python flags: ' + repr(sys.flags) + '\n'
text += 'Python argv: ' + repr(sys.argv) + '\n'
text += 'Python prefix: ' + repr(sys.prefix) + '\n'
text += 'Python exec prefix: ' + repr(sys.exec_prefix) + '\n'
text += 'Python executable: ' + repr(sys.executable) + '\n'
try:
text += 'Long info: ' + repr(sys.long_info) + '\n'
except:
text += 'Long info: (none)\n' # For Python3 compatibility
try:
text += 'Float repr style: ' + repr(sys.float_repr_style) + '\n\n'
except:
text += 'Float repr style: (none) \n\n' # For Python 2.6 compatibility
text += 'Variable __name__: ' + __name__ + '\n'
text += 'Current directory: ' + os.getcwd() + '\n\n'
text += 'Python path: \n'
text += '\n'.join(sys.path) + '\n'
text += '\n## End of diagnostic output ## \n'
return text | python | def _getDiagnosticString():
"""Generate a diagnostic string, showing the module version, the platform, current directory etc.
Returns:
A descriptive string.
"""
text = '\n## Diagnostic output from minimalmodbus ## \n\n'
text += 'Minimalmodbus version: ' + __version__ + '\n'
text += 'Minimalmodbus status: ' + __status__ + '\n'
text += 'File name (with relative path): ' + __file__ + '\n'
text += 'Full file path: ' + os.path.abspath(__file__) + '\n\n'
text += 'pySerial version: ' + serial.VERSION + '\n'
text += 'pySerial full file path: ' + os.path.abspath(serial.__file__) + '\n\n'
text += 'Platform: ' + sys.platform + '\n'
text += 'Filesystem encoding: ' + repr(sys.getfilesystemencoding()) + '\n'
text += 'Byteorder: ' + sys.byteorder + '\n'
text += 'Python version: ' + sys.version + '\n'
text += 'Python version info: ' + repr(sys.version_info) + '\n'
text += 'Python flags: ' + repr(sys.flags) + '\n'
text += 'Python argv: ' + repr(sys.argv) + '\n'
text += 'Python prefix: ' + repr(sys.prefix) + '\n'
text += 'Python exec prefix: ' + repr(sys.exec_prefix) + '\n'
text += 'Python executable: ' + repr(sys.executable) + '\n'
try:
text += 'Long info: ' + repr(sys.long_info) + '\n'
except:
text += 'Long info: (none)\n' # For Python3 compatibility
try:
text += 'Float repr style: ' + repr(sys.float_repr_style) + '\n\n'
except:
text += 'Float repr style: (none) \n\n' # For Python 2.6 compatibility
text += 'Variable __name__: ' + __name__ + '\n'
text += 'Current directory: ' + os.getcwd() + '\n\n'
text += 'Python path: \n'
text += '\n'.join(sys.path) + '\n'
text += '\n## End of diagnostic output ## \n'
return text | [
"def",
"_getDiagnosticString",
"(",
")",
":",
"text",
"=",
"'\\n## Diagnostic output from minimalmodbus ## \\n\\n'",
"text",
"+=",
"'Minimalmodbus version: '",
"+",
"__version__",
"+",
"'\\n'",
"text",
"+=",
"'Minimalmodbus status: '",
"+",
"__status__",
"+",
"'\\n'",
"text",
"+=",
"'File name (with relative path): '",
"+",
"__file__",
"+",
"'\\n'",
"text",
"+=",
"'Full file path: '",
"+",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
"+",
"'\\n\\n'",
"text",
"+=",
"'pySerial version: '",
"+",
"serial",
".",
"VERSION",
"+",
"'\\n'",
"text",
"+=",
"'pySerial full file path: '",
"+",
"os",
".",
"path",
".",
"abspath",
"(",
"serial",
".",
"__file__",
")",
"+",
"'\\n\\n'",
"text",
"+=",
"'Platform: '",
"+",
"sys",
".",
"platform",
"+",
"'\\n'",
"text",
"+=",
"'Filesystem encoding: '",
"+",
"repr",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
"+",
"'\\n'",
"text",
"+=",
"'Byteorder: '",
"+",
"sys",
".",
"byteorder",
"+",
"'\\n'",
"text",
"+=",
"'Python version: '",
"+",
"sys",
".",
"version",
"+",
"'\\n'",
"text",
"+=",
"'Python version info: '",
"+",
"repr",
"(",
"sys",
".",
"version_info",
")",
"+",
"'\\n'",
"text",
"+=",
"'Python flags: '",
"+",
"repr",
"(",
"sys",
".",
"flags",
")",
"+",
"'\\n'",
"text",
"+=",
"'Python argv: '",
"+",
"repr",
"(",
"sys",
".",
"argv",
")",
"+",
"'\\n'",
"text",
"+=",
"'Python prefix: '",
"+",
"repr",
"(",
"sys",
".",
"prefix",
")",
"+",
"'\\n'",
"text",
"+=",
"'Python exec prefix: '",
"+",
"repr",
"(",
"sys",
".",
"exec_prefix",
")",
"+",
"'\\n'",
"text",
"+=",
"'Python executable: '",
"+",
"repr",
"(",
"sys",
".",
"executable",
")",
"+",
"'\\n'",
"try",
":",
"text",
"+=",
"'Long info: '",
"+",
"repr",
"(",
"sys",
".",
"long_info",
")",
"+",
"'\\n'",
"except",
":",
"text",
"+=",
"'Long info: (none)\\n'",
"# For Python3 compatibility",
"try",
":",
"text",
"+=",
"'Float repr style: '",
"+",
"repr",
"(",
"sys",
".",
"float_repr_style",
")",
"+",
"'\\n\\n'",
"except",
":",
"text",
"+=",
"'Float repr style: (none) \\n\\n'",
"# For Python 2.6 compatibility",
"text",
"+=",
"'Variable __name__: '",
"+",
"__name__",
"+",
"'\\n'",
"text",
"+=",
"'Current directory: '",
"+",
"os",
".",
"getcwd",
"(",
")",
"+",
"'\\n\\n'",
"text",
"+=",
"'Python path: \\n'",
"text",
"+=",
"'\\n'",
".",
"join",
"(",
"sys",
".",
"path",
")",
"+",
"'\\n'",
"text",
"+=",
"'\\n## End of diagnostic output ## \\n'",
"return",
"text"
] | Generate a diagnostic string, showing the module version, the platform, current directory etc.
Returns:
A descriptive string. | [
"Generate",
"a",
"diagnostic",
"string",
"showing",
"the",
"module",
"version",
"the",
"platform",
"current",
"directory",
"etc",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2513-L2550 |
5,958 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.read_bit | def read_bit(self, registeraddress, functioncode=2):
"""Read one bit from the slave.
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 1 or 2.
Returns:
The bit value 0 or 1 (int).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [1, 2])
return self._genericCommand(functioncode, registeraddress) | python | def read_bit(self, registeraddress, functioncode=2):
"""Read one bit from the slave.
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 1 or 2.
Returns:
The bit value 0 or 1 (int).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [1, 2])
return self._genericCommand(functioncode, registeraddress) | [
"def",
"read_bit",
"(",
"self",
",",
"registeraddress",
",",
"functioncode",
"=",
"2",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"1",
",",
"2",
"]",
")",
"return",
"self",
".",
"_genericCommand",
"(",
"functioncode",
",",
"registeraddress",
")"
] | Read one bit from the slave.
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 1 or 2.
Returns:
The bit value 0 or 1 (int).
Raises:
ValueError, TypeError, IOError | [
"Read",
"one",
"bit",
"from",
"the",
"slave",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L178-L193 |
5,959 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.write_bit | def write_bit(self, registeraddress, value, functioncode=5):
"""Write one bit to the slave.
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int): 0 or 1
* functioncode (int): Modbus function code. Can be 5 or 15.
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [5, 15])
_checkInt(value, minvalue=0, maxvalue=1, description='input value')
self._genericCommand(functioncode, registeraddress, value) | python | def write_bit(self, registeraddress, value, functioncode=5):
"""Write one bit to the slave.
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int): 0 or 1
* functioncode (int): Modbus function code. Can be 5 or 15.
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [5, 15])
_checkInt(value, minvalue=0, maxvalue=1, description='input value')
self._genericCommand(functioncode, registeraddress, value) | [
"def",
"write_bit",
"(",
"self",
",",
"registeraddress",
",",
"value",
",",
"functioncode",
"=",
"5",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"5",
",",
"15",
"]",
")",
"_checkInt",
"(",
"value",
",",
"minvalue",
"=",
"0",
",",
"maxvalue",
"=",
"1",
",",
"description",
"=",
"'input value'",
")",
"self",
".",
"_genericCommand",
"(",
"functioncode",
",",
"registeraddress",
",",
"value",
")"
] | Write one bit to the slave.
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int): 0 or 1
* functioncode (int): Modbus function code. Can be 5 or 15.
Returns:
None
Raises:
ValueError, TypeError, IOError | [
"Write",
"one",
"bit",
"to",
"the",
"slave",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L196-L213 |
5,960 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.read_register | def read_register(self, registeraddress, numberOfDecimals=0, functioncode=3, signed=False):
"""Read an integer from one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* numberOfDecimals (int): The number of decimals for content conversion.
* functioncode (int): Modbus function code. Can be 3 or 4.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
If a value of 77.0 is stored internally in the slave register as 770, then use ``numberOfDecimals=1``
which will divide the received data by 10 before returning the value.
Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value.
Some manufacturers allow negative values for some registers. Instead of
an allowed integer range 0 to 65535, a range -32768 to 32767 is allowed. This is
implemented as any received value in the upper range (32768 to 65535) is
interpreted as negative value (in the range -32768 to -1).
Use the parameter ``signed=True`` if reading from a register that can hold
negative values. Then upper range data will be automatically converted into
negative return values (two's complement).
============== ================== ================ ===============
``signed`` Data type in slave Alternative name Range
============== ================== ================ ===============
:const:`False` Unsigned INT16 Unsigned short 0 to 65535
:const:`True` INT16 Short -32768 to 32767
============== ================== ================ ===============
Returns:
The register data in numerical value (int or float).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [3, 4])
_checkInt(numberOfDecimals, minvalue=0, maxvalue=10, description='number of decimals')
_checkBool(signed, description='signed')
return self._genericCommand(functioncode, registeraddress, numberOfDecimals=numberOfDecimals, signed=signed) | python | def read_register(self, registeraddress, numberOfDecimals=0, functioncode=3, signed=False):
"""Read an integer from one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* numberOfDecimals (int): The number of decimals for content conversion.
* functioncode (int): Modbus function code. Can be 3 or 4.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
If a value of 77.0 is stored internally in the slave register as 770, then use ``numberOfDecimals=1``
which will divide the received data by 10 before returning the value.
Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value.
Some manufacturers allow negative values for some registers. Instead of
an allowed integer range 0 to 65535, a range -32768 to 32767 is allowed. This is
implemented as any received value in the upper range (32768 to 65535) is
interpreted as negative value (in the range -32768 to -1).
Use the parameter ``signed=True`` if reading from a register that can hold
negative values. Then upper range data will be automatically converted into
negative return values (two's complement).
============== ================== ================ ===============
``signed`` Data type in slave Alternative name Range
============== ================== ================ ===============
:const:`False` Unsigned INT16 Unsigned short 0 to 65535
:const:`True` INT16 Short -32768 to 32767
============== ================== ================ ===============
Returns:
The register data in numerical value (int or float).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [3, 4])
_checkInt(numberOfDecimals, minvalue=0, maxvalue=10, description='number of decimals')
_checkBool(signed, description='signed')
return self._genericCommand(functioncode, registeraddress, numberOfDecimals=numberOfDecimals, signed=signed) | [
"def",
"read_register",
"(",
"self",
",",
"registeraddress",
",",
"numberOfDecimals",
"=",
"0",
",",
"functioncode",
"=",
"3",
",",
"signed",
"=",
"False",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"3",
",",
"4",
"]",
")",
"_checkInt",
"(",
"numberOfDecimals",
",",
"minvalue",
"=",
"0",
",",
"maxvalue",
"=",
"10",
",",
"description",
"=",
"'number of decimals'",
")",
"_checkBool",
"(",
"signed",
",",
"description",
"=",
"'signed'",
")",
"return",
"self",
".",
"_genericCommand",
"(",
"functioncode",
",",
"registeraddress",
",",
"numberOfDecimals",
"=",
"numberOfDecimals",
",",
"signed",
"=",
"signed",
")"
] | Read an integer from one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* numberOfDecimals (int): The number of decimals for content conversion.
* functioncode (int): Modbus function code. Can be 3 or 4.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
If a value of 77.0 is stored internally in the slave register as 770, then use ``numberOfDecimals=1``
which will divide the received data by 10 before returning the value.
Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value.
Some manufacturers allow negative values for some registers. Instead of
an allowed integer range 0 to 65535, a range -32768 to 32767 is allowed. This is
implemented as any received value in the upper range (32768 to 65535) is
interpreted as negative value (in the range -32768 to -1).
Use the parameter ``signed=True`` if reading from a register that can hold
negative values. Then upper range data will be automatically converted into
negative return values (two's complement).
============== ================== ================ ===============
``signed`` Data type in slave Alternative name Range
============== ================== ================ ===============
:const:`False` Unsigned INT16 Unsigned short 0 to 65535
:const:`True` INT16 Short -32768 to 32767
============== ================== ================ ===============
Returns:
The register data in numerical value (int or float).
Raises:
ValueError, TypeError, IOError | [
"Read",
"an",
"integer",
"from",
"one",
"16",
"-",
"bit",
"register",
"in",
"the",
"slave",
"possibly",
"scaling",
"it",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L216-L258 |
5,961 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.write_register | def write_register(self, registeraddress, value, numberOfDecimals=0, functioncode=16, signed=False):
"""Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int or float): The value to store in the slave register (might be scaled before sending).
* numberOfDecimals (int): The number of decimals for content conversion.
* functioncode (int): Modbus function code. Can be 6 or 16.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
To store for example ``value=77.0``, use ``numberOfDecimals=1`` if the slave register will hold it as 770 internally.
This will multiply ``value`` by 10 before sending it to the slave register.
Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register.
For discussion on negative values, the range and on alternative names, see :meth:`.read_register`.
Use the parameter ``signed=True`` if writing to a register that can hold
negative values. Then negative input will be automatically converted into
upper range data (two's complement).
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [6, 16])
_checkInt(numberOfDecimals, minvalue=0, maxvalue=10, description='number of decimals')
_checkBool(signed, description='signed')
_checkNumerical(value, description='input value')
self._genericCommand(functioncode, registeraddress, value, numberOfDecimals, signed=signed) | python | def write_register(self, registeraddress, value, numberOfDecimals=0, functioncode=16, signed=False):
"""Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int or float): The value to store in the slave register (might be scaled before sending).
* numberOfDecimals (int): The number of decimals for content conversion.
* functioncode (int): Modbus function code. Can be 6 or 16.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
To store for example ``value=77.0``, use ``numberOfDecimals=1`` if the slave register will hold it as 770 internally.
This will multiply ``value`` by 10 before sending it to the slave register.
Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register.
For discussion on negative values, the range and on alternative names, see :meth:`.read_register`.
Use the parameter ``signed=True`` if writing to a register that can hold
negative values. Then negative input will be automatically converted into
upper range data (two's complement).
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [6, 16])
_checkInt(numberOfDecimals, minvalue=0, maxvalue=10, description='number of decimals')
_checkBool(signed, description='signed')
_checkNumerical(value, description='input value')
self._genericCommand(functioncode, registeraddress, value, numberOfDecimals, signed=signed) | [
"def",
"write_register",
"(",
"self",
",",
"registeraddress",
",",
"value",
",",
"numberOfDecimals",
"=",
"0",
",",
"functioncode",
"=",
"16",
",",
"signed",
"=",
"False",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"6",
",",
"16",
"]",
")",
"_checkInt",
"(",
"numberOfDecimals",
",",
"minvalue",
"=",
"0",
",",
"maxvalue",
"=",
"10",
",",
"description",
"=",
"'number of decimals'",
")",
"_checkBool",
"(",
"signed",
",",
"description",
"=",
"'signed'",
")",
"_checkNumerical",
"(",
"value",
",",
"description",
"=",
"'input value'",
")",
"self",
".",
"_genericCommand",
"(",
"functioncode",
",",
"registeraddress",
",",
"value",
",",
"numberOfDecimals",
",",
"signed",
"=",
"signed",
")"
] | Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int or float): The value to store in the slave register (might be scaled before sending).
* numberOfDecimals (int): The number of decimals for content conversion.
* functioncode (int): Modbus function code. Can be 6 or 16.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
To store for example ``value=77.0``, use ``numberOfDecimals=1`` if the slave register will hold it as 770 internally.
This will multiply ``value`` by 10 before sending it to the slave register.
Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register.
For discussion on negative values, the range and on alternative names, see :meth:`.read_register`.
Use the parameter ``signed=True`` if writing to a register that can hold
negative values. Then negative input will be automatically converted into
upper range data (two's complement).
Returns:
None
Raises:
ValueError, TypeError, IOError | [
"Write",
"an",
"integer",
"to",
"one",
"16",
"-",
"bit",
"register",
"in",
"the",
"slave",
"possibly",
"scaling",
"it",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L261-L296 |
5,962 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.read_float | def read_float(self, registeraddress, functioncode=3, numberOfRegisters=2):
"""Read a floating point number from the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave. The
encoding is according to the standard IEEE 754.
There are differences in the byte order used by different manufacturers. A floating
point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this
implementation the data will be sent as ``'\\x3f\\x80'`` and ``'\\x00\\x00'``
to two consecutetive registers . Make sure to test that it makes sense for your instrument.
It is pretty straight-forward to change this code if some other byte order is
required by anyone (see support section).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 3 or 4.
* numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
====================================== ================= =========== =================
Type of floating point number in slave Size Registers Range
====================================== ================= =========== =================
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308
====================================== ================= =========== =================
Returns:
The numerical value (float).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [3, 4])
_checkInt(numberOfRegisters, minvalue=2, maxvalue=4, description='number of registers')
return self._genericCommand(functioncode, registeraddress, numberOfRegisters=numberOfRegisters, payloadformat='float') | python | def read_float(self, registeraddress, functioncode=3, numberOfRegisters=2):
"""Read a floating point number from the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave. The
encoding is according to the standard IEEE 754.
There are differences in the byte order used by different manufacturers. A floating
point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this
implementation the data will be sent as ``'\\x3f\\x80'`` and ``'\\x00\\x00'``
to two consecutetive registers . Make sure to test that it makes sense for your instrument.
It is pretty straight-forward to change this code if some other byte order is
required by anyone (see support section).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 3 or 4.
* numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
====================================== ================= =========== =================
Type of floating point number in slave Size Registers Range
====================================== ================= =========== =================
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308
====================================== ================= =========== =================
Returns:
The numerical value (float).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [3, 4])
_checkInt(numberOfRegisters, minvalue=2, maxvalue=4, description='number of registers')
return self._genericCommand(functioncode, registeraddress, numberOfRegisters=numberOfRegisters, payloadformat='float') | [
"def",
"read_float",
"(",
"self",
",",
"registeraddress",
",",
"functioncode",
"=",
"3",
",",
"numberOfRegisters",
"=",
"2",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"3",
",",
"4",
"]",
")",
"_checkInt",
"(",
"numberOfRegisters",
",",
"minvalue",
"=",
"2",
",",
"maxvalue",
"=",
"4",
",",
"description",
"=",
"'number of registers'",
")",
"return",
"self",
".",
"_genericCommand",
"(",
"functioncode",
",",
"registeraddress",
",",
"numberOfRegisters",
"=",
"numberOfRegisters",
",",
"payloadformat",
"=",
"'float'",
")"
] | Read a floating point number from the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave. The
encoding is according to the standard IEEE 754.
There are differences in the byte order used by different manufacturers. A floating
point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this
implementation the data will be sent as ``'\\x3f\\x80'`` and ``'\\x00\\x00'``
to two consecutetive registers . Make sure to test that it makes sense for your instrument.
It is pretty straight-forward to change this code if some other byte order is
required by anyone (see support section).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 3 or 4.
* numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
====================================== ================= =========== =================
Type of floating point number in slave Size Registers Range
====================================== ================= =========== =================
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308
====================================== ================= =========== =================
Returns:
The numerical value (float).
Raises:
ValueError, TypeError, IOError | [
"Read",
"a",
"floating",
"point",
"number",
"from",
"the",
"slave",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L358-L392 |
5,963 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.write_float | def write_float(self, registeraddress, value, numberOfRegisters=2):
"""Write a floating point number to the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave.
Uses Modbus function code 16.
For discussion on precision, number of registers and on byte order, see :meth:`.read_float`.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* value (float or int): The value to store in the slave
* numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
_checkNumerical(value, description='input value')
_checkInt(numberOfRegisters, minvalue=2, maxvalue=4, description='number of registers')
self._genericCommand(16, registeraddress, value, \
numberOfRegisters=numberOfRegisters, payloadformat='float') | python | def write_float(self, registeraddress, value, numberOfRegisters=2):
"""Write a floating point number to the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave.
Uses Modbus function code 16.
For discussion on precision, number of registers and on byte order, see :meth:`.read_float`.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* value (float or int): The value to store in the slave
* numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
_checkNumerical(value, description='input value')
_checkInt(numberOfRegisters, minvalue=2, maxvalue=4, description='number of registers')
self._genericCommand(16, registeraddress, value, \
numberOfRegisters=numberOfRegisters, payloadformat='float') | [
"def",
"write_float",
"(",
"self",
",",
"registeraddress",
",",
"value",
",",
"numberOfRegisters",
"=",
"2",
")",
":",
"_checkNumerical",
"(",
"value",
",",
"description",
"=",
"'input value'",
")",
"_checkInt",
"(",
"numberOfRegisters",
",",
"minvalue",
"=",
"2",
",",
"maxvalue",
"=",
"4",
",",
"description",
"=",
"'number of registers'",
")",
"self",
".",
"_genericCommand",
"(",
"16",
",",
"registeraddress",
",",
"value",
",",
"numberOfRegisters",
"=",
"numberOfRegisters",
",",
"payloadformat",
"=",
"'float'",
")"
] | Write a floating point number to the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave.
Uses Modbus function code 16.
For discussion on precision, number of registers and on byte order, see :meth:`.read_float`.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* value (float or int): The value to store in the slave
* numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
Returns:
None
Raises:
ValueError, TypeError, IOError | [
"Write",
"a",
"floating",
"point",
"number",
"to",
"the",
"slave",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L395-L419 |
5,964 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.read_string | def read_string(self, registeraddress, numberOfRegisters=16, functioncode=3):
"""Read a string from the slave.
Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits).
For example 16 consecutive registers can hold 32 characters (32 bytes).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* numberOfRegisters (int): The number of registers allocated for the string.
* functioncode (int): Modbus function code. Can be 3 or 4.
Returns:
The string (str).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [3, 4])
_checkInt(numberOfRegisters, minvalue=1, description='number of registers for read string')
return self._genericCommand(functioncode, registeraddress, \
numberOfRegisters=numberOfRegisters, payloadformat='string') | python | def read_string(self, registeraddress, numberOfRegisters=16, functioncode=3):
"""Read a string from the slave.
Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits).
For example 16 consecutive registers can hold 32 characters (32 bytes).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* numberOfRegisters (int): The number of registers allocated for the string.
* functioncode (int): Modbus function code. Can be 3 or 4.
Returns:
The string (str).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [3, 4])
_checkInt(numberOfRegisters, minvalue=1, description='number of registers for read string')
return self._genericCommand(functioncode, registeraddress, \
numberOfRegisters=numberOfRegisters, payloadformat='string') | [
"def",
"read_string",
"(",
"self",
",",
"registeraddress",
",",
"numberOfRegisters",
"=",
"16",
",",
"functioncode",
"=",
"3",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"3",
",",
"4",
"]",
")",
"_checkInt",
"(",
"numberOfRegisters",
",",
"minvalue",
"=",
"1",
",",
"description",
"=",
"'number of registers for read string'",
")",
"return",
"self",
".",
"_genericCommand",
"(",
"functioncode",
",",
"registeraddress",
",",
"numberOfRegisters",
"=",
"numberOfRegisters",
",",
"payloadformat",
"=",
"'string'",
")"
] | Read a string from the slave.
Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits).
For example 16 consecutive registers can hold 32 characters (32 bytes).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* numberOfRegisters (int): The number of registers allocated for the string.
* functioncode (int): Modbus function code. Can be 3 or 4.
Returns:
The string (str).
Raises:
ValueError, TypeError, IOError | [
"Read",
"a",
"string",
"from",
"the",
"slave",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L422-L443 |
5,965 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.write_string | def write_string(self, registeraddress, textstring, numberOfRegisters=16):
"""Write a string to the slave.
Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits).
For example 16 consecutive registers can hold 32 characters (32 bytes).
Uses Modbus function code 16.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* textstring (str): The string to store in the slave
* numberOfRegisters (int): The number of registers allocated for the string.
If the textstring is longer than the 2*numberOfRegisters, an error is raised.
Shorter strings are padded with spaces.
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
_checkInt(numberOfRegisters, minvalue=1, description='number of registers for write string')
_checkString(textstring, 'input string', minlength=1, maxlength=2 * numberOfRegisters)
self._genericCommand(16, registeraddress, textstring, \
numberOfRegisters=numberOfRegisters, payloadformat='string') | python | def write_string(self, registeraddress, textstring, numberOfRegisters=16):
"""Write a string to the slave.
Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits).
For example 16 consecutive registers can hold 32 characters (32 bytes).
Uses Modbus function code 16.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* textstring (str): The string to store in the slave
* numberOfRegisters (int): The number of registers allocated for the string.
If the textstring is longer than the 2*numberOfRegisters, an error is raised.
Shorter strings are padded with spaces.
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
_checkInt(numberOfRegisters, minvalue=1, description='number of registers for write string')
_checkString(textstring, 'input string', minlength=1, maxlength=2 * numberOfRegisters)
self._genericCommand(16, registeraddress, textstring, \
numberOfRegisters=numberOfRegisters, payloadformat='string') | [
"def",
"write_string",
"(",
"self",
",",
"registeraddress",
",",
"textstring",
",",
"numberOfRegisters",
"=",
"16",
")",
":",
"_checkInt",
"(",
"numberOfRegisters",
",",
"minvalue",
"=",
"1",
",",
"description",
"=",
"'number of registers for write string'",
")",
"_checkString",
"(",
"textstring",
",",
"'input string'",
",",
"minlength",
"=",
"1",
",",
"maxlength",
"=",
"2",
"*",
"numberOfRegisters",
")",
"self",
".",
"_genericCommand",
"(",
"16",
",",
"registeraddress",
",",
"textstring",
",",
"numberOfRegisters",
"=",
"numberOfRegisters",
",",
"payloadformat",
"=",
"'string'",
")"
] | Write a string to the slave.
Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits).
For example 16 consecutive registers can hold 32 characters (32 bytes).
Uses Modbus function code 16.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* textstring (str): The string to store in the slave
* numberOfRegisters (int): The number of registers allocated for the string.
If the textstring is longer than the 2*numberOfRegisters, an error is raised.
Shorter strings are padded with spaces.
Returns:
None
Raises:
ValueError, TypeError, IOError | [
"Write",
"a",
"string",
"to",
"the",
"slave",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L446-L472 |
5,966 | pyhys/minimalmodbus | minimalmodbus.py | Instrument.write_registers | def write_registers(self, registeraddress, values):
"""Write integers to 16-bit registers in the slave.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Uses Modbus function code 16.
The number of registers that will be written is defined by the length of the ``values`` list.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* values (list of int): The values to store in the slave registers.
Any scaling of the register data, or converting it to negative number (two's complement)
must be done manually.
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
if not isinstance(values, list):
raise TypeError('The "values parameter" must be a list. Given: {0!r}'.format(values))
_checkInt(len(values), minvalue=1, description='length of input list')
# Note: The content of the list is checked at content conversion.
self._genericCommand(16, registeraddress, values, numberOfRegisters=len(values), payloadformat='registers') | python | def write_registers(self, registeraddress, values):
"""Write integers to 16-bit registers in the slave.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Uses Modbus function code 16.
The number of registers that will be written is defined by the length of the ``values`` list.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* values (list of int): The values to store in the slave registers.
Any scaling of the register data, or converting it to negative number (two's complement)
must be done manually.
Returns:
None
Raises:
ValueError, TypeError, IOError
"""
if not isinstance(values, list):
raise TypeError('The "values parameter" must be a list. Given: {0!r}'.format(values))
_checkInt(len(values), minvalue=1, description='length of input list')
# Note: The content of the list is checked at content conversion.
self._genericCommand(16, registeraddress, values, numberOfRegisters=len(values), payloadformat='registers') | [
"def",
"write_registers",
"(",
"self",
",",
"registeraddress",
",",
"values",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'The \"values parameter\" must be a list. Given: {0!r}'",
".",
"format",
"(",
"values",
")",
")",
"_checkInt",
"(",
"len",
"(",
"values",
")",
",",
"minvalue",
"=",
"1",
",",
"description",
"=",
"'length of input list'",
")",
"# Note: The content of the list is checked at content conversion.",
"self",
".",
"_genericCommand",
"(",
"16",
",",
"registeraddress",
",",
"values",
",",
"numberOfRegisters",
"=",
"len",
"(",
"values",
")",
",",
"payloadformat",
"=",
"'registers'",
")"
] | Write integers to 16-bit registers in the slave.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Uses Modbus function code 16.
The number of registers that will be written is defined by the length of the ``values`` list.
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* values (list of int): The values to store in the slave registers.
Any scaling of the register data, or converting it to negative number (two's complement)
must be done manually.
Returns:
None
Raises:
ValueError, TypeError, IOError | [
"Write",
"integers",
"to",
"16",
"-",
"bit",
"registers",
"in",
"the",
"slave",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L501-L529 |
5,967 | pyhys/minimalmodbus | minimalmodbus.py | Instrument._communicate | def _communicate(self, request, number_of_bytes_to_read):
"""Talk to the slave via a serial port.
Args:
request (str): The raw request that is to be sent to the slave.
number_of_bytes_to_read (int): number of bytes to read
Returns:
The raw data (string) returned from the slave.
Raises:
TypeError, ValueError, IOError
Note that the answer might have strange ASCII control signs, which
makes it difficult to print it in the promt (messes up a bit).
Use repr() to make the string printable (shows ASCII values for control signs.)
Will block until reaching *number_of_bytes_to_read* or timeout.
If the attribute :attr:`Instrument.debug` is :const:`True`, the communication details are printed.
If the attribute :attr:`Instrument.close_port_after_each_call` is :const:`True` the
serial port is closed after each call.
Timing::
Request from master (Master is writing)
|
| Response from slave (Master is reading)
| |
----W----R----------------------------W-------R----------------------------------------
| | |
|<----- Silent period ------>| |
| |
Roundtrip time ---->|-------|<--
The resolution for Python's time.time() is lower on Windows than on Linux.
It is about 16 ms on Windows according to
http://stackoverflow.com/questions/157359/accurate-timestamping-in-python
For Python3, the information sent to and from pySerial should be of the type bytes.
This is taken care of automatically by MinimalModbus.
"""
_checkString(request, minlength=1, description='request')
_checkInt(number_of_bytes_to_read)
if self.debug:
_print_out('\nMinimalModbus debug mode. Writing to instrument (expecting {} bytes back): {!r} ({})'. \
format(number_of_bytes_to_read, request, _hexlify(request)))
if self.close_port_after_each_call:
self.serial.open()
#self.serial.flushInput() TODO
if sys.version_info[0] > 2:
request = bytes(request, encoding='latin1') # Convert types to make it Python3 compatible
# Sleep to make sure 3.5 character times have passed
minimum_silent_period = _calculate_minimum_silent_period(self.serial.baudrate)
time_since_read = time.time() - _LATEST_READ_TIMES.get(self.serial.port, 0)
if time_since_read < minimum_silent_period:
sleep_time = minimum_silent_period - time_since_read
if self.debug:
template = 'MinimalModbus debug mode. Sleeping for {:.1f} ms. ' + \
'Minimum silent period: {:.1f} ms, time since read: {:.1f} ms.'
text = template.format(
sleep_time * _SECONDS_TO_MILLISECONDS,
minimum_silent_period * _SECONDS_TO_MILLISECONDS,
time_since_read * _SECONDS_TO_MILLISECONDS)
_print_out(text)
time.sleep(sleep_time)
elif self.debug:
template = 'MinimalModbus debug mode. No sleep required before write. ' + \
'Time since previous read: {:.1f} ms, minimum silent period: {:.2f} ms.'
text = template.format(
time_since_read * _SECONDS_TO_MILLISECONDS,
minimum_silent_period * _SECONDS_TO_MILLISECONDS)
_print_out(text)
# Write request
latest_write_time = time.time()
self.serial.write(request)
# Read and discard local echo
if self.handle_local_echo:
localEchoToDiscard = self.serial.read(len(request))
if self.debug:
template = 'MinimalModbus debug mode. Discarding this local echo: {!r} ({} bytes).'
text = template.format(localEchoToDiscard, len(localEchoToDiscard))
_print_out(text)
if localEchoToDiscard != request:
template = 'Local echo handling is enabled, but the local echo does not match the sent request. ' + \
'Request: {!r} ({} bytes), local echo: {!r} ({} bytes).'
text = template.format(request, len(request), localEchoToDiscard, len(localEchoToDiscard))
raise IOError(text)
# Read response
answer = self.serial.read(number_of_bytes_to_read)
_LATEST_READ_TIMES[self.serial.port] = time.time()
if self.close_port_after_each_call:
self.serial.close()
if sys.version_info[0] > 2:
answer = str(answer, encoding='latin1') # Convert types to make it Python3 compatible
if self.debug:
template = 'MinimalModbus debug mode. Response from instrument: {!r} ({}) ({} bytes), ' + \
'roundtrip time: {:.1f} ms. Timeout setting: {:.1f} ms.\n'
text = template.format(
answer,
_hexlify(answer),
len(answer),
(_LATEST_READ_TIMES.get(self.serial.port, 0) - latest_write_time) * _SECONDS_TO_MILLISECONDS,
self.serial.timeout * _SECONDS_TO_MILLISECONDS)
_print_out(text)
if len(answer) == 0:
raise IOError('No communication with the instrument (no answer)')
return answer | python | def _communicate(self, request, number_of_bytes_to_read):
"""Talk to the slave via a serial port.
Args:
request (str): The raw request that is to be sent to the slave.
number_of_bytes_to_read (int): number of bytes to read
Returns:
The raw data (string) returned from the slave.
Raises:
TypeError, ValueError, IOError
Note that the answer might have strange ASCII control signs, which
makes it difficult to print it in the promt (messes up a bit).
Use repr() to make the string printable (shows ASCII values for control signs.)
Will block until reaching *number_of_bytes_to_read* or timeout.
If the attribute :attr:`Instrument.debug` is :const:`True`, the communication details are printed.
If the attribute :attr:`Instrument.close_port_after_each_call` is :const:`True` the
serial port is closed after each call.
Timing::
Request from master (Master is writing)
|
| Response from slave (Master is reading)
| |
----W----R----------------------------W-------R----------------------------------------
| | |
|<----- Silent period ------>| |
| |
Roundtrip time ---->|-------|<--
The resolution for Python's time.time() is lower on Windows than on Linux.
It is about 16 ms on Windows according to
http://stackoverflow.com/questions/157359/accurate-timestamping-in-python
For Python3, the information sent to and from pySerial should be of the type bytes.
This is taken care of automatically by MinimalModbus.
"""
_checkString(request, minlength=1, description='request')
_checkInt(number_of_bytes_to_read)
if self.debug:
_print_out('\nMinimalModbus debug mode. Writing to instrument (expecting {} bytes back): {!r} ({})'. \
format(number_of_bytes_to_read, request, _hexlify(request)))
if self.close_port_after_each_call:
self.serial.open()
#self.serial.flushInput() TODO
if sys.version_info[0] > 2:
request = bytes(request, encoding='latin1') # Convert types to make it Python3 compatible
# Sleep to make sure 3.5 character times have passed
minimum_silent_period = _calculate_minimum_silent_period(self.serial.baudrate)
time_since_read = time.time() - _LATEST_READ_TIMES.get(self.serial.port, 0)
if time_since_read < minimum_silent_period:
sleep_time = minimum_silent_period - time_since_read
if self.debug:
template = 'MinimalModbus debug mode. Sleeping for {:.1f} ms. ' + \
'Minimum silent period: {:.1f} ms, time since read: {:.1f} ms.'
text = template.format(
sleep_time * _SECONDS_TO_MILLISECONDS,
minimum_silent_period * _SECONDS_TO_MILLISECONDS,
time_since_read * _SECONDS_TO_MILLISECONDS)
_print_out(text)
time.sleep(sleep_time)
elif self.debug:
template = 'MinimalModbus debug mode. No sleep required before write. ' + \
'Time since previous read: {:.1f} ms, minimum silent period: {:.2f} ms.'
text = template.format(
time_since_read * _SECONDS_TO_MILLISECONDS,
minimum_silent_period * _SECONDS_TO_MILLISECONDS)
_print_out(text)
# Write request
latest_write_time = time.time()
self.serial.write(request)
# Read and discard local echo
if self.handle_local_echo:
localEchoToDiscard = self.serial.read(len(request))
if self.debug:
template = 'MinimalModbus debug mode. Discarding this local echo: {!r} ({} bytes).'
text = template.format(localEchoToDiscard, len(localEchoToDiscard))
_print_out(text)
if localEchoToDiscard != request:
template = 'Local echo handling is enabled, but the local echo does not match the sent request. ' + \
'Request: {!r} ({} bytes), local echo: {!r} ({} bytes).'
text = template.format(request, len(request), localEchoToDiscard, len(localEchoToDiscard))
raise IOError(text)
# Read response
answer = self.serial.read(number_of_bytes_to_read)
_LATEST_READ_TIMES[self.serial.port] = time.time()
if self.close_port_after_each_call:
self.serial.close()
if sys.version_info[0] > 2:
answer = str(answer, encoding='latin1') # Convert types to make it Python3 compatible
if self.debug:
template = 'MinimalModbus debug mode. Response from instrument: {!r} ({}) ({} bytes), ' + \
'roundtrip time: {:.1f} ms. Timeout setting: {:.1f} ms.\n'
text = template.format(
answer,
_hexlify(answer),
len(answer),
(_LATEST_READ_TIMES.get(self.serial.port, 0) - latest_write_time) * _SECONDS_TO_MILLISECONDS,
self.serial.timeout * _SECONDS_TO_MILLISECONDS)
_print_out(text)
if len(answer) == 0:
raise IOError('No communication with the instrument (no answer)')
return answer | [
"def",
"_communicate",
"(",
"self",
",",
"request",
",",
"number_of_bytes_to_read",
")",
":",
"_checkString",
"(",
"request",
",",
"minlength",
"=",
"1",
",",
"description",
"=",
"'request'",
")",
"_checkInt",
"(",
"number_of_bytes_to_read",
")",
"if",
"self",
".",
"debug",
":",
"_print_out",
"(",
"'\\nMinimalModbus debug mode. Writing to instrument (expecting {} bytes back): {!r} ({})'",
".",
"format",
"(",
"number_of_bytes_to_read",
",",
"request",
",",
"_hexlify",
"(",
"request",
")",
")",
")",
"if",
"self",
".",
"close_port_after_each_call",
":",
"self",
".",
"serial",
".",
"open",
"(",
")",
"#self.serial.flushInput() TODO",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"request",
"=",
"bytes",
"(",
"request",
",",
"encoding",
"=",
"'latin1'",
")",
"# Convert types to make it Python3 compatible",
"# Sleep to make sure 3.5 character times have passed",
"minimum_silent_period",
"=",
"_calculate_minimum_silent_period",
"(",
"self",
".",
"serial",
".",
"baudrate",
")",
"time_since_read",
"=",
"time",
".",
"time",
"(",
")",
"-",
"_LATEST_READ_TIMES",
".",
"get",
"(",
"self",
".",
"serial",
".",
"port",
",",
"0",
")",
"if",
"time_since_read",
"<",
"minimum_silent_period",
":",
"sleep_time",
"=",
"minimum_silent_period",
"-",
"time_since_read",
"if",
"self",
".",
"debug",
":",
"template",
"=",
"'MinimalModbus debug mode. Sleeping for {:.1f} ms. '",
"+",
"'Minimum silent period: {:.1f} ms, time since read: {:.1f} ms.'",
"text",
"=",
"template",
".",
"format",
"(",
"sleep_time",
"*",
"_SECONDS_TO_MILLISECONDS",
",",
"minimum_silent_period",
"*",
"_SECONDS_TO_MILLISECONDS",
",",
"time_since_read",
"*",
"_SECONDS_TO_MILLISECONDS",
")",
"_print_out",
"(",
"text",
")",
"time",
".",
"sleep",
"(",
"sleep_time",
")",
"elif",
"self",
".",
"debug",
":",
"template",
"=",
"'MinimalModbus debug mode. No sleep required before write. '",
"+",
"'Time since previous read: {:.1f} ms, minimum silent period: {:.2f} ms.'",
"text",
"=",
"template",
".",
"format",
"(",
"time_since_read",
"*",
"_SECONDS_TO_MILLISECONDS",
",",
"minimum_silent_period",
"*",
"_SECONDS_TO_MILLISECONDS",
")",
"_print_out",
"(",
"text",
")",
"# Write request",
"latest_write_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"serial",
".",
"write",
"(",
"request",
")",
"# Read and discard local echo",
"if",
"self",
".",
"handle_local_echo",
":",
"localEchoToDiscard",
"=",
"self",
".",
"serial",
".",
"read",
"(",
"len",
"(",
"request",
")",
")",
"if",
"self",
".",
"debug",
":",
"template",
"=",
"'MinimalModbus debug mode. Discarding this local echo: {!r} ({} bytes).'",
"text",
"=",
"template",
".",
"format",
"(",
"localEchoToDiscard",
",",
"len",
"(",
"localEchoToDiscard",
")",
")",
"_print_out",
"(",
"text",
")",
"if",
"localEchoToDiscard",
"!=",
"request",
":",
"template",
"=",
"'Local echo handling is enabled, but the local echo does not match the sent request. '",
"+",
"'Request: {!r} ({} bytes), local echo: {!r} ({} bytes).'",
"text",
"=",
"template",
".",
"format",
"(",
"request",
",",
"len",
"(",
"request",
")",
",",
"localEchoToDiscard",
",",
"len",
"(",
"localEchoToDiscard",
")",
")",
"raise",
"IOError",
"(",
"text",
")",
"# Read response",
"answer",
"=",
"self",
".",
"serial",
".",
"read",
"(",
"number_of_bytes_to_read",
")",
"_LATEST_READ_TIMES",
"[",
"self",
".",
"serial",
".",
"port",
"]",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"close_port_after_each_call",
":",
"self",
".",
"serial",
".",
"close",
"(",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"answer",
"=",
"str",
"(",
"answer",
",",
"encoding",
"=",
"'latin1'",
")",
"# Convert types to make it Python3 compatible",
"if",
"self",
".",
"debug",
":",
"template",
"=",
"'MinimalModbus debug mode. Response from instrument: {!r} ({}) ({} bytes), '",
"+",
"'roundtrip time: {:.1f} ms. Timeout setting: {:.1f} ms.\\n'",
"text",
"=",
"template",
".",
"format",
"(",
"answer",
",",
"_hexlify",
"(",
"answer",
")",
",",
"len",
"(",
"answer",
")",
",",
"(",
"_LATEST_READ_TIMES",
".",
"get",
"(",
"self",
".",
"serial",
".",
"port",
",",
"0",
")",
"-",
"latest_write_time",
")",
"*",
"_SECONDS_TO_MILLISECONDS",
",",
"self",
".",
"serial",
".",
"timeout",
"*",
"_SECONDS_TO_MILLISECONDS",
")",
"_print_out",
"(",
"text",
")",
"if",
"len",
"(",
"answer",
")",
"==",
"0",
":",
"raise",
"IOError",
"(",
"'No communication with the instrument (no answer)'",
")",
"return",
"answer"
] | Talk to the slave via a serial port.
Args:
request (str): The raw request that is to be sent to the slave.
number_of_bytes_to_read (int): number of bytes to read
Returns:
The raw data (string) returned from the slave.
Raises:
TypeError, ValueError, IOError
Note that the answer might have strange ASCII control signs, which
makes it difficult to print it in the promt (messes up a bit).
Use repr() to make the string printable (shows ASCII values for control signs.)
Will block until reaching *number_of_bytes_to_read* or timeout.
If the attribute :attr:`Instrument.debug` is :const:`True`, the communication details are printed.
If the attribute :attr:`Instrument.close_port_after_each_call` is :const:`True` the
serial port is closed after each call.
Timing::
Request from master (Master is writing)
|
| Response from slave (Master is reading)
| |
----W----R----------------------------W-------R----------------------------------------
| | |
|<----- Silent period ------>| |
| |
Roundtrip time ---->|-------|<--
The resolution for Python's time.time() is lower on Windows than on Linux.
It is about 16 ms on Windows according to
http://stackoverflow.com/questions/157359/accurate-timestamping-in-python
For Python3, the information sent to and from pySerial should be of the type bytes.
This is taken care of automatically by MinimalModbus. | [
"Talk",
"to",
"the",
"slave",
"via",
"a",
"serial",
"port",
"."
] | e99f4d74c83258c6039073082955ac9bed3f2155 | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L802-L932 |
5,968 | TaylorSMarks/playsound | playsound.py | _playsoundWin | def _playsoundWin(sound, block = True):
'''
Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on
Windows 7 with Python 2.7. Probably works with more file formats.
Probably works on Windows XP thru Windows 10. Probably works with all
versions of Python.
Inspired by (but not copied from) Michael Gundlach <[email protected]>'s mp3play:
https://github.com/michaelgundlach/mp3play
I never would have tried using windll.winmm without seeing his code.
'''
from ctypes import c_buffer, windll
from random import random
from time import sleep
from sys import getfilesystemencoding
def winCommand(*command):
buf = c_buffer(255)
command = ' '.join(command).encode(getfilesystemencoding())
errorCode = int(windll.winmm.mciSendStringA(command, buf, 254, 0))
if errorCode:
errorBuffer = c_buffer(255)
windll.winmm.mciGetErrorStringA(errorCode, errorBuffer, 254)
exceptionMessage = ('\n Error ' + str(errorCode) + ' for command:'
'\n ' + command.decode() +
'\n ' + errorBuffer.value.decode())
raise PlaysoundException(exceptionMessage)
return buf.value
alias = 'playsound_' + str(random())
winCommand('open "' + sound + '" alias', alias)
winCommand('set', alias, 'time format milliseconds')
durationInMS = winCommand('status', alias, 'length')
winCommand('play', alias, 'from 0 to', durationInMS.decode())
if block:
sleep(float(durationInMS) / 1000.0) | python | def _playsoundWin(sound, block = True):
'''
Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on
Windows 7 with Python 2.7. Probably works with more file formats.
Probably works on Windows XP thru Windows 10. Probably works with all
versions of Python.
Inspired by (but not copied from) Michael Gundlach <[email protected]>'s mp3play:
https://github.com/michaelgundlach/mp3play
I never would have tried using windll.winmm without seeing his code.
'''
from ctypes import c_buffer, windll
from random import random
from time import sleep
from sys import getfilesystemencoding
def winCommand(*command):
buf = c_buffer(255)
command = ' '.join(command).encode(getfilesystemencoding())
errorCode = int(windll.winmm.mciSendStringA(command, buf, 254, 0))
if errorCode:
errorBuffer = c_buffer(255)
windll.winmm.mciGetErrorStringA(errorCode, errorBuffer, 254)
exceptionMessage = ('\n Error ' + str(errorCode) + ' for command:'
'\n ' + command.decode() +
'\n ' + errorBuffer.value.decode())
raise PlaysoundException(exceptionMessage)
return buf.value
alias = 'playsound_' + str(random())
winCommand('open "' + sound + '" alias', alias)
winCommand('set', alias, 'time format milliseconds')
durationInMS = winCommand('status', alias, 'length')
winCommand('play', alias, 'from 0 to', durationInMS.decode())
if block:
sleep(float(durationInMS) / 1000.0) | [
"def",
"_playsoundWin",
"(",
"sound",
",",
"block",
"=",
"True",
")",
":",
"from",
"ctypes",
"import",
"c_buffer",
",",
"windll",
"from",
"random",
"import",
"random",
"from",
"time",
"import",
"sleep",
"from",
"sys",
"import",
"getfilesystemencoding",
"def",
"winCommand",
"(",
"*",
"command",
")",
":",
"buf",
"=",
"c_buffer",
"(",
"255",
")",
"command",
"=",
"' '",
".",
"join",
"(",
"command",
")",
".",
"encode",
"(",
"getfilesystemencoding",
"(",
")",
")",
"errorCode",
"=",
"int",
"(",
"windll",
".",
"winmm",
".",
"mciSendStringA",
"(",
"command",
",",
"buf",
",",
"254",
",",
"0",
")",
")",
"if",
"errorCode",
":",
"errorBuffer",
"=",
"c_buffer",
"(",
"255",
")",
"windll",
".",
"winmm",
".",
"mciGetErrorStringA",
"(",
"errorCode",
",",
"errorBuffer",
",",
"254",
")",
"exceptionMessage",
"=",
"(",
"'\\n Error '",
"+",
"str",
"(",
"errorCode",
")",
"+",
"' for command:'",
"'\\n '",
"+",
"command",
".",
"decode",
"(",
")",
"+",
"'\\n '",
"+",
"errorBuffer",
".",
"value",
".",
"decode",
"(",
")",
")",
"raise",
"PlaysoundException",
"(",
"exceptionMessage",
")",
"return",
"buf",
".",
"value",
"alias",
"=",
"'playsound_'",
"+",
"str",
"(",
"random",
"(",
")",
")",
"winCommand",
"(",
"'open \"'",
"+",
"sound",
"+",
"'\" alias'",
",",
"alias",
")",
"winCommand",
"(",
"'set'",
",",
"alias",
",",
"'time format milliseconds'",
")",
"durationInMS",
"=",
"winCommand",
"(",
"'status'",
",",
"alias",
",",
"'length'",
")",
"winCommand",
"(",
"'play'",
",",
"alias",
",",
"'from 0 to'",
",",
"durationInMS",
".",
"decode",
"(",
")",
")",
"if",
"block",
":",
"sleep",
"(",
"float",
"(",
"durationInMS",
")",
"/",
"1000.0",
")"
] | Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on
Windows 7 with Python 2.7. Probably works with more file formats.
Probably works on Windows XP thru Windows 10. Probably works with all
versions of Python.
Inspired by (but not copied from) Michael Gundlach <[email protected]>'s mp3play:
https://github.com/michaelgundlach/mp3play
I never would have tried using windll.winmm without seeing his code. | [
"Utilizes",
"windll",
".",
"winmm",
".",
"Tested",
"and",
"known",
"to",
"work",
"with",
"MP3",
"and",
"WAVE",
"on",
"Windows",
"7",
"with",
"Python",
"2",
".",
"7",
".",
"Probably",
"works",
"with",
"more",
"file",
"formats",
".",
"Probably",
"works",
"on",
"Windows",
"XP",
"thru",
"Windows",
"10",
".",
"Probably",
"works",
"with",
"all",
"versions",
"of",
"Python",
"."
] | 907f1fe73375a2156f7e0900c4b42c0a60fa1d00 | https://github.com/TaylorSMarks/playsound/blob/907f1fe73375a2156f7e0900c4b42c0a60fa1d00/playsound.py#L4-L41 |
5,969 | TaylorSMarks/playsound | playsound.py | _playsoundOSX | def _playsoundOSX(sound, block = True):
'''
Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on
OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports.
Probably works on OS X 10.5 and newer. Probably works with all versions of
Python.
Inspired by (but not copied from) Aaron's Stack Overflow answer here:
http://stackoverflow.com/a/34568298/901641
I never would have tried using AppKit.NSSound without seeing his code.
'''
from AppKit import NSSound
from Foundation import NSURL
from time import sleep
if '://' not in sound:
if not sound.startswith('/'):
from os import getcwd
sound = getcwd() + '/' + sound
sound = 'file://' + sound
url = NSURL.URLWithString_(sound)
nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True)
if not nssound:
raise IOError('Unable to load sound named: ' + sound)
nssound.play()
if block:
sleep(nssound.duration()) | python | def _playsoundOSX(sound, block = True):
'''
Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on
OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports.
Probably works on OS X 10.5 and newer. Probably works with all versions of
Python.
Inspired by (but not copied from) Aaron's Stack Overflow answer here:
http://stackoverflow.com/a/34568298/901641
I never would have tried using AppKit.NSSound without seeing his code.
'''
from AppKit import NSSound
from Foundation import NSURL
from time import sleep
if '://' not in sound:
if not sound.startswith('/'):
from os import getcwd
sound = getcwd() + '/' + sound
sound = 'file://' + sound
url = NSURL.URLWithString_(sound)
nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True)
if not nssound:
raise IOError('Unable to load sound named: ' + sound)
nssound.play()
if block:
sleep(nssound.duration()) | [
"def",
"_playsoundOSX",
"(",
"sound",
",",
"block",
"=",
"True",
")",
":",
"from",
"AppKit",
"import",
"NSSound",
"from",
"Foundation",
"import",
"NSURL",
"from",
"time",
"import",
"sleep",
"if",
"'://'",
"not",
"in",
"sound",
":",
"if",
"not",
"sound",
".",
"startswith",
"(",
"'/'",
")",
":",
"from",
"os",
"import",
"getcwd",
"sound",
"=",
"getcwd",
"(",
")",
"+",
"'/'",
"+",
"sound",
"sound",
"=",
"'file://'",
"+",
"sound",
"url",
"=",
"NSURL",
".",
"URLWithString_",
"(",
"sound",
")",
"nssound",
"=",
"NSSound",
".",
"alloc",
"(",
")",
".",
"initWithContentsOfURL_byReference_",
"(",
"url",
",",
"True",
")",
"if",
"not",
"nssound",
":",
"raise",
"IOError",
"(",
"'Unable to load sound named: '",
"+",
"sound",
")",
"nssound",
".",
"play",
"(",
")",
"if",
"block",
":",
"sleep",
"(",
"nssound",
".",
"duration",
"(",
")",
")"
] | Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on
OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports.
Probably works on OS X 10.5 and newer. Probably works with all versions of
Python.
Inspired by (but not copied from) Aaron's Stack Overflow answer here:
http://stackoverflow.com/a/34568298/901641
I never would have tried using AppKit.NSSound without seeing his code. | [
"Utilizes",
"AppKit",
".",
"NSSound",
".",
"Tested",
"and",
"known",
"to",
"work",
"with",
"MP3",
"and",
"WAVE",
"on",
"OS",
"X",
"10",
".",
"11",
"with",
"Python",
"2",
".",
"7",
".",
"Probably",
"works",
"with",
"anything",
"QuickTime",
"supports",
".",
"Probably",
"works",
"on",
"OS",
"X",
"10",
".",
"5",
"and",
"newer",
".",
"Probably",
"works",
"with",
"all",
"versions",
"of",
"Python",
"."
] | 907f1fe73375a2156f7e0900c4b42c0a60fa1d00 | https://github.com/TaylorSMarks/playsound/blob/907f1fe73375a2156f7e0900c4b42c0a60fa1d00/playsound.py#L43-L71 |
5,970 | TaylorSMarks/playsound | playsound.py | _playsoundNix | def _playsoundNix(sound, block=True):
"""Play a sound using GStreamer.
Inspired by this:
https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html
"""
if not block:
raise NotImplementedError(
"block=False cannot be used on this platform yet")
# pathname2url escapes non-URL-safe characters
import os
try:
from urllib.request import pathname2url
except ImportError:
# python 2
from urllib import pathname2url
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
Gst.init(None)
playbin = Gst.ElementFactory.make('playbin', 'playbin')
if sound.startswith(('http://', 'https://')):
playbin.props.uri = sound
else:
playbin.props.uri = 'file://' + pathname2url(os.path.abspath(sound))
set_result = playbin.set_state(Gst.State.PLAYING)
if set_result != Gst.StateChangeReturn.ASYNC:
raise PlaysoundException(
"playbin.set_state returned " + repr(set_result))
# FIXME: use some other bus method than poll() with block=False
# https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.html
bus = playbin.get_bus()
bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)
playbin.set_state(Gst.State.NULL) | python | def _playsoundNix(sound, block=True):
"""Play a sound using GStreamer.
Inspired by this:
https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html
"""
if not block:
raise NotImplementedError(
"block=False cannot be used on this platform yet")
# pathname2url escapes non-URL-safe characters
import os
try:
from urllib.request import pathname2url
except ImportError:
# python 2
from urllib import pathname2url
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
Gst.init(None)
playbin = Gst.ElementFactory.make('playbin', 'playbin')
if sound.startswith(('http://', 'https://')):
playbin.props.uri = sound
else:
playbin.props.uri = 'file://' + pathname2url(os.path.abspath(sound))
set_result = playbin.set_state(Gst.State.PLAYING)
if set_result != Gst.StateChangeReturn.ASYNC:
raise PlaysoundException(
"playbin.set_state returned " + repr(set_result))
# FIXME: use some other bus method than poll() with block=False
# https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.html
bus = playbin.get_bus()
bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)
playbin.set_state(Gst.State.NULL) | [
"def",
"_playsoundNix",
"(",
"sound",
",",
"block",
"=",
"True",
")",
":",
"if",
"not",
"block",
":",
"raise",
"NotImplementedError",
"(",
"\"block=False cannot be used on this platform yet\"",
")",
"# pathname2url escapes non-URL-safe characters",
"import",
"os",
"try",
":",
"from",
"urllib",
".",
"request",
"import",
"pathname2url",
"except",
"ImportError",
":",
"# python 2",
"from",
"urllib",
"import",
"pathname2url",
"import",
"gi",
"gi",
".",
"require_version",
"(",
"'Gst'",
",",
"'1.0'",
")",
"from",
"gi",
".",
"repository",
"import",
"Gst",
"Gst",
".",
"init",
"(",
"None",
")",
"playbin",
"=",
"Gst",
".",
"ElementFactory",
".",
"make",
"(",
"'playbin'",
",",
"'playbin'",
")",
"if",
"sound",
".",
"startswith",
"(",
"(",
"'http://'",
",",
"'https://'",
")",
")",
":",
"playbin",
".",
"props",
".",
"uri",
"=",
"sound",
"else",
":",
"playbin",
".",
"props",
".",
"uri",
"=",
"'file://'",
"+",
"pathname2url",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"sound",
")",
")",
"set_result",
"=",
"playbin",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"PLAYING",
")",
"if",
"set_result",
"!=",
"Gst",
".",
"StateChangeReturn",
".",
"ASYNC",
":",
"raise",
"PlaysoundException",
"(",
"\"playbin.set_state returned \"",
"+",
"repr",
"(",
"set_result",
")",
")",
"# FIXME: use some other bus method than poll() with block=False",
"# https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.html",
"bus",
"=",
"playbin",
".",
"get_bus",
"(",
")",
"bus",
".",
"poll",
"(",
"Gst",
".",
"MessageType",
".",
"EOS",
",",
"Gst",
".",
"CLOCK_TIME_NONE",
")",
"playbin",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"NULL",
")"
] | Play a sound using GStreamer.
Inspired by this:
https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html | [
"Play",
"a",
"sound",
"using",
"GStreamer",
"."
] | 907f1fe73375a2156f7e0900c4b42c0a60fa1d00 | https://github.com/TaylorSMarks/playsound/blob/907f1fe73375a2156f7e0900c4b42c0a60fa1d00/playsound.py#L73-L112 |
5,971 | mfitzp/padua | padua/filters.py | remove_rows_matching | def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Column indexer
:param match: ``str`` match target
:return: Pandas ``DataFrame`` filtered
"""
df = df.copy()
mask = df[column].values != match
return df.iloc[mask, :] | python | def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Column indexer
:param match: ``str`` match target
:return: Pandas ``DataFrame`` filtered
"""
df = df.copy()
mask = df[column].values != match
return df.iloc[mask, :] | [
"def",
"remove_rows_matching",
"(",
"df",
",",
"column",
",",
"match",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"mask",
"=",
"df",
"[",
"column",
"]",
".",
"values",
"!=",
"match",
"return",
"df",
".",
"iloc",
"[",
"mask",
",",
":",
"]"
] | Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Column indexer
:param match: ``str`` match target
:return: Pandas ``DataFrame`` filtered | [
"Return",
"a",
"DataFrame",
"with",
"rows",
"where",
"column",
"values",
"match",
"match",
"are",
"removed",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L4-L18 |
5,972 | mfitzp/padua | padua/filters.py | remove_rows_containing | def remove_rows_containing(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values containing `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that contain it are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Column indexer
:param match: ``str`` match target
:return: Pandas ``DataFrame`` filtered
"""
df = df.copy()
mask = [match not in str(v) for v in df[column].values]
return df.iloc[mask, :] | python | def remove_rows_containing(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values containing `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that contain it are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Column indexer
:param match: ``str`` match target
:return: Pandas ``DataFrame`` filtered
"""
df = df.copy()
mask = [match not in str(v) for v in df[column].values]
return df.iloc[mask, :] | [
"def",
"remove_rows_containing",
"(",
"df",
",",
"column",
",",
"match",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"mask",
"=",
"[",
"match",
"not",
"in",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"df",
"[",
"column",
"]",
".",
"values",
"]",
"return",
"df",
".",
"iloc",
"[",
"mask",
",",
":",
"]"
] | Return a ``DataFrame`` with rows where `column` values containing `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that contain it are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Column indexer
:param match: ``str`` match target
:return: Pandas ``DataFrame`` filtered | [
"Return",
"a",
"DataFrame",
"with",
"rows",
"where",
"column",
"values",
"containing",
"match",
"are",
"removed",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L21-L35 |
5,973 | mfitzp/padua | padua/filters.py | filter_localization_probability | def filter_localization_probability(df, threshold=0.75):
"""
Remove rows with a localization probability below 0.75
Return a ``DataFrame`` where the rows with a value < `threshold` (default 0.75) in column 'Localization prob' are removed.
Filters data to remove poorly localized peptides (non Class-I by default).
:param df: Pandas ``DataFrame``
:param threshold: Cut-off below which rows are discarded (default 0.75)
:return: Pandas ``DataFrame``
"""
df = df.copy()
localization_probability_mask = df['Localization prob'].values >= threshold
return df.iloc[localization_probability_mask, :] | python | def filter_localization_probability(df, threshold=0.75):
"""
Remove rows with a localization probability below 0.75
Return a ``DataFrame`` where the rows with a value < `threshold` (default 0.75) in column 'Localization prob' are removed.
Filters data to remove poorly localized peptides (non Class-I by default).
:param df: Pandas ``DataFrame``
:param threshold: Cut-off below which rows are discarded (default 0.75)
:return: Pandas ``DataFrame``
"""
df = df.copy()
localization_probability_mask = df['Localization prob'].values >= threshold
return df.iloc[localization_probability_mask, :] | [
"def",
"filter_localization_probability",
"(",
"df",
",",
"threshold",
"=",
"0.75",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"localization_probability_mask",
"=",
"df",
"[",
"'Localization prob'",
"]",
".",
"values",
">=",
"threshold",
"return",
"df",
".",
"iloc",
"[",
"localization_probability_mask",
",",
":",
"]"
] | Remove rows with a localization probability below 0.75
Return a ``DataFrame`` where the rows with a value < `threshold` (default 0.75) in column 'Localization prob' are removed.
Filters data to remove poorly localized peptides (non Class-I by default).
:param df: Pandas ``DataFrame``
:param threshold: Cut-off below which rows are discarded (default 0.75)
:return: Pandas ``DataFrame`` | [
"Remove",
"rows",
"with",
"a",
"localization",
"probability",
"below",
"0",
".",
"75"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L77-L90 |
5,974 | mfitzp/padua | padua/filters.py | minimum_valid_values_in_any_group | def minimum_valid_values_in_any_group(df, levels=None, n=1, invalid=np.nan):
"""
Filter ``DataFrame`` by at least n valid values in at least one group.
Taking a Pandas ``DataFrame`` with a ``MultiIndex`` column index, filters rows to remove
rows where there are less than `n` valid values per group. Groups are defined by the `levels` parameter indexing
into the column index. For example, a ``MultiIndex`` with top and second level Group (A,B,C) and Replicate (1,2,3) using
``levels=[0,1]`` would filter on `n` valid values per replicate. Alternatively, ``levels=[0]`` would filter on `n`
valid values at the Group level only, e.g. A, B or C.
By default valid values are determined by `np.nan`. However, alternatives can be supplied via `invalid`.
:param df: Pandas ``DataFrame``
:param levels: ``list`` of ``int`` specifying levels of column ``MultiIndex`` to group by
:param n: ``int`` minimum number of valid values threshold
:param invalid: matching invalid value
:return: filtered Pandas ``DataFrame``
"""
df = df.copy()
if levels is None:
if 'Group' in df.columns.names:
levels = [df.columns.names.index('Group')]
# Filter by at least 7 (values in class:timepoint) at least in at least one group
if invalid is np.nan:
dfx = ~np.isnan(df)
else:
dfx = df != invalid
dfc = dfx.astype(int).sum(axis=1, level=levels)
dfm = dfc.max(axis=1) >= n
mask = dfm.values
return df.iloc[mask, :] | python | def minimum_valid_values_in_any_group(df, levels=None, n=1, invalid=np.nan):
"""
Filter ``DataFrame`` by at least n valid values in at least one group.
Taking a Pandas ``DataFrame`` with a ``MultiIndex`` column index, filters rows to remove
rows where there are less than `n` valid values per group. Groups are defined by the `levels` parameter indexing
into the column index. For example, a ``MultiIndex`` with top and second level Group (A,B,C) and Replicate (1,2,3) using
``levels=[0,1]`` would filter on `n` valid values per replicate. Alternatively, ``levels=[0]`` would filter on `n`
valid values at the Group level only, e.g. A, B or C.
By default valid values are determined by `np.nan`. However, alternatives can be supplied via `invalid`.
:param df: Pandas ``DataFrame``
:param levels: ``list`` of ``int`` specifying levels of column ``MultiIndex`` to group by
:param n: ``int`` minimum number of valid values threshold
:param invalid: matching invalid value
:return: filtered Pandas ``DataFrame``
"""
df = df.copy()
if levels is None:
if 'Group' in df.columns.names:
levels = [df.columns.names.index('Group')]
# Filter by at least 7 (values in class:timepoint) at least in at least one group
if invalid is np.nan:
dfx = ~np.isnan(df)
else:
dfx = df != invalid
dfc = dfx.astype(int).sum(axis=1, level=levels)
dfm = dfc.max(axis=1) >= n
mask = dfm.values
return df.iloc[mask, :] | [
"def",
"minimum_valid_values_in_any_group",
"(",
"df",
",",
"levels",
"=",
"None",
",",
"n",
"=",
"1",
",",
"invalid",
"=",
"np",
".",
"nan",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"if",
"levels",
"is",
"None",
":",
"if",
"'Group'",
"in",
"df",
".",
"columns",
".",
"names",
":",
"levels",
"=",
"[",
"df",
".",
"columns",
".",
"names",
".",
"index",
"(",
"'Group'",
")",
"]",
"# Filter by at least 7 (values in class:timepoint) at least in at least one group",
"if",
"invalid",
"is",
"np",
".",
"nan",
":",
"dfx",
"=",
"~",
"np",
".",
"isnan",
"(",
"df",
")",
"else",
":",
"dfx",
"=",
"df",
"!=",
"invalid",
"dfc",
"=",
"dfx",
".",
"astype",
"(",
"int",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
",",
"level",
"=",
"levels",
")",
"dfm",
"=",
"dfc",
".",
"max",
"(",
"axis",
"=",
"1",
")",
">=",
"n",
"mask",
"=",
"dfm",
".",
"values",
"return",
"df",
".",
"iloc",
"[",
"mask",
",",
":",
"]"
] | Filter ``DataFrame`` by at least n valid values in at least one group.
Taking a Pandas ``DataFrame`` with a ``MultiIndex`` column index, filters rows to remove
rows where there are less than `n` valid values per group. Groups are defined by the `levels` parameter indexing
into the column index. For example, a ``MultiIndex`` with top and second level Group (A,B,C) and Replicate (1,2,3) using
``levels=[0,1]`` would filter on `n` valid values per replicate. Alternatively, ``levels=[0]`` would filter on `n`
valid values at the Group level only, e.g. A, B or C.
By default valid values are determined by `np.nan`. However, alternatives can be supplied via `invalid`.
:param df: Pandas ``DataFrame``
:param levels: ``list`` of ``int`` specifying levels of column ``MultiIndex`` to group by
:param n: ``int`` minimum number of valid values threshold
:param invalid: matching invalid value
:return: filtered Pandas ``DataFrame`` | [
"Filter",
"DataFrame",
"by",
"at",
"least",
"n",
"valid",
"values",
"in",
"at",
"least",
"one",
"group",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L93-L129 |
5,975 | mfitzp/padua | padua/filters.py | search | def search(df, match, columns=['Proteins','Protein names','Gene names']):
"""
Search for a given string in a set of columns in a processed ``DataFrame``.
Returns a filtered ``DataFrame`` where `match` is contained in one of the `columns`.
:param df: Pandas ``DataFrame``
:param match: ``str`` to search for in columns
:param columns: ``list`` of ``str`` to search for match
:return: filtered Pandas ``DataFrame``
"""
df = df.copy()
dft = df.reset_index()
mask = np.zeros((dft.shape[0],), dtype=bool)
idx = ['Proteins','Protein names','Gene names']
for i in idx:
if i in dft.columns:
mask = mask | np.array([match in str(l) for l in dft[i].values])
return df.iloc[mask] | python | def search(df, match, columns=['Proteins','Protein names','Gene names']):
"""
Search for a given string in a set of columns in a processed ``DataFrame``.
Returns a filtered ``DataFrame`` where `match` is contained in one of the `columns`.
:param df: Pandas ``DataFrame``
:param match: ``str`` to search for in columns
:param columns: ``list`` of ``str`` to search for match
:return: filtered Pandas ``DataFrame``
"""
df = df.copy()
dft = df.reset_index()
mask = np.zeros((dft.shape[0],), dtype=bool)
idx = ['Proteins','Protein names','Gene names']
for i in idx:
if i in dft.columns:
mask = mask | np.array([match in str(l) for l in dft[i].values])
return df.iloc[mask] | [
"def",
"search",
"(",
"df",
",",
"match",
",",
"columns",
"=",
"[",
"'Proteins'",
",",
"'Protein names'",
",",
"'Gene names'",
"]",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"dft",
"=",
"df",
".",
"reset_index",
"(",
")",
"mask",
"=",
"np",
".",
"zeros",
"(",
"(",
"dft",
".",
"shape",
"[",
"0",
"]",
",",
")",
",",
"dtype",
"=",
"bool",
")",
"idx",
"=",
"[",
"'Proteins'",
",",
"'Protein names'",
",",
"'Gene names'",
"]",
"for",
"i",
"in",
"idx",
":",
"if",
"i",
"in",
"dft",
".",
"columns",
":",
"mask",
"=",
"mask",
"|",
"np",
".",
"array",
"(",
"[",
"match",
"in",
"str",
"(",
"l",
")",
"for",
"l",
"in",
"dft",
"[",
"i",
"]",
".",
"values",
"]",
")",
"return",
"df",
".",
"iloc",
"[",
"mask",
"]"
] | Search for a given string in a set of columns in a processed ``DataFrame``.
Returns a filtered ``DataFrame`` where `match` is contained in one of the `columns`.
:param df: Pandas ``DataFrame``
:param match: ``str`` to search for in columns
:param columns: ``list`` of ``str`` to search for match
:return: filtered Pandas ``DataFrame`` | [
"Search",
"for",
"a",
"given",
"string",
"in",
"a",
"set",
"of",
"columns",
"in",
"a",
"processed",
"DataFrame",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L132-L152 |
5,976 | mfitzp/padua | padua/filters.py | filter_select_columns_intensity | def filter_select_columns_intensity(df, prefix, columns):
"""
Filter dataframe to include specified columns, retaining any Intensity columns.
"""
# Note: I use %s.+ (not %s.*) so it forces a match with the prefix string, ONLY if it is followed by something.
return df.filter(regex='^(%s.+|%s)$' % (prefix, '|'.join(columns)) ) | python | def filter_select_columns_intensity(df, prefix, columns):
"""
Filter dataframe to include specified columns, retaining any Intensity columns.
"""
# Note: I use %s.+ (not %s.*) so it forces a match with the prefix string, ONLY if it is followed by something.
return df.filter(regex='^(%s.+|%s)$' % (prefix, '|'.join(columns)) ) | [
"def",
"filter_select_columns_intensity",
"(",
"df",
",",
"prefix",
",",
"columns",
")",
":",
"# Note: I use %s.+ (not %s.*) so it forces a match with the prefix string, ONLY if it is followed by something.",
"return",
"df",
".",
"filter",
"(",
"regex",
"=",
"'^(%s.+|%s)$'",
"%",
"(",
"prefix",
",",
"'|'",
".",
"join",
"(",
"columns",
")",
")",
")"
] | Filter dataframe to include specified columns, retaining any Intensity columns. | [
"Filter",
"dataframe",
"to",
"include",
"specified",
"columns",
"retaining",
"any",
"Intensity",
"columns",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L163-L168 |
5,977 | mfitzp/padua | padua/filters.py | filter_intensity | def filter_intensity(df, label="", with_multiplicity=False):
"""
Filter to include only the Intensity values with optional specified label, excluding other
Intensity measurements, but retaining all other columns.
"""
label += ".*__\d" if with_multiplicity else ""
dft = df.filter(regex="^(?!Intensity).*$")
dfi = df.filter(regex='^(.*Intensity.*%s.*__\d)$' % label)
return pd.concat([dft,dfi], axis=1) | python | def filter_intensity(df, label="", with_multiplicity=False):
"""
Filter to include only the Intensity values with optional specified label, excluding other
Intensity measurements, but retaining all other columns.
"""
label += ".*__\d" if with_multiplicity else ""
dft = df.filter(regex="^(?!Intensity).*$")
dfi = df.filter(regex='^(.*Intensity.*%s.*__\d)$' % label)
return pd.concat([dft,dfi], axis=1) | [
"def",
"filter_intensity",
"(",
"df",
",",
"label",
"=",
"\"\"",
",",
"with_multiplicity",
"=",
"False",
")",
":",
"label",
"+=",
"\".*__\\d\"",
"if",
"with_multiplicity",
"else",
"\"\"",
"dft",
"=",
"df",
".",
"filter",
"(",
"regex",
"=",
"\"^(?!Intensity).*$\"",
")",
"dfi",
"=",
"df",
".",
"filter",
"(",
"regex",
"=",
"'^(.*Intensity.*%s.*__\\d)$'",
"%",
"label",
")",
"return",
"pd",
".",
"concat",
"(",
"[",
"dft",
",",
"dfi",
"]",
",",
"axis",
"=",
"1",
")"
] | Filter to include only the Intensity values with optional specified label, excluding other
Intensity measurements, but retaining all other columns. | [
"Filter",
"to",
"include",
"only",
"the",
"Intensity",
"values",
"with",
"optional",
"specified",
"label",
"excluding",
"other",
"Intensity",
"measurements",
"but",
"retaining",
"all",
"other",
"columns",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L177-L187 |
5,978 | mfitzp/padua | padua/filters.py | filter_ratio | def filter_ratio(df, label="", with_multiplicity=False):
"""
Filter to include only the Ratio values with optional specified label, excluding other
Intensity measurements, but retaining all other columns.
"""
label += ".*__\d" if with_multiplicity else ""
dft = df.filter(regex="^(?!Ratio).*$")
dfr = df.filter(regex='^(.*Ratio.*%s)$' % label)
return pd.concat([dft,dfr], axis=1) | python | def filter_ratio(df, label="", with_multiplicity=False):
"""
Filter to include only the Ratio values with optional specified label, excluding other
Intensity measurements, but retaining all other columns.
"""
label += ".*__\d" if with_multiplicity else ""
dft = df.filter(regex="^(?!Ratio).*$")
dfr = df.filter(regex='^(.*Ratio.*%s)$' % label)
return pd.concat([dft,dfr], axis=1) | [
"def",
"filter_ratio",
"(",
"df",
",",
"label",
"=",
"\"\"",
",",
"with_multiplicity",
"=",
"False",
")",
":",
"label",
"+=",
"\".*__\\d\"",
"if",
"with_multiplicity",
"else",
"\"\"",
"dft",
"=",
"df",
".",
"filter",
"(",
"regex",
"=",
"\"^(?!Ratio).*$\"",
")",
"dfr",
"=",
"df",
".",
"filter",
"(",
"regex",
"=",
"'^(.*Ratio.*%s)$'",
"%",
"label",
")",
"return",
"pd",
".",
"concat",
"(",
"[",
"dft",
",",
"dfr",
"]",
",",
"axis",
"=",
"1",
")"
] | Filter to include only the Ratio values with optional specified label, excluding other
Intensity measurements, but retaining all other columns. | [
"Filter",
"to",
"include",
"only",
"the",
"Ratio",
"values",
"with",
"optional",
"specified",
"label",
"excluding",
"other",
"Intensity",
"measurements",
"but",
"retaining",
"all",
"other",
"columns",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L201-L211 |
5,979 | mfitzp/padua | padua/io.py | read_perseus | def read_perseus(f):
"""
Load a Perseus processed data table
:param f: Source file
:return: Pandas dataframe of imported data
"""
df = pd.read_csv(f, delimiter='\t', header=[0,1,2,3], low_memory=False)
df.columns = pd.MultiIndex.from_tuples([(x,) for x in df.columns.get_level_values(0)])
return df | python | def read_perseus(f):
"""
Load a Perseus processed data table
:param f: Source file
:return: Pandas dataframe of imported data
"""
df = pd.read_csv(f, delimiter='\t', header=[0,1,2,3], low_memory=False)
df.columns = pd.MultiIndex.from_tuples([(x,) for x in df.columns.get_level_values(0)])
return df | [
"def",
"read_perseus",
"(",
"f",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"f",
",",
"delimiter",
"=",
"'\\t'",
",",
"header",
"=",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
",",
"low_memory",
"=",
"False",
")",
"df",
".",
"columns",
"=",
"pd",
".",
"MultiIndex",
".",
"from_tuples",
"(",
"[",
"(",
"x",
",",
")",
"for",
"x",
"in",
"df",
".",
"columns",
".",
"get_level_values",
"(",
"0",
")",
"]",
")",
"return",
"df"
] | Load a Perseus processed data table
:param f: Source file
:return: Pandas dataframe of imported data | [
"Load",
"a",
"Perseus",
"processed",
"data",
"table"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L21-L30 |
5,980 | mfitzp/padua | padua/io.py | write_perseus | def write_perseus(f, df):
"""
Export a dataframe to Perseus; recreating the format
:param f:
:param df:
:return:
"""
### Generate the Perseus like type index
FIELD_TYPE_MAP = {
'Amino acid':'C',
'Charge':'C',
'Reverse':'C',
'Potential contaminant':'C',
'Multiplicity':'C',
'Localization prob':'N',
'PEP':'N',
'Score':'N',
'Delta score':'N',
'Score for localization':'N',
'Mass error [ppm]':'N',
'Intensity':'N',
'Position':'N',
'Proteins':'T',
'Positions within proteins':'T',
'Leading proteins':'T',
'Protein names':'T',
'Gene names':'T',
'Sequence window':'T',
'Unique identifier':'T',
}
def map_field_type(n, c):
try:
t = FIELD_TYPE_MAP[c]
except:
t = "E"
# In the first element, add type indicator
if n == 0:
t = "#!{Type}%s" % t
return t
df = df.copy()
df.columns = pd.MultiIndex.from_tuples([(k, map_field_type(n, k)) for n, k in enumerate(df.columns)], names=["Label","Type"])
df = df.transpose().reset_index().transpose()
df.to_csv(f, index=False, header=False) | python | def write_perseus(f, df):
"""
Export a dataframe to Perseus; recreating the format
:param f:
:param df:
:return:
"""
### Generate the Perseus like type index
FIELD_TYPE_MAP = {
'Amino acid':'C',
'Charge':'C',
'Reverse':'C',
'Potential contaminant':'C',
'Multiplicity':'C',
'Localization prob':'N',
'PEP':'N',
'Score':'N',
'Delta score':'N',
'Score for localization':'N',
'Mass error [ppm]':'N',
'Intensity':'N',
'Position':'N',
'Proteins':'T',
'Positions within proteins':'T',
'Leading proteins':'T',
'Protein names':'T',
'Gene names':'T',
'Sequence window':'T',
'Unique identifier':'T',
}
def map_field_type(n, c):
try:
t = FIELD_TYPE_MAP[c]
except:
t = "E"
# In the first element, add type indicator
if n == 0:
t = "#!{Type}%s" % t
return t
df = df.copy()
df.columns = pd.MultiIndex.from_tuples([(k, map_field_type(n, k)) for n, k in enumerate(df.columns)], names=["Label","Type"])
df = df.transpose().reset_index().transpose()
df.to_csv(f, index=False, header=False) | [
"def",
"write_perseus",
"(",
"f",
",",
"df",
")",
":",
"### Generate the Perseus like type index",
"FIELD_TYPE_MAP",
"=",
"{",
"'Amino acid'",
":",
"'C'",
",",
"'Charge'",
":",
"'C'",
",",
"'Reverse'",
":",
"'C'",
",",
"'Potential contaminant'",
":",
"'C'",
",",
"'Multiplicity'",
":",
"'C'",
",",
"'Localization prob'",
":",
"'N'",
",",
"'PEP'",
":",
"'N'",
",",
"'Score'",
":",
"'N'",
",",
"'Delta score'",
":",
"'N'",
",",
"'Score for localization'",
":",
"'N'",
",",
"'Mass error [ppm]'",
":",
"'N'",
",",
"'Intensity'",
":",
"'N'",
",",
"'Position'",
":",
"'N'",
",",
"'Proteins'",
":",
"'T'",
",",
"'Positions within proteins'",
":",
"'T'",
",",
"'Leading proteins'",
":",
"'T'",
",",
"'Protein names'",
":",
"'T'",
",",
"'Gene names'",
":",
"'T'",
",",
"'Sequence window'",
":",
"'T'",
",",
"'Unique identifier'",
":",
"'T'",
",",
"}",
"def",
"map_field_type",
"(",
"n",
",",
"c",
")",
":",
"try",
":",
"t",
"=",
"FIELD_TYPE_MAP",
"[",
"c",
"]",
"except",
":",
"t",
"=",
"\"E\"",
"# In the first element, add type indicator",
"if",
"n",
"==",
"0",
":",
"t",
"=",
"\"#!{Type}%s\"",
"%",
"t",
"return",
"t",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"df",
".",
"columns",
"=",
"pd",
".",
"MultiIndex",
".",
"from_tuples",
"(",
"[",
"(",
"k",
",",
"map_field_type",
"(",
"n",
",",
"k",
")",
")",
"for",
"n",
",",
"k",
"in",
"enumerate",
"(",
"df",
".",
"columns",
")",
"]",
",",
"names",
"=",
"[",
"\"Label\"",
",",
"\"Type\"",
"]",
")",
"df",
"=",
"df",
".",
"transpose",
"(",
")",
".",
"reset_index",
"(",
")",
".",
"transpose",
"(",
")",
"df",
".",
"to_csv",
"(",
"f",
",",
"index",
"=",
"False",
",",
"header",
"=",
"False",
")"
] | Export a dataframe to Perseus; recreating the format
:param f:
:param df:
:return: | [
"Export",
"a",
"dataframe",
"to",
"Perseus",
";",
"recreating",
"the",
"format"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L33-L82 |
5,981 | mfitzp/padua | padua/io.py | write_phosphopath_ratio | def write_phosphopath_ratio(df, f, a, *args, **kwargs):
"""
Write out the data frame ratio between two groups
protein-Rsite-multiplicity-timepoint
ID Ratio
Q13619-S10-1-1 0.5
Q9H3Z4-S10-1-1 0.502
Q6GQQ9-S100-1-1 0.504
Q86YP4-S100-1-1 0.506
Q9H307-S100-1-1 0.508
Q8NEY1-S1000-1-1 0.51
Q13541-S101-1-1 0.512
O95785-S1012-2-1 0.514
O95785-S1017-2-1 0.516
Q9Y4G8-S1022-1-1 0.518
P35658-S1023-1-1 0.52
Provide a dataframe, filename for output and a control selector. A series of
selectors following this will be compared (ratio mean) to the first. If you
provide a kwargs timepoint_idx the timepoint information from your selection will
be added from the selector index, e.g. timepoint_idx=1 will use the first level
of the selector as timepoint information, so ("Control", 30) would give timepoint 30.
:param df:
:param a:
:param *args
:param **kwargs: use timepoint= to define column index for timepoint information, extracted from args.
:return:
"""
timepoint_idx = kwargs.get('timepoint_idx', None)
proteins = [get_protein_id(k) for k in df.index.get_level_values('Proteins')]
amino_acids = df.index.get_level_values('Amino acid')
positions = _get_positions(df)
multiplicity = [int(k[-1]) for k in df.index.get_level_values('Multiplicity')]
apos = ["%s%s" % x for x in zip(amino_acids, positions)]
phdfs = []
# Convert timepoints to 1-based ordinal.
tp_map = set()
for c in args:
tp_map.add(c[timepoint_idx])
tp_map = sorted(tp_map)
for c in args:
v = df[a].mean(axis=1).values / df[c].mean(axis=1).values
tp = [1 + tp_map.index(c[timepoint_idx])]
tps = tp * len(proteins) if timepoint_idx else [1] * len(proteins)
prar = ["%s-%s-%d-%d" % x for x in zip(proteins, apos, multiplicity, tps)]
phdf = pd.DataFrame(np.array(list(zip(prar, v))))
phdf.columns = ["ID", "Ratio"]
phdfs.append(phdf)
pd.concat(phdfs).to_csv(f, sep='\t', index=None) | python | def write_phosphopath_ratio(df, f, a, *args, **kwargs):
"""
Write out the data frame ratio between two groups
protein-Rsite-multiplicity-timepoint
ID Ratio
Q13619-S10-1-1 0.5
Q9H3Z4-S10-1-1 0.502
Q6GQQ9-S100-1-1 0.504
Q86YP4-S100-1-1 0.506
Q9H307-S100-1-1 0.508
Q8NEY1-S1000-1-1 0.51
Q13541-S101-1-1 0.512
O95785-S1012-2-1 0.514
O95785-S1017-2-1 0.516
Q9Y4G8-S1022-1-1 0.518
P35658-S1023-1-1 0.52
Provide a dataframe, filename for output and a control selector. A series of
selectors following this will be compared (ratio mean) to the first. If you
provide a kwargs timepoint_idx the timepoint information from your selection will
be added from the selector index, e.g. timepoint_idx=1 will use the first level
of the selector as timepoint information, so ("Control", 30) would give timepoint 30.
:param df:
:param a:
:param *args
:param **kwargs: use timepoint= to define column index for timepoint information, extracted from args.
:return:
"""
timepoint_idx = kwargs.get('timepoint_idx', None)
proteins = [get_protein_id(k) for k in df.index.get_level_values('Proteins')]
amino_acids = df.index.get_level_values('Amino acid')
positions = _get_positions(df)
multiplicity = [int(k[-1]) for k in df.index.get_level_values('Multiplicity')]
apos = ["%s%s" % x for x in zip(amino_acids, positions)]
phdfs = []
# Convert timepoints to 1-based ordinal.
tp_map = set()
for c in args:
tp_map.add(c[timepoint_idx])
tp_map = sorted(tp_map)
for c in args:
v = df[a].mean(axis=1).values / df[c].mean(axis=1).values
tp = [1 + tp_map.index(c[timepoint_idx])]
tps = tp * len(proteins) if timepoint_idx else [1] * len(proteins)
prar = ["%s-%s-%d-%d" % x for x in zip(proteins, apos, multiplicity, tps)]
phdf = pd.DataFrame(np.array(list(zip(prar, v))))
phdf.columns = ["ID", "Ratio"]
phdfs.append(phdf)
pd.concat(phdfs).to_csv(f, sep='\t', index=None) | [
"def",
"write_phosphopath_ratio",
"(",
"df",
",",
"f",
",",
"a",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timepoint_idx",
"=",
"kwargs",
".",
"get",
"(",
"'timepoint_idx'",
",",
"None",
")",
"proteins",
"=",
"[",
"get_protein_id",
"(",
"k",
")",
"for",
"k",
"in",
"df",
".",
"index",
".",
"get_level_values",
"(",
"'Proteins'",
")",
"]",
"amino_acids",
"=",
"df",
".",
"index",
".",
"get_level_values",
"(",
"'Amino acid'",
")",
"positions",
"=",
"_get_positions",
"(",
"df",
")",
"multiplicity",
"=",
"[",
"int",
"(",
"k",
"[",
"-",
"1",
"]",
")",
"for",
"k",
"in",
"df",
".",
"index",
".",
"get_level_values",
"(",
"'Multiplicity'",
")",
"]",
"apos",
"=",
"[",
"\"%s%s\"",
"%",
"x",
"for",
"x",
"in",
"zip",
"(",
"amino_acids",
",",
"positions",
")",
"]",
"phdfs",
"=",
"[",
"]",
"# Convert timepoints to 1-based ordinal.",
"tp_map",
"=",
"set",
"(",
")",
"for",
"c",
"in",
"args",
":",
"tp_map",
".",
"add",
"(",
"c",
"[",
"timepoint_idx",
"]",
")",
"tp_map",
"=",
"sorted",
"(",
"tp_map",
")",
"for",
"c",
"in",
"args",
":",
"v",
"=",
"df",
"[",
"a",
"]",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
".",
"values",
"/",
"df",
"[",
"c",
"]",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
".",
"values",
"tp",
"=",
"[",
"1",
"+",
"tp_map",
".",
"index",
"(",
"c",
"[",
"timepoint_idx",
"]",
")",
"]",
"tps",
"=",
"tp",
"*",
"len",
"(",
"proteins",
")",
"if",
"timepoint_idx",
"else",
"[",
"1",
"]",
"*",
"len",
"(",
"proteins",
")",
"prar",
"=",
"[",
"\"%s-%s-%d-%d\"",
"%",
"x",
"for",
"x",
"in",
"zip",
"(",
"proteins",
",",
"apos",
",",
"multiplicity",
",",
"tps",
")",
"]",
"phdf",
"=",
"pd",
".",
"DataFrame",
"(",
"np",
".",
"array",
"(",
"list",
"(",
"zip",
"(",
"prar",
",",
"v",
")",
")",
")",
")",
"phdf",
".",
"columns",
"=",
"[",
"\"ID\"",
",",
"\"Ratio\"",
"]",
"phdfs",
".",
"append",
"(",
"phdf",
")",
"pd",
".",
"concat",
"(",
"phdfs",
")",
".",
"to_csv",
"(",
"f",
",",
"sep",
"=",
"'\\t'",
",",
"index",
"=",
"None",
")"
] | Write out the data frame ratio between two groups
protein-Rsite-multiplicity-timepoint
ID Ratio
Q13619-S10-1-1 0.5
Q9H3Z4-S10-1-1 0.502
Q6GQQ9-S100-1-1 0.504
Q86YP4-S100-1-1 0.506
Q9H307-S100-1-1 0.508
Q8NEY1-S1000-1-1 0.51
Q13541-S101-1-1 0.512
O95785-S1012-2-1 0.514
O95785-S1017-2-1 0.516
Q9Y4G8-S1022-1-1 0.518
P35658-S1023-1-1 0.52
Provide a dataframe, filename for output and a control selector. A series of
selectors following this will be compared (ratio mean) to the first. If you
provide a kwargs timepoint_idx the timepoint information from your selection will
be added from the selector index, e.g. timepoint_idx=1 will use the first level
of the selector as timepoint information, so ("Control", 30) would give timepoint 30.
:param df:
:param a:
:param *args
:param **kwargs: use timepoint= to define column index for timepoint information, extracted from args.
:return: | [
"Write",
"out",
"the",
"data",
"frame",
"ratio",
"between",
"two",
"groups",
"protein",
"-",
"Rsite",
"-",
"multiplicity",
"-",
"timepoint",
"ID",
"Ratio",
"Q13619",
"-",
"S10",
"-",
"1",
"-",
"1",
"0",
".",
"5",
"Q9H3Z4",
"-",
"S10",
"-",
"1",
"-",
"1",
"0",
".",
"502",
"Q6GQQ9",
"-",
"S100",
"-",
"1",
"-",
"1",
"0",
".",
"504",
"Q86YP4",
"-",
"S100",
"-",
"1",
"-",
"1",
"0",
".",
"506",
"Q9H307",
"-",
"S100",
"-",
"1",
"-",
"1",
"0",
".",
"508",
"Q8NEY1",
"-",
"S1000",
"-",
"1",
"-",
"1",
"0",
".",
"51",
"Q13541",
"-",
"S101",
"-",
"1",
"-",
"1",
"0",
".",
"512",
"O95785",
"-",
"S1012",
"-",
"2",
"-",
"1",
"0",
".",
"514",
"O95785",
"-",
"S1017",
"-",
"2",
"-",
"1",
"0",
".",
"516",
"Q9Y4G8",
"-",
"S1022",
"-",
"1",
"-",
"1",
"0",
".",
"518",
"P35658",
"-",
"S1023",
"-",
"1",
"-",
"1",
"0",
".",
"52"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L129-L185 |
5,982 | mfitzp/padua | padua/io.py | write_r | def write_r(df, f, sep=",", index_join="@", columns_join="."):
"""
Export dataframe in a format easily importable to R
Index fields are joined with "@" and column fields by "." by default.
:param df:
:param f:
:param index_join:
:param columns_join:
:return:
"""
df = df.copy()
df.index = ["@".join([str(s) for s in v]) for v in df.index.values]
df.columns = [".".join([str(s) for s in v]) for v in df.index.values]
df.to_csv(f, sep=sep) | python | def write_r(df, f, sep=",", index_join="@", columns_join="."):
"""
Export dataframe in a format easily importable to R
Index fields are joined with "@" and column fields by "." by default.
:param df:
:param f:
:param index_join:
:param columns_join:
:return:
"""
df = df.copy()
df.index = ["@".join([str(s) for s in v]) for v in df.index.values]
df.columns = [".".join([str(s) for s in v]) for v in df.index.values]
df.to_csv(f, sep=sep) | [
"def",
"write_r",
"(",
"df",
",",
"f",
",",
"sep",
"=",
"\",\"",
",",
"index_join",
"=",
"\"@\"",
",",
"columns_join",
"=",
"\".\"",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"df",
".",
"index",
"=",
"[",
"\"@\"",
".",
"join",
"(",
"[",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"v",
"]",
")",
"for",
"v",
"in",
"df",
".",
"index",
".",
"values",
"]",
"df",
".",
"columns",
"=",
"[",
"\".\"",
".",
"join",
"(",
"[",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"v",
"]",
")",
"for",
"v",
"in",
"df",
".",
"index",
".",
"values",
"]",
"df",
".",
"to_csv",
"(",
"f",
",",
"sep",
"=",
"sep",
")"
] | Export dataframe in a format easily importable to R
Index fields are joined with "@" and column fields by "." by default.
:param df:
:param f:
:param index_join:
:param columns_join:
:return: | [
"Export",
"dataframe",
"in",
"a",
"format",
"easily",
"importable",
"to",
"R"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L188-L203 |
5,983 | mfitzp/padua | padua/imputation.py | gaussian | def gaussian(df, width=0.3, downshift=-1.8, prefix=None):
"""
Impute missing values by drawing from a normal distribution
:param df:
:param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column.
:param downshift: Shift the imputed values down, in units of std. dev. Can be a single number or list of one per column
:param prefix: The column prefix for imputed columns
:return:
"""
df = df.copy()
imputed = df.isnull() # Keep track of what's real
if prefix:
mask = np.array([l.startswith(prefix) for l in df.columns.values])
mycols = np.arange(0, df.shape[1])[mask]
else:
mycols = np.arange(0, df.shape[1])
if type(width) is not list:
width = [width] * len(mycols)
elif len(mycols) != len(width):
raise ValueError("Length of iterable 'width' does not match # of columns")
if type(downshift) is not list:
downshift = [downshift] * len(mycols)
elif len(mycols) != len(downshift):
raise ValueError("Length of iterable 'downshift' does not match # of columns")
for i in mycols:
data = df.iloc[:, i]
mask = data.isnull().values
mean = data.mean(axis=0)
stddev = data.std(axis=0)
m = mean + downshift[i]*stddev
s = stddev*width[i]
# Generate a list of random numbers for filling in
values = np.random.normal(loc=m, scale=s, size=df.shape[0])
# Now fill them in
df.iloc[mask, i] = values[mask]
return df, imputed | python | def gaussian(df, width=0.3, downshift=-1.8, prefix=None):
"""
Impute missing values by drawing from a normal distribution
:param df:
:param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column.
:param downshift: Shift the imputed values down, in units of std. dev. Can be a single number or list of one per column
:param prefix: The column prefix for imputed columns
:return:
"""
df = df.copy()
imputed = df.isnull() # Keep track of what's real
if prefix:
mask = np.array([l.startswith(prefix) for l in df.columns.values])
mycols = np.arange(0, df.shape[1])[mask]
else:
mycols = np.arange(0, df.shape[1])
if type(width) is not list:
width = [width] * len(mycols)
elif len(mycols) != len(width):
raise ValueError("Length of iterable 'width' does not match # of columns")
if type(downshift) is not list:
downshift = [downshift] * len(mycols)
elif len(mycols) != len(downshift):
raise ValueError("Length of iterable 'downshift' does not match # of columns")
for i in mycols:
data = df.iloc[:, i]
mask = data.isnull().values
mean = data.mean(axis=0)
stddev = data.std(axis=0)
m = mean + downshift[i]*stddev
s = stddev*width[i]
# Generate a list of random numbers for filling in
values = np.random.normal(loc=m, scale=s, size=df.shape[0])
# Now fill them in
df.iloc[mask, i] = values[mask]
return df, imputed | [
"def",
"gaussian",
"(",
"df",
",",
"width",
"=",
"0.3",
",",
"downshift",
"=",
"-",
"1.8",
",",
"prefix",
"=",
"None",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"imputed",
"=",
"df",
".",
"isnull",
"(",
")",
"# Keep track of what's real",
"if",
"prefix",
":",
"mask",
"=",
"np",
".",
"array",
"(",
"[",
"l",
".",
"startswith",
"(",
"prefix",
")",
"for",
"l",
"in",
"df",
".",
"columns",
".",
"values",
"]",
")",
"mycols",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"df",
".",
"shape",
"[",
"1",
"]",
")",
"[",
"mask",
"]",
"else",
":",
"mycols",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"df",
".",
"shape",
"[",
"1",
"]",
")",
"if",
"type",
"(",
"width",
")",
"is",
"not",
"list",
":",
"width",
"=",
"[",
"width",
"]",
"*",
"len",
"(",
"mycols",
")",
"elif",
"len",
"(",
"mycols",
")",
"!=",
"len",
"(",
"width",
")",
":",
"raise",
"ValueError",
"(",
"\"Length of iterable 'width' does not match # of columns\"",
")",
"if",
"type",
"(",
"downshift",
")",
"is",
"not",
"list",
":",
"downshift",
"=",
"[",
"downshift",
"]",
"*",
"len",
"(",
"mycols",
")",
"elif",
"len",
"(",
"mycols",
")",
"!=",
"len",
"(",
"downshift",
")",
":",
"raise",
"ValueError",
"(",
"\"Length of iterable 'downshift' does not match # of columns\"",
")",
"for",
"i",
"in",
"mycols",
":",
"data",
"=",
"df",
".",
"iloc",
"[",
":",
",",
"i",
"]",
"mask",
"=",
"data",
".",
"isnull",
"(",
")",
".",
"values",
"mean",
"=",
"data",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"stddev",
"=",
"data",
".",
"std",
"(",
"axis",
"=",
"0",
")",
"m",
"=",
"mean",
"+",
"downshift",
"[",
"i",
"]",
"*",
"stddev",
"s",
"=",
"stddev",
"*",
"width",
"[",
"i",
"]",
"# Generate a list of random numbers for filling in",
"values",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"loc",
"=",
"m",
",",
"scale",
"=",
"s",
",",
"size",
"=",
"df",
".",
"shape",
"[",
"0",
"]",
")",
"# Now fill them in",
"df",
".",
"iloc",
"[",
"mask",
",",
"i",
"]",
"=",
"values",
"[",
"mask",
"]",
"return",
"df",
",",
"imputed"
] | Impute missing values by drawing from a normal distribution
:param df:
:param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column.
:param downshift: Shift the imputed values down, in units of std. dev. Can be a single number or list of one per column
:param prefix: The column prefix for imputed columns
:return: | [
"Impute",
"missing",
"values",
"by",
"drawing",
"from",
"a",
"normal",
"distribution"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/imputation.py#L14-L63 |
5,984 | mfitzp/padua | padua/visualize.py | _pca_scores | def _pca_scores(
scores,
pc1=0,
pc2=1,
fcol=None,
ecol=None,
marker='o',
markersize=30,
label_scores=None,
show_covariance_ellipse=True,
optimize_label_iter=OPTIMIZE_LABEL_ITER_DEFAULT,
**kwargs
):
"""
Plot a scores plot for two principal components as AxB scatter plot.
Returns the plotted axis.
:param scores: DataFrame containing scores
:param pc1: Column indexer into scores for PC1
:param pc2: Column indexer into scores for PC2
:param fcol: Face (fill) color definition
:param ecol: Edge color definition
:param marker: Marker style (matplotlib; default 'o')
:param markersize: int Size of the marker
:param label_scores: Index level to label markers with
:param show_covariance_ellipse: Plot covariance (2*std) ellipse around each grouping
:param optimize_label_iter: Number of iterations to run label adjustment algorithm
:return: Generated axes
"""
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1,1,1)
levels = [0,1]
for c in set(scores.columns.values):
try:
data = scores[c].values.reshape(2,-1)
except:
continue
fc = hierarchical_match(fcol, c, 'k')
ec = hierarchical_match(ecol, c)
if ec is None:
ec = fc
if type(markersize) == str:
# Use as a key vs. index value in this levels
idx = scores.columns.names.index(markersize)
s = c[idx]
elif callable(markersize):
s = markersize(c)
else:
s = markersize
ax.scatter(data[pc1,:], data[pc2,:], s=s, marker=marker, edgecolors=ec, c=fc)
if show_covariance_ellipse and data.shape[1] > 2:
cov = data[[pc1, pc2], :].T
ellip = plot_point_cov(cov, nstd=2, linestyle='dashed', linewidth=0.5, edgecolor=ec or fc,
alpha=0.8) #**kwargs for ellipse styling
ax.add_artist(ellip)
if label_scores:
scores_f = scores.iloc[ [pc1, pc2] ]
idxs = get_index_list( scores_f.columns.names, label_scores )
texts = []
for n, (x, y) in enumerate(scores_f.T.values):
t = ax.text(x, y, build_combined_label( scores_f.columns.values[n], idxs, ', '), bbox=dict(boxstyle='round,pad=0.3', fc='#ffffff', ec='none', alpha=0.6))
texts.append(t)
if texts and optimize_label_iter:
adjust_text(
texts,
lim=optimize_label_iter
)
ax.set_xlabel(scores.index[pc1], fontsize=16)
ax.set_ylabel(scores.index[pc2], fontsize=16)
fig.tight_layout()
return ax | python | def _pca_scores(
scores,
pc1=0,
pc2=1,
fcol=None,
ecol=None,
marker='o',
markersize=30,
label_scores=None,
show_covariance_ellipse=True,
optimize_label_iter=OPTIMIZE_LABEL_ITER_DEFAULT,
**kwargs
):
"""
Plot a scores plot for two principal components as AxB scatter plot.
Returns the plotted axis.
:param scores: DataFrame containing scores
:param pc1: Column indexer into scores for PC1
:param pc2: Column indexer into scores for PC2
:param fcol: Face (fill) color definition
:param ecol: Edge color definition
:param marker: Marker style (matplotlib; default 'o')
:param markersize: int Size of the marker
:param label_scores: Index level to label markers with
:param show_covariance_ellipse: Plot covariance (2*std) ellipse around each grouping
:param optimize_label_iter: Number of iterations to run label adjustment algorithm
:return: Generated axes
"""
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1,1,1)
levels = [0,1]
for c in set(scores.columns.values):
try:
data = scores[c].values.reshape(2,-1)
except:
continue
fc = hierarchical_match(fcol, c, 'k')
ec = hierarchical_match(ecol, c)
if ec is None:
ec = fc
if type(markersize) == str:
# Use as a key vs. index value in this levels
idx = scores.columns.names.index(markersize)
s = c[idx]
elif callable(markersize):
s = markersize(c)
else:
s = markersize
ax.scatter(data[pc1,:], data[pc2,:], s=s, marker=marker, edgecolors=ec, c=fc)
if show_covariance_ellipse and data.shape[1] > 2:
cov = data[[pc1, pc2], :].T
ellip = plot_point_cov(cov, nstd=2, linestyle='dashed', linewidth=0.5, edgecolor=ec or fc,
alpha=0.8) #**kwargs for ellipse styling
ax.add_artist(ellip)
if label_scores:
scores_f = scores.iloc[ [pc1, pc2] ]
idxs = get_index_list( scores_f.columns.names, label_scores )
texts = []
for n, (x, y) in enumerate(scores_f.T.values):
t = ax.text(x, y, build_combined_label( scores_f.columns.values[n], idxs, ', '), bbox=dict(boxstyle='round,pad=0.3', fc='#ffffff', ec='none', alpha=0.6))
texts.append(t)
if texts and optimize_label_iter:
adjust_text(
texts,
lim=optimize_label_iter
)
ax.set_xlabel(scores.index[pc1], fontsize=16)
ax.set_ylabel(scores.index[pc2], fontsize=16)
fig.tight_layout()
return ax | [
"def",
"_pca_scores",
"(",
"scores",
",",
"pc1",
"=",
"0",
",",
"pc2",
"=",
"1",
",",
"fcol",
"=",
"None",
",",
"ecol",
"=",
"None",
",",
"marker",
"=",
"'o'",
",",
"markersize",
"=",
"30",
",",
"label_scores",
"=",
"None",
",",
"show_covariance_ellipse",
"=",
"True",
",",
"optimize_label_iter",
"=",
"OPTIMIZE_LABEL_ITER_DEFAULT",
",",
"*",
"*",
"kwargs",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"8",
",",
"8",
")",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"1",
",",
"1",
",",
"1",
")",
"levels",
"=",
"[",
"0",
",",
"1",
"]",
"for",
"c",
"in",
"set",
"(",
"scores",
".",
"columns",
".",
"values",
")",
":",
"try",
":",
"data",
"=",
"scores",
"[",
"c",
"]",
".",
"values",
".",
"reshape",
"(",
"2",
",",
"-",
"1",
")",
"except",
":",
"continue",
"fc",
"=",
"hierarchical_match",
"(",
"fcol",
",",
"c",
",",
"'k'",
")",
"ec",
"=",
"hierarchical_match",
"(",
"ecol",
",",
"c",
")",
"if",
"ec",
"is",
"None",
":",
"ec",
"=",
"fc",
"if",
"type",
"(",
"markersize",
")",
"==",
"str",
":",
"# Use as a key vs. index value in this levels",
"idx",
"=",
"scores",
".",
"columns",
".",
"names",
".",
"index",
"(",
"markersize",
")",
"s",
"=",
"c",
"[",
"idx",
"]",
"elif",
"callable",
"(",
"markersize",
")",
":",
"s",
"=",
"markersize",
"(",
"c",
")",
"else",
":",
"s",
"=",
"markersize",
"ax",
".",
"scatter",
"(",
"data",
"[",
"pc1",
",",
":",
"]",
",",
"data",
"[",
"pc2",
",",
":",
"]",
",",
"s",
"=",
"s",
",",
"marker",
"=",
"marker",
",",
"edgecolors",
"=",
"ec",
",",
"c",
"=",
"fc",
")",
"if",
"show_covariance_ellipse",
"and",
"data",
".",
"shape",
"[",
"1",
"]",
">",
"2",
":",
"cov",
"=",
"data",
"[",
"[",
"pc1",
",",
"pc2",
"]",
",",
":",
"]",
".",
"T",
"ellip",
"=",
"plot_point_cov",
"(",
"cov",
",",
"nstd",
"=",
"2",
",",
"linestyle",
"=",
"'dashed'",
",",
"linewidth",
"=",
"0.5",
",",
"edgecolor",
"=",
"ec",
"or",
"fc",
",",
"alpha",
"=",
"0.8",
")",
"#**kwargs for ellipse styling",
"ax",
".",
"add_artist",
"(",
"ellip",
")",
"if",
"label_scores",
":",
"scores_f",
"=",
"scores",
".",
"iloc",
"[",
"[",
"pc1",
",",
"pc2",
"]",
"]",
"idxs",
"=",
"get_index_list",
"(",
"scores_f",
".",
"columns",
".",
"names",
",",
"label_scores",
")",
"texts",
"=",
"[",
"]",
"for",
"n",
",",
"(",
"x",
",",
"y",
")",
"in",
"enumerate",
"(",
"scores_f",
".",
"T",
".",
"values",
")",
":",
"t",
"=",
"ax",
".",
"text",
"(",
"x",
",",
"y",
",",
"build_combined_label",
"(",
"scores_f",
".",
"columns",
".",
"values",
"[",
"n",
"]",
",",
"idxs",
",",
"', '",
")",
",",
"bbox",
"=",
"dict",
"(",
"boxstyle",
"=",
"'round,pad=0.3'",
",",
"fc",
"=",
"'#ffffff'",
",",
"ec",
"=",
"'none'",
",",
"alpha",
"=",
"0.6",
")",
")",
"texts",
".",
"append",
"(",
"t",
")",
"if",
"texts",
"and",
"optimize_label_iter",
":",
"adjust_text",
"(",
"texts",
",",
"lim",
"=",
"optimize_label_iter",
")",
"ax",
".",
"set_xlabel",
"(",
"scores",
".",
"index",
"[",
"pc1",
"]",
",",
"fontsize",
"=",
"16",
")",
"ax",
".",
"set_ylabel",
"(",
"scores",
".",
"index",
"[",
"pc2",
"]",
",",
"fontsize",
"=",
"16",
")",
"fig",
".",
"tight_layout",
"(",
")",
"return",
"ax"
] | Plot a scores plot for two principal components as AxB scatter plot.
Returns the plotted axis.
:param scores: DataFrame containing scores
:param pc1: Column indexer into scores for PC1
:param pc2: Column indexer into scores for PC2
:param fcol: Face (fill) color definition
:param ecol: Edge color definition
:param marker: Marker style (matplotlib; default 'o')
:param markersize: int Size of the marker
:param label_scores: Index level to label markers with
:param show_covariance_ellipse: Plot covariance (2*std) ellipse around each grouping
:param optimize_label_iter: Number of iterations to run label adjustment algorithm
:return: Generated axes | [
"Plot",
"a",
"scores",
"plot",
"for",
"two",
"principal",
"components",
"as",
"AxB",
"scatter",
"plot",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L117-L200 |
5,985 | mfitzp/padua | padua/visualize.py | modifiedaminoacids | def modifiedaminoacids(df, kind='pie'):
"""
Generate a plot of relative numbers of modified amino acids in source DataFrame.
Plot a pie or bar chart showing the number and percentage of modified amino
acids in the supplied data frame. The amino acids displayed will be
determined from the supplied data/modification type.
:param df: processed DataFrame
:param kind: `str` type of plot; either "pie" or "bar"
:return: matplotlib ax
"""
colors = ['#6baed6','#c6dbef','#bdbdbd']
total_aas, quants = analysis.modifiedaminoacids(df)
df = pd.DataFrame()
for a, n in quants.items():
df[a] = [n]
df.sort_index(axis=1, inplace=True)
if kind == 'bar' or kind == 'both':
ax1 = df.plot(kind='bar', figsize=(7,7), color=colors)
ax1.set_ylabel('Number of phosphorylated amino acids')
ax1.set_xlabel('Amino acid')
ax1.set_xticks([])
ylim = np.max(df.values)+1000
ax1.set_ylim(0, ylim )
_bartoplabel(ax1, 100*df.values[0], total_aas, ylim )
ax1.set_xlim((-0.3, 0.3))
return ax
if kind == 'pie' or kind == 'both':
dfp =df.T
residues = dfp.index.values
dfp.index = ["%.2f%% (%d)" % (100*df[i].values[0]/total_aas, df[i].values[0]) for i in dfp.index.values ]
ax2 = dfp.plot(kind='pie', y=0, colors=colors)
ax2.legend(residues, loc='upper left', bbox_to_anchor=(1.0, 1.0))
ax2.set_ylabel('')
ax2.set_xlabel('')
ax2.figure.set_size_inches(6,6)
for t in ax2.texts:
t.set_fontsize(15)
return ax2
return ax1, ax2 | python | def modifiedaminoacids(df, kind='pie'):
"""
Generate a plot of relative numbers of modified amino acids in source DataFrame.
Plot a pie or bar chart showing the number and percentage of modified amino
acids in the supplied data frame. The amino acids displayed will be
determined from the supplied data/modification type.
:param df: processed DataFrame
:param kind: `str` type of plot; either "pie" or "bar"
:return: matplotlib ax
"""
colors = ['#6baed6','#c6dbef','#bdbdbd']
total_aas, quants = analysis.modifiedaminoacids(df)
df = pd.DataFrame()
for a, n in quants.items():
df[a] = [n]
df.sort_index(axis=1, inplace=True)
if kind == 'bar' or kind == 'both':
ax1 = df.plot(kind='bar', figsize=(7,7), color=colors)
ax1.set_ylabel('Number of phosphorylated amino acids')
ax1.set_xlabel('Amino acid')
ax1.set_xticks([])
ylim = np.max(df.values)+1000
ax1.set_ylim(0, ylim )
_bartoplabel(ax1, 100*df.values[0], total_aas, ylim )
ax1.set_xlim((-0.3, 0.3))
return ax
if kind == 'pie' or kind == 'both':
dfp =df.T
residues = dfp.index.values
dfp.index = ["%.2f%% (%d)" % (100*df[i].values[0]/total_aas, df[i].values[0]) for i in dfp.index.values ]
ax2 = dfp.plot(kind='pie', y=0, colors=colors)
ax2.legend(residues, loc='upper left', bbox_to_anchor=(1.0, 1.0))
ax2.set_ylabel('')
ax2.set_xlabel('')
ax2.figure.set_size_inches(6,6)
for t in ax2.texts:
t.set_fontsize(15)
return ax2
return ax1, ax2 | [
"def",
"modifiedaminoacids",
"(",
"df",
",",
"kind",
"=",
"'pie'",
")",
":",
"colors",
"=",
"[",
"'#6baed6'",
",",
"'#c6dbef'",
",",
"'#bdbdbd'",
"]",
"total_aas",
",",
"quants",
"=",
"analysis",
".",
"modifiedaminoacids",
"(",
"df",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"for",
"a",
",",
"n",
"in",
"quants",
".",
"items",
"(",
")",
":",
"df",
"[",
"a",
"]",
"=",
"[",
"n",
"]",
"df",
".",
"sort_index",
"(",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
"if",
"kind",
"==",
"'bar'",
"or",
"kind",
"==",
"'both'",
":",
"ax1",
"=",
"df",
".",
"plot",
"(",
"kind",
"=",
"'bar'",
",",
"figsize",
"=",
"(",
"7",
",",
"7",
")",
",",
"color",
"=",
"colors",
")",
"ax1",
".",
"set_ylabel",
"(",
"'Number of phosphorylated amino acids'",
")",
"ax1",
".",
"set_xlabel",
"(",
"'Amino acid'",
")",
"ax1",
".",
"set_xticks",
"(",
"[",
"]",
")",
"ylim",
"=",
"np",
".",
"max",
"(",
"df",
".",
"values",
")",
"+",
"1000",
"ax1",
".",
"set_ylim",
"(",
"0",
",",
"ylim",
")",
"_bartoplabel",
"(",
"ax1",
",",
"100",
"*",
"df",
".",
"values",
"[",
"0",
"]",
",",
"total_aas",
",",
"ylim",
")",
"ax1",
".",
"set_xlim",
"(",
"(",
"-",
"0.3",
",",
"0.3",
")",
")",
"return",
"ax",
"if",
"kind",
"==",
"'pie'",
"or",
"kind",
"==",
"'both'",
":",
"dfp",
"=",
"df",
".",
"T",
"residues",
"=",
"dfp",
".",
"index",
".",
"values",
"dfp",
".",
"index",
"=",
"[",
"\"%.2f%% (%d)\"",
"%",
"(",
"100",
"*",
"df",
"[",
"i",
"]",
".",
"values",
"[",
"0",
"]",
"/",
"total_aas",
",",
"df",
"[",
"i",
"]",
".",
"values",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"dfp",
".",
"index",
".",
"values",
"]",
"ax2",
"=",
"dfp",
".",
"plot",
"(",
"kind",
"=",
"'pie'",
",",
"y",
"=",
"0",
",",
"colors",
"=",
"colors",
")",
"ax2",
".",
"legend",
"(",
"residues",
",",
"loc",
"=",
"'upper left'",
",",
"bbox_to_anchor",
"=",
"(",
"1.0",
",",
"1.0",
")",
")",
"ax2",
".",
"set_ylabel",
"(",
"''",
")",
"ax2",
".",
"set_xlabel",
"(",
"''",
")",
"ax2",
".",
"figure",
".",
"set_size_inches",
"(",
"6",
",",
"6",
")",
"for",
"t",
"in",
"ax2",
".",
"texts",
":",
"t",
".",
"set_fontsize",
"(",
"15",
")",
"return",
"ax2",
"return",
"ax1",
",",
"ax2"
] | Generate a plot of relative numbers of modified amino acids in source DataFrame.
Plot a pie or bar chart showing the number and percentage of modified amino
acids in the supplied data frame. The amino acids displayed will be
determined from the supplied data/modification type.
:param df: processed DataFrame
:param kind: `str` type of plot; either "pie" or "bar"
:return: matplotlib ax | [
"Generate",
"a",
"plot",
"of",
"relative",
"numbers",
"of",
"modified",
"amino",
"acids",
"in",
"source",
"DataFrame",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L697-L748 |
5,986 | mfitzp/padua | padua/visualize.py | venn | def venn(df1, df2, df3=None, labels=None, ix1=None, ix2=None, ix3=None, return_intersection=False, fcols=None):
"""
Plot a 2 or 3-part venn diagram showing the overlap between 2 or 3 pandas DataFrames.
Provided with two or three Pandas DataFrames, this will return a venn diagram showing the overlap calculated between
the DataFrame indexes provided as ix1, ix2, ix3. Labels for each DataFrame can be provided as a list in the same order,
while `fcol` can be used to specify the colors of each section.
:param df1: Pandas DataFrame
:param df2: Pandas DataFrame
:param df3: Pandas DataFrame (optional)
:param labels: List of labels for the provided dataframes
:param ix1: Index level name of of Dataframe 1 to use for comparison
:param ix2: Index level name of of Dataframe 2 to use for comparison
:param ix3: Index level name of of Dataframe 3 to use for comparison
:param return_intersection: Return the intersection of the supplied indices
:param fcols: List of colors for the provided dataframes
:return: ax, or ax with intersection
"""
try:
import matplotlib_venn as mplv
except ImportError:
raise ImportError("To plot venn diagrams, install matplotlib-venn package: pip install matplotlib-venn")
plt.gcf().clear()
if labels is None:
labels = ["A", "B", "C"]
s1 = _process_ix(df1.index, ix1)
s2 = _process_ix(df2.index, ix2)
if df3 is not None:
s3 = _process_ix(df3.index, ix3)
kwargs = {}
if fcols:
kwargs['set_colors'] = [fcols[l] for l in labels]
if df3 is not None:
vn = mplv.venn3([s1,s2,s3], set_labels=labels, **kwargs)
intersection = s1 & s2 & s3
else:
vn = mplv.venn2([s1,s2], set_labels=labels, **kwargs)
intersection = s1 & s2
ax = plt.gca()
if return_intersection:
return ax, list(intersection)
else:
return ax | python | def venn(df1, df2, df3=None, labels=None, ix1=None, ix2=None, ix3=None, return_intersection=False, fcols=None):
"""
Plot a 2 or 3-part venn diagram showing the overlap between 2 or 3 pandas DataFrames.
Provided with two or three Pandas DataFrames, this will return a venn diagram showing the overlap calculated between
the DataFrame indexes provided as ix1, ix2, ix3. Labels for each DataFrame can be provided as a list in the same order,
while `fcol` can be used to specify the colors of each section.
:param df1: Pandas DataFrame
:param df2: Pandas DataFrame
:param df3: Pandas DataFrame (optional)
:param labels: List of labels for the provided dataframes
:param ix1: Index level name of of Dataframe 1 to use for comparison
:param ix2: Index level name of of Dataframe 2 to use for comparison
:param ix3: Index level name of of Dataframe 3 to use for comparison
:param return_intersection: Return the intersection of the supplied indices
:param fcols: List of colors for the provided dataframes
:return: ax, or ax with intersection
"""
try:
import matplotlib_venn as mplv
except ImportError:
raise ImportError("To plot venn diagrams, install matplotlib-venn package: pip install matplotlib-venn")
plt.gcf().clear()
if labels is None:
labels = ["A", "B", "C"]
s1 = _process_ix(df1.index, ix1)
s2 = _process_ix(df2.index, ix2)
if df3 is not None:
s3 = _process_ix(df3.index, ix3)
kwargs = {}
if fcols:
kwargs['set_colors'] = [fcols[l] for l in labels]
if df3 is not None:
vn = mplv.venn3([s1,s2,s3], set_labels=labels, **kwargs)
intersection = s1 & s2 & s3
else:
vn = mplv.venn2([s1,s2], set_labels=labels, **kwargs)
intersection = s1 & s2
ax = plt.gca()
if return_intersection:
return ax, list(intersection)
else:
return ax | [
"def",
"venn",
"(",
"df1",
",",
"df2",
",",
"df3",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"ix1",
"=",
"None",
",",
"ix2",
"=",
"None",
",",
"ix3",
"=",
"None",
",",
"return_intersection",
"=",
"False",
",",
"fcols",
"=",
"None",
")",
":",
"try",
":",
"import",
"matplotlib_venn",
"as",
"mplv",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"To plot venn diagrams, install matplotlib-venn package: pip install matplotlib-venn\"",
")",
"plt",
".",
"gcf",
"(",
")",
".",
"clear",
"(",
")",
"if",
"labels",
"is",
"None",
":",
"labels",
"=",
"[",
"\"A\"",
",",
"\"B\"",
",",
"\"C\"",
"]",
"s1",
"=",
"_process_ix",
"(",
"df1",
".",
"index",
",",
"ix1",
")",
"s2",
"=",
"_process_ix",
"(",
"df2",
".",
"index",
",",
"ix2",
")",
"if",
"df3",
"is",
"not",
"None",
":",
"s3",
"=",
"_process_ix",
"(",
"df3",
".",
"index",
",",
"ix3",
")",
"kwargs",
"=",
"{",
"}",
"if",
"fcols",
":",
"kwargs",
"[",
"'set_colors'",
"]",
"=",
"[",
"fcols",
"[",
"l",
"]",
"for",
"l",
"in",
"labels",
"]",
"if",
"df3",
"is",
"not",
"None",
":",
"vn",
"=",
"mplv",
".",
"venn3",
"(",
"[",
"s1",
",",
"s2",
",",
"s3",
"]",
",",
"set_labels",
"=",
"labels",
",",
"*",
"*",
"kwargs",
")",
"intersection",
"=",
"s1",
"&",
"s2",
"&",
"s3",
"else",
":",
"vn",
"=",
"mplv",
".",
"venn2",
"(",
"[",
"s1",
",",
"s2",
"]",
",",
"set_labels",
"=",
"labels",
",",
"*",
"*",
"kwargs",
")",
"intersection",
"=",
"s1",
"&",
"s2",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"if",
"return_intersection",
":",
"return",
"ax",
",",
"list",
"(",
"intersection",
")",
"else",
":",
"return",
"ax"
] | Plot a 2 or 3-part venn diagram showing the overlap between 2 or 3 pandas DataFrames.
Provided with two or three Pandas DataFrames, this will return a venn diagram showing the overlap calculated between
the DataFrame indexes provided as ix1, ix2, ix3. Labels for each DataFrame can be provided as a list in the same order,
while `fcol` can be used to specify the colors of each section.
:param df1: Pandas DataFrame
:param df2: Pandas DataFrame
:param df3: Pandas DataFrame (optional)
:param labels: List of labels for the provided dataframes
:param ix1: Index level name of of Dataframe 1 to use for comparison
:param ix2: Index level name of of Dataframe 2 to use for comparison
:param ix3: Index level name of of Dataframe 3 to use for comparison
:param return_intersection: Return the intersection of the supplied indices
:param fcols: List of colors for the provided dataframes
:return: ax, or ax with intersection | [
"Plot",
"a",
"2",
"or",
"3",
"-",
"part",
"venn",
"diagram",
"showing",
"the",
"overlap",
"between",
"2",
"or",
"3",
"pandas",
"DataFrames",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L979-L1033 |
5,987 | mfitzp/padua | padua/visualize.py | sitespeptidesproteins | def sitespeptidesproteins(df, labels=None, colors=None, site_localization_probability=0.75):
"""
Plot the number of sites, peptides and proteins in the dataset.
Generates a plot with sites, peptides and proteins displayed hierarchically in chevrons.
The site count is limited to Class I (<=0.75 site localization probability) by default
but may be altered using the `site_localization_probability` parameter.
Labels and alternate colours may be supplied as a 3-entry iterable.
:param df: pandas DataFrame to calculate numbers from
:param labels: list/tuple of 3 strings containing labels
:param colors: list/tuple of 3 colours as hex codes or matplotlib color codes
:param site_localization_probability: the cut-off for site inclusion (default=0.75; Class I)
:return:
"""
fig = plt.figure(figsize=(4,6))
ax = fig.add_subplot(1,1,1)
shift = 0.5
values = analysis.sitespeptidesproteins(df, site_localization_probability)
if labels is None:
labels = ['Sites (Class I)', 'Peptides', 'Proteins']
if colors is None:
colors = ['#756bb1', '#bcbddc', '#dadaeb']
for n, (c, l, v) in enumerate(zip(colors, labels, values)):
ax.fill_between([0,1,2], np.array([shift,0,shift]) + n, np.array([1+shift,1,1+shift]) + n, color=c, alpha=0.5 )
ax.text(1, 0.5 + n, "{}\n{:,}".format(l, v), ha='center', color='k', fontsize=16 )
ax.set_xticks([])
ax.set_yticks([])
ax.set_axis_off()
return ax | python | def sitespeptidesproteins(df, labels=None, colors=None, site_localization_probability=0.75):
"""
Plot the number of sites, peptides and proteins in the dataset.
Generates a plot with sites, peptides and proteins displayed hierarchically in chevrons.
The site count is limited to Class I (<=0.75 site localization probability) by default
but may be altered using the `site_localization_probability` parameter.
Labels and alternate colours may be supplied as a 3-entry iterable.
:param df: pandas DataFrame to calculate numbers from
:param labels: list/tuple of 3 strings containing labels
:param colors: list/tuple of 3 colours as hex codes or matplotlib color codes
:param site_localization_probability: the cut-off for site inclusion (default=0.75; Class I)
:return:
"""
fig = plt.figure(figsize=(4,6))
ax = fig.add_subplot(1,1,1)
shift = 0.5
values = analysis.sitespeptidesproteins(df, site_localization_probability)
if labels is None:
labels = ['Sites (Class I)', 'Peptides', 'Proteins']
if colors is None:
colors = ['#756bb1', '#bcbddc', '#dadaeb']
for n, (c, l, v) in enumerate(zip(colors, labels, values)):
ax.fill_between([0,1,2], np.array([shift,0,shift]) + n, np.array([1+shift,1,1+shift]) + n, color=c, alpha=0.5 )
ax.text(1, 0.5 + n, "{}\n{:,}".format(l, v), ha='center', color='k', fontsize=16 )
ax.set_xticks([])
ax.set_yticks([])
ax.set_axis_off()
return ax | [
"def",
"sitespeptidesproteins",
"(",
"df",
",",
"labels",
"=",
"None",
",",
"colors",
"=",
"None",
",",
"site_localization_probability",
"=",
"0.75",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"4",
",",
"6",
")",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"1",
",",
"1",
",",
"1",
")",
"shift",
"=",
"0.5",
"values",
"=",
"analysis",
".",
"sitespeptidesproteins",
"(",
"df",
",",
"site_localization_probability",
")",
"if",
"labels",
"is",
"None",
":",
"labels",
"=",
"[",
"'Sites (Class I)'",
",",
"'Peptides'",
",",
"'Proteins'",
"]",
"if",
"colors",
"is",
"None",
":",
"colors",
"=",
"[",
"'#756bb1'",
",",
"'#bcbddc'",
",",
"'#dadaeb'",
"]",
"for",
"n",
",",
"(",
"c",
",",
"l",
",",
"v",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"colors",
",",
"labels",
",",
"values",
")",
")",
":",
"ax",
".",
"fill_between",
"(",
"[",
"0",
",",
"1",
",",
"2",
"]",
",",
"np",
".",
"array",
"(",
"[",
"shift",
",",
"0",
",",
"shift",
"]",
")",
"+",
"n",
",",
"np",
".",
"array",
"(",
"[",
"1",
"+",
"shift",
",",
"1",
",",
"1",
"+",
"shift",
"]",
")",
"+",
"n",
",",
"color",
"=",
"c",
",",
"alpha",
"=",
"0.5",
")",
"ax",
".",
"text",
"(",
"1",
",",
"0.5",
"+",
"n",
",",
"\"{}\\n{:,}\"",
".",
"format",
"(",
"l",
",",
"v",
")",
",",
"ha",
"=",
"'center'",
",",
"color",
"=",
"'k'",
",",
"fontsize",
"=",
"16",
")",
"ax",
".",
"set_xticks",
"(",
"[",
"]",
")",
"ax",
".",
"set_yticks",
"(",
"[",
"]",
")",
"ax",
".",
"set_axis_off",
"(",
")",
"return",
"ax"
] | Plot the number of sites, peptides and proteins in the dataset.
Generates a plot with sites, peptides and proteins displayed hierarchically in chevrons.
The site count is limited to Class I (<=0.75 site localization probability) by default
but may be altered using the `site_localization_probability` parameter.
Labels and alternate colours may be supplied as a 3-entry iterable.
:param df: pandas DataFrame to calculate numbers from
:param labels: list/tuple of 3 strings containing labels
:param colors: list/tuple of 3 colours as hex codes or matplotlib color codes
:param site_localization_probability: the cut-off for site inclusion (default=0.75; Class I)
:return: | [
"Plot",
"the",
"number",
"of",
"sites",
"peptides",
"and",
"proteins",
"in",
"the",
"dataset",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L1036-L1071 |
5,988 | mfitzp/padua | padua/visualize.py | _areadist | def _areadist(ax, v, xr, c, bins=100, by=None, alpha=1, label=None):
"""
Plot the histogram distribution but as an area plot
"""
y, x = np.histogram(v[~np.isnan(v)], bins)
x = x[:-1]
if by is None:
by = np.zeros((bins,))
ax.fill_between(x, y, by, facecolor=c, alpha=alpha, label=label)
return y | python | def _areadist(ax, v, xr, c, bins=100, by=None, alpha=1, label=None):
"""
Plot the histogram distribution but as an area plot
"""
y, x = np.histogram(v[~np.isnan(v)], bins)
x = x[:-1]
if by is None:
by = np.zeros((bins,))
ax.fill_between(x, y, by, facecolor=c, alpha=alpha, label=label)
return y | [
"def",
"_areadist",
"(",
"ax",
",",
"v",
",",
"xr",
",",
"c",
",",
"bins",
"=",
"100",
",",
"by",
"=",
"None",
",",
"alpha",
"=",
"1",
",",
"label",
"=",
"None",
")",
":",
"y",
",",
"x",
"=",
"np",
".",
"histogram",
"(",
"v",
"[",
"~",
"np",
".",
"isnan",
"(",
"v",
")",
"]",
",",
"bins",
")",
"x",
"=",
"x",
"[",
":",
"-",
"1",
"]",
"if",
"by",
"is",
"None",
":",
"by",
"=",
"np",
".",
"zeros",
"(",
"(",
"bins",
",",
")",
")",
"ax",
".",
"fill_between",
"(",
"x",
",",
"y",
",",
"by",
",",
"facecolor",
"=",
"c",
",",
"alpha",
"=",
"alpha",
",",
"label",
"=",
"label",
")",
"return",
"y"
] | Plot the histogram distribution but as an area plot | [
"Plot",
"the",
"histogram",
"distribution",
"but",
"as",
"an",
"area",
"plot"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L1374-L1385 |
5,989 | mfitzp/padua | padua/visualize.py | hierarchical_timecourse | def hierarchical_timecourse(
df,
cluster_cols=True,
cluster_rows=False,
n_col_clusters=False,
n_row_clusters=False,
fcol=None,
z_score=0,
method='ward',
cmap=cm.PuOr_r,
return_clusters=False,
rdistance_fn=distance.pdist,
cdistance_fn=distance.pdist,
xlabel='Timepoint',
ylabel='log$_2$ Fold Change'
):
"""
Hierarchical clustering of samples across timecourse experiment.
Peform a hiearchical clustering on a pandas DataFrame and display the resulting clustering as a
timecourse density plot.
Samples are z-scored along the 0-axis (y) by default. To override this use the `z_score` param with the axis to `z_score`
or alternatively, `None`, to turn it off.
If a `n_col_clusters` or `n_row_clusters` is specified, this defines the number of clusters to identify and highlight
in the resulting heatmap. At *least* this number of clusters will be selected, in some instances there will be more
if 2 clusters rank equally at the determined cutoff.
If specified `fcol` will be used to colour the axes for matching samples.
:param df: Pandas ``DataFrame`` to cluster
:param n_col_clusters: ``int`` the ideal number of highlighted clusters in cols
:param n_row_clusters: ``int`` the ideal number of highlighted clusters in rows
:param fcol: ``dict`` of label:colors to be applied along the axes
:param z_score: ``int`` to specify the axis to Z score or `None` to disable
:param method: ``str`` describing cluster method, default ward
:param cmap: matplotlib colourmap for heatmap
:param return_clusters: ``bool`` return clusters in addition to axis
:return: matplotlib axis, or axis and cluster data
"""
dfc, row_clusters, row_denD, col_clusters, col_denD, edges = _cluster(df,
cluster_cols=cluster_cols, cluster_rows=cluster_rows, n_col_clusters=n_col_clusters,
n_row_clusters=n_row_clusters, z_score=z_score, method='ward',
rdistance_fn=rdistance_fn, cdistance_fn=cdistance_fn
)
# FIXME: Need to apply a sort function to the DataFrame to order by the clustering
# so we can slice the edges.
dfh = dfc.iloc[row_denD['leaves'], col_denD['leaves']]
dfh = dfh.mean(axis=0, level=[0, 1])
vmax = np.max(dfh.values)
color = ScalarMappable(norm=Normalize(vmin=0, vmax=vmax), cmap=viridis)
fig = plt.figure(figsize=(12, 6))
edges = [0] + edges + [dfh.shape[1]]
for n in range(len(edges) - 1):
ax = fig.add_subplot(2, 4, n + 1)
dfhf = dfh.iloc[:, edges[n]:edges[n + 1]]
xpos = dfhf.index.get_level_values(1)
mv = dfhf.mean(axis=1)
distances = [distance.euclidean(mv, dfhf.values[:, n]) for n in range(dfhf.shape[1])]
colors = [color.to_rgba(v) for v in distances]
order = np.argsort(distances)[::-1]
for y in order:
ax.plot(xpos, dfhf.values[:, y], c=colors[y], alpha=0.5, lw=1) # dfhf.index.get_level_values(1),
ax.set_xticks(xpos)
if n > 3:
ax.set_xticklabels(xpos)
ax.set_xlabel(xlabel)
else:
ax.set_xticklabels([])
if n % 4 != 0:
ax.set_yticklabels([])
else:
ax.set_ylabel(ylabel)
ax.set_ylim((-3, +3))
fig.subplots_adjust(hspace=0.15, wspace=0.15)
if return_clusters:
return fig, dfh, edges
else:
return fig | python | def hierarchical_timecourse(
df,
cluster_cols=True,
cluster_rows=False,
n_col_clusters=False,
n_row_clusters=False,
fcol=None,
z_score=0,
method='ward',
cmap=cm.PuOr_r,
return_clusters=False,
rdistance_fn=distance.pdist,
cdistance_fn=distance.pdist,
xlabel='Timepoint',
ylabel='log$_2$ Fold Change'
):
"""
Hierarchical clustering of samples across timecourse experiment.
Peform a hiearchical clustering on a pandas DataFrame and display the resulting clustering as a
timecourse density plot.
Samples are z-scored along the 0-axis (y) by default. To override this use the `z_score` param with the axis to `z_score`
or alternatively, `None`, to turn it off.
If a `n_col_clusters` or `n_row_clusters` is specified, this defines the number of clusters to identify and highlight
in the resulting heatmap. At *least* this number of clusters will be selected, in some instances there will be more
if 2 clusters rank equally at the determined cutoff.
If specified `fcol` will be used to colour the axes for matching samples.
:param df: Pandas ``DataFrame`` to cluster
:param n_col_clusters: ``int`` the ideal number of highlighted clusters in cols
:param n_row_clusters: ``int`` the ideal number of highlighted clusters in rows
:param fcol: ``dict`` of label:colors to be applied along the axes
:param z_score: ``int`` to specify the axis to Z score or `None` to disable
:param method: ``str`` describing cluster method, default ward
:param cmap: matplotlib colourmap for heatmap
:param return_clusters: ``bool`` return clusters in addition to axis
:return: matplotlib axis, or axis and cluster data
"""
dfc, row_clusters, row_denD, col_clusters, col_denD, edges = _cluster(df,
cluster_cols=cluster_cols, cluster_rows=cluster_rows, n_col_clusters=n_col_clusters,
n_row_clusters=n_row_clusters, z_score=z_score, method='ward',
rdistance_fn=rdistance_fn, cdistance_fn=cdistance_fn
)
# FIXME: Need to apply a sort function to the DataFrame to order by the clustering
# so we can slice the edges.
dfh = dfc.iloc[row_denD['leaves'], col_denD['leaves']]
dfh = dfh.mean(axis=0, level=[0, 1])
vmax = np.max(dfh.values)
color = ScalarMappable(norm=Normalize(vmin=0, vmax=vmax), cmap=viridis)
fig = plt.figure(figsize=(12, 6))
edges = [0] + edges + [dfh.shape[1]]
for n in range(len(edges) - 1):
ax = fig.add_subplot(2, 4, n + 1)
dfhf = dfh.iloc[:, edges[n]:edges[n + 1]]
xpos = dfhf.index.get_level_values(1)
mv = dfhf.mean(axis=1)
distances = [distance.euclidean(mv, dfhf.values[:, n]) for n in range(dfhf.shape[1])]
colors = [color.to_rgba(v) for v in distances]
order = np.argsort(distances)[::-1]
for y in order:
ax.plot(xpos, dfhf.values[:, y], c=colors[y], alpha=0.5, lw=1) # dfhf.index.get_level_values(1),
ax.set_xticks(xpos)
if n > 3:
ax.set_xticklabels(xpos)
ax.set_xlabel(xlabel)
else:
ax.set_xticklabels([])
if n % 4 != 0:
ax.set_yticklabels([])
else:
ax.set_ylabel(ylabel)
ax.set_ylim((-3, +3))
fig.subplots_adjust(hspace=0.15, wspace=0.15)
if return_clusters:
return fig, dfh, edges
else:
return fig | [
"def",
"hierarchical_timecourse",
"(",
"df",
",",
"cluster_cols",
"=",
"True",
",",
"cluster_rows",
"=",
"False",
",",
"n_col_clusters",
"=",
"False",
",",
"n_row_clusters",
"=",
"False",
",",
"fcol",
"=",
"None",
",",
"z_score",
"=",
"0",
",",
"method",
"=",
"'ward'",
",",
"cmap",
"=",
"cm",
".",
"PuOr_r",
",",
"return_clusters",
"=",
"False",
",",
"rdistance_fn",
"=",
"distance",
".",
"pdist",
",",
"cdistance_fn",
"=",
"distance",
".",
"pdist",
",",
"xlabel",
"=",
"'Timepoint'",
",",
"ylabel",
"=",
"'log$_2$ Fold Change'",
")",
":",
"dfc",
",",
"row_clusters",
",",
"row_denD",
",",
"col_clusters",
",",
"col_denD",
",",
"edges",
"=",
"_cluster",
"(",
"df",
",",
"cluster_cols",
"=",
"cluster_cols",
",",
"cluster_rows",
"=",
"cluster_rows",
",",
"n_col_clusters",
"=",
"n_col_clusters",
",",
"n_row_clusters",
"=",
"n_row_clusters",
",",
"z_score",
"=",
"z_score",
",",
"method",
"=",
"'ward'",
",",
"rdistance_fn",
"=",
"rdistance_fn",
",",
"cdistance_fn",
"=",
"cdistance_fn",
")",
"# FIXME: Need to apply a sort function to the DataFrame to order by the clustering",
"# so we can slice the edges.",
"dfh",
"=",
"dfc",
".",
"iloc",
"[",
"row_denD",
"[",
"'leaves'",
"]",
",",
"col_denD",
"[",
"'leaves'",
"]",
"]",
"dfh",
"=",
"dfh",
".",
"mean",
"(",
"axis",
"=",
"0",
",",
"level",
"=",
"[",
"0",
",",
"1",
"]",
")",
"vmax",
"=",
"np",
".",
"max",
"(",
"dfh",
".",
"values",
")",
"color",
"=",
"ScalarMappable",
"(",
"norm",
"=",
"Normalize",
"(",
"vmin",
"=",
"0",
",",
"vmax",
"=",
"vmax",
")",
",",
"cmap",
"=",
"viridis",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"12",
",",
"6",
")",
")",
"edges",
"=",
"[",
"0",
"]",
"+",
"edges",
"+",
"[",
"dfh",
".",
"shape",
"[",
"1",
"]",
"]",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"edges",
")",
"-",
"1",
")",
":",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"2",
",",
"4",
",",
"n",
"+",
"1",
")",
"dfhf",
"=",
"dfh",
".",
"iloc",
"[",
":",
",",
"edges",
"[",
"n",
"]",
":",
"edges",
"[",
"n",
"+",
"1",
"]",
"]",
"xpos",
"=",
"dfhf",
".",
"index",
".",
"get_level_values",
"(",
"1",
")",
"mv",
"=",
"dfhf",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
"distances",
"=",
"[",
"distance",
".",
"euclidean",
"(",
"mv",
",",
"dfhf",
".",
"values",
"[",
":",
",",
"n",
"]",
")",
"for",
"n",
"in",
"range",
"(",
"dfhf",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"colors",
"=",
"[",
"color",
".",
"to_rgba",
"(",
"v",
")",
"for",
"v",
"in",
"distances",
"]",
"order",
"=",
"np",
".",
"argsort",
"(",
"distances",
")",
"[",
":",
":",
"-",
"1",
"]",
"for",
"y",
"in",
"order",
":",
"ax",
".",
"plot",
"(",
"xpos",
",",
"dfhf",
".",
"values",
"[",
":",
",",
"y",
"]",
",",
"c",
"=",
"colors",
"[",
"y",
"]",
",",
"alpha",
"=",
"0.5",
",",
"lw",
"=",
"1",
")",
"# dfhf.index.get_level_values(1),",
"ax",
".",
"set_xticks",
"(",
"xpos",
")",
"if",
"n",
">",
"3",
":",
"ax",
".",
"set_xticklabels",
"(",
"xpos",
")",
"ax",
".",
"set_xlabel",
"(",
"xlabel",
")",
"else",
":",
"ax",
".",
"set_xticklabels",
"(",
"[",
"]",
")",
"if",
"n",
"%",
"4",
"!=",
"0",
":",
"ax",
".",
"set_yticklabels",
"(",
"[",
"]",
")",
"else",
":",
"ax",
".",
"set_ylabel",
"(",
"ylabel",
")",
"ax",
".",
"set_ylim",
"(",
"(",
"-",
"3",
",",
"+",
"3",
")",
")",
"fig",
".",
"subplots_adjust",
"(",
"hspace",
"=",
"0.15",
",",
"wspace",
"=",
"0.15",
")",
"if",
"return_clusters",
":",
"return",
"fig",
",",
"dfh",
",",
"edges",
"else",
":",
"return",
"fig"
] | Hierarchical clustering of samples across timecourse experiment.
Peform a hiearchical clustering on a pandas DataFrame and display the resulting clustering as a
timecourse density plot.
Samples are z-scored along the 0-axis (y) by default. To override this use the `z_score` param with the axis to `z_score`
or alternatively, `None`, to turn it off.
If a `n_col_clusters` or `n_row_clusters` is specified, this defines the number of clusters to identify and highlight
in the resulting heatmap. At *least* this number of clusters will be selected, in some instances there will be more
if 2 clusters rank equally at the determined cutoff.
If specified `fcol` will be used to colour the axes for matching samples.
:param df: Pandas ``DataFrame`` to cluster
:param n_col_clusters: ``int`` the ideal number of highlighted clusters in cols
:param n_row_clusters: ``int`` the ideal number of highlighted clusters in rows
:param fcol: ``dict`` of label:colors to be applied along the axes
:param z_score: ``int`` to specify the axis to Z score or `None` to disable
:param method: ``str`` describing cluster method, default ward
:param cmap: matplotlib colourmap for heatmap
:param return_clusters: ``bool`` return clusters in addition to axis
:return: matplotlib axis, or axis and cluster data | [
"Hierarchical",
"clustering",
"of",
"samples",
"across",
"timecourse",
"experiment",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L1872-L1965 |
5,990 | mfitzp/padua | padua/normalization.py | subtract_column_median | def subtract_column_median(df, prefix='Intensity '):
"""
Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return:
"""
df = df.copy()
df.replace([np.inf, -np.inf], np.nan, inplace=True)
mask = [l.startswith(prefix) for l in df.columns.values]
df.iloc[:, mask] = df.iloc[:, mask] - df.iloc[:, mask].median(axis=0)
return df | python | def subtract_column_median(df, prefix='Intensity '):
"""
Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return:
"""
df = df.copy()
df.replace([np.inf, -np.inf], np.nan, inplace=True)
mask = [l.startswith(prefix) for l in df.columns.values]
df.iloc[:, mask] = df.iloc[:, mask] - df.iloc[:, mask].median(axis=0)
return df | [
"def",
"subtract_column_median",
"(",
"df",
",",
"prefix",
"=",
"'Intensity '",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"df",
".",
"replace",
"(",
"[",
"np",
".",
"inf",
",",
"-",
"np",
".",
"inf",
"]",
",",
"np",
".",
"nan",
",",
"inplace",
"=",
"True",
")",
"mask",
"=",
"[",
"l",
".",
"startswith",
"(",
"prefix",
")",
"for",
"l",
"in",
"df",
".",
"columns",
".",
"values",
"]",
"df",
".",
"iloc",
"[",
":",
",",
"mask",
"]",
"=",
"df",
".",
"iloc",
"[",
":",
",",
"mask",
"]",
"-",
"df",
".",
"iloc",
"[",
":",
",",
"mask",
"]",
".",
"median",
"(",
"axis",
"=",
"0",
")",
"return",
"df"
] | Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return: | [
"Apply",
"column",
"-",
"wise",
"normalisation",
"to",
"expression",
"columns",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/normalization.py#L4-L22 |
5,991 | mfitzp/padua | padua/utils.py | get_protein_id_list | def get_protein_id_list(df, level=0):
"""
Return a complete list of shortform IDs from a DataFrame
Extract all protein IDs from a dataframe from multiple rows containing
protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268
Long names (containing species information) are eliminated (split on ' ') and
isoforms are removed (split on '_').
:param df: DataFrame
:type df: pandas.DataFrame
:param level: Level of DataFrame index to extract IDs from
:type level: int or str
:return: list of string ids
"""
protein_list = []
for s in df.index.get_level_values(level):
protein_list.extend( get_protein_ids(s) )
return list(set(protein_list)) | python | def get_protein_id_list(df, level=0):
"""
Return a complete list of shortform IDs from a DataFrame
Extract all protein IDs from a dataframe from multiple rows containing
protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268
Long names (containing species information) are eliminated (split on ' ') and
isoforms are removed (split on '_').
:param df: DataFrame
:type df: pandas.DataFrame
:param level: Level of DataFrame index to extract IDs from
:type level: int or str
:return: list of string ids
"""
protein_list = []
for s in df.index.get_level_values(level):
protein_list.extend( get_protein_ids(s) )
return list(set(protein_list)) | [
"def",
"get_protein_id_list",
"(",
"df",
",",
"level",
"=",
"0",
")",
":",
"protein_list",
"=",
"[",
"]",
"for",
"s",
"in",
"df",
".",
"index",
".",
"get_level_values",
"(",
"level",
")",
":",
"protein_list",
".",
"extend",
"(",
"get_protein_ids",
"(",
"s",
")",
")",
"return",
"list",
"(",
"set",
"(",
"protein_list",
")",
")"
] | Return a complete list of shortform IDs from a DataFrame
Extract all protein IDs from a dataframe from multiple rows containing
protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268
Long names (containing species information) are eliminated (split on ' ') and
isoforms are removed (split on '_').
:param df: DataFrame
:type df: pandas.DataFrame
:param level: Level of DataFrame index to extract IDs from
:type level: int or str
:return: list of string ids | [
"Return",
"a",
"complete",
"list",
"of",
"shortform",
"IDs",
"from",
"a",
"DataFrame"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/utils.py#L142-L162 |
5,992 | mfitzp/padua | padua/utils.py | hierarchical_match | def hierarchical_match(d, k, default=None):
"""
Match a key against a dict, simplifying element at a time
:param df: DataFrame
:type df: pandas.DataFrame
:param level: Level of DataFrame index to extract IDs from
:type level: int or str
:return: hiearchically matched value or default
"""
if d is None:
return default
if type(k) != list and type(k) != tuple:
k = [k]
for n, _ in enumerate(k):
key = tuple(k[0:len(k)-n])
if len(key) == 1:
key = key[0]
try:
d[key]
except:
pass
else:
return d[key]
return default | python | def hierarchical_match(d, k, default=None):
"""
Match a key against a dict, simplifying element at a time
:param df: DataFrame
:type df: pandas.DataFrame
:param level: Level of DataFrame index to extract IDs from
:type level: int or str
:return: hiearchically matched value or default
"""
if d is None:
return default
if type(k) != list and type(k) != tuple:
k = [k]
for n, _ in enumerate(k):
key = tuple(k[0:len(k)-n])
if len(key) == 1:
key = key[0]
try:
d[key]
except:
pass
else:
return d[key]
return default | [
"def",
"hierarchical_match",
"(",
"d",
",",
"k",
",",
"default",
"=",
"None",
")",
":",
"if",
"d",
"is",
"None",
":",
"return",
"default",
"if",
"type",
"(",
"k",
")",
"!=",
"list",
"and",
"type",
"(",
"k",
")",
"!=",
"tuple",
":",
"k",
"=",
"[",
"k",
"]",
"for",
"n",
",",
"_",
"in",
"enumerate",
"(",
"k",
")",
":",
"key",
"=",
"tuple",
"(",
"k",
"[",
"0",
":",
"len",
"(",
"k",
")",
"-",
"n",
"]",
")",
"if",
"len",
"(",
"key",
")",
"==",
"1",
":",
"key",
"=",
"key",
"[",
"0",
"]",
"try",
":",
"d",
"[",
"key",
"]",
"except",
":",
"pass",
"else",
":",
"return",
"d",
"[",
"key",
"]",
"return",
"default"
] | Match a key against a dict, simplifying element at a time
:param df: DataFrame
:type df: pandas.DataFrame
:param level: Level of DataFrame index to extract IDs from
:type level: int or str
:return: hiearchically matched value or default | [
"Match",
"a",
"key",
"against",
"a",
"dict",
"simplifying",
"element",
"at",
"a",
"time"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/utils.py#L228-L256 |
5,993 | mfitzp/padua | padua/utils.py | calculate_s0_curve | def calculate_s0_curve(s0, minpval, maxpval, minratio, maxratio, curve_interval=0.1):
"""
Calculate s0 curve for volcano plot.
Taking an min and max p value, and a min and max ratio, calculate an smooth
curve starting from parameter `s0` in each direction.
The `curve_interval` parameter defines the smoothness of the resulting curve.
:param s0: `float` offset of curve from interset
:param minpval: `float` minimum p value
:param maxpval: `float` maximum p value
:param minratio: `float` minimum ratio
:param maxratio: `float` maximum ratio
:param curve_interval: `float` stepsize (smoothness) of curve generator
:return: x, y, fn x,y points of curve, and fn generator
"""
mminpval = -np.log10(minpval)
mmaxpval = -np.log10(maxpval)
maxpval_adjust = mmaxpval - mminpval
ax0 = (s0 + maxpval_adjust * minratio) / maxpval_adjust
edge_offset = (maxratio-ax0) % curve_interval
max_x = maxratio-edge_offset
if (max_x > ax0):
x = np.arange(ax0, max_x, curve_interval)
else:
x = np.arange(max_x, ax0, curve_interval)
fn = lambda x: 10 ** (-s0/(x-minratio) - mminpval)
y = fn(x)
return x, y, fn | python | def calculate_s0_curve(s0, minpval, maxpval, minratio, maxratio, curve_interval=0.1):
"""
Calculate s0 curve for volcano plot.
Taking an min and max p value, and a min and max ratio, calculate an smooth
curve starting from parameter `s0` in each direction.
The `curve_interval` parameter defines the smoothness of the resulting curve.
:param s0: `float` offset of curve from interset
:param minpval: `float` minimum p value
:param maxpval: `float` maximum p value
:param minratio: `float` minimum ratio
:param maxratio: `float` maximum ratio
:param curve_interval: `float` stepsize (smoothness) of curve generator
:return: x, y, fn x,y points of curve, and fn generator
"""
mminpval = -np.log10(minpval)
mmaxpval = -np.log10(maxpval)
maxpval_adjust = mmaxpval - mminpval
ax0 = (s0 + maxpval_adjust * minratio) / maxpval_adjust
edge_offset = (maxratio-ax0) % curve_interval
max_x = maxratio-edge_offset
if (max_x > ax0):
x = np.arange(ax0, max_x, curve_interval)
else:
x = np.arange(max_x, ax0, curve_interval)
fn = lambda x: 10 ** (-s0/(x-minratio) - mminpval)
y = fn(x)
return x, y, fn | [
"def",
"calculate_s0_curve",
"(",
"s0",
",",
"minpval",
",",
"maxpval",
",",
"minratio",
",",
"maxratio",
",",
"curve_interval",
"=",
"0.1",
")",
":",
"mminpval",
"=",
"-",
"np",
".",
"log10",
"(",
"minpval",
")",
"mmaxpval",
"=",
"-",
"np",
".",
"log10",
"(",
"maxpval",
")",
"maxpval_adjust",
"=",
"mmaxpval",
"-",
"mminpval",
"ax0",
"=",
"(",
"s0",
"+",
"maxpval_adjust",
"*",
"minratio",
")",
"/",
"maxpval_adjust",
"edge_offset",
"=",
"(",
"maxratio",
"-",
"ax0",
")",
"%",
"curve_interval",
"max_x",
"=",
"maxratio",
"-",
"edge_offset",
"if",
"(",
"max_x",
">",
"ax0",
")",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"ax0",
",",
"max_x",
",",
"curve_interval",
")",
"else",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"max_x",
",",
"ax0",
",",
"curve_interval",
")",
"fn",
"=",
"lambda",
"x",
":",
"10",
"**",
"(",
"-",
"s0",
"/",
"(",
"x",
"-",
"minratio",
")",
"-",
"mminpval",
")",
"y",
"=",
"fn",
"(",
"x",
")",
"return",
"x",
",",
"y",
",",
"fn"
] | Calculate s0 curve for volcano plot.
Taking an min and max p value, and a min and max ratio, calculate an smooth
curve starting from parameter `s0` in each direction.
The `curve_interval` parameter defines the smoothness of the resulting curve.
:param s0: `float` offset of curve from interset
:param minpval: `float` minimum p value
:param maxpval: `float` maximum p value
:param minratio: `float` minimum ratio
:param maxratio: `float` maximum ratio
:param curve_interval: `float` stepsize (smoothness) of curve generator
:return: x, y, fn x,y points of curve, and fn generator | [
"Calculate",
"s0",
"curve",
"for",
"volcano",
"plot",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/utils.py#L282-L317 |
5,994 | mfitzp/padua | padua/analysis.py | correlation | def correlation(df, rowvar=False):
"""
Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``
Input data is masked to ignore NaNs when calculating correlations. Data is returned as
a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
both axes.
:param df: Pandas DataFrame
:return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations
"""
# Create a correlation matrix for all correlations
# of the columns (filled with na for all values)
df = df.copy()
maskv = np.ma.masked_where(np.isnan(df.values), df.values)
cdf = np.ma.corrcoef(maskv, rowvar=False)
cdf = pd.DataFrame(np.array(cdf))
cdf.columns = df.columns
cdf.index = df.columns
cdf = cdf.sort_index(level=0, axis=1)
cdf = cdf.sort_index(level=0)
return cdf | python | def correlation(df, rowvar=False):
"""
Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``
Input data is masked to ignore NaNs when calculating correlations. Data is returned as
a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
both axes.
:param df: Pandas DataFrame
:return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations
"""
# Create a correlation matrix for all correlations
# of the columns (filled with na for all values)
df = df.copy()
maskv = np.ma.masked_where(np.isnan(df.values), df.values)
cdf = np.ma.corrcoef(maskv, rowvar=False)
cdf = pd.DataFrame(np.array(cdf))
cdf.columns = df.columns
cdf.index = df.columns
cdf = cdf.sort_index(level=0, axis=1)
cdf = cdf.sort_index(level=0)
return cdf | [
"def",
"correlation",
"(",
"df",
",",
"rowvar",
"=",
"False",
")",
":",
"# Create a correlation matrix for all correlations",
"# of the columns (filled with na for all values)",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"maskv",
"=",
"np",
".",
"ma",
".",
"masked_where",
"(",
"np",
".",
"isnan",
"(",
"df",
".",
"values",
")",
",",
"df",
".",
"values",
")",
"cdf",
"=",
"np",
".",
"ma",
".",
"corrcoef",
"(",
"maskv",
",",
"rowvar",
"=",
"False",
")",
"cdf",
"=",
"pd",
".",
"DataFrame",
"(",
"np",
".",
"array",
"(",
"cdf",
")",
")",
"cdf",
".",
"columns",
"=",
"df",
".",
"columns",
"cdf",
".",
"index",
"=",
"df",
".",
"columns",
"cdf",
"=",
"cdf",
".",
"sort_index",
"(",
"level",
"=",
"0",
",",
"axis",
"=",
"1",
")",
"cdf",
"=",
"cdf",
".",
"sort_index",
"(",
"level",
"=",
"0",
")",
"return",
"cdf"
] | Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``
Input data is masked to ignore NaNs when calculating correlations. Data is returned as
a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
both axes.
:param df: Pandas DataFrame
:return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations | [
"Calculate",
"column",
"-",
"wise",
"Pearson",
"correlations",
"using",
"numpy",
".",
"ma",
".",
"corrcoef"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L26-L48 |
5,995 | mfitzp/padua | padua/analysis.py | pca | def pca(df, n_components=2, mean_center=False, **kwargs):
"""
Principal Component Analysis, based on `sklearn.decomposition.PCA`
Performs a principal component analysis (PCA) on the supplied dataframe, selecting the first ``n_components`` components
in the resulting model. The model scores and weights are returned.
For more information on PCA and the algorithm used, see the `scikit-learn documentation <http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html>`_.
:param df: Pandas ``DataFrame`` to perform the analysis on
:param n_components: ``int`` number of components to select
:param mean_center: ``bool`` mean center the data before performing PCA
:param kwargs: additional keyword arguments to `sklearn.decomposition.PCA`
:return: scores ``DataFrame`` of PCA scores n_components x n_samples
weights ``DataFrame`` of PCA weights n_variables x n_components
"""
if not sklearn:
assert('This library depends on scikit-learn (sklearn) to perform PCA analysis')
from sklearn.decomposition import PCA
df = df.copy()
# We have to zero fill, nan errors in PCA
df[ np.isnan(df) ] = 0
if mean_center:
mean = np.mean(df.values, axis=0)
df = df - mean
pca = PCA(n_components=n_components, **kwargs)
pca.fit(df.values.T)
scores = pd.DataFrame(pca.transform(df.values.T)).T
scores.index = ['Principal Component %d (%.2f%%)' % ( (n+1), pca.explained_variance_ratio_[n]*100 ) for n in range(0, scores.shape[0])]
scores.columns = df.columns
weights = pd.DataFrame(pca.components_).T
weights.index = df.index
weights.columns = ['Weights on Principal Component %d' % (n+1) for n in range(0, weights.shape[1])]
return scores, weights | python | def pca(df, n_components=2, mean_center=False, **kwargs):
"""
Principal Component Analysis, based on `sklearn.decomposition.PCA`
Performs a principal component analysis (PCA) on the supplied dataframe, selecting the first ``n_components`` components
in the resulting model. The model scores and weights are returned.
For more information on PCA and the algorithm used, see the `scikit-learn documentation <http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html>`_.
:param df: Pandas ``DataFrame`` to perform the analysis on
:param n_components: ``int`` number of components to select
:param mean_center: ``bool`` mean center the data before performing PCA
:param kwargs: additional keyword arguments to `sklearn.decomposition.PCA`
:return: scores ``DataFrame`` of PCA scores n_components x n_samples
weights ``DataFrame`` of PCA weights n_variables x n_components
"""
if not sklearn:
assert('This library depends on scikit-learn (sklearn) to perform PCA analysis')
from sklearn.decomposition import PCA
df = df.copy()
# We have to zero fill, nan errors in PCA
df[ np.isnan(df) ] = 0
if mean_center:
mean = np.mean(df.values, axis=0)
df = df - mean
pca = PCA(n_components=n_components, **kwargs)
pca.fit(df.values.T)
scores = pd.DataFrame(pca.transform(df.values.T)).T
scores.index = ['Principal Component %d (%.2f%%)' % ( (n+1), pca.explained_variance_ratio_[n]*100 ) for n in range(0, scores.shape[0])]
scores.columns = df.columns
weights = pd.DataFrame(pca.components_).T
weights.index = df.index
weights.columns = ['Weights on Principal Component %d' % (n+1) for n in range(0, weights.shape[1])]
return scores, weights | [
"def",
"pca",
"(",
"df",
",",
"n_components",
"=",
"2",
",",
"mean_center",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"sklearn",
":",
"assert",
"(",
"'This library depends on scikit-learn (sklearn) to perform PCA analysis'",
")",
"from",
"sklearn",
".",
"decomposition",
"import",
"PCA",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"# We have to zero fill, nan errors in PCA",
"df",
"[",
"np",
".",
"isnan",
"(",
"df",
")",
"]",
"=",
"0",
"if",
"mean_center",
":",
"mean",
"=",
"np",
".",
"mean",
"(",
"df",
".",
"values",
",",
"axis",
"=",
"0",
")",
"df",
"=",
"df",
"-",
"mean",
"pca",
"=",
"PCA",
"(",
"n_components",
"=",
"n_components",
",",
"*",
"*",
"kwargs",
")",
"pca",
".",
"fit",
"(",
"df",
".",
"values",
".",
"T",
")",
"scores",
"=",
"pd",
".",
"DataFrame",
"(",
"pca",
".",
"transform",
"(",
"df",
".",
"values",
".",
"T",
")",
")",
".",
"T",
"scores",
".",
"index",
"=",
"[",
"'Principal Component %d (%.2f%%)'",
"%",
"(",
"(",
"n",
"+",
"1",
")",
",",
"pca",
".",
"explained_variance_ratio_",
"[",
"n",
"]",
"*",
"100",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"scores",
".",
"shape",
"[",
"0",
"]",
")",
"]",
"scores",
".",
"columns",
"=",
"df",
".",
"columns",
"weights",
"=",
"pd",
".",
"DataFrame",
"(",
"pca",
".",
"components_",
")",
".",
"T",
"weights",
".",
"index",
"=",
"df",
".",
"index",
"weights",
".",
"columns",
"=",
"[",
"'Weights on Principal Component %d'",
"%",
"(",
"n",
"+",
"1",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"weights",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"return",
"scores",
",",
"weights"
] | Principal Component Analysis, based on `sklearn.decomposition.PCA`
Performs a principal component analysis (PCA) on the supplied dataframe, selecting the first ``n_components`` components
in the resulting model. The model scores and weights are returned.
For more information on PCA and the algorithm used, see the `scikit-learn documentation <http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html>`_.
:param df: Pandas ``DataFrame`` to perform the analysis on
:param n_components: ``int`` number of components to select
:param mean_center: ``bool`` mean center the data before performing PCA
:param kwargs: additional keyword arguments to `sklearn.decomposition.PCA`
:return: scores ``DataFrame`` of PCA scores n_components x n_samples
weights ``DataFrame`` of PCA weights n_variables x n_components | [
"Principal",
"Component",
"Analysis",
"based",
"on",
"sklearn",
".",
"decomposition",
".",
"PCA"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L51-L93 |
5,996 | mfitzp/padua | padua/analysis.py | plsda | def plsda(df, a, b, n_components=2, mean_center=False, scale=True, **kwargs):
"""
Partial Least Squares Discriminant Analysis, based on `sklearn.cross_decomposition.PLSRegression`
Performs a binary group partial least squares discriminant analysis (PLS-DA) on the supplied
dataframe, selecting the first ``n_components``.
Sample groups are defined by the selectors ``a`` and ``b`` which are used to select columns
from the supplied dataframe. The result model is applied to the entire dataset,
projecting non-selected samples into the same space.
For more information on PLS regression and the algorithm used, see the `scikit-learn documentation <http://scikit-learn.org/stable/modules/generated/sklearn.cross_decomposition.PLSRegression.html>`_.
:param df: Pandas ``DataFrame`` to perform the analysis on
:param a: Column selector for group a
:param b: Column selector for group b
:param n_components: ``int`` number of components to select
:param mean_center: ``bool`` mean center the data before performing PLS regression
:param kwargs: additional keyword arguments to `sklearn.cross_decomposition.PLSRegression`
:return: scores ``DataFrame`` of PLSDA scores n_components x n_samples
weights ``DataFrame`` of PLSDA weights n_variables x n_components
"""
if not sklearn:
assert('This library depends on scikit-learn (sklearn) to perform PLS-DA')
from sklearn.cross_decomposition import PLSRegression
df = df.copy()
# We have to zero fill, nan errors in PLSRegression
df[ np.isnan(df) ] = 0
if mean_center:
mean = np.mean(df.values, axis=0)
df = df - mean
sxa, _ = df.columns.get_loc_level(a)
sxb, _ = df.columns.get_loc_level(b)
dfa = df.iloc[:, sxa]
dfb = df.iloc[:, sxb]
dff = pd.concat([dfa, dfb], axis=1)
y = np.ones(dff.shape[1])
y[np.arange(dfa.shape[1])] = 0
plsr = PLSRegression(n_components=n_components, scale=scale, **kwargs)
plsr.fit(dff.values.T, y)
# Apply the generated model to the original data
x_scores = plsr.transform(df.values.T)
scores = pd.DataFrame(x_scores.T)
scores.index = ['Latent Variable %d' % (n+1) for n in range(0, scores.shape[0])]
scores.columns = df.columns
weights = pd.DataFrame(plsr.x_weights_)
weights.index = df.index
weights.columns = ['Weights on Latent Variable %d' % (n+1) for n in range(0, weights.shape[1])]
loadings = pd.DataFrame(plsr.x_loadings_)
loadings.index = df.index
loadings.columns = ['Loadings on Latent Variable %d' % (n+1) for n in range(0, loadings.shape[1])]
return scores, weights, loadings | python | def plsda(df, a, b, n_components=2, mean_center=False, scale=True, **kwargs):
"""
Partial Least Squares Discriminant Analysis, based on `sklearn.cross_decomposition.PLSRegression`
Performs a binary group partial least squares discriminant analysis (PLS-DA) on the supplied
dataframe, selecting the first ``n_components``.
Sample groups are defined by the selectors ``a`` and ``b`` which are used to select columns
from the supplied dataframe. The result model is applied to the entire dataset,
projecting non-selected samples into the same space.
For more information on PLS regression and the algorithm used, see the `scikit-learn documentation <http://scikit-learn.org/stable/modules/generated/sklearn.cross_decomposition.PLSRegression.html>`_.
:param df: Pandas ``DataFrame`` to perform the analysis on
:param a: Column selector for group a
:param b: Column selector for group b
:param n_components: ``int`` number of components to select
:param mean_center: ``bool`` mean center the data before performing PLS regression
:param kwargs: additional keyword arguments to `sklearn.cross_decomposition.PLSRegression`
:return: scores ``DataFrame`` of PLSDA scores n_components x n_samples
weights ``DataFrame`` of PLSDA weights n_variables x n_components
"""
if not sklearn:
assert('This library depends on scikit-learn (sklearn) to perform PLS-DA')
from sklearn.cross_decomposition import PLSRegression
df = df.copy()
# We have to zero fill, nan errors in PLSRegression
df[ np.isnan(df) ] = 0
if mean_center:
mean = np.mean(df.values, axis=0)
df = df - mean
sxa, _ = df.columns.get_loc_level(a)
sxb, _ = df.columns.get_loc_level(b)
dfa = df.iloc[:, sxa]
dfb = df.iloc[:, sxb]
dff = pd.concat([dfa, dfb], axis=1)
y = np.ones(dff.shape[1])
y[np.arange(dfa.shape[1])] = 0
plsr = PLSRegression(n_components=n_components, scale=scale, **kwargs)
plsr.fit(dff.values.T, y)
# Apply the generated model to the original data
x_scores = plsr.transform(df.values.T)
scores = pd.DataFrame(x_scores.T)
scores.index = ['Latent Variable %d' % (n+1) for n in range(0, scores.shape[0])]
scores.columns = df.columns
weights = pd.DataFrame(plsr.x_weights_)
weights.index = df.index
weights.columns = ['Weights on Latent Variable %d' % (n+1) for n in range(0, weights.shape[1])]
loadings = pd.DataFrame(plsr.x_loadings_)
loadings.index = df.index
loadings.columns = ['Loadings on Latent Variable %d' % (n+1) for n in range(0, loadings.shape[1])]
return scores, weights, loadings | [
"def",
"plsda",
"(",
"df",
",",
"a",
",",
"b",
",",
"n_components",
"=",
"2",
",",
"mean_center",
"=",
"False",
",",
"scale",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"sklearn",
":",
"assert",
"(",
"'This library depends on scikit-learn (sklearn) to perform PLS-DA'",
")",
"from",
"sklearn",
".",
"cross_decomposition",
"import",
"PLSRegression",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"# We have to zero fill, nan errors in PLSRegression",
"df",
"[",
"np",
".",
"isnan",
"(",
"df",
")",
"]",
"=",
"0",
"if",
"mean_center",
":",
"mean",
"=",
"np",
".",
"mean",
"(",
"df",
".",
"values",
",",
"axis",
"=",
"0",
")",
"df",
"=",
"df",
"-",
"mean",
"sxa",
",",
"_",
"=",
"df",
".",
"columns",
".",
"get_loc_level",
"(",
"a",
")",
"sxb",
",",
"_",
"=",
"df",
".",
"columns",
".",
"get_loc_level",
"(",
"b",
")",
"dfa",
"=",
"df",
".",
"iloc",
"[",
":",
",",
"sxa",
"]",
"dfb",
"=",
"df",
".",
"iloc",
"[",
":",
",",
"sxb",
"]",
"dff",
"=",
"pd",
".",
"concat",
"(",
"[",
"dfa",
",",
"dfb",
"]",
",",
"axis",
"=",
"1",
")",
"y",
"=",
"np",
".",
"ones",
"(",
"dff",
".",
"shape",
"[",
"1",
"]",
")",
"y",
"[",
"np",
".",
"arange",
"(",
"dfa",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"=",
"0",
"plsr",
"=",
"PLSRegression",
"(",
"n_components",
"=",
"n_components",
",",
"scale",
"=",
"scale",
",",
"*",
"*",
"kwargs",
")",
"plsr",
".",
"fit",
"(",
"dff",
".",
"values",
".",
"T",
",",
"y",
")",
"# Apply the generated model to the original data",
"x_scores",
"=",
"plsr",
".",
"transform",
"(",
"df",
".",
"values",
".",
"T",
")",
"scores",
"=",
"pd",
".",
"DataFrame",
"(",
"x_scores",
".",
"T",
")",
"scores",
".",
"index",
"=",
"[",
"'Latent Variable %d'",
"%",
"(",
"n",
"+",
"1",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"scores",
".",
"shape",
"[",
"0",
"]",
")",
"]",
"scores",
".",
"columns",
"=",
"df",
".",
"columns",
"weights",
"=",
"pd",
".",
"DataFrame",
"(",
"plsr",
".",
"x_weights_",
")",
"weights",
".",
"index",
"=",
"df",
".",
"index",
"weights",
".",
"columns",
"=",
"[",
"'Weights on Latent Variable %d'",
"%",
"(",
"n",
"+",
"1",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"weights",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"loadings",
"=",
"pd",
".",
"DataFrame",
"(",
"plsr",
".",
"x_loadings_",
")",
"loadings",
".",
"index",
"=",
"df",
".",
"index",
"loadings",
".",
"columns",
"=",
"[",
"'Loadings on Latent Variable %d'",
"%",
"(",
"n",
"+",
"1",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"loadings",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"return",
"scores",
",",
"weights",
",",
"loadings"
] | Partial Least Squares Discriminant Analysis, based on `sklearn.cross_decomposition.PLSRegression`
Performs a binary group partial least squares discriminant analysis (PLS-DA) on the supplied
dataframe, selecting the first ``n_components``.
Sample groups are defined by the selectors ``a`` and ``b`` which are used to select columns
from the supplied dataframe. The result model is applied to the entire dataset,
projecting non-selected samples into the same space.
For more information on PLS regression and the algorithm used, see the `scikit-learn documentation <http://scikit-learn.org/stable/modules/generated/sklearn.cross_decomposition.PLSRegression.html>`_.
:param df: Pandas ``DataFrame`` to perform the analysis on
:param a: Column selector for group a
:param b: Column selector for group b
:param n_components: ``int`` number of components to select
:param mean_center: ``bool`` mean center the data before performing PLS regression
:param kwargs: additional keyword arguments to `sklearn.cross_decomposition.PLSRegression`
:return: scores ``DataFrame`` of PLSDA scores n_components x n_samples
weights ``DataFrame`` of PLSDA weights n_variables x n_components | [
"Partial",
"Least",
"Squares",
"Discriminant",
"Analysis",
"based",
"on",
"sklearn",
".",
"cross_decomposition",
".",
"PLSRegression"
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L96-L161 |
5,997 | mfitzp/padua | padua/analysis.py | enrichment_from_evidence | def enrichment_from_evidence(dfe, modification="Phospho (STY)"):
"""
Calculate relative enrichment of peptide modifications from evidence.txt.
Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified
modification in the table.
The returned data columns are generated from the input data columns.
:param df: Pandas ``DataFrame`` of evidence
:return: Pandas ``DataFrame`` of percentage modifications in the supplied data.
"""
dfe = dfe.reset_index().set_index('Experiment')
dfe['Modifications'] = np.array([modification in m for m in dfe['Modifications']])
dfe = dfe.set_index('Modifications', append=True)
dfes = dfe.sum(axis=0, level=[0,1]).T
columns = dfes.sum(axis=1, level=0).columns
total = dfes.sum(axis=1, level=0).values.flatten() # Total values
modified = dfes.iloc[0, dfes.columns.get_level_values('Modifications').values ].values # Modified
enrichment = modified / total
return pd.DataFrame([enrichment], columns=columns, index=['% Enrichment']) | python | def enrichment_from_evidence(dfe, modification="Phospho (STY)"):
"""
Calculate relative enrichment of peptide modifications from evidence.txt.
Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified
modification in the table.
The returned data columns are generated from the input data columns.
:param df: Pandas ``DataFrame`` of evidence
:return: Pandas ``DataFrame`` of percentage modifications in the supplied data.
"""
dfe = dfe.reset_index().set_index('Experiment')
dfe['Modifications'] = np.array([modification in m for m in dfe['Modifications']])
dfe = dfe.set_index('Modifications', append=True)
dfes = dfe.sum(axis=0, level=[0,1]).T
columns = dfes.sum(axis=1, level=0).columns
total = dfes.sum(axis=1, level=0).values.flatten() # Total values
modified = dfes.iloc[0, dfes.columns.get_level_values('Modifications').values ].values # Modified
enrichment = modified / total
return pd.DataFrame([enrichment], columns=columns, index=['% Enrichment']) | [
"def",
"enrichment_from_evidence",
"(",
"dfe",
",",
"modification",
"=",
"\"Phospho (STY)\"",
")",
":",
"dfe",
"=",
"dfe",
".",
"reset_index",
"(",
")",
".",
"set_index",
"(",
"'Experiment'",
")",
"dfe",
"[",
"'Modifications'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"modification",
"in",
"m",
"for",
"m",
"in",
"dfe",
"[",
"'Modifications'",
"]",
"]",
")",
"dfe",
"=",
"dfe",
".",
"set_index",
"(",
"'Modifications'",
",",
"append",
"=",
"True",
")",
"dfes",
"=",
"dfe",
".",
"sum",
"(",
"axis",
"=",
"0",
",",
"level",
"=",
"[",
"0",
",",
"1",
"]",
")",
".",
"T",
"columns",
"=",
"dfes",
".",
"sum",
"(",
"axis",
"=",
"1",
",",
"level",
"=",
"0",
")",
".",
"columns",
"total",
"=",
"dfes",
".",
"sum",
"(",
"axis",
"=",
"1",
",",
"level",
"=",
"0",
")",
".",
"values",
".",
"flatten",
"(",
")",
"# Total values",
"modified",
"=",
"dfes",
".",
"iloc",
"[",
"0",
",",
"dfes",
".",
"columns",
".",
"get_level_values",
"(",
"'Modifications'",
")",
".",
"values",
"]",
".",
"values",
"# Modified",
"enrichment",
"=",
"modified",
"/",
"total",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"enrichment",
"]",
",",
"columns",
"=",
"columns",
",",
"index",
"=",
"[",
"'% Enrichment'",
"]",
")"
] | Calculate relative enrichment of peptide modifications from evidence.txt.
Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified
modification in the table.
The returned data columns are generated from the input data columns.
:param df: Pandas ``DataFrame`` of evidence
:return: Pandas ``DataFrame`` of percentage modifications in the supplied data. | [
"Calculate",
"relative",
"enrichment",
"of",
"peptide",
"modifications",
"from",
"evidence",
".",
"txt",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L232-L258 |
5,998 | mfitzp/padua | padua/analysis.py | enrichment_from_msp | def enrichment_from_msp(dfmsp, modification="Phospho (STY)"):
"""
Calculate relative enrichment of peptide modifications from modificationSpecificPeptides.txt.
Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified
modification in the table.
The returned data columns are generated from the input data columns.
:param df: Pandas ``DataFrame`` of modificationSpecificPeptides
:return: Pandas ``DataFrame`` of percentage modifications in the supplied data.
"""
dfmsp['Modifications'] = np.array([modification in m for m in dfmsp['Modifications']])
dfmsp = dfmsp.set_index(['Modifications'])
dfmsp = dfmsp.filter(regex='Intensity ')
dfmsp[ dfmsp == 0] = np.nan
df_r = dfmsp.sum(axis=0, level=0)
modified = df_r.loc[True].values
total = df_r.sum(axis=0).values
enrichment = modified / total
return pd.DataFrame([enrichment], columns=dfmsp.columns, index=['% Enrichment']) | python | def enrichment_from_msp(dfmsp, modification="Phospho (STY)"):
"""
Calculate relative enrichment of peptide modifications from modificationSpecificPeptides.txt.
Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified
modification in the table.
The returned data columns are generated from the input data columns.
:param df: Pandas ``DataFrame`` of modificationSpecificPeptides
:return: Pandas ``DataFrame`` of percentage modifications in the supplied data.
"""
dfmsp['Modifications'] = np.array([modification in m for m in dfmsp['Modifications']])
dfmsp = dfmsp.set_index(['Modifications'])
dfmsp = dfmsp.filter(regex='Intensity ')
dfmsp[ dfmsp == 0] = np.nan
df_r = dfmsp.sum(axis=0, level=0)
modified = df_r.loc[True].values
total = df_r.sum(axis=0).values
enrichment = modified / total
return pd.DataFrame([enrichment], columns=dfmsp.columns, index=['% Enrichment']) | [
"def",
"enrichment_from_msp",
"(",
"dfmsp",
",",
"modification",
"=",
"\"Phospho (STY)\"",
")",
":",
"dfmsp",
"[",
"'Modifications'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"modification",
"in",
"m",
"for",
"m",
"in",
"dfmsp",
"[",
"'Modifications'",
"]",
"]",
")",
"dfmsp",
"=",
"dfmsp",
".",
"set_index",
"(",
"[",
"'Modifications'",
"]",
")",
"dfmsp",
"=",
"dfmsp",
".",
"filter",
"(",
"regex",
"=",
"'Intensity '",
")",
"dfmsp",
"[",
"dfmsp",
"==",
"0",
"]",
"=",
"np",
".",
"nan",
"df_r",
"=",
"dfmsp",
".",
"sum",
"(",
"axis",
"=",
"0",
",",
"level",
"=",
"0",
")",
"modified",
"=",
"df_r",
".",
"loc",
"[",
"True",
"]",
".",
"values",
"total",
"=",
"df_r",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
".",
"values",
"enrichment",
"=",
"modified",
"/",
"total",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"enrichment",
"]",
",",
"columns",
"=",
"dfmsp",
".",
"columns",
",",
"index",
"=",
"[",
"'% Enrichment'",
"]",
")"
] | Calculate relative enrichment of peptide modifications from modificationSpecificPeptides.txt.
Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified
modification in the table.
The returned data columns are generated from the input data columns.
:param df: Pandas ``DataFrame`` of modificationSpecificPeptides
:return: Pandas ``DataFrame`` of percentage modifications in the supplied data. | [
"Calculate",
"relative",
"enrichment",
"of",
"peptide",
"modifications",
"from",
"modificationSpecificPeptides",
".",
"txt",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L263-L287 |
5,999 | mfitzp/padua | padua/analysis.py | sitespeptidesproteins | def sitespeptidesproteins(df, site_localization_probability=0.75):
"""
Generate summary count of modified sites, peptides and proteins in a processed dataset ``DataFrame``.
Returns the number of sites, peptides and proteins as calculated as follows:
- `sites` (>0.75; or specified site localization probability) count of all sites > threshold
- `peptides` the set of `Sequence windows` in the dataset (unique peptides)
- `proteins` the set of unique leading proteins in the dataset
:param df: Pandas ``DataFrame`` of processed data
:param site_localization_probability: ``float`` site localization probability threshold (for sites calculation)
:return: ``tuple`` of ``int``, containing sites, peptides, proteins
"""
sites = filters.filter_localization_probability(df, site_localization_probability)['Sequence window']
peptides = set(df['Sequence window'])
proteins = set([str(p).split(';')[0] for p in df['Proteins']])
return len(sites), len(peptides), len(proteins) | python | def sitespeptidesproteins(df, site_localization_probability=0.75):
"""
Generate summary count of modified sites, peptides and proteins in a processed dataset ``DataFrame``.
Returns the number of sites, peptides and proteins as calculated as follows:
- `sites` (>0.75; or specified site localization probability) count of all sites > threshold
- `peptides` the set of `Sequence windows` in the dataset (unique peptides)
- `proteins` the set of unique leading proteins in the dataset
:param df: Pandas ``DataFrame`` of processed data
:param site_localization_probability: ``float`` site localization probability threshold (for sites calculation)
:return: ``tuple`` of ``int``, containing sites, peptides, proteins
"""
sites = filters.filter_localization_probability(df, site_localization_probability)['Sequence window']
peptides = set(df['Sequence window'])
proteins = set([str(p).split(';')[0] for p in df['Proteins']])
return len(sites), len(peptides), len(proteins) | [
"def",
"sitespeptidesproteins",
"(",
"df",
",",
"site_localization_probability",
"=",
"0.75",
")",
":",
"sites",
"=",
"filters",
".",
"filter_localization_probability",
"(",
"df",
",",
"site_localization_probability",
")",
"[",
"'Sequence window'",
"]",
"peptides",
"=",
"set",
"(",
"df",
"[",
"'Sequence window'",
"]",
")",
"proteins",
"=",
"set",
"(",
"[",
"str",
"(",
"p",
")",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
"for",
"p",
"in",
"df",
"[",
"'Proteins'",
"]",
"]",
")",
"return",
"len",
"(",
"sites",
")",
",",
"len",
"(",
"peptides",
")",
",",
"len",
"(",
"proteins",
")"
] | Generate summary count of modified sites, peptides and proteins in a processed dataset ``DataFrame``.
Returns the number of sites, peptides and proteins as calculated as follows:
- `sites` (>0.75; or specified site localization probability) count of all sites > threshold
- `peptides` the set of `Sequence windows` in the dataset (unique peptides)
- `proteins` the set of unique leading proteins in the dataset
:param df: Pandas ``DataFrame`` of processed data
:param site_localization_probability: ``float`` site localization probability threshold (for sites calculation)
:return: ``tuple`` of ``int``, containing sites, peptides, proteins | [
"Generate",
"summary",
"count",
"of",
"modified",
"sites",
"peptides",
"and",
"proteins",
"in",
"a",
"processed",
"dataset",
"DataFrame",
"."
] | 8b14bf4d2f895da6aea5d7885d409315bd303ec6 | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L291-L309 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.