code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def f(*args, **kw):
code = func(*args, **kw)
check_error(code, context="client")
return f | def error_wrap(func) | Parses a s7 error code returned the decorated function. | 5.697443 | 5.271413 | 1.080819 |
logger.info("creating snap7 client")
self.library.Cli_Create.restype = c_void_p
self.pointer = S7Object(self.library.Cli_Create()) | def create(self) | create a SNAP7 client. | 9.177818 | 5.844172 | 1.570422 |
logger.info("destroying snap7 client")
if self.library:
return self.library.Cli_Destroy(byref(self.pointer)) | def destroy(self) | destroy a client. | 13.768198 | 11.298713 | 1.218563 |
state = c_int(0)
self.library.Cli_GetPlcStatus(self.pointer,byref(state))
try:
status_string = cpu_statuses[state.value]
except KeyError:
status_string = None
if not status_string:
raise Snap7Exception("The cpu state ... | def get_cpu_state(self) | Retrieves CPU state from client | 4.77621 | 4.400432 | 1.085396 |
info = snap7.snap7types.S7CpuInfo()
result = self.library.Cli_GetCpuInfo(self.pointer, byref(info))
check_error(result, context="client")
return info | def get_cpu_info(self) | Retrieves CPU info from client | 7.260617 | 6.596595 | 1.100661 |
logger.info("connecting to %s:%s rack %s slot %s" % (address, tcpport,
rack, slot))
self.set_param(snap7.snap7types.RemotePort, tcpport)
return self.library.Cli_ConnectTo(
self.pointer, c_char_p(six.b(address)),
... | def connect(self, address, rack, slot, tcpport=102) | Connect to a S7 server.
:param address: IP address of server
:param rack: rack on server
:param slot: slot on server. | 5.216284 | 5.426397 | 0.961279 |
logger.debug("db_read, db_number:%s, start:%s, size:%s" %
(db_number, start, size))
type_ = snap7.snap7types.wordlen_to_ctypes[snap7.snap7types.S7WLByte]
data = (type_ * size)()
result = (self.library.Cli_DBRead(
self.pointer, db_number, start, ... | def db_read(self, db_number, start, size) | This is a lean function of Cli_ReadArea() to read PLC DB.
:returns: user buffer. | 4.214458 | 4.398449 | 0.958169 |
logger.info("deleting block")
blocktype = snap7.snap7types.block_types[block_type]
result = self.library.Cli_Delete(self.pointer, blocktype, block_num)
return result | def delete(self, block_type, block_num) | Deletes a block
:param block_type: Type of block
:param block_num: Bloc number | 7.194447 | 6.947194 | 1.03559 |
_buffer = buffer_type()
size = c_int(sizeof(_buffer))
block_type = snap7.snap7types.block_types[_type]
result = self.library.Cli_FullUpload(self.pointer, block_type,
block_num, byref(_buffer),
... | def full_upload(self, _type, block_num) | Uploads a full block body from AG.
The whole block (including header and footer) is copied into the user
buffer.
:param block_num: Number of Block | 5.427703 | 6.109787 | 0.888362 |
logger.debug("db_upload block_num: %s" % (block_num))
block_type = snap7.snap7types.block_types['DB']
_buffer = buffer_type()
size = c_int(sizeof(_buffer))
result = self.library.Cli_Upload(self.pointer, block_type, block_num,
by... | def upload(self, block_num) | Uploads a block body from AG
:param data: bytearray | 6.299854 | 6.540388 | 0.963223 |
type_ = c_byte
size = len(data)
cdata = (type_ * len(data)).from_buffer_copy(data)
result = self.library.Cli_Download(self.pointer, block_num,
byref(cdata), size)
return result | def download(self, data, block_num=-1) | Downloads a DB data into the AG.
A whole block (including header and footer) must be available into the
user buffer.
:param block_num: New Block number (or -1)
:param data: the user buffer | 4.983525 | 5.678849 | 0.877559 |
logger.debug("db_get db_number: %s" % db_number)
_buffer = buffer_type()
result = self.library.Cli_DBGet(
self.pointer, db_number, byref(_buffer),
byref(c_int(buffer_size)))
check_error(result, context="client")
return bytearray(_buffer) | def db_get(self, db_number) | Uploads a DB from AG. | 5.404613 | 5.598053 | 0.965445 |
assert area in snap7.snap7types.areas.values()
wordlen = snap7.snap7types.S7WLByte
type_ = snap7.snap7types.wordlen_to_ctypes[wordlen]
logger.debug("reading area: %s dbnumber: %s start: %s: amount %s: "
"wordlen: %s" % (area, dbnumber, start, size, wordlen)... | def read_area(self, area, dbnumber, start, size) | This is the main function to read data from a PLC.
With it you can read DB, Inputs, Outputs, Merkers, Timers and Counters.
:param dbnumber: The DB number, only used when area= S7AreaDB
:param start: offset to start writing
:param size: number of units to read | 4.560488 | 4.905274 | 0.929711 |
wordlen = snap7.snap7types.S7WLByte
type_ = snap7.snap7types.wordlen_to_ctypes[wordlen]
size = len(data)
logger.debug("writing area: %s dbnumber: %s start: %s: size %s: "
"type: %s" % (area, dbnumber, start, size, type_))
cdata = (type_ * len(data))... | def write_area(self, area, dbnumber, start, data) | This is the main function to write data into a PLC. It's the
complementary function of Cli_ReadArea(), the parameters and their
meanings are the same. The only difference is that the data is
transferred from the buffer pointed by pUsrData into PLC.
:param dbnumber: The DB number, only u... | 3.979146 | 4.027802 | 0.98792 |
result = self.library.Cli_ReadMultiVars(self.pointer, byref(items),
c_int32(len(items)))
check_error(result, context="client")
return result, items | def read_multi_vars(self, items) | This function read multiple variables from the PLC.
:param items: list of S7DataItem objects
:returns: a tuple with the return code and a list of data items | 7.283792 | 9.052207 | 0.804643 |
logger.debug("listing blocks")
blocksList = BlocksList()
result = self.library.Cli_ListBlocks(self.pointer, byref(blocksList))
check_error(result, context="client")
logger.debug("blocks: %s" % blocksList)
return blocksList | def list_blocks(self) | Returns the AG blocks amount divided by type.
:returns: a snap7.types.BlocksList object. | 6.44191 | 5.28482 | 1.218946 |
blocktype = snap7.snap7types.block_types.get(blocktype)
if not blocktype:
raise Snap7Exception("The blocktype parameter was invalid")
logger.debug("listing blocks of type: %s size: %s" %
(blocktype, size))
if (size == 0):
return ... | def list_blocks_of_type(self, blocktype, size) | This function returns the AG list of a specified block type. | 4.668419 | 4.713413 | 0.990454 |
blocktype = snap7.snap7types.block_types.get(blocktype)
if not blocktype:
raise Snap7Exception("The blocktype parameter was invalid")
logger.debug("retrieving block info for block %s of type %s" %
(db_number, blocktype))
data = TS7BlockInfo(... | def get_block_info(self, blocktype, db_number) | Returns the block information for the specified block. | 6.342787 | 6.040474 | 1.050048 |
assert len(password) <= 8, 'maximum password length is 8'
return self.library.Cli_SetSessionPassword(self.pointer,
c_char_p(six.b(password))) | def set_session_password(self, password) | Send the password to the PLC to meet its security level. | 7.140455 | 6.390303 | 1.117389 |
assert re.match(ipv4, address), '%s is invalid ipv4' % address
result = self.library.Cli_SetConnectionParams(self.pointer, address,
c_uint16(local_tsap),
c_uint16(remote_tsap))
if... | def set_connection_params(self, address, local_tsap, remote_tsap) | Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates.
This function must be called just before Cli_Connect().
:param address: PLC/Equipment IPV4 Address, for example "192.168.1.12"
:param local_tsap: Local TSAP (PC TSAP)
:param remote_tsap: Remote TSAP (PLC TSAP) | 5.08572 | 4.949068 | 1.027612 |
result = self.library.Cli_SetConnectionType(self.pointer,
c_uint16(connection_type))
if result != 0:
raise Snap7Exception("The parameter was invalid") | def set_connection_type(self, connection_type) | Sets the connection resource type, i.e the way in which the Clients
connects to a PLC.
:param connection_type: 1 for PG, 2 for OP, 3 to 10 for S7 Basic | 7.915272 | 9.762186 | 0.810809 |
connected = c_int32()
result = self.library.Cli_GetConnected(self.pointer, byref(connected))
check_error(result, context="client")
return bool(connected) | def get_connected(self) | Returns the connection status
:returns: a boolean that indicates if connected. | 6.254706 | 7.379225 | 0.84761 |
wordlen = snap7.snap7types.S7WLByte
type_ = snap7.snap7types.wordlen_to_ctypes[wordlen]
data = (type_ * size)()
logger.debug("ab_read: start: %s: size %s: " % (start, size))
result = self.library.Cli_ABRead(self.pointer, start, size,
... | def ab_read(self, start, size) | This is a lean function of Cli_ReadArea() to read PLC process outputs. | 5.171206 | 4.808223 | 1.075492 |
wordlen = snap7.snap7types.S7WLByte
type_ = snap7.snap7types.wordlen_to_ctypes[wordlen]
size = len(data)
cdata = (type_ * size).from_buffer_copy(data)
logger.debug("ab write: start: %s: size: %s: " % (start, size))
return self.library.Cli_AsABWrite(
s... | def as_ab_write(self, start, data) | This is the asynchronous counterpart of Cli_ABWrite. | 4.759725 | 4.342157 | 1.096166 |
logger.debug("db_get db_number: %s" % db_number)
_buffer = buffer_type()
result = self.library.Cli_AsDBGet(self.pointer, db_number,
byref(_buffer),
byref(c_int(buffer_size)))
check_error(result, ... | def as_db_get(self, db_number) | This is the asynchronous counterpart of Cli_DBGet. | 5.72008 | 5.618135 | 1.018146 |
size = len(data)
type_ = c_byte * len(data)
cdata = type_.from_buffer_copy(data)
return self.library.Cli_AsDownload(self.pointer, block_num,
byref(cdata), size) | def as_download(self, data, block_num=-1) | Downloads a DB data into the AG asynchronously.
A whole block (including header and footer) must be available into the
user buffer.
:param block_num: New Block number (or -1)
:param data: the user buffer | 5.600897 | 5.964437 | 0.939049 |
logger.debug("setting param number %s to %s" % (number, value))
type_ = param_types[number]
return self.library.Cli_SetParam(self.pointer, number,
byref(type_(value))) | def set_param(self, number, value) | Sets an internal Server object parameter. | 6.155745 | 6.178511 | 0.996315 |
logger.debug("retreiving param number %s" % number)
type_ = param_types[number]
value = type_()
code = self.library.Cli_GetParam(self.pointer, c_int(number),
byref(value))
check_error(code)
return value.value | def get_param(self, number) | Reads an internal Client object parameter. | 6.22709 | 5.668584 | 1.098527 |
logger.info("getting PDU length")
requested_ = c_uint16()
negotiated_ = c_uint16()
code = self.library.Cli_GetPduLength(self.pointer, byref(requested_), byref(negotiated_))
check_error(code)
return negotiated_.value | def get_pdu_length(self) | Returns info about the PDU length. | 5.271955 | 4.759974 | 1.10756 |
type_ = c_int32
buffer = (type_ * 9)()
result = self.library.Cli_GetPlcDateTime(self.pointer, byref(buffer))
check_error(result, context="client")
return datetime(
year = buffer[5] + 1900,
month = buffer[4] + 1,
day = buffer[3],
... | def get_plc_datetime(self) | Get date and time from PLC.
:return: date and time as datetime | 3.505775 | 3.557796 | 0.985379 |
type_ = c_int32
buffer = (type_ * 9)()
buffer[0] = dt.second
buffer[1] = dt.minute
buffer[2] = dt.hour
buffer[3] = dt.day
buffer[4] = dt.month - 1
buffer[5] = dt.year - 1900
return self.library.Cli_SetPlcDateTime(self.pointer, byref(buffe... | def set_plc_datetime(self, dt) | Set date and time in PLC
:param dt: date and time as datetime | 2.999451 | 3.117498 | 0.962134 |
all_data = client.db_get(1)
for i in range(400): # items in db
row_size = 130 # size of item
index = i * row_size
offset = index + row_size # end of row in db
util.print_row(all_data[index:offset]) | def get_db1() | Here we read out DB1, all data we is put in the all_data
variable and is a bytearray with the raw plc data | 8.924904 | 7.704375 | 1.15842 |
type_ = snap7.snap7types.wordlen_to_ctypes[snap7.snap7types.S7WLByte]
data = client.db_read(db, start, type_, size)
# print_row(data[:60])
return data | def get_db_row(db, start, size) | Here you see and example of readying out a part of a DB
Args:
db (int): The db to use
start (int): The index of where to start in db data
size (int): The size of the db data to read | 7.683846 | 10.472345 | 0.733727 |
client.db_write(db, start, size, _bytearray) | def set_db_row(db, start, size, _bytearray) | Here we replace a piece of data in a db block with new data
Args:
db (int): The db to use
start(int): The start within the db
size(int): The size of the data in bytes
_butearray (enumerable): The data to put in the db | 5.699961 | 7.207298 | 0.79086 |
row_size = 126
while True:
data = get_db_row(1, 4 + x * row_size, row_size)
row = snap7.util.DB_Row(data, rc_if_db_1_layout,
layout_offset=4)
print 'name', row['RC_IF_NAME']
print row['RC_IF_NAME']
break | def show_row(x) | print data in DB of row/object X in | 11.96584 | 12.055403 | 0.992571 |
row_size = 126
set_db_row(1, 4 + x * row_size, row_size, row._bytearray) | def set_row(x, row) | We use db 1, use offset 4, we replace row x. To find the correct
start_index we mulitpy by row_size by x and we put the
byte array representation of row in the PLC | 12.403646 | 8.362205 | 1.483299 |
index_value = 1 << bool_index
byte_value = _bytearray[byte_index]
current_value = byte_value & index_value
return current_value == index_value | def get_bool(_bytearray, byte_index, bool_index) | Get the boolean value from location in bytearray | 2.906806 | 2.900747 | 1.002089 |
assert value in [0, 1, True, False]
current_value = get_bool(_bytearray, byte_index, bool_index)
index_value = 1 << bool_index
# check if bool already has correct value
if current_value == value:
return
if value:
# make sure index_v is IN current byte
_bytearray[by... | def set_bool(_bytearray, byte_index, bool_index, value) | Set boolean value on location in bytearray | 3.448036 | 3.4863 | 0.989024 |
# make sure were dealing with an int
_int = int(_int)
_bytes = struct.unpack('2B', struct.pack('>h', _int))
bytearray_[byte_index:byte_index + 2] = _bytes
return bytearray_ | def set_int(bytearray_, byte_index, _int) | Set value in bytearray to int | 3.583524 | 3.685725 | 0.972271 |
data = bytearray_[byte_index:byte_index + 2]
data[1] = data[1] & 0xff
data[0] = data[0] & 0xff
packed = struct.pack('2B', *data)
value = struct.unpack('>h', packed)[0]
return value | def get_int(bytearray_, byte_index) | Get int value from bytearray.
int are represented in two bytes | 2.381602 | 2.52022 | 0.944998 |
real = float(real)
real = struct.pack('>f', real)
_bytes = struct.unpack('4B', real)
for i, b in enumerate(_bytes):
_bytearray[byte_index + i] = b | def set_real(_bytearray, byte_index, real) | Set Real value
make 4 byte data from real | 2.835458 | 2.697303 | 1.05122 |
x = _bytearray[byte_index:byte_index + 4]
real = struct.unpack('>f', struct.pack('4B', *x))[0]
return real | def get_real(_bytearray, byte_index) | Get real value. create float from 4 bytes | 2.604885 | 2.421554 | 1.075708 |
if six.PY2:
assert isinstance(value, (str, unicode))
else:
assert isinstance(value, str)
size = len(value)
# FAIL HARD WHEN trying to write too much data into PLC
if size > max_size:
raise ValueError('size %s > max_size %s %s' % (size, max_size, value))
# set len co... | def set_string(_bytearray, byte_index, value, max_size) | Set string value
:params value: string data
:params max_size: max possible string size | 4.26521 | 4.322743 | 0.986691 |
size = _bytearray[byte_index + 1]
if max_size < size:
logger.error("the string is to big for the size encountered in specification")
logger.error("WRONG SIZED STRING ENCOUNTERED")
size = max_size
data = map(chr, _bytearray[byte_index + 2:byte_index + 2 + size])
return "".j... | def get_string(_bytearray, byte_index, max_size) | parse string from bytearray | 4.752224 | 4.80834 | 0.988329 |
parsed_db_specification = OrderedDict()
for line in db_specification.split('\n'):
if line and not line.startswith('#'):
row = line.split('#')[0] # remove trailing comment
index, var_name, _type = row.split()
parsed_db_specification[var_name] = (index, _type)
... | def parse_specification(db_specification) | Create a db specification derived from a
dataview of a db in which the byte layout
is specified | 3.279186 | 3.554615 | 0.922515 |
if isinstance(self._bytearray, DB):
return self._bytearray._bytearray
return self._bytearray | def get_bytearray(self) | return bytearray from self or DB parent | 5.843395 | 3.087398 | 1.89266 |
data = {}
for key in self._specification:
data[key] = self[key]
return data | def export(self) | export dictionary with values | 6.590983 | 5.306347 | 1.242094 |
assert(isinstance(self._bytearray, DB))
assert(self.row_size >= 0)
db_nr = self._bytearray.db_number
offset = self.db_offset
data = self.get_bytearray()[offset:offset+self.row_size]
db_offset = self.db_offset
# indicate start of write only area of row!
... | def write(self, client) | Write current data to db in plc | 5.23563 | 4.867388 | 1.075655 |
assert(isinstance(self._bytearray, DB))
assert(self.row_size >= 0)
db_nr = self._bytearray.db_number
_bytearray = client.db_read(db_nr, self.db_offset, self.row_size)
data = self.get_bytearray()
# replace data in bytearray
for i, b in enumerate(_bytearra... | def read(self, client) | read current data of db row from plc | 5.623104 | 5.050521 | 1.113371 |
logger.info("disconnecting snap7 client")
result = self.library.Cli_Disconnect(self.pointer)
check_error(result, context="client")
return result | def disconnect(self) | disconnect a client. | 13.507651 | 13.060687 | 1.034222 |
logger.info("connecting to %s:%s tsap_snap7 %s tsap_logo %s" % (ip_address, tcpport,
tsap_snap7, tsap_logo))
# special handling for Siemens Logo
# 1st set connection params
# 2nd connect without any parameters
... | def connect(self, ip_address, tsap_snap7, tsap_logo, tcpport=102) | Connect to a Siemens LOGO server. Howto setup Logo communication configuration see: http://snap7.sourceforge.net/logo.html
:param ip_address: IP ip_address of server
:param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 = 0x1000)
:param tsap_logo: TSAP Logo Server (e.g. 20.00 = 0x2000) | 5.727399 | 5.515993 | 1.038326 |
area = snap7types.S7AreaDB
db_number = 1
size = 1
start = 0
wordlen = 0
logger.debug("read, vm_address:%s" % (vm_address))
if re.match("V[0-9]{1,4}\.[0-7]{1}", vm_address):
## bit value
logger.info("read, Bit address: " + vm_addres... | def read(self, vm_address) | Reads from VM addresses of Siemens Logo. Examples: read("V40") / read("VW64") / read("V10.2")
:param vm_address: of Logo memory (e.g. V30.1, VW32, V24)
:returns: integer | 2.70131 | 2.651754 | 1.018688 |
area = snap7types.S7AreaDB
db_number = 1
start = 0
amount = 1
wordlen = 0
data = bytearray(0)
logger.debug("write, vm_address:%s, value:%s" %
(vm_address, value))
if re.match("^V[0-9]{1,4}\.[0-7]{1}$", vm_address):
... | def write (self, vm_address, value) | Writes to VM addresses of Siemens Logo.
Example: write("VW10", 200) or write("V10.3", 1)
:param vm_address: write offset
:param value: integer | 2.56185 | 2.53002 | 1.012581 |
assert re.match(ipv4, ip_address), '%s is invalid ipv4' % ip_address
result = self.library.Cli_SetConnectionParams(self.pointer, ip_address.encode(),
c_uint16(tsap_snap7),
c_uint16(tsap_l... | def set_connection_params(self, ip_address, tsap_snap7, tsap_logo) | Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates.
This function must be called just before Cli_Connect().
:param ip_address: IP ip_address of server
:param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 = 0x1000)
:param tsap_logo: TSAP Logo Server (e.g. 20.00 = 0x2000) | 4.478539 | 4.131078 | 1.084109 |
op_result = ctypes.c_int32()
result = self.library.Par_CheckAsBSendCompletion(self.pointer,
ctypes.byref(op_result))
return_values = {
0: "job complete",
1: "job in progress",
-2: "invalid handled suppl... | def check_as_b_send_completion(self) | Checks if the current asynchronous send job was completed and terminates
immediately. | 7.474755 | 7.150213 | 1.045389 |
self.library.Par_Create.restype = snap7.snap7types.S7Object
self.pointer = snap7.snap7types.S7Object(self.library.Par_Create(int(active))) | def create(self, active=False) | Creates a Partner and returns its handle, which is the reference that
you have to use every time you refer to that Partner.
:param active: 0
:returns: a pointer to the partner object | 7.671576 | 7.073243 | 1.084591 |
if self.library:
return self.library.Par_Destroy(ctypes.byref(self.pointer)) | def destroy(self) | Destroy a Partner of given handle.
Before destruction the Partner is stopped, all clients disconnected and
all shared memory blocks released. | 12.063819 | 11.48265 | 1.050613 |
error = ctypes.c_int32()
result = self.library.Par_GetLastError(self.pointer, ctypes.byref(error))
check_error(result, "partner")
return error | def get_last_error(self) | Returns the last job result. | 6.388121 | 5.763985 | 1.108282 |
logger.debug("retreiving param number %s" % number)
type_ = snap7.snap7types.param_types[number]
value = type_()
code = self.library.Par_GetParam(self.pointer, ctypes.c_int(number),
ctypes.byref(value))
check_error(code)
r... | def get_param(self, number) | Reads an internal Partner object parameter. | 5.887104 | 5.509097 | 1.068615 |
sent = ctypes.c_uint32()
recv = ctypes.c_uint32()
send_errors = ctypes.c_uint32()
recv_errors = ctypes.c_uint32()
result = self.library.Par_GetStats(self.pointer, ctypes.byref(sent),
ctypes.byref(recv),
... | def get_stats(self) | Returns some statistics.
:returns: a tuple containing bytes send, received, send errors, recv errors | 2.977477 | 2.769884 | 1.074946 |
status = ctypes.c_int32()
result = self.library.Par_GetStatus(self.pointer, ctypes.byref(status))
check_error(result, "partner")
return status | def get_status(self) | Returns the Partner status. | 6.760022 | 4.558339 | 1.483001 |
send_time = ctypes.c_int32()
recv_time = ctypes.c_int32()
result = self.library.Par_GetTimes(self.pointer, ctypes.byref(send_time),
ctypes.byref(recv_time))
check_error(result, "partner")
return send_time, recv_time | def get_times(self) | Returns the last send and recv jobs execution time in milliseconds. | 4.121496 | 3.471848 | 1.187119 |
assert re.match(ipv4, local_ip), '%s is invalid ipv4' % local_ip
assert re.match(ipv4, remote_ip), '%s is invalid ipv4' % remote_ip
logger.info("starting partnering from %s to %s" % (local_ip, remote_ip))
return self.library.Par_StartTo(self.pointer, local_ip, remote_ip,
... | def start_to(self, local_ip, remote_ip, local_tsap, remote_tsap) | Starts the Partner and binds it to the specified IP address and the
IsoTCP port.
:param local_ip: PC host IPV4 Address. "0.0.0.0" is the default adapter
:param remote_ip: PLC IPV4 Address
:param local_tsap: Local TSAP
:param remote_tsap: PLC TSAP | 3.002221 | 2.972703 | 1.00993 |
directions = session.block_directions()
if directions == 0:
return 0
readfds = [_socket] \
if (directions & LIBSSH2_SESSION_BLOCK_INBOUND) else ()
writefds = [_socket] \
if (directions & LIBSSH2_SESSION_BLOCK_OUTBOUND) else ()
return select(readfds, writefds, (), timeout... | def wait_socket(_socket, session, timeout=1) | Helper function for testing non-blocking mode.
This function blocks the calling thread for <timeout> seconds -
to be used only for testing purposes.
Also available at `ssh2.utils.wait_socket` | 4.759029 | 5.342892 | 0.890722 |
if not weights is None:
kwargs['weights'] = weights
partition = partition_type(graph,
initial_membership=initial_membership,
**kwargs)
optimiser = Optimiser()
if (not seed is None):
optimiser.set_rng_seed(seed)
optimiser.optimise_partition... | def find_partition(graph, partition_type, initial_membership=None, weights=None, n_iterations=2, seed=None, **kwargs) | Detect communities using the default settings.
This function detects communities given the specified method in the
``partition_type``. This should be type derived from
:class:`VertexPartition.MutableVertexPartition`, e.g.
:class:`ModularityVertexPartition` or :class:`CPMVertexPartition`. Optionally
an initia... | 3.455798 | 4.687882 | 0.737177 |
G_slices = _ig.Graph.Tree(len(graphs), 1, mode=_ig.TREE_UNDIRECTED)
G_slices.es[weight_attr] = interslice_weight
G_slices.vs[slice_attr] = graphs
return slices_to_layers(G_slices,
slice_attr,
vertex_id_attr,
edge_type_attr,
... | def time_slices_to_layers(graphs,
interslice_weight=1,
slice_attr='slice',
vertex_id_attr='id',
edge_type_attr='type',
weight_attr='weight') | Convert time slices to layer graphs.
Each graph is considered to represent a time slice. This function simply
connects all the consecutive slices (i.e. the slice graph) with an
``interslice_weight``. The further conversion is then delegated to
:func:`slices_to_layers`, which also provides further details.
... | 3.801911 | 4.610813 | 0.824564 |
new_partition = cls(partition.graph, partition.membership, **kwargs)
return new_partition | def FromPartition(cls, partition, **kwargs) | Create a new partition from an existing partition.
Parameters
----------
partition
The :class:`~VertexPartition.MutableVertexPartition` to replicate.
**kwargs
Any remaining keyword arguments will be passed on to the constructor of
the new partition.
Notes
-----
This may ... | 7.789579 | 8.772543 | 0.88795 |
_c_leiden._MutableVertexPartition_set_membership(self._partition, list(membership))
self._update_internal_membership() | def set_membership(self, membership) | Set membership. | 33.595726 | 31.08861 | 1.080644 |
return _c_leiden._MutableVertexPartition_diff_move(self._partition, v, new_comm) | def diff_move(self,v,new_comm) | Calculate the difference in the quality function if node ``v`` is
moved to community ``new_comm``.
Parameters
----------
v
The node to move.
new_comm
The community to move to.
Returns
-------
float
Difference in quality function.
Notes
-----
The differen... | 37.201668 | 24.962385 | 1.490309 |
partition_agg = self._FromCPartition(_c_leiden._MutableVertexPartition_aggregate_partition(self._partition))
if (not membership_partition is None):
membership = partition_agg.membership
for v in self.graph.vs:
membership[self.membership[v.index]] = membership_partition.membership[v.ind... | def aggregate_partition(self, membership_partition=None) | Aggregate the graph according to the current partition and provide a
default partition for it.
The aggregated graph can then be found as a parameter of the partition
``partition.graph``.
Notes
-----
This function contrasts to the function ``cluster_graph`` in igraph itself,
which also prov... | 6.719339 | 8.812041 | 0.762518 |
_c_leiden._MutableVertexPartition_move_node(self._partition, v, new_comm)
# Make sure this move is also reflected in the membership vector of the python object
self._membership[v] = new_comm
self._modularity_dirty = True | def move_node(self,v,new_comm) | Move node ``v`` to community ``new_comm``.
Parameters
----------
v
Node to move.
new_comm
Community to move to.
Examples
--------
>>> G = ig.Graph.Famous('Zachary')
>>> partition = la.ModularityVertexPartition(G)
>>> partition.move_node(0, 1) | 15.257352 | 15.005445 | 1.016788 |
# Read the coarser partition
_c_leiden._MutableVertexPartition_from_coarse_partition(self._partition,
partition.membership, coarse_node)
self._update_internal_membership() | def from_coarse_partition(self, partition, coarse_node=None) | Update current partition according to coarser partition.
Parameters
----------
partition : :class:`~VertexPartition.MutableVertexPartition`
The coarser partition used to update the current partition.
coarse_node : list of int
The coarser node which represent the current node in the partiti... | 17.354744 | 18.417509 | 0.942296 |
return _c_leiden._MutableVertexPartition_weight_to_comm(self._partition, v, comm) | def weight_to_comm(self, v, comm) | The total number of edges (or sum of weights) from node ``v`` to
community ``comm``.
See Also
--------
:func:`~VertexPartition.MutableVertexPartition.weight_from_comm` | 33.556988 | 22.289663 | 1.505495 |
return _c_leiden._MutableVertexPartition_weight_from_comm(self._partition, v, comm) | def weight_from_comm(self, v, comm) | The total number of edges (or sum of weights) to node ``v`` from
community ``comm``.
See Also
--------
:func:`~VertexPartition.MutableVertexPartition.weight_to_comm` | 32.930038 | 24.678999 | 1.334334 |
itr = 0
diff = 0
continue_iteration = itr < n_iterations or n_iterations < 0
while continue_iteration:
diff_inc = _c_leiden._Optimiser_optimise_partition(self._optimiser, partition._partition)
diff += diff_inc
itr += 1
if n_iterations < 0:
continue_iteration = (diff... | def optimise_partition(self, partition, n_iterations=2) | Optimise the given partition.
Parameters
----------
partition
The :class:`~VertexPartition.MutableVertexPartition` to optimise.
n_iterations : int
Number of iterations to run the Leiden algorithm. By default, 2 iterations
are run. If the number of iterations is negative, the Leiden a... | 5.392625 | 5.161186 | 1.044842 |
if not layer_weights:
layer_weights = [1]*len(partitions)
itr = 0
diff = 0
continue_iteration = itr < n_iterations or n_iterations < 0
while continue_iteration:
diff_inc = _c_leiden._Optimiser_optimise_partition_multiplex(
self._optimiser,
[partition._partition for ... | def optimise_partition_multiplex(self, partitions, layer_weights=None, n_iterations=2) | Optimise the given partitions simultaneously.
Parameters
----------
partitions
List of :class:`~VertexPartition.MutableVertexPartition` layers to optimise.
layer_weights
List of weights of layers.
n_iterations : int
Number of iterations to run the Leiden algorithm. By default, 2... | 4.070471 | 4.373457 | 0.930722 |
if (consider_comms is None):
consider_comms = self.consider_comms
diff = _c_leiden._Optimiser_move_nodes(self._optimiser, partition._partition, consider_comms)
partition._update_internal_membership()
return diff | def move_nodes(self, partition, consider_comms=None) | Move nodes to alternative communities for *optimising* the partition.
Parameters
----------
partition
The partition for which to move nodes.
consider_comms
If ``None`` uses :attr:`consider_comms`, but can be set to
something else.
Returns
-------
float
Improvement ... | 8.337783 | 9.514514 | 0.876323 |
if (consider_comms is None):
consider_comms = self.refine_consider_comms
diff = _c_leiden._Optimiser_move_nodes_constrained(self._optimiser, partition._partition, constrained_partition._partition, consider_comms)
partition._update_internal_membership()
return diff | def move_nodes_constrained(self, partition, constrained_partition, consider_comms=None) | Move nodes to alternative communities for *refining* the partition.
Parameters
----------
partition
The partition for which to move nodes.
constrained_partition
The partition within which we may move nodes.
consider_comms
If ``None`` uses :attr:`refine_consider_comms`, but can b... | 6.952215 | 6.85333 | 1.014429 |
if (consider_comms is None):
consider_comms = self.consider_comms
diff = _c_leiden._Optimiser_merge_nodes(self._optimiser, partition._partition, consider_comms)
partition._update_internal_membership()
return diff | def merge_nodes(self, partition, consider_comms=None) | Merge nodes for *optimising* the partition.
Parameters
----------
partition
The partition for which to merge nodes.
consider_comms
If ``None`` uses :attr:`consider_comms`, but can be set to
something else.
Returns
-------
float
Improvement in quality function.
... | 8.900633 | 9.576852 | 0.92939 |
if (consider_comms is None):
consider_comms = self.refine_consider_comms
diff = _c_leiden._Optimiser_merge_nodes_constrained(self._optimiser, partition._partition, constrained_partition._partition, consider_comms)
partition._update_internal_membership()
return diff | def merge_nodes_constrained(self, partition, constrained_partition, consider_comms=None) | Merge nodes for *refining* the partition.
Parameters
----------
partition
The partition for which to merge nodes.
constrained_partition
The partition within which we may merge nodes.
consider_comms
If ``None`` uses :attr:`refine_consider_comms`, but can be set
to something... | 7.172556 | 7.118969 | 1.007527 |
if dirname is not None and os.path.exists(dirname):
shutil.rmtree(dirname) | def cleanup_tmpdir(dirname) | Removes the given temporary directory if it exists. | 2.439484 | 2.288966 | 1.065758 |
path = os.path.join(*args)
if not os.path.isdir(path):
os.makedirs(path) | def create_dir_unless_exists(*args) | Creates a directory unless it exists already. | 2.351105 | 2.143333 | 1.096939 |
path = os.path.join(*args)
if os.path.isdir(path):
shutil.rmtree(path) | def ensure_dir_does_not_exist(*args) | Ensures that the given directory does not exist. | 2.403139 | 2.405171 | 0.999155 |
variants = ["lib{0}.a", "{0}.a", "{0}.lib", "lib{0}.lib"]
if is_unix_like():
extra_libdirs = ["/usr/local/lib64", "/usr/local/lib",
"/usr/lib64", "/usr/lib", "/lib64", "/lib"]
else:
extra_libdirs = []
for path in extra_libdirs:
if path not in library_path a... | def find_static_library(library_name, library_path) | Given the raw name of a library in `library_name`, tries to find a
static library with this name in the given `library_path`. `library_path`
is automatically extended with common library directories on Linux and Mac
OS X. | 2.333334 | 2.259191 | 1.032819 |
p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.stdin.close()
p.stderr.close()
line=p.stdout.readline().strip()
p.wait()
if type(line).__name__ == "bytes":
line = str(line, encoding="utf-8")
return line, p.returncode | def get_output(command) | Returns the output of a command returning a single line of output. | 2.588539 | 2.555802 | 1.012809 |
class HEADRequest(Request):
def get_method(self):
return "HEAD"
try:
response = urlopen(HEADRequest(url))
return True
except URLError:
return False | def http_url_exists(url) | Returns whether the given HTTP URL 'exists' in the sense that it is returning
an HTTP error code or not. A URL is considered to exist if it does not return
an HTTP error code. | 2.92593 | 3.615318 | 0.809315 |
platform = platform or sys.platform
platform = platform.lower()
return platform.startswith("linux") or platform.startswith("darwin") or \
platform.startswith("cygwin") | def is_unix_like(platform=None) | Returns whether the given platform is a Unix-like platform with the usual
Unix filesystem. When the parameter is omitted, it defaults to ``sys.platform`` | 2.953384 | 2.986538 | 0.988899 |
global LIBIGRAPH_FALLBACK_INCLUDE_DIRS
global LIBIGRAPH_FALLBACK_LIBRARY_DIRS
global LIBIGRAPH_FALLBACK_LIBRARIES
if os.name == 'nt' and distutils.ccompiler.get_default_compiler() == 'msvc':
# if this setup is run in the source checkout *and* the igraph msvc was build,
# this c... | def preprocess_fallback_config() | Preprocesses the fallback include and library paths depending on the
platform. | 2.939641 | 2.89541 | 1.015276 |
result = [version]
# Add trailing ".0" as needed to ensure that we have at least
# major.minor.patch
parts = version.split(".")
while len(parts) < 3:
parts.append("0")
result.append(".".join(parts))
return result | def version_variants(version) | Given an igraph version number, returns a list of possible version
number variants to try when looking for a suitable nightly build of the
C core to download from igraph.org. | 4.948467 | 5.20105 | 0.951436 |
if self._tmpdir is None:
self._tmpdir = tempfile.mkdtemp(prefix="igraph.")
atexit.register(cleanup_tmpdir, self._tmpdir)
return self._tmpdir | def tmpdir(self) | The temporary directory in which igraph is downloaded and extracted. | 3.364722 | 2.471976 | 1.361147 |
def _progress_hook(count, block_size, total_size):
if total_size < 0:
sys.stdout.write("\rDownloading %s... please wait." % local_file)
else:
percentage = count * block_size * 100.0 / total_size
percentage = min(percentage, 100.0)... | def download_and_compile(self) | Downloads and compiles the C core of igraph. | 2.718544 | 2.638881 | 1.030188 |
for version in self.versions_to_try:
remote_url = self.get_download_url(version=version)
if http_url_exists(remote_url):
return version, remote_url
return None, None | def find_first_version(self) | Finds the first version of igraph that exists in the nightly build
repo from the version numbers provided in ``self.versions_to_try``. | 4.320722 | 3.428013 | 1.260416 |
if self._has_pkgconfig is None:
if self.use_pkgconfig:
line, exit_code = get_output("pkg-config igraph")
self._has_pkgconfig = (exit_code == 0)
else:
self._has_pkgconfig = False
return self._has_pkgconfig | def has_pkgconfig(self) | Returns whether ``pkg-config`` is available on the current system
and it knows about igraph or not. | 3.208175 | 2.628871 | 1.220362 |
ext.include_dirs += self.include_dirs
ext.library_dirs += self.library_dirs
ext.libraries += self.libraries
ext.extra_compile_args += self.extra_compile_args
ext.extra_link_args += self.extra_link_args
ext.extra_objects += self.extra_objects | def configure(self, ext) | Configures the given Extension object using this build configuration. | 1.639977 | 1.560137 | 1.051175 |
if not buildcfg.has_pkgconfig:
print("Cannot find the C core of igraph on this system using pkg-config.")
return False
cmd = "pkg-config igraph --cflags --libs"
if self.static_extension:
cmd += " --static"
line, exit_code = get_output(cmd)
... | def detect_from_pkgconfig(self) | Detects the igraph include directory, library directory and the
list of libraries to link to using ``pkg-config``. | 3.480415 | 3.391077 | 1.026345 |
print("We will now try to download and compile the C core from scratch.")
print("Version number of the C core: %s" % self.c_core_versions[0])
if len(self.c_core_versions) > 1:
print("We will also try: %s" % ", ".join(self.c_core_versions[1:]))
print("")
igra... | def download_and_compile_igraph(self) | Downloads and compiles the C core of igraph. | 3.905708 | 3.492857 | 1.118199 |
if self.static_extension:
build_type = "static extension"
else:
build_type = "dynamic extension"
print("Build type: %s" % build_type)
print("Include path: %s" % " ".join(self.include_dirs))
print("Library path: %s" % " ".join(self.library_dirs))
... | def print_build_info(self) | Prints the include and library path being used for debugging purposes. | 1.973156 | 1.885847 | 1.046297 |
# Yes, this is ugly, but we don't want to interfere with setup.py's own
# option handling
opts_to_remove = []
for idx, option in enumerate(sys.argv):
if not option.startswith("--"):
continue
if option == "--static":
opts_to... | def process_args_from_command_line(self) | Preprocesses the command line options before they are passed to
setup.py and sets up the build configuration. | 2.226313 | 2.178824 | 1.021796 |
if "stdc++" not in self.libraries:
self.libraries.append("stdc++")
if exclusions is None:
exclusions = []
for library_name in set(self.libraries) - set(exclusions):
static_lib = find_static_library(library_name, self.library_dirs)
if sta... | def replace_static_libraries(self, exclusions=None) | Replaces references to libraries with full paths to their static
versions if the static version is to be found on the library path. | 2.356017 | 2.384603 | 0.988012 |
buildcfg.include_dirs = [os.path.join("igraphcore", "include")]
buildcfg.library_dirs = [os.path.join("igraphcore", "lib")]
buildcfg.static_extension = True
buildcfg_file = os.path.join("igraphcore", "build.cfg")
if os.path.exists(buildcfg_file):
buildcfg.li... | def use_built_igraph(self) | Assumes that igraph is built already in ``igraphcore`` and sets up
the include and library paths and the library names accordingly. | 3.586426 | 3.002829 | 1.194349 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.