INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
Adds the unlock command arguments to the parser.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None`` | def add_arguments(self, parser):
"""Adds the unlock command arguments to the parser.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None``
"""
parser.add_argument('name', nargs=1, choices=['kinetis'],
help='name of MCU to unlock')
return self.add_common_arguments(parser, True) |
Unlocks the target device.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | def run(self, args):
"""Unlocks the target device.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
mcu = args.name[0].lower()
if pylink.unlock(jlink, mcu):
print('Successfully unlocked device!')
else:
print('Failed to unlock device!') |
Runs the license command.
Args:
self (LicenseCommand): the ``LicenseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | def run(self, args):
"""Runs the license command.
Args:
self (LicenseCommand): the ``LicenseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.list:
print('Built-in Licenses: %s' % ', '.join(jlink.licenses.split(',')))
print('Custom Licenses: %s' % ', '.join(jlink.custom_licenses.split(',')))
elif args.add is not None:
if jlink.add_license(args.add):
print('Successfully added license.')
else:
print('License already exists.')
elif args.erase:
if jlink.erase_licenses():
print('Successfully erased all custom licenses.')
else:
print('Failed to erase custom licenses.') |
Adds the information commands to the parser.
Args:
self (InfoCommand): the ``InfoCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None`` | def add_arguments(self, parser):
"""Adds the information commands to the parser.
Args:
self (InfoCommand): the ``InfoCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None``
"""
parser.add_argument('-p', '--product', action='store_true',
help='print the production information')
parser.add_argument('-j', '--jtag', action='store_true',
help='print the JTAG pin status')
return self.add_common_arguments(parser, False) |
Runs the information command.
Args:
self (InfoCommand): the ``InfoCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | def run(self, args):
"""Runs the information command.
Args:
self (InfoCommand): the ``InfoCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.product:
print('Product: %s' % jlink.product_name)
manufacturer = 'SEGGER' if jlink.oem is None else jlink.oem
print('Manufacturer: %s' % manufacturer)
print('Hardware Version: %s' % jlink.hardware_version)
print('Firmware: %s' % jlink.firmware_version)
print('DLL Version: %s' % jlink.version)
print('Features: %s' % ', '.join(jlink.features))
elif args.jtag:
status = jlink.hardware_status
print('TCK Pin Status: %d' % status.tck)
print('TDI Pin Status: %d' % status.tdi)
print('TDO Pin Status: %d' % status.tdo)
print('TMS Pin Status: %d' % status.tms)
print('TRES Pin Status: %d' % status.tres)
print('TRST Pin Status: %d' % status.trst) |
Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` | def add_arguments(self, parser):
"""Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-l', '--list', nargs='?',
type=str.lower, default='_',
choices=['usb', 'ip'],
help='list all the connected emulators')
group.add_argument('-s', '--supported', nargs=1,
help='query whether a device is supported')
group.add_argument('-t', '--test', action='store_true',
help='perform a self-test')
return None |
Runs the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
args (Namespace): arguments to parse
Returns:
``None`` | def run(self, args):
"""Runs the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = pylink.JLink()
if args.test:
if jlink.test():
print('Self-test succeeded.')
else:
print('Self-test failed.')
elif args.list is None or args.list in ['usb', 'ip']:
host = pylink.JLinkHost.USB_OR_IP
if args.list == 'usb':
host = pylink.JLinkHost.USB
elif args.list == 'ip':
host = pylink.JLinkHost.IP
emulators = jlink.connected_emulators(host)
for (index, emulator) in enumerate(emulators):
if index > 0:
print('')
print('Product Name: %s' % emulator.acProduct.decode())
print('Serial Number: %s' % emulator.SerialNumber)
usb = bool(emulator.Connection)
if not usb:
print('Nickname: %s' % emulator.acNickname.decode())
print('Firmware: %s' % emulator.acFWString.decode())
print('Connection: %s' % ('USB' if usb else 'IP'))
if not usb:
print('IP Address: %s' % emulator.aIPAddr)
elif args.supported is not None:
device = args.supported[0]
num_supported_devices = jlink.num_supported_devices()
for i in range(num_supported_devices):
found_device = jlink.supported_device(i)
if device.lower() == found_device.name.lower():
print('Device Name: %s' % device)
print('Core ID: %s' % found_device.CoreId)
print('Flash Address: %s' % found_device.FlashAddr)
print('Flash Size: %s bytes' % found_device.FlashSize)
print('RAM Address: %s' % found_device.RAMAddr)
print('RAM Size: %s bytes' % found_device.RAMSize)
print('Manufacturer: %s' % found_device.manufacturer)
break
else:
print('%s is not supported :(' % device)
return None |
Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` | def add_arguments(self, parser):
"""Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-d', '--downgrade', action='store_true',
help='downgrade the J-Link firmware')
group.add_argument('-u', '--upgrade', action='store_true',
help='upgrade the J-Link firmware')
return self.add_common_arguments(parser, False) |
Runs the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse
Returns:
``None`` | def run(self, args):
"""Runs the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.downgrade:
if not jlink.firmware_newer():
print('DLL firmware is not older than J-Link firmware.')
else:
jlink.invalidate_firmware()
try:
# Change to the firmware of the connected DLL.
jlink.update_firmware()
except pylink.JLinkException as e:
# On J-Link versions < 5.0.0, an exception will be thrown as
# the connection will be lost, so we have to re-establish.
jlink = self.create_jlink(args)
print('Firmware Downgraded: %s' % jlink.firmware_version)
elif args.upgrade:
if not jlink.firmware_outdated():
print('DLL firmware is not newer than J-Link firmware.')
else:
try:
# Upgrade the firmware.
jlink.update_firmware()
except pylink.JLinkException as e:
# On J-Link versions < 5.0.0, an exception will be thrown as
# the connection will be lost, so we have to re-establish.
jlink = self.create_jlink(args)
print('Firmware Updated: %s' % jlink.firmware_version)
return None |
Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name. | def name(self):
"""Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name.
"""
return ctypes.cast(self.sName, ctypes.c_char_p).value.decode() |
Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name. | def manufacturer(self):
"""Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name.
"""
buf = ctypes.cast(self.sManu, ctypes.c_char_p).value
return buf.decode() if buf else None |
Returns whether this is a software breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a software breakpoint, otherwise
``False``. | def software_breakpoint(self):
"""Returns whether this is a software breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a software breakpoint, otherwise
``False``.
"""
software_types = [
enums.JLinkBreakpoint.SW_RAM,
enums.JLinkBreakpoint.SW_FLASH,
enums.JLinkBreakpoint.SW
]
return any(self.Type & stype for stype in software_types) |
Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\\Program Files\\SEGGER\\JLink``
- ``C:\\Program Files (x86)\\SEGGER\\JLink``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found. | def find_library_windows(cls):
"""Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\\Program Files\\SEGGER\\JLink``
- ``C:\\Program Files (x86)\\SEGGER\\JLink``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found.
"""
dll = cls.get_appropriate_windows_sdk_name() + '.dll'
root = 'C:\\'
for d in os.listdir(root):
dir_path = os.path.join(root, d)
# Have to account for the different Program Files directories.
if d.startswith('Program Files') and os.path.isdir(dir_path):
dir_path = os.path.join(dir_path, 'SEGGER')
if not os.path.isdir(dir_path):
continue
# Find all the versioned J-Link directories.
ds = filter(lambda x: x.startswith('JLink'), os.listdir(dir_path))
for jlink_dir in ds:
# The DLL always has the same name, so if it is found, just
# return it.
lib_path = os.path.join(dir_path, jlink_dir, dll)
if os.path.isfile(lib_path):
yield lib_path |
Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found. | def find_library_linux(cls):
"""Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found.
"""
dll = Library.JLINK_SDK_NAME
root = os.path.join('/', 'opt', 'SEGGER')
for (directory_name, subdirs, files) in os.walk(root):
fnames = []
x86_found = False
for f in files:
path = os.path.join(directory_name, f)
if os.path.isfile(path) and f.startswith(dll):
fnames.append(f)
if '_x86' in path:
x86_found = True
for fname in fnames:
fpath = os.path.join(directory_name, fname)
if util.is_os_64bit():
if '_x86' not in fname:
yield fpath
elif x86_found:
if '_x86' in fname:
yield fpath
else:
yield fpath |
Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in one of three ways dependent on which
which version of the SEGGER tools are installed:
======== ============================================================
Versions Directory
======== ============================================================
< 5.0.0 ``/Applications/SEGGER/JLink\\ NUMBER``
< 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib``
>= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm``
======== ============================================================
Args:
cls (Library): the ``Library`` class
Returns:
The path to the J-Link library files in the order they are found. | def find_library_darwin(cls):
"""Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in one of three ways dependent on which
which version of the SEGGER tools are installed:
======== ============================================================
Versions Directory
======== ============================================================
< 5.0.0 ``/Applications/SEGGER/JLink\\ NUMBER``
< 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib``
>= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm``
======== ============================================================
Args:
cls (Library): the ``Library`` class
Returns:
The path to the J-Link library files in the order they are found.
"""
dll = Library.JLINK_SDK_NAME
root = os.path.join('/', 'Applications', 'SEGGER')
if not os.path.isdir(root):
return
for d in os.listdir(root):
dir_path = os.path.join(root, d)
# Navigate through each JLink directory.
if os.path.isdir(dir_path) and d.startswith('JLink'):
files = list(f for f in os.listdir(dir_path) if
os.path.isfile(os.path.join(dir_path, f)))
# For versions >= 6.0.0 and < 5.0.0, this file will exist, so
# we want to use this one instead of the versioned one.
if (dll + '.dylib') in files:
yield os.path.join(dir_path, dll + '.dylib')
# For versions >= 5.0.0 and < 6.0.0, there is no strictly
# linked library file, so try and find the versioned one.
for f in files:
if f.startswith(dll):
yield os.path.join(dir_path, f) |
Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was loaded, otherwise ``False``. | def load_default(self):
"""Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was loaded, otherwise ``False``.
"""
path = ctypes_util.find_library(self._sdk)
if path is None:
# Couldn't find it the standard way. Fallback to the non-standard
# way of finding the J-Link library. These methods are operating
# system specific.
if self._windows or self._cygwin:
path = next(self.find_library_windows(), None)
elif sys.platform.startswith('linux'):
path = next(self.find_library_linux(), None)
elif sys.platform.startswith('darwin'):
path = next(self.find_library_darwin(), None)
if path is not None:
return self.load(path)
return False |
Loads the specified DLL, if any, otherwise re-loads the current DLL.
If ``path`` is specified, loads the DLL at the given ``path``,
otherwise re-loads the DLL currently specified by this library.
Note:
This creates a temporary DLL file to use for the instance. This is
necessary to work around a limitation of the J-Link DLL in which
multiple J-Links cannot be accessed from the same process.
Args:
self (Library): the ``Library`` instance
path (path): path to the DLL to load
Returns:
``True`` if library was loaded successfully.
Raises:
OSError: if there is no J-LINK SDK DLL present at the path.
See Also:
`J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_. | def load(self, path=None):
"""Loads the specified DLL, if any, otherwise re-loads the current DLL.
If ``path`` is specified, loads the DLL at the given ``path``,
otherwise re-loads the DLL currently specified by this library.
Note:
This creates a temporary DLL file to use for the instance. This is
necessary to work around a limitation of the J-Link DLL in which
multiple J-Links cannot be accessed from the same process.
Args:
self (Library): the ``Library`` instance
path (path): path to the DLL to load
Returns:
``True`` if library was loaded successfully.
Raises:
OSError: if there is no J-LINK SDK DLL present at the path.
See Also:
`J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_.
"""
self.unload()
self._path = path or self._path
# Windows requires a proper suffix in order to load the library file,
# so it must be set here.
if self._windows or self._cygwin:
suffix = '.dll'
elif sys.platform.startswith('darwin'):
suffix = '.dylib'
else:
suffix = '.so'
# Copy the J-Link DLL to a temporary file. This will be cleaned up the
# next time we load a DLL using this library or if this library is
# cleaned up.
tf = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
with open(tf.name, 'wb') as outputfile:
with open(self._path, 'rb') as inputfile:
outputfile.write(inputfile.read())
# This is needed to work around a WindowsError where the file is not
# being properly cleaned up after exiting the with statement.
tf.close()
self._temp = tf
self._lib = ctypes.cdll.LoadLibrary(tf.name)
if self._windows:
# The J-Link library uses a mix of __cdecl and __stdcall function
# calls. While this is fine on a nix platform or in cygwin, this
# causes issues with Windows, where it expects the __stdcall
# methods to follow the standard calling convention. As a result,
# we have to convert them to windows function calls.
self._winlib = ctypes.windll.LoadLibrary(tf.name)
for stdcall in self._standard_calls_:
if hasattr(self._winlib, stdcall):
# Backwards compatibility. Some methods do not exist on
# older versions of the J-Link firmware, so ignore them in
# these cases.
setattr(self._lib, stdcall, getattr(self._winlib, stdcall))
return True |
Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, otherwise ``False``. | def unload(self):
"""Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, otherwise ``False``.
"""
unloaded = False
if self._lib is not None:
if self._winlib is not None:
# ctypes passes integers as 32-bit C integer types, which will
# truncate the value of a 64-bit pointer in 64-bit python, so
# we have to change the FreeLibrary method to take a pointer
# instead of an integer handle.
ctypes.windll.kernel32.FreeLibrary.argtypes = (
ctypes.c_void_p,
)
# On Windows we must free both loaded libraries before the
# temporary file can be cleaned up.
ctypes.windll.kernel32.FreeLibrary(self._lib._handle)
ctypes.windll.kernel32.FreeLibrary(self._winlib._handle)
self._lib = None
self._winlib = None
unloaded = True
else:
# On OSX and Linux, just release the library; it's not safe
# to close a dll that ctypes is using.
del self._lib
self._lib = None
unloaded = True
if self._temp is not None:
os.remove(self._temp.name)
self._temp = None
return unloaded |
Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults to ``None``.
mode (str): The mode that should be used to open the file.
Yields:
A file handle. | def _open(filename=None, mode='r'):
"""Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults to ``None``.
mode (str): The mode that should be used to open the file.
Yields:
A file handle.
"""
if not filename or filename == '-':
if not mode or 'r' in mode:
file = sys.stdin
elif 'w' in mode:
file = sys.stdout
else:
raise ValueError('Invalid mode for file: {}'.format(mode))
else:
file = open(filename, mode)
try:
yield file
finally:
if file not in (sys.stdin, sys.stdout):
file.close() |
Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names. | def get_pkg_names(pkgs):
"""Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names.
"""
result = set()
with open(join("mapping"), "r") as f:
data = dict(x.strip().split(":") for x in f)
for pkg in pkgs:
# Look up the mapped requirement. If a mapping isn't found,
# simply use the package name.
result.add(data.get(pkg, pkg))
# Return a sorted list for backward compatibility.
return sorted(result, key=lambda s: s.lower()) |
Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when accessing a given font set
ttf_filename: str
Ttf font filename
charmap_filename: str
Character map filename
directory: str or None, optional
Directory for font and charmap files
Example
-------
The spyder ide uses qtawesome and uses a custom font for spyder-specific
icons::
qta.load_font('spyder', 'spyder.ttf', 'spyder-charmap.json') | def load_font(prefix, ttf_filename, charmap_filename, directory=None):
"""
Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when accessing a given font set
ttf_filename: str
Ttf font filename
charmap_filename: str
Character map filename
directory: str or None, optional
Directory for font and charmap files
Example
-------
The spyder ide uses qtawesome and uses a custom font for spyder-specific
icons::
qta.load_font('spyder', 'spyder.ttf', 'spyder-charmap.json')
"""
return _instance().load_font(prefix, ttf_filename, charmap_filename, directory) |
Return the character map used for a given font.
Returns
-------
return_value: dict
The dictionary mapping the icon names to the corresponding unicode character. | def charmap(prefixed_name):
"""
Return the character map used for a given font.
Returns
-------
return_value: dict
The dictionary mapping the icon names to the corresponding unicode character.
"""
prefix, name = prefixed_name.split('.')
return _instance().charmap[prefix][name] |
Set global defaults for the options passed to the icon painter. | def set_global_defaults(**kwargs):
"""Set global defaults for the options passed to the icon painter."""
valid_options = [
'active', 'selected', 'disabled', 'on', 'off',
'on_active', 'on_selected', 'on_disabled',
'off_active', 'off_selected', 'off_disabled',
'color', 'color_on', 'color_off',
'color_active', 'color_selected', 'color_disabled',
'color_on_selected', 'color_on_active', 'color_on_disabled',
'color_off_selected', 'color_off_active', 'color_off_disabled',
'animation', 'offset', 'scale_factor',
]
for kw in kwargs:
if kw in valid_options:
_default_options[kw] = kwargs[kw]
else:
error = "Invalid option '{0}'".format(kw)
raise KeyError(error) |
Main paint method. | def paint(self, iconic, painter, rect, mode, state, options):
"""Main paint method."""
for opt in options:
self._paint_icon(iconic, painter, rect, mode, state, opt) |
Paint a single icon. | def _paint_icon(self, iconic, painter, rect, mode, state, options):
"""Paint a single icon."""
painter.save()
color = options['color']
char = options['char']
color_options = {
QIcon.On: {
QIcon.Normal: (options['color_on'], options['on']),
QIcon.Disabled: (options['color_on_disabled'],
options['on_disabled']),
QIcon.Active: (options['color_on_active'],
options['on_active']),
QIcon.Selected: (options['color_on_selected'],
options['on_selected'])
},
QIcon.Off: {
QIcon.Normal: (options['color_off'], options['off']),
QIcon.Disabled: (options['color_off_disabled'],
options['off_disabled']),
QIcon.Active: (options['color_off_active'],
options['off_active']),
QIcon.Selected: (options['color_off_selected'],
options['off_selected'])
}
}
color, char = color_options[state][mode]
painter.setPen(QColor(color))
# A 16 pixel-high icon yields a font size of 14, which is pixel perfect
# for font-awesome. 16 * 0.875 = 14
# The reason why the glyph size is smaller than the icon size is to
# account for font bearing.
draw_size = 0.875 * round(rect.height() * options['scale_factor'])
prefix = options['prefix']
# Animation setup hook
animation = options.get('animation')
if animation is not None:
animation.setup(self, painter, rect)
painter.setFont(iconic.font(prefix, draw_size))
if 'offset' in options:
rect = QRect(rect)
rect.translate(options['offset'][0] * rect.width(),
options['offset'][1] * rect.height())
painter.setOpacity(options.get('opacity', 1.0))
painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char)
painter.restore() |
Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when accessing a given font set
ttf_filename: str
Ttf font filename
charmap_filename: str
Charmap filename
directory: str or None, optional
Directory for font and charmap files | def load_font(self, prefix, ttf_filename, charmap_filename, directory=None):
"""Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when accessing a given font set
ttf_filename: str
Ttf font filename
charmap_filename: str
Charmap filename
directory: str or None, optional
Directory for font and charmap files
"""
def hook(obj):
result = {}
for key in obj:
result[key] = unichr(int(obj[key], 16))
return result
if directory is None:
directory = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'fonts')
# Load font
if QApplication.instance() is not None:
id_ = QFontDatabase.addApplicationFont(os.path.join(directory,
ttf_filename))
loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)
if(loadedFontFamilies):
self.fontname[prefix] = loadedFontFamilies[0]
else:
raise FontError(u"Font at '{0}' appears to be empty. "
"If you are on Windows 10, please read "
"https://support.microsoft.com/"
"en-us/kb/3053676 "
"to know how to prevent Windows from blocking "
"the fonts that come with QtAwesome.".format(
os.path.join(directory, ttf_filename)))
with open(os.path.join(directory, charmap_filename), 'r') as codes:
self.charmap[prefix] = json.load(codes, object_hook=hook)
# Verify that vendorized fonts are not corrupt
if not SYSTEM_FONTS:
ttf_hash = MD5_HASHES.get(ttf_filename, None)
if ttf_hash is not None:
hasher = hashlib.md5()
with open(os.path.join(directory, ttf_filename),
'rb') as f:
content = f.read()
hasher.update(content)
ttf_calculated_hash_code = hasher.hexdigest()
if ttf_calculated_hash_code != ttf_hash:
raise FontError(u"Font is corrupt at: '{0}'".format(
os.path.join(directory, ttf_filename))) |
Return a QIcon object corresponding to the provided icon name. | def icon(self, *names, **kwargs):
"""Return a QIcon object corresponding to the provided icon name."""
cache_key = '{}{}'.format(names,kwargs)
if cache_key not in self.icon_cache:
options_list = kwargs.pop('options', [{}] * len(names))
general_options = kwargs
if len(options_list) != len(names):
error = '"options" must be a list of size {0}'.format(len(names))
raise Exception(error)
if QApplication.instance() is not None:
parsed_options = []
for i in range(len(options_list)):
specific_options = options_list[i]
parsed_options.append(self._parse_options(specific_options,
general_options,
names[i]))
# Process high level API
api_options = parsed_options
self.icon_cache[cache_key] = self._icon_by_painter(self.painter, api_options)
else:
warnings.warn("You need to have a running "
"QApplication to use QtAwesome!")
return QIcon()
return self.icon_cache[cache_key] |
Return a QFont corresponding to the given prefix and size. | def font(self, prefix, size):
"""Return a QFont corresponding to the given prefix and size."""
font = QFont(self.fontname[prefix])
font.setPixelSize(size)
if prefix[-1] == 's': # solid style
font.setStyleName('Solid')
return font |
Return the custom icon corresponding to the given name. | def _custom_icon(self, name, **kwargs):
"""Return the custom icon corresponding to the given name."""
options = dict(_default_options, **kwargs)
if name in self.painters:
painter = self.painters[name]
return self._icon_by_painter(painter, options)
else:
return QIcon() |
Return the icon corresponding to the given painter. | def _icon_by_painter(self, painter, options):
"""Return the icon corresponding to the given painter."""
engine = CharIconEngine(self, painter, options)
return QIcon(engine) |
Font renaming code originally from:
https://github.com/chrissimpkins/fontname.py/blob/master/fontname.py | def rename_font(font_path, font_name):
"""
Font renaming code originally from:
https://github.com/chrissimpkins/fontname.py/blob/master/fontname.py
"""
tt = ttLib.TTFont(font_path)
namerecord_list = tt["name"].names
variant = ""
# determine font variant for this file path from name record nameID 2
for record in namerecord_list:
if record.nameID == 2:
variant = (
record.toUnicode()
) # cast to str type in Py 3, unicode type in Py 2
break
# test that a variant name was found in the OpenType tables of the font
if len(variant) == 0:
raise ValueError(
"Unable to detect the font variant from the OpenType name table in: %s" % font_path)
# used for the Postscript name in the name table (no spaces allowed)
postscript_font_name = font_name.replace(" ", "")
# font family name
nameID1_string = font_name
# full font name
nameID4_string = font_name + " " + variant
# Postscript name
# - no spaces allowed in family name or the PostScript suffix. should be dash delimited
nameID6_string = postscript_font_name + "-" + variant.replace(" ", "")
# modify the opentype table data in memory with updated values
for record in namerecord_list:
if record.nameID == 1:
record.string = nameID1_string
elif record.nameID == 4:
record.string = nameID4_string
elif record.nameID == 6:
record.string = nameID6_string
# write changes to the font file
try:
tt.save(font_path)
except:
raise RuntimeError(
"ERROR: unable to write new name to OpenType tables for: %s" % font_path) |
Validate the command options. | def finalize_options(self):
"""Validate the command options."""
assert bool(self.fa_version), 'FA version is mandatory for this command.'
if self.zip_path:
assert os.path.exists(self.zip_path), (
'Local zipfile does not exist: %s' % self.zip_path) |
Shortcut for printing with the distutils logger. | def __print(self, msg):
"""Shortcut for printing with the distutils logger."""
self.announce(msg, level=distutils.log.INFO) |
Get a file object of the FA zip file. | def __zip_file(self):
"""Get a file object of the FA zip file."""
if self.zip_path:
# If using a local file, just open it:
self.__print('Opening local zipfile: %s' % self.zip_path)
return open(self.zip_path, 'rb')
# Otherwise, download it and make a file object in-memory:
url = self.__release_url
self.__print('Downloading from URL: %s' % url)
response = urlopen(url)
return io.BytesIO(response.read()) |
Get a dict of all files of interest from the FA release zipfile. | def __zipped_files_data(self):
"""Get a dict of all files of interest from the FA release zipfile."""
files = {}
with zipfile.ZipFile(self.__zip_file) as thezip:
for zipinfo in thezip.infolist():
if zipinfo.filename.endswith('metadata/icons.json'):
with thezip.open(zipinfo) as compressed_file:
files['icons.json'] = compressed_file.read()
elif zipinfo.filename.endswith('.ttf'):
# For the record, the paths usually look like this:
# webfonts/fa-brands-400.ttf
# webfonts/fa-regular-400.ttf
# webfonts/fa-solid-900.ttf
name = os.path.basename(zipinfo.filename)
tokens = name.split('-')
style = tokens[1]
if style in self.FA_STYLES:
with thezip.open(zipinfo) as compressed_file:
files[style] = compressed_file.read()
# Safety checks:
assert all(style in files for style in self.FA_STYLES), \
'Not all FA styles found! Update code is broken.'
assert 'icons.json' in files, 'icons.json not found! Update code is broken.'
return files |
Run command. | def run(self):
"""Run command."""
files = self.__zipped_files_data
hashes = {}
icons = {}
# Read icons.json (from the webfont zip download)
data = json.loads(files['icons.json'])
# Group icons by style, since not all icons exist for all styles:
for icon, info in data.iteritems():
for style in info['styles']:
icons.setdefault(str(style), {})
icons[str(style)][icon] = str(info['unicode'])
# For every FA "style":
for style, details in icons.iteritems():
# Dump a .json charmap file:
charmapPath = self.__get_charmap_path(style)
self.__print('Dumping updated "%s" charmap: %s' % (style, charmapPath))
with open(charmapPath, 'w+') as f:
json.dump(details, f, indent=4, sort_keys=True)
# Dump a .ttf font file:
font_path = self.__get_ttf_path(style)
data = files[style]
self.__print('Dumping updated "%s" font: %s' % (style, font_path))
with open(font_path, 'w+') as f:
f.write(data)
# Fix to prevent repeated font names:
if style in ('regular', 'solid'):
new_name = str("Font Awesome 5 Free %s") % style.title()
self.__print('Renaming font to "%s" in: %s' % (new_name, font_path))
if ttLib is not None:
rename_font(font_path, new_name)
else:
sys.exit(
"This special command requires the module 'fonttools': "
"https://github.com/fonttools/fonttools/")
# Reread the data since we just edited the font file:
with open(font_path, 'rb') as f:
data = f.read()
files[style] = data
# Store hashes for later:
hashes[style] = hashlib.md5(data).hexdigest()
# Now it's time to patch "iconic_font.py":
iconic_path = self.ICONIC_FONT_PY_PATH
self.__print('Patching new MD5 hashes in: %s' % iconic_path)
with open(iconic_path, 'r') as iconic_file:
contents = iconic_file.read()
# We read it in full, then use regex substitution:
for style, md5 in hashes.iteritems():
self.__print('New "%s" hash is: %s' % (style, md5))
regex = r"('fontawesome5-%s-webfont.ttf':\s+)'(\w+)'" % style
subst = r"\g<1>'" + md5 + "'"
contents = re.sub(regex, subst, contents, 1)
# and finally overwrite with the modified file:
self.__print('Dumping updated file: %s' % iconic_path)
with open(iconic_path, 'w') as iconic_file:
iconic_file.write(contents)
self.__print(
'\nFinished!\n'
'Please check the git diff to make sure everything went okay.\n'
'You should also edit README.md and '
'qtawesome/docs/source/usage.rst to reflect the changes.') |
Traverse a path ($PATH by default) to find the protoc compiler | def find_protoc(path=os.environ['PATH']):
'''
Traverse a path ($PATH by default) to find the protoc compiler
'''
protoc_filename = 'protoc'
bin_search_paths = path.split(':') or []
for search_path in bin_search_paths:
bin_path = os.path.join(search_path, protoc_filename)
if os.path.isfile(bin_path) and os.access(bin_path, os.X_OK):
return bin_path
raise ProtocNotFound("Protobuf compiler not found") |
Produce a Protobuf module from a string description.
Return the module if successfully compiled, otherwise raise a BadProtobuf
exception. | def from_string(proto_str):
'''
Produce a Protobuf module from a string description.
Return the module if successfully compiled, otherwise raise a BadProtobuf
exception.
'''
_, proto_file = tempfile.mkstemp(suffix='.proto')
with open(proto_file, 'w+') as proto_f:
proto_f.write(proto_str)
return from_file(proto_file) |
Helper to load a Python file at path and return as a module | def _load_module(path):
'Helper to load a Python file at path and return as a module'
module_name = os.path.splitext(os.path.basename(path))[0]
module = None
if sys.version_info.minor < 5:
loader = importlib.machinery.SourceFileLoader(module_name, path)
module = loader.load_module()
else:
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module |
Helper to compile protobuf files | def _compile_proto(full_path, dest):
'Helper to compile protobuf files'
proto_path = os.path.dirname(full_path)
protoc_args = [find_protoc(),
'--python_out={}'.format(dest),
'--proto_path={}'.format(proto_path),
full_path]
proc = subprocess.Popen(protoc_args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
outs, errs = proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
return False
if proc.returncode != 0:
msg = 'Failed compiling "{}": \n\nstderr: {}\nstdout: {}'.format(
full_path, errs.decode('utf-8'), outs.decode('utf-8'))
raise BadProtobuf(msg)
return True |
Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception. | def from_file(proto_file):
'''
Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception.
'''
if not proto_file.endswith('.proto'):
raise BadProtobuf()
dest = tempfile.mkdtemp()
full_path = os.path.abspath(proto_file)
_compile_proto(full_path, dest)
filename = os.path.split(full_path)[-1]
name = re.search(r'^(.*)\.proto$', filename).group(1)
target = os.path.join(dest, name+'_pb2.py')
return _load_module(target) |
Return protobuf class types from an imported generated module. | def types_from_module(pb_module):
'''
Return protobuf class types from an imported generated module.
'''
types = pb_module.DESCRIPTOR.message_types_by_name
return [getattr(pb_module, name) for name in types] |
Commit an arbitrary (picklable) object to the log | def log(self, obj):
'''
Commit an arbitrary (picklable) object to the log
'''
entries = self.get()
entries.append(obj)
# Only log the last |n| entries if set
if self._size > 0:
entries = entries[-self._size:]
self._write_entries(entries) |
Return a member generator by a dot-delimited path | def _resolve_child(self, path):
'Return a member generator by a dot-delimited path'
obj = self
for component in path.split('.'):
ptr = obj
if not isinstance(ptr, Permuter):
raise self.MessageNotFound("Bad element path [wrong type]")
# pylint: disable=protected-access
found_gen = (_ for _ in ptr._generators if _.name() == component)
obj = next(found_gen, None)
if not obj:
raise self.MessageNotFound("Path '{}' unresolved to member."
.format(path))
return ptr, obj |
Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x + 1)
Going forward, 'two' will only contain values that are (one+1) | def make_dependent(self, source, target, action):
'''
Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x + 1)
Going forward, 'two' will only contain values that are (one+1)
'''
if not self._generators:
return
src_permuter, src = self._resolve_child(source)
dest = self._resolve_child(target)[1]
# pylint: disable=protected-access
container = src_permuter._generators
idx = container.index(src)
container[idx] = DependentValueGenerator(src.name(), dest, action)
self._update_independent_generators() |
Retrieve the most recent value generated | def get(self):
'Retrieve the most recent value generated'
# If you attempt to use a generator comprehension below, it will
# consume the StopIteration exception and just return an empty tuple,
# instead of stopping iteration normally
return tuple([(x.name(), x.get()) for x in self._generators]) |
Helper to grab some integers from fuzzdb | def _fuzzdb_integers(limit=0):
'Helper to grab some integers from fuzzdb'
path = os.path.join(BASE_PATH, 'integer-overflow/integer-overflows.txt')
stream = _open_fuzzdb_file(path)
for line in _limit_helper(stream, limit):
yield int(line.decode('utf-8'), 0) |
Helper to get all the strings from fuzzdb | def _fuzzdb_get_strings(max_len=0):
'Helper to get all the strings from fuzzdb'
ignored = ['integer-overflow']
for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH):
if subdir in ignored:
continue
path = '{}/{}'.format(BASE_PATH, subdir)
listing = pkg_resources.resource_listdir('protofuzz', path)
for filename in listing:
if not filename.endswith('.txt'):
continue
path = '{}/{}/{}'.format(BASE_PATH, subdir, filename)
source = _open_fuzzdb_file(path)
for line in source:
string = line.decode('utf-8').strip()
if not string or string.startswith('#'):
continue
if max_len != 0 and len(line) > max_len:
continue
yield string |
Get integers from fuzzdb database
bitwidth - The bitwidth that has to contain the integer
unsigned - Whether the type is unsigned
limit - Limit to |limit| results | def get_integers(bitwidth, unsigned, limit=0):
'''
Get integers from fuzzdb database
bitwidth - The bitwidth that has to contain the integer
unsigned - Whether the type is unsigned
limit - Limit to |limit| results
'''
if unsigned:
start, stop = 0, ((1 << bitwidth) - 1)
else:
start, stop = (-(1 << bitwidth-1)), (1 << (bitwidth-1)-1)
for num in _fuzzdb_integers(limit):
if num >= start and num <= stop:
yield num |
Return a number of interesting floating point values | def get_floats(bitwidth, limit=0):
'''
Return a number of interesting floating point values
'''
assert bitwidth in (32, 64, 80)
values = [0.0, -1.0, 1.0, -1231231231231.0123, 123123123123123.123]
for val in _limit_helper(values, limit):
yield val |
Helper to create a basic integer value generator | def _int_generator(descriptor, bitwidth, unsigned):
'Helper to create a basic integer value generator'
vals = list(values.get_integers(bitwidth, unsigned))
return gen.IterValueGenerator(descriptor.name, vals) |
Helper to create a string generator | def _string_generator(descriptor, max_length=0, limit=0):
'Helper to create a string generator'
vals = list(values.get_strings(max_length, limit))
return gen.IterValueGenerator(descriptor.name, vals) |
Helper to create bytes values. (Derived from string generator) | def _bytes_generator(descriptor, max_length=0, limit=0):
'Helper to create bytes values. (Derived from string generator)'
strs = values.get_strings(max_length, limit)
vals = [bytes(_, 'utf-8') for _ in strs]
return gen.IterValueGenerator(descriptor.name, vals) |
Helper to create floating point values | def _float_generator(descriptor, bitwidth):
'Helper to create floating point values'
return gen.IterValueGenerator(descriptor.name, values.get_floats(bitwidth)) |
Helper to create protobuf enums | def _enum_generator(descriptor):
'Helper to create protobuf enums'
vals = descriptor.enum_type.values_by_number.keys()
return gen.IterValueGenerator(descriptor.name, vals) |
Helper to map a descriptor to a protofuzz generator | def _prototype_to_generator(descriptor, cls):
'Helper to map a descriptor to a protofuzz generator'
_fd = D.FieldDescriptor
generator = None
ints32 = [_fd.TYPE_INT32, _fd.TYPE_UINT32, _fd.TYPE_FIXED32,
_fd.TYPE_SFIXED32, _fd.TYPE_SINT32]
ints64 = [_fd.TYPE_INT64, _fd.TYPE_UINT64, _fd.TYPE_FIXED64,
_fd.TYPE_SFIXED64, _fd.TYPE_SINT64]
ints_signed = [_fd.TYPE_INT32, _fd.TYPE_SFIXED32, _fd.TYPE_SINT32,
_fd.TYPE_INT64, _fd.TYPE_SFIXED64, _fd.TYPE_SINT64]
if descriptor.type in ints32+ints64:
bitwidth = [32, 64][descriptor.type in ints64]
unsigned = descriptor.type not in ints_signed
generator = _int_generator(descriptor, bitwidth, unsigned)
elif descriptor.type == _fd.TYPE_DOUBLE:
generator = _float_generator(descriptor, 64)
elif descriptor.type == _fd.TYPE_FLOAT:
generator = _float_generator(descriptor, 32)
elif descriptor.type == _fd.TYPE_STRING:
generator = _string_generator(descriptor)
elif descriptor.type == _fd.TYPE_BYTES:
generator = _bytes_generator(descriptor)
elif descriptor.type == _fd.TYPE_BOOL:
generator = gen.IterValueGenerator(descriptor.name, [True, False])
elif descriptor.type == _fd.TYPE_ENUM:
generator = _enum_generator(descriptor)
elif descriptor.type == _fd.TYPE_MESSAGE:
generator = descriptor_to_generator(descriptor.message_type, cls)
generator.set_name(descriptor.name)
else:
raise RuntimeError("type {} unsupported".format(descriptor.type))
return generator |
Convert a protobuf descriptor to a protofuzz generator for same type | def descriptor_to_generator(cls_descriptor, cls, limit=0):
'Convert a protobuf descriptor to a protofuzz generator for same type'
generators = []
for descriptor in cls_descriptor.fields_by_name.values():
generator = _prototype_to_generator(descriptor, cls)
if limit != 0:
generator.set_limit(limit)
generators.append(generator)
obj = cls(cls_descriptor.name, *generators)
return obj |
Helper to assign an arbitrary value to a protobuf field | def _assign_to_field(obj, name, val):
'Helper to assign an arbitrary value to a protobuf field'
target = getattr(obj, name)
if isinstance(target, containers.RepeatedScalarFieldContainer):
target.append(val)
elif isinstance(target, containers.RepeatedCompositeFieldContainer):
target = target.add()
target.CopyFrom(val)
elif isinstance(target, (int, float, bool, str, bytes)):
setattr(obj, name, val)
elif isinstance(target, message.Message):
target.CopyFrom(val)
else:
raise RuntimeError("Unsupported type: {}".format(type(target))) |
Helper to convert a descriptor and a set of fields to a Protobuf instance | def _fields_to_object(descriptor, fields):
'Helper to convert a descriptor and a set of fields to a Protobuf instance'
# pylint: disable=protected-access
obj = descriptor._concrete_class()
for name, value in fields:
if isinstance(value, tuple):
subtype = descriptor.fields_by_name[name].message_type
value = _fields_to_object(subtype, value)
_assign_to_field(obj, name, value)
return obj |
Convert a protobuf module to a dict of generators.
This is typically used with modules that contain multiple type definitions. | def _module_to_generators(pb_module):
'''
Convert a protobuf module to a dict of generators.
This is typically used with modules that contain multiple type definitions.
'''
if not pb_module:
return None
message_types = pb_module.DESCRIPTOR.message_types_by_name
return {k: ProtobufGenerator(v) for k, v in message_types.items()} |
Create a dependency between fields source and target via callable
action.
>>> permuter = protofuzz.from_description_string("""
... message Address {
... required uint32 one = 1;
... required uint32 two = 2;
... }""")['Address']
>>> permuter.add_dependency('one', 'two', lambda val: max(0,val-1))
>>> for obj in permuter.linear():
... print("obj = {}".format(obj))
...
obj = one: 0
two: 1
obj = one: 256
two: 257
obj = one: 4096
two: 4097
obj = one: 1073741823
two: 1073741824 | def add_dependency(self, source, target, action):
'''
Create a dependency between fields source and target via callable
action.
>>> permuter = protofuzz.from_description_string("""
... message Address {
... required uint32 one = 1;
... required uint32 two = 2;
... }""")['Address']
>>> permuter.add_dependency('one', 'two', lambda val: max(0,val-1))
>>> for obj in permuter.linear():
... print("obj = {}".format(obj))
...
obj = one: 0
two: 1
obj = one: 256
two: 257
obj = one: 4096
two: 4097
obj = one: 1073741823
two: 1073741824
'''
self._dependencies.append((source, target, action)) |
Print Compare report.
:return: None | def print_report(self):
"""
Print Compare report.
:return: None
"""
report = compare_report_print(
self.sorted, self.scores, self.best_name)
print(report) |
Save Compare report in .comp (flat file format).
:param name: filename
:type name : str
:param address: flag for address return
:type address : bool
:return: saving Status as dict {"Status":bool , "Message":str} | def save_report(
self,
name,
address=True):
"""
Save Compare report in .comp (flat file format).
:param name: filename
:type name : str
:param address: flag for address return
:type address : bool
:return: saving Status as dict {"Status":bool , "Message":str}
"""
try:
message = None
file = open(name + ".comp", "w")
report = compare_report_print(
self.sorted, self.scores, self.best_name)
file.write(report)
file.close()
if address:
message = os.path.join(os.getcwd(), name + ".comp")
return {"Status": True, "Message": message}
except Exception as e:
return {"Status": False, "Message": str(e)} |
Calculate accuracy.
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: accuracy as float | def ACC_calc(TP, TN, FP, FN):
"""
Calculate accuracy.
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: accuracy as float
"""
try:
result = (TP + TN) / (TP + TN + FN + FP)
return result
except ZeroDivisionError:
return "None" |
Calculate F-score.
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param beta : beta coefficient
:type beta : float
:return: F score as float | def F_calc(TP, FP, FN, beta):
"""
Calculate F-score.
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param beta : beta coefficient
:type beta : float
:return: F score as float
"""
try:
result = ((1 + (beta)**2) * TP) / \
((1 + (beta)**2) * TP + FP + (beta**2) * FN)
return result
except ZeroDivisionError:
return "None" |
Calculate MCC (Matthews correlation coefficient).
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: MCC as float | def MCC_calc(TP, TN, FP, FN):
"""
Calculate MCC (Matthews correlation coefficient).
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: MCC as float
"""
try:
result = (TP * TN - FP * FN) / \
(math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN)))
return result
except ZeroDivisionError:
return "None" |
Calculate G-measure & G-mean.
:param item1: PPV or TPR or TNR
:type item1 : float
:param item2: PPV or TPR or TNR
:type item2 : float
:return: G-measure or G-mean as float | def G_calc(item1, item2):
"""
Calculate G-measure & G-mean.
:param item1: PPV or TPR or TNR
:type item1 : float
:param item2: PPV or TPR or TNR
:type item2 : float
:return: G-measure or G-mean as float
"""
try:
result = math.sqrt(item1 * item2)
return result
except Exception:
return "None" |
Calculate random accuracy.
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP:int
:return: RACC as float | def RACC_calc(TOP, P, POP):
"""
Calculate random accuracy.
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP:int
:return: RACC as float
"""
try:
result = (TOP * P) / ((POP) ** 2)
return result
except Exception:
return "None" |
Calculate RACCU (Random accuracy unbiased).
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP : int
:return: RACCU as float | def RACCU_calc(TOP, P, POP):
"""
Calculate RACCU (Random accuracy unbiased).
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP : int
:return: RACCU as float
"""
try:
result = ((TOP + P) / (2 * POP))**2
return result
except Exception:
return "None" |
Calculate IS (Information score).
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param POP: population
:type POP : int
:return: IS as float | def IS_calc(TP, FP, FN, POP):
"""
Calculate IS (Information score).
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param POP: population
:type POP : int
:return: IS as float
"""
try:
result = -math.log(((TP + FN) / POP), 2) + \
math.log((TP / (TP + FP)), 2)
return result
except Exception:
return "None" |
Calculate misclassification probability of classifying.
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param i: table row index (class name)
:type i : any valid type
:param j: table col index (class name)
:type j : any valid type
:param subject_class: subject to class (class name)
:type subject_class: any valid type
:param modified : modified mode flag
:type modified : bool
:return: misclassification probability of classifying as float | def CEN_misclassification_calc(
table,
TOP,
P,
i,
j,
subject_class,
modified=False):
"""
Calculate misclassification probability of classifying.
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param i: table row index (class name)
:type i : any valid type
:param j: table col index (class name)
:type j : any valid type
:param subject_class: subject to class (class name)
:type subject_class: any valid type
:param modified : modified mode flag
:type modified : bool
:return: misclassification probability of classifying as float
"""
try:
result = TOP + P
if modified:
result -= table[subject_class][subject_class]
result = table[i][j] / result
return result
except Exception:
return "None" |
Calculate CEN (Confusion Entropy)/ MCEN(Modified Confusion Entropy).
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param class_name: reviewed class name
:type class_name : any valid type
:param modified : modified mode flag
:type modified : bool
:return: CEN(MCEN) as float | def CEN_calc(classes, table, TOP, P, class_name, modified=False):
"""
Calculate CEN (Confusion Entropy)/ MCEN(Modified Confusion Entropy).
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param class_name: reviewed class name
:type class_name : any valid type
:param modified : modified mode flag
:type modified : bool
:return: CEN(MCEN) as float
"""
try:
result = 0
class_number = len(classes)
for k in classes:
if k != class_name:
P_j_k = CEN_misclassification_calc(
table, TOP, P, class_name, k, class_name, modified)
P_k_j = CEN_misclassification_calc(
table, TOP, P, k, class_name, class_name, modified)
if P_j_k != 0:
result += P_j_k * math.log(P_j_k, 2 * (class_number - 1))
if P_k_j != 0:
result += P_k_j * math.log(P_k_j, 2 * (class_number - 1))
if result != 0:
result = result * (-1)
return result
except Exception:
return "None" |
Calculate dInd (Distance index).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: dInd as float | def dInd_calc(TNR, TPR):
"""
Calculate dInd (Distance index).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: dInd as float
"""
try:
result = math.sqrt(((1 - TNR)**2) + ((1 - TPR)**2))
return result
except Exception:
return "None" |
Calculate DP (Discriminant power).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: DP as float | def DP_calc(TPR, TNR):
"""
Calculate DP (Discriminant power).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: DP as float
"""
try:
X = TPR / (1 - TPR)
Y = TNR / (1 - TNR)
return (math.sqrt(3) / math.pi) * (math.log(X, 10) + math.log(Y, 10))
except Exception:
return "None" |
Calculate OP (Optimized precision).
:param ACC: accuracy
:type ACC : float
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: OP as float | def OP_calc(ACC, TPR, TNR):
"""
Calculate OP (Optimized precision).
:param ACC: accuracy
:type ACC : float
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: OP as float
"""
try:
RI = abs(TNR - TPR) / (TPR + TNR)
return ACC - RI
except Exception:
return "None" |
Calculate IBA (Index of balanced accuracy).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:param alpha : alpha coefficient
:type alpha : float
:return: IBA as float | def IBA_calc(TPR, TNR, alpha=1):
"""
Calculate IBA (Index of balanced accuracy).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:param alpha : alpha coefficient
:type alpha : float
:return: IBA as float
"""
try:
IBA = (1 + alpha * (TPR - TNR)) * TPR * TNR
return IBA
except Exception:
return "None" |
Calculate BCD (Bray-Curtis dissimilarity).
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param AM: Automatic/Manual
:type AM : int
:return: BCD as float | def BCD_calc(TOP, P, AM):
"""
Calculate BCD (Bray-Curtis dissimilarity).
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param AM: Automatic/Manual
:type AM : int
:return: BCD as float
"""
try:
TOP_sum = sum(TOP.values())
P_sum = sum(P.values())
return abs(AM) / (P_sum + TOP_sum)
except Exception:
return "None" |
Return all class statistics.
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: result as dict | def class_statistics(TP, TN, FP, FN, classes, table):
"""
Return all class statistics.
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: result as dict
"""
TPR = {}
TNR = {}
PPV = {}
NPV = {}
FNR = {}
FPR = {}
FDR = {}
FOR = {}
ACC = {}
F1_SCORE = {}
MCC = {}
BM = {}
MK = {}
PLR = {}
NLR = {}
DOR = {}
POP = {}
P = {}
N = {}
TOP = {}
TON = {}
PRE = {}
G = {}
RACC = {}
F05_Score = {}
F2_Score = {}
ERR = {}
RACCU = {}
Jaccrd_Index = {}
IS = {}
CEN = {}
MCEN = {}
AUC = {}
dInd = {}
sInd = {}
DP = {}
Y = {}
PLRI = {}
DPI = {}
AUCI = {}
GI = {}
LS = {}
AM = {}
BCD = {}
OP = {}
IBA = {}
GM = {}
for i in TP.keys():
POP[i] = TP[i] + TN[i] + FP[i] + FN[i]
P[i] = TP[i] + FN[i]
N[i] = TN[i] + FP[i]
TOP[i] = TP[i] + FP[i]
TON[i] = TN[i] + FN[i]
TPR[i] = TTPN_calc(TP[i], FN[i])
TNR[i] = TTPN_calc(TN[i], FP[i])
PPV[i] = TTPN_calc(TP[i], FP[i])
NPV[i] = TTPN_calc(TN[i], FN[i])
FNR[i] = FXR_calc(TPR[i])
FPR[i] = FXR_calc(TNR[i])
FDR[i] = FXR_calc(PPV[i])
FOR[i] = FXR_calc(NPV[i])
ACC[i] = ACC_calc(TP[i], TN[i], FP[i], FN[i])
F1_SCORE[i] = F_calc(TP[i], FP[i], FN[i], 1)
F05_Score[i] = F_calc(TP[i], FP[i], FN[i], 0.5)
F2_Score[i] = F_calc(TP[i], FP[i], FN[i], 2)
MCC[i] = MCC_calc(TP[i], TN[i], FP[i], FN[i])
BM[i] = MK_BM_calc(TPR[i], TNR[i])
MK[i] = MK_BM_calc(PPV[i], NPV[i])
PLR[i] = LR_calc(TPR[i], FPR[i])
NLR[i] = LR_calc(FNR[i], TNR[i])
DOR[i] = LR_calc(PLR[i], NLR[i])
PRE[i] = PRE_calc(P[i], POP[i])
G[i] = G_calc(PPV[i], TPR[i])
RACC[i] = RACC_calc(TOP[i], P[i], POP[i])
ERR[i] = ERR_calc(ACC[i])
RACCU[i] = RACCU_calc(TOP[i], P[i], POP[i])
Jaccrd_Index[i] = jaccard_index_calc(TP[i], TOP[i], P[i])
IS[i] = IS_calc(TP[i], FP[i], FN[i], POP[i])
CEN[i] = CEN_calc(classes, table, TOP[i], P[i], i)
MCEN[i] = CEN_calc(classes, table, TOP[i], P[i], i, True)
AUC[i] = AUC_calc(TNR[i], TPR[i])
dInd[i] = dInd_calc(TNR[i], TPR[i])
sInd[i] = sInd_calc(dInd[i])
DP[i] = DP_calc(TPR[i], TNR[i])
Y[i] = BM[i]
PLRI[i] = PLR_analysis(PLR[i])
DPI[i] = DP_analysis(DP[i])
AUCI[i] = AUC_analysis(AUC[i])
GI[i] = GI_calc(AUC[i])
LS[i] = lift_calc(PPV[i], PRE[i])
AM[i] = AM_calc(TOP[i], P[i])
OP[i] = OP_calc(ACC[i], TPR[i], TNR[i])
IBA[i] = IBA_calc(TPR[i], TNR[i])
GM[i] = G_calc(TNR[i], TPR[i])
for i in TP.keys():
BCD[i] = BCD_calc(TOP, P, AM[i])
result = {
"TPR": TPR,
"TNR": TNR,
"PPV": PPV,
"NPV": NPV,
"FNR": FNR,
"FPR": FPR,
"FDR": FDR,
"FOR": FOR,
"ACC": ACC,
"F1": F1_SCORE,
"MCC": MCC,
"BM": BM,
"MK": MK,
"PLR": PLR,
"NLR": NLR,
"DOR": DOR,
"TP": TP,
"TN": TN,
"FP": FP,
"FN": FN,
"POP": POP,
"P": P,
"N": N,
"TOP": TOP,
"TON": TON,
"PRE": PRE,
"G": G,
"RACC": RACC,
"F0.5": F05_Score,
"F2": F2_Score,
"ERR": ERR,
"RACCU": RACCU,
"J": Jaccrd_Index,
"IS": IS,
"CEN": CEN,
"MCEN": MCEN,
"AUC": AUC,
"sInd": sInd,
"dInd": dInd,
"DP": DP,
"Y": Y,
"PLRI": PLRI,
"DPI": DPI,
"AUCI": AUCI,
"GI": GI,
"LS": LS,
"AM": AM,
"BCD": BCD,
"OP": OP,
"IBA": IBA,
"GM": GM}
return result |
Return HTML report file first lines.
:param name: name of file
:type name : str
:return: html_init as str | def html_init(name):
"""
Return HTML report file first lines.
:param name: name of file
:type name : str
:return: html_init as str
"""
result = ""
result += "<html>\n"
result += "<head>\n"
result += "<title>" + str(name) + "</title>\n"
result += "</head>\n"
result += "<body>\n"
result += '<h1 style="border-bottom:1px solid ' \
'black;text-align:center;">PyCM Report</h1>'
return result |
Return HTML report file dataset type.
:param is_binary: is_binary flag (binary : True , multi-class : False)
:type is_binary: bool
:param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False)
:type is_imbalanced: bool
:return: dataset_type as str | def html_dataset_type(is_binary, is_imbalanced):
"""
Return HTML report file dataset type.
:param is_binary: is_binary flag (binary : True , multi-class : False)
:type is_binary: bool
:param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False)
:type is_imbalanced: bool
:return: dataset_type as str
"""
result = "<h2>Dataset Type : </h2>\n"
balance_type = "Balanced"
class_type = "Binary Classification"
if is_imbalanced:
balance_type = "Imbalanced"
if not is_binary:
class_type = "Multi-Class Classification"
result += "<ul>\n\n<li>{0}</li>\n\n<li>{1}</li>\n</ul>\n".format(
class_type, balance_type)
result += "<p>{0}</p>\n".format(RECOMMEND_HTML_MESSAGE)
result += "<p>{0}</p>\n".format(RECOMMEND_HTML_MESSAGE2)
return result |
Check input color format.
:param color: input color
:type color : tuple
:return: color as list | def color_check(color):
"""
Check input color format.
:param color: input color
:type color : tuple
:return: color as list
"""
if isinstance(color, (tuple, list)):
if all(map(lambda x: isinstance(x, int), color)):
if all(map(lambda x: x < 256, color)):
return list(color)
if isinstance(color, str):
color_lower = color.lower()
if color_lower in TABLE_COLOR.keys():
return TABLE_COLOR[color_lower]
return [0, 0, 0] |
Return background color of each cell of table.
:param row: row dictionary
:type row : dict
:param item: cell number
:type item : int
:param color : input color
:type color : tuple
:return: background color as list [R,G,B] | def html_table_color(row, item, color=(0, 0, 0)):
"""
Return background color of each cell of table.
:param row: row dictionary
:type row : dict
:param item: cell number
:type item : int
:param color : input color
:type color : tuple
:return: background color as list [R,G,B]
"""
result = [0, 0, 0]
color_list = color_check(color)
max_color = max(color_list)
back_color_index = 255 - int((item / (sum(list(row.values())) + 1)) * 255)
for i in range(3):
result[i] = back_color_index - (max_color - color_list[i])
if result[i] < 0:
result[i] = 0
return result |
Return HTML report file confusion matrix.
:param classes: matrix classes
:type classes: list
:param table: matrix
:type table : dict
:param rgb_color : input color
:type rgb_color : tuple
:param normalize : save normalize matrix flag
:type normalize : bool
:return: html_table as str | def html_table(classes, table, rgb_color, normalize=False):
"""
Return HTML report file confusion matrix.
:param classes: matrix classes
:type classes: list
:param table: matrix
:type table : dict
:param rgb_color : input color
:type rgb_color : tuple
:param normalize : save normalize matrix flag
:type normalize : bool
:return: html_table as str
"""
result = ""
result += "<h2>Confusion Matrix "
if normalize:
result += "(Normalized)"
result += ": </h2>\n"
result += '<table>\n'
result += '<tr align="center">' + "\n"
result += '<td>Actual</td>\n'
result += '<td>Predict\n'
table_size = str((len(classes) + 1) * 7) + "em"
result += '<table style="border:1px solid black;border-collapse: collapse;height:{0};width:{0};">\n'\
.format(table_size)
classes.sort()
result += '<tr align="center">\n<td></td>\n'
part_2 = ""
for i in classes:
class_name = str(i)
if len(class_name) > 6:
class_name = class_name[:4] + "..."
result += '<td style="border:1px solid ' \
'black;padding:10px;height:7em;width:7em;">' + \
class_name + '</td>\n'
part_2 += '<tr align="center">\n'
part_2 += '<td style="border:1px solid ' \
'black;padding:10px;height:7em;width:7em;">' + \
class_name + '</td>\n'
for j in classes:
item = table[i][j]
color = "black;"
back_color = html_table_color(table[i], item, rgb_color)
if min(back_color) < 128:
color = "white"
part_2 += '<td style="background-color: rgb({0},{1},{2});color:{3};padding:10px;height:7em;width:7em;">'.format(
str(back_color[0]), str(back_color[1]), str(back_color[2]), color) + str(item) + '</td>\n'
part_2 += "</tr>\n"
result += '</tr>\n'
part_2 += "</table>\n</td>\n</tr>\n</table>\n"
result += part_2
return result |
Return HTML report file class_stat.
:param classes: matrix classes
:type classes: list
:param class_stat: class stat
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : Class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:param recommended_list: recommended statistics list
:type recommended_list : list or tuple
:return: html_class_stat as str | def html_class_stat(
classes,
class_stat,
digit=5,
class_param=None,
recommended_list=()):
"""
Return HTML report file class_stat.
:param classes: matrix classes
:type classes: list
:param class_stat: class stat
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : Class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:param recommended_list: recommended statistics list
:type recommended_list : list or tuple
:return: html_class_stat as str
"""
result = ""
result += "<h2>Class Statistics : </h2>\n"
result += '<table style="border:1px solid black;border-collapse: collapse;">\n'
result += '<tr align="center">\n<td>Class</td>\n'
for i in classes:
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;">' + \
str(i) + '</td>\n'
result += '<td>Description</td>\n'
result += '</tr>\n'
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = class_param
classes.sort()
if len(classes) < 1 or len(class_stat_keys) < 1:
return ""
for i in class_stat_keys:
background_color = DEFAULT_BACKGROUND_COLOR
if i in recommended_list:
background_color = RECOMMEND_BACKGROUND_COLOR
result += '<tr align="center" style="border:1px solid black;border-collapse: collapse;">\n'
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;background-color:{};"><a href="'.format(
background_color) + DOCUMENT_ADR + PARAMS_LINK[i] + '" style="text-decoration:None;">' + str(i) + '</a></td>\n'
for j in classes:
if i in BENCHMARK_LIST:
background_color = BENCHMARK_COLOR[class_stat[i][j]]
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;background-color:{};">'.format(
background_color)
else:
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;">'
result += rounder(class_stat[i][j], digit) + '</td>\n'
params_text = PARAMS_DESCRIPTION[i]
if i not in CAPITALIZE_FILTER:
params_text = params_text.capitalize()
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;text-align:left;">' + \
params_text + '</td>\n'
result += "</tr>\n"
result += "</table>\n"
return result |
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: | def csv_matrix_print(classes, table):
"""
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return:
"""
result = ""
classes.sort()
for i in classes:
for j in classes:
result += str(table[i][j]) + ","
result = result[:-1] + "\n"
return result[:-1] |
Return printable confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: printable table as str | def table_print(classes, table):
"""
Return printable confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: printable table as str
"""
classes_len = len(classes)
table_list = []
for key in classes:
table_list.extend(list(table[key].values()))
table_list.extend(classes)
table_max_length = max(map(len, map(str, table_list)))
shift = "%-" + str(7 + table_max_length) + "s"
result = shift % "Predict" + shift * \
classes_len % tuple(map(str, classes)) + "\n"
result = result + "Actual\n"
classes.sort()
for key in classes:
row = [table[key][i] for i in classes]
result += shift % str(key) + \
shift * classes_len % tuple(map(str, row)) + "\n\n"
if classes_len >= CLASS_NUMBER_THRESHOLD:
result += "\n" + "Warning : " + CLASS_NUMBER_WARNING + "\n"
return result |
Return csv file data.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: csv file data as str | def csv_print(classes, class_stat, digit=5, class_param=None):
"""
Return csv file data.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: csv file data as str
"""
result = "Class"
classes.sort()
for item in classes:
result += ',"' + str(item) + '"'
result += "\n"
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = class_param
if len(class_stat_keys) < 1 or len(classes) < 1:
return ""
for key in class_stat_keys:
row = [rounder(class_stat[key][i], digit) for i in classes]
result += key + "," + ",".join(row)
result += "\n"
return result |
Return printable statistics table.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param overall_stat : overall statistic result
:type overall_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param overall_param : overall parameters list for print, Example : ["Kappa","Scott PI]
:type overall_param : list
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: printable result as str | def stat_print(
classes,
class_stat,
overall_stat,
digit=5,
overall_param=None,
class_param=None):
"""
Return printable statistics table.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param overall_stat : overall statistic result
:type overall_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param overall_param : overall parameters list for print, Example : ["Kappa","Scott PI]
:type overall_param : list
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: printable result as str
"""
shift = max(map(len, PARAMS_DESCRIPTION.values())) + 5
classes_len = len(classes)
overall_stat_keys = sorted(overall_stat.keys())
result = ""
if isinstance(overall_param, list):
if set(overall_param) <= set(overall_stat_keys):
overall_stat_keys = sorted(overall_param)
if len(overall_stat_keys) > 0:
result = "Overall Statistics : " + "\n\n"
for key in overall_stat_keys:
result += key + " " * (shift - len(key) + 7) + \
rounder(overall_stat[key], digit) + "\n"
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = sorted(class_param)
classes.sort()
if len(class_stat_keys) > 0 and len(classes) > 0:
class_shift = max(
max(map(lambda x: len(str(x)), classes)) + 5, digit + 6, 14)
class_shift_format = "%-" + str(class_shift) + "s"
result += "\nClass Statistics :\n\n"
result += "Classes" + shift * " " + class_shift_format * \
classes_len % tuple(map(str, classes)) + "\n"
rounder_map = partial(rounder, digit=digit)
for key in class_stat_keys:
row = [class_stat[key][i] for i in classes]
params_text = PARAMS_DESCRIPTION[key]
if key not in CAPITALIZE_FILTER:
params_text = params_text.capitalize()
result += key + "(" + params_text + ")" + " " * (
shift - len(key) - len(PARAMS_DESCRIPTION[key]) + 5) + class_shift_format * classes_len % tuple(
map(rounder_map, row)) + "\n"
if classes_len >= CLASS_NUMBER_THRESHOLD:
result += "\n" + "Warning : " + CLASS_NUMBER_WARNING + "\n"
return result |
Return compare report.
:param sorted_list: sorted list of cm's
:type sorted_list: list
:param scores: scores of cm's
:type scores: dict
:param best_name: best cm name
:type best_name: str
:return: printable result as str | def compare_report_print(sorted_list, scores, best_name):
"""
Return compare report.
:param sorted_list: sorted list of cm's
:type sorted_list: list
:param scores: scores of cm's
:type scores: dict
:param best_name: best cm name
:type best_name: str
:return: printable result as str
"""
title_items = ["Rank", "Name", "Class-Score", "Overall-Score"]
class_scores_len = map(lambda x: len(
str(x["class"])), list(scores.values()))
shifts = ["%-" +
str(len(sorted_list) +
4) +
"s", "%-" +
str(max(map(lambda x: len(str(x)), sorted_list)) +
4) +
"s", "%-" +
str(max(class_scores_len) + 11) + "s"]
result = ""
result += "Best : " + str(best_name) + "\n\n"
result += ("".join(shifts)
) % tuple(title_items[:-1]) + title_items[-1] + "\n"
prev_rank = 0
for index, cm in enumerate(sorted_list):
rank = index
if scores[sorted_list[rank]] == scores[sorted_list[prev_rank]]:
rank = prev_rank
result += ("".join(shifts)) % (str(rank + 1), str(cm),
str(scores[cm]["class"])) + str(scores[cm]["overall"]) + "\n"
prev_rank = rank
if best_name is None:
result += "\nWarning: " + COMPARE_RESULT_WARNING
return result |
Open online document in web browser.
:param param: input parameter
:type param : int or str
:return: None | def online_help(param=None):
"""
Open online document in web browser.
:param param: input parameter
:type param : int or str
:return: None
"""
try:
PARAMS_LINK_KEYS = sorted(PARAMS_LINK.keys())
if param in PARAMS_LINK_KEYS:
webbrowser.open_new_tab(DOCUMENT_ADR + PARAMS_LINK[param])
elif param in range(1, len(PARAMS_LINK_KEYS) + 1):
webbrowser.open_new_tab(
DOCUMENT_ADR + PARAMS_LINK[PARAMS_LINK_KEYS[param - 1]])
else:
print("Please choose one parameter : \n")
print('Example : online_help("J") or online_help(2)\n')
for index, item in enumerate(PARAMS_LINK_KEYS):
print(str(index + 1) + "-" + item)
except Exception:
print("Error in online help") |
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str | def rounder(input_number, digit=5):
"""
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str
"""
if isinstance(input_number, tuple):
tuple_list = list(input_number)
tuple_str = []
for i in tuple_list:
if isfloat(i):
tuple_str.append(str(numpy.around(i, digit)))
else:
tuple_str.append(str(i))
return "(" + ",".join(tuple_str) + ")"
if isfloat(input_number):
return str(numpy.around(input_number, digit))
return str(input_number) |
Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list | def class_filter(classes, class_name):
"""
Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list
"""
result_classes = classes
if isinstance(class_name, list):
if set(class_name) <= set(classes):
result_classes = class_name
return result_classes |
Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool | def vector_check(vector):
"""
Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if isinstance(i, int) is False:
return False
if i < 0:
return False
return True |
Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool | def matrix_check(table):
"""
Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool
"""
try:
if len(table.keys()) == 0:
return False
for i in table.keys():
if table.keys() != table[i].keys() or vector_check(
list(table[i].values())) is False:
return False
return True
except Exception:
return False |
Convert different type of items in vectors to str.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:return: new actual and predict vector | def vector_filter(actual_vector, predict_vector):
"""
Convert different type of items in vectors to str.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:return: new actual and predict vector
"""
temp = []
temp.extend(actual_vector)
temp.extend(predict_vector)
types = set(map(type, temp))
if len(types) > 1:
return [list(map(str, actual_vector)), list(map(str, predict_vector))]
return [actual_vector, predict_vector] |
Check different items in matrix classes.
:param vector: input vector
:type vector : list
:return: bool | def class_check(vector):
"""
Check different items in matrix classes.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if not isinstance(i, type(vector[0])):
return False
return True |
One-Vs-All mode handler.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:param class_name : target class name for One-Vs-All mode
:type class_name : any valid type
:return: [classes , table ] as list | def one_vs_all_func(classes, table, TP, TN, FP, FN, class_name):
"""
One-Vs-All mode handler.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:param class_name : target class name for One-Vs-All mode
:type class_name : any valid type
:return: [classes , table ] as list
"""
try:
report_classes = [str(class_name), "~"]
report_table = {str(class_name): {str(class_name): TP[class_name],
"~": FN[class_name]},
"~": {str(class_name): FP[class_name],
"~": TN[class_name]}}
return [report_classes, report_table]
except Exception:
return [classes, table] |
Return normalized confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: normalized table as dict | def normalized_table_calc(classes, table):
"""
Return normalized confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: normalized table as dict
"""
map_dict = {k: 0 for k in classes}
new_table = {k: map_dict.copy() for k in classes}
for key in classes:
div = sum(table[key].values())
if div == 0:
div = 1
for item in classes:
new_table[key][item] = numpy.around(table[key][item] / div, 5)
return new_table |
Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict | def transpose_func(classes, table):
"""
Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict
"""
transposed_table = table
for i, item1 in enumerate(classes):
for j, item2 in enumerate(classes):
if i > j:
temp = transposed_table[item1][item2]
transposed_table[item1][item2] = transposed_table[item2][item1]
transposed_table[item2][item1] = temp
return transposed_table |
Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN] | def matrix_params_from_table(table, transpose=False):
"""
Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN]
"""
classes = sorted(table.keys())
map_dict = {k: 0 for k in classes}
TP_dict = map_dict.copy()
TN_dict = map_dict.copy()
FP_dict = map_dict.copy()
FN_dict = map_dict.copy()
for i in classes:
TP_dict[i] = table[i][i]
sum_row = sum(list(table[i].values()))
for j in classes:
if j != i:
FN_dict[i] += table[i][j]
FP_dict[j] += table[i][j]
TN_dict[j] += sum_row - table[i][j]
if transpose:
temp = FN_dict
FN_dict = FP_dict
FP_dict = temp
table = transpose_func(classes, table)
return [classes, table, TP_dict, TN_dict, FP_dict, FN_dict] |