Static Analyzer for Solidity
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
slither/utils/similarity/plot.py

79 lines
2.2 KiB

6 years ago
import logging
import sys
import traceback
import operator
import numpy as np
import random
from .model import load_model
from .encode import load_and_encode, parse_target
6 years ago
try:
from sklearn import decomposition
import matplotlib.pyplot as plt
except ImportError:
decomposition = None
plt = None
6 years ago
6 years ago
logger = logging.getLogger("Slither-simil")
6 years ago
def plot(args):
6 years ago
if decomposition is None or plt is None:
6 years ago
logger.error("ERROR: In order to use plot mode in slither-simil, you need to install sklearn and matplotlib:")
logger.error("$ pip3 install sklearn matplotlib --user")
6 years ago
sys.exit(-1)
6 years ago
try:
6 years ago
6 years ago
model = args.model
model = load_model(model)
filename = args.filename
#contract = args.contract
contract, fname = parse_target(args.fname)
#solc = args.solc
6 years ago
infile = args.input
#ext = args.filter
#nsamples = args.nsamples
6 years ago
6 years ago
if fname is None or infile is None:
logger.error('The plot mode requieres fname and input parameters.')
6 years ago
sys.exit(-1)
6 years ago
logger.info('Loading data..')
cache = load_and_encode(infile, **vars(args))
6 years ago
data = list()
fs = list()
6 years ago
logger.info('Procesing data..')
6 years ago
for (f,c,n),y in cache.items():
6 years ago
if (c == contract or contract is None) and n == fname:
6 years ago
fs.append(f)
data.append(y)
6 years ago
if len(data) == 0:
logger.error('No contract was found with function %s', fname)
sys.exit(-1)
6 years ago
data = np.array(data)
pca = decomposition.PCA(n_components=2)
tdata = pca.fit_transform(data)
6 years ago
logger.info('Plotting data..')
6 years ago
plt.figure(figsize=(20,10))
6 years ago
assert(len(tdata) == len(fs))
for ([x,y],l) in zip(tdata, fs):
x = random.gauss(0, 0.01) + x
y = random.gauss(0, 0.01) + y
plt.scatter(x, y, c='blue')
6 years ago
plt.text(x-0.001,y+0.001, l)
6 years ago
6 years ago
logger.info('Saving figure to plot.png..')
6 years ago
plt.savefig('plot.png', bbox_inches='tight')
6 years ago
except Exception:
logger.error('Error in %s' % args.filename)
logger.error(traceback.format_exc())
sys.exit(-1)