idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
49,900
def connect ( self ) : self . serial = serial . Serial ( port = self . port , baudrate = self . baudrate , timeout = self . timeout ) 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
49,901
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
49,902
def _readLoop ( self ) : try : readTermSeq = list ( self . RX_EOL_SEQ ) readTermLen = len ( readTermSeq ) rxBuffer = [ ] while self . alive : data = self . serial . read ( 1 ) if data != '' : rxBuffer . append ( data ) if rxBuffer [ - readTermLen : ] == readTermSeq : line = '' . join ( rxBuffer [ : - readTermLen ] ) rx...
Read thread main loop Reads lines from the connected device
49,903
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
49,904
def decodeUcs2 ( byteIter , numBytes ) : userData = [ ] i = 0 try : while i < numBytes : userData . append ( unichr ( ( next ( byteIter ) << 8 ) | next ( byteIter ) ) ) i += 2 except StopIteration : pass return '' . join ( userData )
Decodes UCS2 - encoded text from the specified byte iterator up to a maximum of numBytes
49,905
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
49,906
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 . ad...
Argument parser for Python 2 . 6
49,907
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
49,908
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
49,909
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
49,910
def clean ( decrypted : bytes ) -> str : r last = decrypted [ - 1 ] if isinstance ( last , int ) : return decrypted [ : - last ] . decode ( 'utf8' ) return decrypted [ : - ord ( last ) ] . decode ( 'utf8' )
r Strip padding from decrypted value .
49,911
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 ( ...
Set the setpoint value for a step .
49,912
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 .
49,913
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 .
49,914
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 .
49,915
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 .
49,916
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 .
49,917
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 , v...
Set the number of additional cycles for a given pattern .
49,918
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 .
49,919
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 ( patternnu...
Get all variables for a given pattern at one time .
49,920
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_...
Set all variables for a given pattern at one time .
49,921
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 .
49,922
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 , encodi...
Write to a port on dummy_serial .
49,923
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 : r...
Read from a port on dummy_serial .
49,924
def _embedPayload ( slaveaddress , mode , functioncode , payloaddata ) : _checkSlaveaddress ( slaveaddress ) _checkMode ( mode ) _checkFunctioncode ( functioncode , None ) _checkString ( payloaddata , description = 'payload' ) firstPart = _numToOneByteString ( slaveaddress ) + _numToOneByteString ( functioncode ) + pay...
Build a request from the slaveaddress the function code and the payload data .
49,925
def _extractPayload ( response , slaveaddress , mode , functioncode ) : BYTEPOSITION_FOR_ASCII_HEADER = 0 BYTEPOSITION_FOR_SLAVEADDRESS = 0 BYTEPOSITION_FOR_FUNCTIONCODE = 1 NUMBER_OF_RESPONSE_STARTBYTES = 2 NUMBER_OF_CRC_BYTES = 2 NUMBER_OF_LRC_BYTES = 1 BITNUMBER_FUNCTIONCODE_ERRORINDICATION = 7 MINIMAL_RESPONSE_LENG...
Extract the payload data part from the slave s response .
49,926
def _predictResponseSize ( mode , functioncode , payloadToSlave ) : MIN_PAYLOAD_LENGTH = 4 BYTERANGE_FOR_GIVEN_SIZE = slice ( 2 , 4 ) 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_RESPO...
Calculate the number of bytes that should be received from the slave .
49,927
def _calculate_minimum_silent_period ( baudrate ) : _checkNumerical ( baudrate , minvalue = 1 , description = 'baudrate' ) 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 .
49,928
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 = ...
Convert a numerical value to a two - byte string possibly scaling it .
49,929
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...
Convert a two - byte string to a numerical value possibly scaling it .
49,930
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...
Pack a value into a bytestring .
49,931
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' ) try : value = struct . unpack ( formatstring , pa...
Unpack a bytestring into a value .
49,932
def _hexencode ( bytestring , insert_spaces = False ) : _checkString ( bytestring , description = 'byte string' ) separator = '' if not insert_spaces else ' ' byte_representions = [ ] for c in bytestring : byte_representions . append ( '{0:02X}' . format ( ord ( c ) ) ) return separator . join ( byte_representions ) . ...
Convert a byte string to a hex encoded string .
49,933
def _hexdecode ( hexstring ) : _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 . ...
Convert a hex encoded string to a byte string .
49,934
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 v...
Convert a response string to a numerical value .
49,935
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 ...
Create the bit pattern that is used for writing single bits .
49,936
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...
Calculate the two s complement of an integer .
49,937
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 .
49,938
def _calculateCrcString ( inputstring ) : _checkString ( inputstring , description = 'input CRC string' ) register = 0xFFFF for char in inputstring : register = ( register >> 8 ) ^ _CRC16TABLE [ ( register ^ ord ( char ) ) & 0xFF ] return _numToTwoByteString ( register , LsbFirst = True )
Calculate CRC - 16 for Modbus .
49,939
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 .
49,940
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 .
49,941
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 ( '...
Check that the given functioncode is in the listOfAllowedValues .
49,942
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 givenNumbe...
Check that the number of bytes as given in the response is correct .
49,943
def _checkResponseRegisterAddress ( payload , registeraddress ) : _checkString ( payload , minlength = 2 , description = 'payload' ) _checkRegisteraddress ( registeraddress ) BYTERANGE_FOR_STARTADDRESS = slice ( 0 , 2 ) bytesForStartAddress = payload [ BYTERANGE_FOR_STARTADDRESS ] receivedStartAddress = _twoByteStringT...
Check that the start adress as given in the response is correct .
49,944
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 = ...
Check that the number of written registers as given in the response is correct .
49,945
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 receivedWri...
Check that the write data as given in the response is correct .
49,946
def _checkString ( inputstring , description , minlength = 0 , maxlength = None ) : 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...
Check that the given string is valid .
49,947
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...
Check that the given integer is valid .
49,948
def _checkNumerical ( 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 , float ) ) : raise TypeError ( 'T...
Check that the given numerical value is valid .
49,949
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 .
49,950
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__ )...
Generate a diagnostic string showing the module version the platform current directory etc .
49,951
def read_bit ( self , registeraddress , functioncode = 2 ) : _checkFunctioncode ( functioncode , [ 1 , 2 ] ) return self . _genericCommand ( functioncode , registeraddress )
Read one bit from the slave .
49,952
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 .
49,953
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 . _gener...
Read an integer from one 16 - bit register in the slave possibly scaling it .
49,954
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' ) _checkNum...
Write an integer to one 16 - bit register in the slave possibly scaling it .
49,955
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 = ...
Read a floating point number from the slave .
49,956
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 = numberOfReg...
Write a floating point number to the slave .
49,957
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...
Read a string from the slave .
49,958
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 , registe...
Write a string to the slave .
49,959
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' ) self . _genericCommand ( 16 , registeraddress ,...
Write integers to 16 - bit registers in the slave .
49,960
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_r...
Talk to the slave via a serial port .
49,961
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 ...
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 .
49,962
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 = NSSoun...
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 .
49,963
def _playsoundNix ( sound , block = True ) : if not block : raise NotImplementedError ( "block=False cannot be used on this platform yet" ) import os try : from urllib . request import pathname2url except ImportError : from urllib import pathname2url import gi gi . require_version ( 'Gst' , '1.0' ) from gi . repository...
Play a sound using GStreamer .
49,964
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 .
49,965
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 .
49,966
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
49,967
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' ) ] if invalid is np . nan : dfx = ~ np . isnan ( df ) else : dfx = df != invalid dfc = dfx . astype (...
Filter DataFrame by at least n valid values in at least one group .
49,968
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 ( [ mat...
Search for a given string in a set of columns in a processed DataFrame .
49,969
def filter_select_columns_intensity ( df , prefix , columns ) : return df . filter ( regex = '^(%s.+|%s)$' % ( prefix , '|' . join ( columns ) ) )
Filter dataframe to include specified columns retaining any Intensity columns .
49,970
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 .
49,971
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 .
49,972
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
49,973
def write_perseus ( f , df ) : 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' ,...
Export a dataframe to Perseus ; recreating the format
49,974
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 ...
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 - S10...
49,975
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
49,976
def gaussian ( df , width = 0.3 , downshift = - 1.8 , prefix = None ) : df = df . copy ( ) imputed = df . isnull ( ) 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 ] ) ...
Impute missing values by drawing from a normal distribution
49,977
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 = [ ...
Plot a scores plot for two principal components as AxB scatter plot .
49,978
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 ....
Generate a plot of relative numbers of modified amino acids in source DataFrame .
49,979
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 ( ) . ...
Plot a 2 or 3 - part venn diagram showing the overlap between 2 or 3 pandas DataFrames .
49,980
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 (Cl...
Plot the number of sites peptides and proteins in the dataset .
49,981
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
49,982
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...
Hierarchical clustering of samples across timecourse experiment .
49,983
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 ...
Apply column - wise normalisation to expression columns .
49,984
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
49,985
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
49,986
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 ...
Calculate s0 curve for volcano plot .
49,987
def correlation ( df , rowvar = False ) : 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 ...
Calculate column - wise Pearson correlations using numpy . ma . corrcoef
49,988
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 ( ) df [ np . isnan ( df ) ] = 0 if mean_center : mean = np . mean ( df . values , axis = 0 ) ...
Principal Component Analysis based on sklearn . decomposition . PCA
49,989
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 ( ) df [ np . isnan ( df ) ] = 0 if mean_center : mean = np...
Partial Least Squares Discriminant Analysis based on sklearn . cross_decomposition . PLSRegression
49,990
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 =...
Calculate relative enrichment of peptide modifications from evidence . txt .
49,991
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 ( ...
Calculate relative enrichment of peptide modifications from modificationSpecificPeptides . txt .
49,992
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 le...
Generate summary count of modified sites peptides and proteins in a processed dataset DataFrame .
49,993
def modifiedaminoacids ( df ) : amino_acids = list ( df [ 'Amino acid' ] . values ) aas = set ( amino_acids ) quants = { } for aa in aas : quants [ aa ] = amino_acids . count ( aa ) total_aas = len ( amino_acids ) return total_aas , quants
Calculate the number of modified amino acids in supplied DataFrame .
49,994
def build_index_from_design ( df , design , remove_prefix = None , types = None , axis = 1 , auto_convert_numeric = True , unmatched_columns = 'index' ) : df = df . copy ( ) if 'Label' not in design . index . names : design = design . set_index ( 'Label' ) if remove_prefix is None : remove_prefix = [ ] if type ( remove...
Build a MultiIndex from a design table .
49,995
def build_index_from_labels ( df , indices , remove_prefix = None , types = None , axis = 1 ) : df = df . copy ( ) if remove_prefix is None : remove_prefix = [ ] if types is None : types = { } idx = [ df . index , df . columns ] [ axis ] indexes = [ ] for l in idx . get_level_values ( 0 ) : for s in remove_prefix : l =...
Build a MultiIndex from a list of labels and matching regex
49,996
def combine_expression_columns ( df , columns_to_combine , remove_combined = True ) : df = df . copy ( ) for ca , cb in columns_to_combine : df [ "%s_(x+y)/2_%s" % ( ca , cb ) ] = ( df [ ca ] + df [ cb ] ) / 2 if remove_combined : for ca , cb in columns_to_combine : df . drop ( [ ca , cb ] , inplace = True , axis = 1 )...
Combine expression columns calculating the mean for 2 columns
49,997
def expand_side_table ( df ) : df = df . copy ( ) idx = df . index . names df . reset_index ( inplace = True ) def strip_multiplicity ( df ) : df . columns = [ c [ : - 4 ] for c in df . columns ] return df def strip_multiple ( s ) : for sr in [ ' 1' , ' 2' , ' 3' ] : if s . endswith ( sr ) : s = s [ : - 4 ] return s ba...
Perform equivalent of expand side table in Perseus by folding Multiplicity columns down onto duplicate rows
49,998
def apply_experimental_design ( df , f , prefix = 'Intensity ' ) : df = df . copy ( ) edt = pd . read_csv ( f , sep = '\t' , header = 0 ) edt . set_index ( 'Experiment' , inplace = True ) new_column_labels = [ ] for l in df . columns . values : try : l = edt . loc [ l . replace ( prefix , '' ) ] [ 'Name' ] except ( Ind...
Load the experimental design template from MaxQuant and use it to apply the label names to the data columns .
49,999
def transform_expression_columns ( df , fn = np . log2 , prefix = 'Intensity ' ) : df = df . copy ( ) mask = np . array ( [ l . startswith ( prefix ) for l in df . columns . values ] ) df . iloc [ : , mask ] = fn ( df . iloc [ : , mask ] ) df . replace ( [ np . inf , - np . inf ] , np . nan , inplace = True ) return df
Apply transformation to expression columns .