repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
bottom-up-attention
bottom-up-attention-master/caffe/tools/extra/resize_and_crop_images.py
#!/usr/bin/env python from mincepie import mapreducer, launcher import gflags import os import cv2 from PIL import Image # gflags gflags.DEFINE_string('image_lib', 'opencv', 'OpenCV or PIL, case insensitive. The default value is the faster OpenCV.') gflags.DEFINE_string('input_folder', '', 'The folder that contains all input images, organized in synsets.') gflags.DEFINE_integer('output_side_length', 256, 'Expected side length of the output image.') gflags.DEFINE_string('output_folder', '', 'The folder that we write output resized and cropped images to') FLAGS = gflags.FLAGS class OpenCVResizeCrop: def resize_and_crop_image(self, input_file, output_file, output_side_length = 256): '''Takes an image name, resize it and crop the center square ''' img = cv2.imread(input_file) height, width, depth = img.shape new_height = output_side_length new_width = output_side_length if height > width: new_height = output_side_length * height / width else: new_width = output_side_length * width / height resized_img = cv2.resize(img, (new_width, new_height)) height_offset = (new_height - output_side_length) / 2 width_offset = (new_width - output_side_length) / 2 cropped_img = resized_img[height_offset:height_offset + output_side_length, width_offset:width_offset + output_side_length] cv2.imwrite(output_file, cropped_img) class PILResizeCrop: ## http://united-coders.com/christian-harms/image-resizing-tips-every-coder-should-know/ def resize_and_crop_image(self, input_file, output_file, output_side_length = 256, fit = True): '''Downsample the image. ''' img = Image.open(input_file) box = (output_side_length, output_side_length) #preresize image with factor 2, 4, 8 and fast algorithm factor = 1 while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]: factor *=2 if factor > 1: img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST) #calculate the cropping box and get the cropped part if fit: x1 = y1 = 0 x2, y2 = img.size wRatio = 1.0 * x2/box[0] hRatio = 1.0 * y2/box[1] if hRatio > wRatio: y1 = int(y2/2-box[1]*wRatio/2) y2 = int(y2/2+box[1]*wRatio/2) else: x1 = int(x2/2-box[0]*hRatio/2) x2 = int(x2/2+box[0]*hRatio/2) img = img.crop((x1,y1,x2,y2)) #Resize the image with best quality algorithm ANTI-ALIAS img.thumbnail(box, Image.ANTIALIAS) #save it into a file-like object with open(output_file, 'wb') as out: img.save(out, 'JPEG', quality=75) class ResizeCropImagesMapper(mapreducer.BasicMapper): '''The ImageNet Compute mapper. The input value would be the file listing images' paths relative to input_folder. ''' def map(self, key, value): if type(value) is not str: value = str(value) files = [value] image_lib = FLAGS.image_lib.lower() if image_lib == 'pil': resize_crop = PILResizeCrop() else: resize_crop = OpenCVResizeCrop() for i, line in enumerate(files): try: line = line.replace(FLAGS.input_folder, '').strip() line = line.split() image_file_name = line[0] input_file = os.path.join(FLAGS.input_folder, image_file_name) output_file = os.path.join(FLAGS.output_folder, image_file_name) output_dir = output_file[:output_file.rfind('/')] if not os.path.exists(output_dir): os.makedirs(output_dir) feat = resize_crop.resize_and_crop_image(input_file, output_file, FLAGS.output_side_length) except Exception, e: # we ignore the exception (maybe the image is corrupted?) print line, Exception, e yield value, FLAGS.output_folder mapreducer.REGISTER_DEFAULT_MAPPER(ResizeCropImagesMapper) mapreducer.REGISTER_DEFAULT_READER(mapreducer.FileReader) mapreducer.REGISTER_DEFAULT_WRITER(mapreducer.FileWriter) if __name__ == '__main__': launcher.launch()
4,541
40.290909
99
py
bottom-up-attention
bottom-up-attention-master/caffe/tools/extra/parse_log.py
#!/usr/bin/env python """ Parse training log Evolved from parse_log.sh """ import os import re import extract_seconds import argparse import csv from collections import OrderedDict def parse_log(path_to_log): """Parse log file Returns (train_dict_list, test_dict_list) train_dict_list and test_dict_list are lists of dicts that define the table rows """ regex_iteration = re.compile('Iteration (\d+)') regex_train_output = re.compile('Train net output #(\d+): (\S+) = ([\.\deE+-]+)') regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([\.\deE+-]+)') regex_learning_rate = re.compile('lr = ([-+]?[0-9]*\.?[0-9]+([eE]?[-+]?[0-9]+)?)') # Pick out lines of interest iteration = -1 learning_rate = float('NaN') train_dict_list = [] test_dict_list = [] train_row = None test_row = None logfile_year = extract_seconds.get_log_created_year(path_to_log) with open(path_to_log) as f: start_time = extract_seconds.get_start_time(f, logfile_year) last_time = start_time for line in f: iteration_match = regex_iteration.search(line) if iteration_match: iteration = float(iteration_match.group(1)) if iteration == -1: # Only start parsing for other stuff if we've found the first # iteration continue try: time = extract_seconds.extract_datetime_from_line(line, logfile_year) except ValueError: # Skip lines with bad formatting, for example when resuming solver continue # if it's another year if time.month < last_time.month: logfile_year += 1 time = extract_seconds.extract_datetime_from_line(line, logfile_year) last_time = time seconds = (time - start_time).total_seconds() learning_rate_match = regex_learning_rate.search(line) if learning_rate_match: learning_rate = float(learning_rate_match.group(1)) train_dict_list, train_row = parse_line_for_net_output( regex_train_output, train_row, train_dict_list, line, iteration, seconds, learning_rate ) test_dict_list, test_row = parse_line_for_net_output( regex_test_output, test_row, test_dict_list, line, iteration, seconds, learning_rate ) fix_initial_nan_learning_rate(train_dict_list) fix_initial_nan_learning_rate(test_dict_list) return train_dict_list, test_dict_list def parse_line_for_net_output(regex_obj, row, row_dict_list, line, iteration, seconds, learning_rate): """Parse a single line for training or test output Returns a a tuple with (row_dict_list, row) row: may be either a new row or an augmented version of the current row row_dict_list: may be either the current row_dict_list or an augmented version of the current row_dict_list """ output_match = regex_obj.search(line) if output_match: if not row or row['NumIters'] != iteration: # Push the last row and start a new one if row: # If we're on a new iteration, push the last row # This will probably only happen for the first row; otherwise # the full row checking logic below will push and clear full # rows row_dict_list.append(row) row = OrderedDict([ ('NumIters', iteration), ('Seconds', seconds), ('LearningRate', learning_rate) ]) # output_num is not used; may be used in the future # output_num = output_match.group(1) output_name = output_match.group(2) output_val = output_match.group(3) row[output_name] = float(output_val) if row and len(row_dict_list) >= 1 and len(row) == len(row_dict_list[0]): # The row is full, based on the fact that it has the same number of # columns as the first row; append it to the list row_dict_list.append(row) row = None return row_dict_list, row def fix_initial_nan_learning_rate(dict_list): """Correct initial value of learning rate Learning rate is normally not printed until after the initial test and training step, which means the initial testing and training rows have LearningRate = NaN. Fix this by copying over the LearningRate from the second row, if it exists. """ if len(dict_list) > 1: dict_list[0]['LearningRate'] = dict_list[1]['LearningRate'] def save_csv_files(logfile_path, output_dir, train_dict_list, test_dict_list, delimiter=',', verbose=False): """Save CSV files to output_dir If the input log file is, e.g., caffe.INFO, the names will be caffe.INFO.train and caffe.INFO.test """ log_basename = os.path.basename(logfile_path) train_filename = os.path.join(output_dir, log_basename + '.train') write_csv(train_filename, train_dict_list, delimiter, verbose) test_filename = os.path.join(output_dir, log_basename + '.test') write_csv(test_filename, test_dict_list, delimiter, verbose) def write_csv(output_filename, dict_list, delimiter, verbose=False): """Write a CSV file """ if not dict_list: if verbose: print('Not writing %s; no lines to write' % output_filename) return dialect = csv.excel dialect.delimiter = delimiter with open(output_filename, 'w') as f: dict_writer = csv.DictWriter(f, fieldnames=dict_list[0].keys(), dialect=dialect) dict_writer.writeheader() dict_writer.writerows(dict_list) if verbose: print 'Wrote %s' % output_filename def parse_args(): description = ('Parse a Caffe training log into two CSV files ' 'containing training and testing information') parser = argparse.ArgumentParser(description=description) parser.add_argument('logfile_path', help='Path to log file') parser.add_argument('output_dir', help='Directory in which to place output CSV files') parser.add_argument('--verbose', action='store_true', help='Print some extra info (e.g., output filenames)') parser.add_argument('--delimiter', default=',', help=('Column delimiter in output files ' '(default: \'%(default)s\')')) args = parser.parse_args() return args def main(): args = parse_args() train_dict_list, test_dict_list = parse_log(args.logfile_path) save_csv_files(args.logfile_path, args.output_dir, train_dict_list, test_dict_list, delimiter=args.delimiter) if __name__ == '__main__': main()
7,114
32.720379
86
py
bottom-up-attention
bottom-up-attention-master/caffe/examples/web_demo/app.py
import os import time import cPickle import datetime import logging import flask import werkzeug import optparse import tornado.wsgi import tornado.httpserver import numpy as np import pandas as pd from PIL import Image import cStringIO as StringIO import urllib import exifutil import caffe REPO_DIRNAME = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../..') UPLOAD_FOLDER = '/tmp/caffe_demos_uploads' ALLOWED_IMAGE_EXTENSIONS = set(['png', 'bmp', 'jpg', 'jpe', 'jpeg', 'gif']) # Obtain the flask app object app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('index.html', has_result=False) @app.route('/classify_url', methods=['GET']) def classify_url(): imageurl = flask.request.args.get('imageurl', '') try: string_buffer = StringIO.StringIO( urllib.urlopen(imageurl).read()) image = caffe.io.load_image(string_buffer) except Exception as err: # For any exception we encounter in reading the image, we will just # not continue. logging.info('URL Image open error: %s', err) return flask.render_template( 'index.html', has_result=True, result=(False, 'Cannot open image from URL.') ) logging.info('Image: %s', imageurl) result = app.clf.classify_image(image) return flask.render_template( 'index.html', has_result=True, result=result, imagesrc=imageurl) @app.route('/classify_upload', methods=['POST']) def classify_upload(): try: # We will save the file to disk for possible data collection. imagefile = flask.request.files['imagefile'] filename_ = str(datetime.datetime.now()).replace(' ', '_') + \ werkzeug.secure_filename(imagefile.filename) filename = os.path.join(UPLOAD_FOLDER, filename_) imagefile.save(filename) logging.info('Saving to %s.', filename) image = exifutil.open_oriented_im(filename) except Exception as err: logging.info('Uploaded image open error: %s', err) return flask.render_template( 'index.html', has_result=True, result=(False, 'Cannot open uploaded image.') ) result = app.clf.classify_image(image) return flask.render_template( 'index.html', has_result=True, result=result, imagesrc=embed_image_html(image) ) def embed_image_html(image): """Creates an image embedded in HTML base64 format.""" image_pil = Image.fromarray((255 * image).astype('uint8')) image_pil = image_pil.resize((256, 256)) string_buf = StringIO.StringIO() image_pil.save(string_buf, format='png') data = string_buf.getvalue().encode('base64').replace('\n', '') return 'data:image/png;base64,' + data def allowed_file(filename): return ( '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_IMAGE_EXTENSIONS ) class ImagenetClassifier(object): default_args = { 'model_def_file': ( '{}/models/bvlc_reference_caffenet/deploy.prototxt'.format(REPO_DIRNAME)), 'pretrained_model_file': ( '{}/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'.format(REPO_DIRNAME)), 'mean_file': ( '{}/python/caffe/imagenet/ilsvrc_2012_mean.npy'.format(REPO_DIRNAME)), 'class_labels_file': ( '{}/data/ilsvrc12/synset_words.txt'.format(REPO_DIRNAME)), 'bet_file': ( '{}/data/ilsvrc12/imagenet.bet.pickle'.format(REPO_DIRNAME)), } for key, val in default_args.iteritems(): if not os.path.exists(val): raise Exception( "File for {} is missing. Should be at: {}".format(key, val)) default_args['image_dim'] = 256 default_args['raw_scale'] = 255. def __init__(self, model_def_file, pretrained_model_file, mean_file, raw_scale, class_labels_file, bet_file, image_dim, gpu_mode): logging.info('Loading net and associated files...') if gpu_mode: caffe.set_mode_gpu() else: caffe.set_mode_cpu() self.net = caffe.Classifier( model_def_file, pretrained_model_file, image_dims=(image_dim, image_dim), raw_scale=raw_scale, mean=np.load(mean_file).mean(1).mean(1), channel_swap=(2, 1, 0) ) with open(class_labels_file) as f: labels_df = pd.DataFrame([ { 'synset_id': l.strip().split(' ')[0], 'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0] } for l in f.readlines() ]) self.labels = labels_df.sort('synset_id')['name'].values self.bet = cPickle.load(open(bet_file)) # A bias to prefer children nodes in single-chain paths # I am setting the value to 0.1 as a quick, simple model. # We could use better psychological models here... self.bet['infogain'] -= np.array(self.bet['preferences']) * 0.1 def classify_image(self, image): try: starttime = time.time() scores = self.net.predict([image], oversample=True).flatten() endtime = time.time() indices = (-scores).argsort()[:5] predictions = self.labels[indices] # In addition to the prediction text, we will also produce # the length for the progress bar visualization. meta = [ (p, '%.5f' % scores[i]) for i, p in zip(indices, predictions) ] logging.info('result: %s', str(meta)) # Compute expected information gain expected_infogain = np.dot( self.bet['probmat'], scores[self.bet['idmapping']]) expected_infogain *= self.bet['infogain'] # sort the scores infogain_sort = expected_infogain.argsort()[::-1] bet_result = [(self.bet['words'][v], '%.5f' % expected_infogain[v]) for v in infogain_sort[:5]] logging.info('bet result: %s', str(bet_result)) return (True, meta, bet_result, '%.3f' % (endtime - starttime)) except Exception as err: logging.info('Classification error: %s', err) return (False, 'Something went wrong when classifying the ' 'image. Maybe try another one?') def start_tornado(app, port=5000): http_server = tornado.httpserver.HTTPServer( tornado.wsgi.WSGIContainer(app)) http_server.listen(port) print("Tornado server starting on port {}".format(port)) tornado.ioloop.IOLoop.instance().start() def start_from_terminal(app): """ Parse command line options and start the server. """ parser = optparse.OptionParser() parser.add_option( '-d', '--debug', help="enable debug mode", action="store_true", default=False) parser.add_option( '-p', '--port', help="which port to serve content on", type='int', default=5000) parser.add_option( '-g', '--gpu', help="use gpu mode", action='store_true', default=False) opts, args = parser.parse_args() ImagenetClassifier.default_args.update({'gpu_mode': opts.gpu}) # Initialize classifier + warm start by forward for allocation app.clf = ImagenetClassifier(**ImagenetClassifier.default_args) app.clf.net.forward() if opts.debug: app.run(debug=True, host='0.0.0.0', port=opts.port) else: start_tornado(app, opts.port) if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) start_from_terminal(app)
7,793
33.184211
105
py
bottom-up-attention
bottom-up-attention-master/caffe/examples/web_demo/exifutil.py
""" This script handles the skimage exif problem. """ from PIL import Image import numpy as np ORIENTATIONS = { # used in apply_orientation 2: (Image.FLIP_LEFT_RIGHT,), 3: (Image.ROTATE_180,), 4: (Image.FLIP_TOP_BOTTOM,), 5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90), 6: (Image.ROTATE_270,), 7: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_270), 8: (Image.ROTATE_90,) } def open_oriented_im(im_path): im = Image.open(im_path) if hasattr(im, '_getexif'): exif = im._getexif() if exif is not None and 274 in exif: orientation = exif[274] im = apply_orientation(im, orientation) img = np.asarray(im).astype(np.float32) / 255. if img.ndim == 2: img = img[:, :, np.newaxis] img = np.tile(img, (1, 1, 3)) elif img.shape[2] == 4: img = img[:, :, :3] return img def apply_orientation(im, orientation): if orientation in ORIENTATIONS: for method in ORIENTATIONS[orientation]: im = im.transpose(method) return im
1,046
25.175
51
py
bottom-up-attention
bottom-up-attention-master/caffe/examples/pycaffe/caffenet.py
from __future__ import print_function from caffe import layers as L, params as P, to_proto from caffe.proto import caffe_pb2 # helper function for common structures def conv_relu(bottom, ks, nout, stride=1, pad=0, group=1): conv = L.Convolution(bottom, kernel_size=ks, stride=stride, num_output=nout, pad=pad, group=group) return conv, L.ReLU(conv, in_place=True) def fc_relu(bottom, nout): fc = L.InnerProduct(bottom, num_output=nout) return fc, L.ReLU(fc, in_place=True) def max_pool(bottom, ks, stride=1): return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride) def caffenet(lmdb, batch_size=256, include_acc=False): data, label = L.Data(source=lmdb, backend=P.Data.LMDB, batch_size=batch_size, ntop=2, transform_param=dict(crop_size=227, mean_value=[104, 117, 123], mirror=True)) # the net itself conv1, relu1 = conv_relu(data, 11, 96, stride=4) pool1 = max_pool(relu1, 3, stride=2) norm1 = L.LRN(pool1, local_size=5, alpha=1e-4, beta=0.75) conv2, relu2 = conv_relu(norm1, 5, 256, pad=2, group=2) pool2 = max_pool(relu2, 3, stride=2) norm2 = L.LRN(pool2, local_size=5, alpha=1e-4, beta=0.75) conv3, relu3 = conv_relu(norm2, 3, 384, pad=1) conv4, relu4 = conv_relu(relu3, 3, 384, pad=1, group=2) conv5, relu5 = conv_relu(relu4, 3, 256, pad=1, group=2) pool5 = max_pool(relu5, 3, stride=2) fc6, relu6 = fc_relu(pool5, 4096) drop6 = L.Dropout(relu6, in_place=True) fc7, relu7 = fc_relu(drop6, 4096) drop7 = L.Dropout(relu7, in_place=True) fc8 = L.InnerProduct(drop7, num_output=1000) loss = L.SoftmaxWithLoss(fc8, label) if include_acc: acc = L.Accuracy(fc8, label) return to_proto(loss, acc) else: return to_proto(loss) def make_net(): with open('train.prototxt', 'w') as f: print(caffenet('/path/to/caffe-train-lmdb'), file=f) with open('test.prototxt', 'w') as f: print(caffenet('/path/to/caffe-val-lmdb', batch_size=50, include_acc=True), file=f) if __name__ == '__main__': make_net()
2,112
36.732143
91
py
bottom-up-attention
bottom-up-attention-master/caffe/examples/pycaffe/tools.py
import numpy as np class SimpleTransformer: """ SimpleTransformer is a simple class for preprocessing and deprocessing images for caffe. """ def __init__(self, mean=[128, 128, 128]): self.mean = np.array(mean, dtype=np.float32) self.scale = 1.0 def set_mean(self, mean): """ Set the mean to subtract for centering the data. """ self.mean = mean def set_scale(self, scale): """ Set the data scaling. """ self.scale = scale def preprocess(self, im): """ preprocess() emulate the pre-processing occurring in the vgg16 caffe prototxt. """ im = np.float32(im) im = im[:, :, ::-1] # change to BGR im -= self.mean im *= self.scale im = im.transpose((2, 0, 1)) return im def deprocess(self, im): """ inverse of preprocess() """ im = im.transpose(1, 2, 0) im /= self.scale im += self.mean im = im[:, :, ::-1] # change to RGB return np.uint8(im) class CaffeSolver: """ Caffesolver is a class for creating a solver.prototxt file. It sets default values and can export a solver parameter file. Note that all parameters are stored as strings. Strings variables are stored as strings in strings. """ def __init__(self, testnet_prototxt_path="testnet.prototxt", trainnet_prototxt_path="trainnet.prototxt", debug=False): self.sp = {} # critical: self.sp['base_lr'] = '0.001' self.sp['momentum'] = '0.9' # speed: self.sp['test_iter'] = '100' self.sp['test_interval'] = '250' # looks: self.sp['display'] = '25' self.sp['snapshot'] = '2500' self.sp['snapshot_prefix'] = '"snapshot"' # string within a string! # learning rate policy self.sp['lr_policy'] = '"fixed"' # important, but rare: self.sp['gamma'] = '0.1' self.sp['weight_decay'] = '0.0005' self.sp['train_net'] = '"' + trainnet_prototxt_path + '"' self.sp['test_net'] = '"' + testnet_prototxt_path + '"' # pretty much never change these. self.sp['max_iter'] = '100000' self.sp['test_initialization'] = 'false' self.sp['average_loss'] = '25' # this has to do with the display. self.sp['iter_size'] = '1' # this is for accumulating gradients if (debug): self.sp['max_iter'] = '12' self.sp['test_iter'] = '1' self.sp['test_interval'] = '4' self.sp['display'] = '1' def add_from_file(self, filepath): """ Reads a caffe solver prototxt file and updates the Caffesolver instance parameters. """ with open(filepath, 'r') as f: for line in f: if line[0] == '#': continue splitLine = line.split(':') self.sp[splitLine[0].strip()] = splitLine[1].strip() def write(self, filepath): """ Export solver parameters to INPUT "filepath". Sorted alphabetically. """ f = open(filepath, 'w') for key, value in sorted(self.sp.items()): if not(type(value) is str): raise TypeError('All solver parameters must be strings') f.write('%s: %s\n' % (key, value))
3,457
27.344262
79
py
bottom-up-attention
bottom-up-attention-master/caffe/examples/pycaffe/layers/pascal_multilabel_datalayers.py
# imports import json import time import pickle import scipy.misc import skimage.io import caffe import numpy as np import os.path as osp from xml.dom import minidom from random import shuffle from threading import Thread from PIL import Image from tools import SimpleTransformer class PascalMultilabelDataLayerSync(caffe.Layer): """ This is a simple synchronous datalayer for training a multilabel model on PASCAL. """ def setup(self, bottom, top): self.top_names = ['data', 'label'] # === Read input parameters === # params is a python dictionary with layer parameters. params = eval(self.param_str) # Check the parameters for validity. check_params(params) # store input as class variables self.batch_size = params['batch_size'] # Create a batch loader to load the images. self.batch_loader = BatchLoader(params, None) # === reshape tops === # since we use a fixed input image size, we can shape the data layer # once. Else, we'd have to do it in the reshape call. top[0].reshape( self.batch_size, 3, params['im_shape'][0], params['im_shape'][1]) # Note the 20 channels (because PASCAL has 20 classes.) top[1].reshape(self.batch_size, 20) print_info("PascalMultilabelDataLayerSync", params) def forward(self, bottom, top): """ Load data. """ for itt in range(self.batch_size): # Use the batch loader to load the next image. im, multilabel = self.batch_loader.load_next_image() # Add directly to the caffe data layer top[0].data[itt, ...] = im top[1].data[itt, ...] = multilabel def reshape(self, bottom, top): """ There is no need to reshape the data, since the input is of fixed size (rows and columns) """ pass def backward(self, top, propagate_down, bottom): """ These layers does not back propagate """ pass class BatchLoader(object): """ This class abstracts away the loading of images. Images can either be loaded singly, or in a batch. The latter is used for the asyncronous data layer to preload batches while other processing is performed. """ def __init__(self, params, result): self.result = result self.batch_size = params['batch_size'] self.pascal_root = params['pascal_root'] self.im_shape = params['im_shape'] # get list of image indexes. list_file = params['split'] + '.txt' self.indexlist = [line.rstrip('\n') for line in open( osp.join(self.pascal_root, 'ImageSets/Main', list_file))] self._cur = 0 # current image # this class does some simple data-manipulations self.transformer = SimpleTransformer() print "BatchLoader initialized with {} images".format( len(self.indexlist)) def load_next_image(self): """ Load the next image in a batch. """ # Did we finish an epoch? if self._cur == len(self.indexlist): self._cur = 0 shuffle(self.indexlist) # Load an image index = self.indexlist[self._cur] # Get the image index image_file_name = index + '.jpg' im = np.asarray(Image.open( osp.join(self.pascal_root, 'JPEGImages', image_file_name))) im = scipy.misc.imresize(im, self.im_shape) # resize # do a simple horizontal flip as data augmentation flip = np.random.choice(2)*2-1 im = im[:, ::flip, :] # Load and prepare ground truth multilabel = np.zeros(20).astype(np.float32) anns = load_pascal_annotation(index, self.pascal_root) for label in anns['gt_classes']: # in the multilabel problem we don't care how MANY instances # there are of each class. Only if they are present. # The "-1" is b/c we are not interested in the background # class. multilabel[label - 1] = 1 self._cur += 1 return self.transformer.preprocess(im), multilabel def load_pascal_annotation(index, pascal_root): """ This code is borrowed from Ross Girshick's FAST-RCNN code (https://github.com/rbgirshick/fast-rcnn). It parses the PASCAL .xml metadata files. See publication for further details: (http://arxiv.org/abs/1504.08083). Thanks Ross! """ classes = ('__background__', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') class_to_ind = dict(zip(classes, xrange(21))) filename = osp.join(pascal_root, 'Annotations', index + '.xml') # print 'Loading: {}'.format(filename) def get_data_from_tag(node, tag): return node.getElementsByTagName(tag)[0].childNodes[0].data with open(filename) as f: data = minidom.parseString(f.read()) objs = data.getElementsByTagName('object') num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, 21), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): # Make pixel indexes 0-based x1 = float(get_data_from_tag(obj, 'xmin')) - 1 y1 = float(get_data_from_tag(obj, 'ymin')) - 1 x2 = float(get_data_from_tag(obj, 'xmax')) - 1 y2 = float(get_data_from_tag(obj, 'ymax')) - 1 cls = class_to_ind[ str(get_data_from_tag(obj, "name")).lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'index': index} def check_params(params): """ A utility function to check the parameters for the data layers. """ assert 'split' in params.keys( ), 'Params must include split (train, val, or test).' required = ['batch_size', 'pascal_root', 'im_shape'] for r in required: assert r in params.keys(), 'Params must include {}'.format(r) def print_info(name, params): """ Output some info regarding the class """ print "{} initialized for split: {}, with bs: {}, im_shape: {}.".format( name, params['split'], params['batch_size'], params['im_shape'])
6,846
30.552995
78
py
bottom-up-attention
bottom-up-attention-master/caffe/examples/pycaffe/layers/pyloss.py
import caffe import numpy as np class EuclideanLossLayer(caffe.Layer): """ Compute the Euclidean Loss in the same manner as the C++ EuclideanLossLayer to demonstrate the class interface for developing layers in Python. """ def setup(self, bottom, top): # check input pair if len(bottom) != 2: raise Exception("Need two inputs to compute distance.") def reshape(self, bottom, top): # check input dimensions match if bottom[0].count != bottom[1].count: raise Exception("Inputs must have the same dimension.") # difference is shape of inputs self.diff = np.zeros_like(bottom[0].data, dtype=np.float32) # loss output is scalar top[0].reshape(1) def forward(self, bottom, top): self.diff[...] = bottom[0].data - bottom[1].data top[0].data[...] = np.sum(self.diff**2) / bottom[0].num / 2. def backward(self, top, propagate_down, bottom): for i in range(2): if not propagate_down[i]: continue if i == 0: sign = 1 else: sign = -1 bottom[i].diff[...] = sign * self.diff / bottom[i].num
1,223
31.210526
79
py
bottom-up-attention
bottom-up-attention-master/caffe/examples/finetune_flickr_style/assemble_data.py
#!/usr/bin/env python """ Form a subset of the Flickr Style data, download images to dirname, and write Caffe ImagesDataLayer training file. """ import os import urllib import hashlib import argparse import numpy as np import pandas as pd from skimage import io import multiprocessing # Flickr returns a special image if the request is unavailable. MISSING_IMAGE_SHA1 = '6a92790b1c2a301c6e7ddef645dca1f53ea97ac2' example_dirname = os.path.abspath(os.path.dirname(__file__)) caffe_dirname = os.path.abspath(os.path.join(example_dirname, '../..')) training_dirname = os.path.join(caffe_dirname, 'data/flickr_style') def download_image(args_tuple): "For use with multiprocessing map. Returns filename on fail." try: url, filename = args_tuple if not os.path.exists(filename): urllib.urlretrieve(url, filename) with open(filename) as f: assert hashlib.sha1(f.read()).hexdigest() != MISSING_IMAGE_SHA1 test_read_image = io.imread(filename) return True except KeyboardInterrupt: raise Exception() # multiprocessing doesn't catch keyboard exceptions except: return False if __name__ == '__main__': parser = argparse.ArgumentParser( description='Download a subset of Flickr Style to a directory') parser.add_argument( '-s', '--seed', type=int, default=0, help="random seed") parser.add_argument( '-i', '--images', type=int, default=-1, help="number of images to use (-1 for all [default])", ) parser.add_argument( '-w', '--workers', type=int, default=-1, help="num workers used to download images. -x uses (all - x) cores [-1 default]." ) parser.add_argument( '-l', '--labels', type=int, default=0, help="if set to a positive value, only sample images from the first number of labels." ) args = parser.parse_args() np.random.seed(args.seed) # Read data, shuffle order, and subsample. csv_filename = os.path.join(example_dirname, 'flickr_style.csv.gz') df = pd.read_csv(csv_filename, index_col=0, compression='gzip') df = df.iloc[np.random.permutation(df.shape[0])] if args.labels > 0: df = df.loc[df['label'] < args.labels] if args.images > 0 and args.images < df.shape[0]: df = df.iloc[:args.images] # Make directory for images and get local filenames. if training_dirname is None: training_dirname = os.path.join(caffe_dirname, 'data/flickr_style') images_dirname = os.path.join(training_dirname, 'images') if not os.path.exists(images_dirname): os.makedirs(images_dirname) df['image_filename'] = [ os.path.join(images_dirname, _.split('/')[-1]) for _ in df['image_url'] ] # Download images. num_workers = args.workers if num_workers <= 0: num_workers = multiprocessing.cpu_count() + num_workers print('Downloading {} images with {} workers...'.format( df.shape[0], num_workers)) pool = multiprocessing.Pool(processes=num_workers) map_args = zip(df['image_url'], df['image_filename']) results = pool.map(download_image, map_args) # Only keep rows with valid images, and write out training file lists. df = df[results] for split in ['train', 'test']: split_df = df[df['_split'] == split] filename = os.path.join(training_dirname, '{}.txt'.format(split)) split_df[['image_filename', 'label']].to_csv( filename, sep=' ', header=None, index=None) print('Writing train/val for {} successfully downloaded images.'.format( df.shape[0]))
3,636
35.737374
94
py
bottom-up-attention
bottom-up-attention-master/caffe/src/caffe/test/test_data/generate_sample_data.py
""" Generate data used in the HDF5DataLayer and GradientBasedSolver tests. """ import os import numpy as np import h5py script_dir = os.path.dirname(os.path.abspath(__file__)) # Generate HDF5DataLayer sample_data.h5 num_cols = 8 num_rows = 10 height = 6 width = 5 total_size = num_cols * num_rows * height * width data = np.arange(total_size) data = data.reshape(num_rows, num_cols, height, width) data = data.astype('float32') # We had a bug where data was copied into label, but the tests weren't # catching it, so let's make label 1-indexed. label = 1 + np.arange(num_rows)[:, np.newaxis] label = label.astype('float32') # We add an extra label2 dataset to test HDF5 layer's ability # to handle arbitrary number of output ("top") Blobs. label2 = label + 1 print data print label with h5py.File(script_dir + '/sample_data.h5', 'w') as f: f['data'] = data f['label'] = label f['label2'] = label2 with h5py.File(script_dir + '/sample_data_2_gzip.h5', 'w') as f: f.create_dataset( 'data', data=data + total_size, compression='gzip', compression_opts=1 ) f.create_dataset( 'label', data=label, compression='gzip', compression_opts=1, dtype='uint8', ) f.create_dataset( 'label2', data=label2, compression='gzip', compression_opts=1, dtype='uint8', ) with open(script_dir + '/sample_data_list.txt', 'w') as f: f.write('src/caffe/test/test_data/sample_data.h5\n') f.write('src/caffe/test/test_data/sample_data_2_gzip.h5\n') # Generate GradientBasedSolver solver_data.h5 num_cols = 3 num_rows = 8 height = 10 width = 10 data = np.random.randn(num_rows, num_cols, height, width) data = data.reshape(num_rows, num_cols, height, width) data = data.astype('float32') targets = np.random.randn(num_rows, 1) targets = targets.astype('float32') print data print targets with h5py.File(script_dir + '/solver_data.h5', 'w') as f: f['data'] = data f['targets'] = targets with open(script_dir + '/solver_data_list.txt', 'w') as f: f.write('src/caffe/test/test_data/solver_data.h5\n')
2,104
24.670732
70
py
bottom-up-attention
bottom-up-attention-master/caffe/python/draw_net.py
#!/usr/bin/env python """ Draw a graph of the net architecture. """ from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from google.protobuf import text_format import caffe import caffe.draw from caffe.proto import caffe_pb2 def parse_args(): """Parse input arguments """ parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('input_net_proto_file', help='Input network prototxt file') parser.add_argument('output_image_file', help='Output image file') parser.add_argument('--rankdir', help=('One of TB (top-bottom, i.e., vertical), ' 'RL (right-left, i.e., horizontal), or another ' 'valid dot option; see ' 'http://www.graphviz.org/doc/info/' 'attrs.html#k:rankdir'), default='LR') parser.add_argument('--phase', help=('Which network phase to draw: can be TRAIN, ' 'TEST, or ALL. If ALL, then all layers are drawn ' 'regardless of phase.'), default="ALL") args = parser.parse_args() return args def main(): args = parse_args() net = caffe_pb2.NetParameter() text_format.Merge(open(args.input_net_proto_file).read(), net) print('Drawing net to %s' % args.output_image_file) phase=None; if args.phase == "TRAIN": phase = caffe.TRAIN elif args.phase == "TEST": phase = caffe.TEST elif args.phase != "ALL": raise ValueError("Unknown phase: " + args.phase) caffe.draw.draw_net_to_file(net, args.output_image_file, args.rankdir, phase) if __name__ == '__main__': main()
1,934
31.79661
81
py
bottom-up-attention
bottom-up-attention-master/caffe/python/detect.py
#!/usr/bin/env python """ detector.py is an out-of-the-box windowed detector callable from the command line. By default it configures and runs the Caffe reference ImageNet model. Note that this model was trained for image classification and not detection, and finetuning for detection can be expected to improve results. The selective_search_ijcv_with_python code required for the selective search proposal mode is available at https://github.com/sergeyk/selective_search_ijcv_with_python TODO: - batch up image filenames as well: don't want to load all of them into memory - come up with a batching scheme that preserved order / keeps a unique ID """ import numpy as np import pandas as pd import os import argparse import time import caffe CROP_MODES = ['list', 'selective_search'] COORD_COLS = ['ymin', 'xmin', 'ymax', 'xmax'] def main(argv): pycaffe_dir = os.path.dirname(__file__) parser = argparse.ArgumentParser() # Required arguments: input and output. parser.add_argument( "input_file", help="Input txt/csv filename. If .txt, must be list of filenames.\ If .csv, must be comma-separated file with header\ 'filename, xmin, ymin, xmax, ymax'" ) parser.add_argument( "output_file", help="Output h5/csv filename. Format depends on extension." ) # Optional arguments. parser.add_argument( "--model_def", default=os.path.join(pycaffe_dir, "../models/bvlc_reference_caffenet/deploy.prototxt"), help="Model definition file." ) parser.add_argument( "--pretrained_model", default=os.path.join(pycaffe_dir, "../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel"), help="Trained model weights file." ) parser.add_argument( "--crop_mode", default="selective_search", choices=CROP_MODES, help="How to generate windows for detection." ) parser.add_argument( "--gpu", action='store_true', help="Switch for gpu computation." ) parser.add_argument( "--mean_file", default=os.path.join(pycaffe_dir, 'caffe/imagenet/ilsvrc_2012_mean.npy'), help="Data set image mean of H x W x K dimensions (numpy array). " + "Set to '' for no mean subtraction." ) parser.add_argument( "--input_scale", type=float, help="Multiply input features by this scale to finish preprocessing." ) parser.add_argument( "--raw_scale", type=float, default=255.0, help="Multiply raw input by this scale before preprocessing." ) parser.add_argument( "--channel_swap", default='2,1,0', help="Order to permute input channels. The default converts " + "RGB -> BGR since BGR is the Caffe default by way of OpenCV." ) parser.add_argument( "--context_pad", type=int, default='16', help="Amount of surrounding context to collect in input window." ) args = parser.parse_args() mean, channel_swap = None, None if args.mean_file: mean = np.load(args.mean_file) if mean.shape[1:] != (1, 1): mean = mean.mean(1).mean(1) if args.channel_swap: channel_swap = [int(s) for s in args.channel_swap.split(',')] if args.gpu: caffe.set_mode_gpu() print("GPU mode") else: caffe.set_mode_cpu() print("CPU mode") # Make detector. detector = caffe.Detector(args.model_def, args.pretrained_model, mean=mean, input_scale=args.input_scale, raw_scale=args.raw_scale, channel_swap=channel_swap, context_pad=args.context_pad) # Load input. t = time.time() print("Loading input...") if args.input_file.lower().endswith('txt'): with open(args.input_file) as f: inputs = [_.strip() for _ in f.readlines()] elif args.input_file.lower().endswith('csv'): inputs = pd.read_csv(args.input_file, sep=',', dtype={'filename': str}) inputs.set_index('filename', inplace=True) else: raise Exception("Unknown input file type: not in txt or csv.") # Detect. if args.crop_mode == 'list': # Unpack sequence of (image filename, windows). images_windows = [ (ix, inputs.iloc[np.where(inputs.index == ix)][COORD_COLS].values) for ix in inputs.index.unique() ] detections = detector.detect_windows(images_windows) else: detections = detector.detect_selective_search(inputs) print("Processed {} windows in {:.3f} s.".format(len(detections), time.time() - t)) # Collect into dataframe with labeled fields. df = pd.DataFrame(detections) df.set_index('filename', inplace=True) df[COORD_COLS] = pd.DataFrame( data=np.vstack(df['window']), index=df.index, columns=COORD_COLS) del(df['window']) # Save results. t = time.time() if args.output_file.lower().endswith('csv'): # csv # Enumerate the class probabilities. class_cols = ['class{}'.format(x) for x in range(NUM_OUTPUT)] df[class_cols] = pd.DataFrame( data=np.vstack(df['feat']), index=df.index, columns=class_cols) df.to_csv(args.output_file, cols=COORD_COLS + class_cols) else: # h5 df.to_hdf(args.output_file, 'df', mode='w') print("Saved to {} in {:.3f} s.".format(args.output_file, time.time() - t)) if __name__ == "__main__": import sys main(sys.argv)
5,734
31.95977
88
py
bottom-up-attention
bottom-up-attention-master/caffe/python/classify.py
#!/usr/bin/env python """ classify.py is an out-of-the-box image classifer callable from the command line. By default it configures and runs the Caffe reference ImageNet model. """ import numpy as np import os import sys import argparse import glob import time import caffe def main(argv): pycaffe_dir = os.path.dirname(__file__) parser = argparse.ArgumentParser() # Required arguments: input and output files. parser.add_argument( "input_file", help="Input image, directory, or npy." ) parser.add_argument( "output_file", help="Output npy filename." ) # Optional arguments. parser.add_argument( "--model_def", default=os.path.join(pycaffe_dir, "../models/bvlc_reference_caffenet/deploy.prototxt"), help="Model definition file." ) parser.add_argument( "--pretrained_model", default=os.path.join(pycaffe_dir, "../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel"), help="Trained model weights file." ) parser.add_argument( "--gpu", action='store_true', help="Switch for gpu computation." ) parser.add_argument( "--center_only", action='store_true', help="Switch for prediction from center crop alone instead of " + "averaging predictions across crops (default)." ) parser.add_argument( "--images_dim", default='256,256', help="Canonical 'height,width' dimensions of input images." ) parser.add_argument( "--mean_file", default=os.path.join(pycaffe_dir, 'caffe/imagenet/ilsvrc_2012_mean.npy'), help="Data set image mean of [Channels x Height x Width] dimensions " + "(numpy array). Set to '' for no mean subtraction." ) parser.add_argument( "--input_scale", type=float, help="Multiply input features by this scale to finish preprocessing." ) parser.add_argument( "--raw_scale", type=float, default=255.0, help="Multiply raw input by this scale before preprocessing." ) parser.add_argument( "--channel_swap", default='2,1,0', help="Order to permute input channels. The default converts " + "RGB -> BGR since BGR is the Caffe default by way of OpenCV." ) parser.add_argument( "--ext", default='jpg', help="Image file extension to take as input when a directory " + "is given as the input file." ) args = parser.parse_args() image_dims = [int(s) for s in args.images_dim.split(',')] mean, channel_swap = None, None if args.mean_file: mean = np.load(args.mean_file) if args.channel_swap: channel_swap = [int(s) for s in args.channel_swap.split(',')] if args.gpu: caffe.set_mode_gpu() print("GPU mode") else: caffe.set_mode_cpu() print("CPU mode") # Make classifier. classifier = caffe.Classifier(args.model_def, args.pretrained_model, image_dims=image_dims, mean=mean, input_scale=args.input_scale, raw_scale=args.raw_scale, channel_swap=channel_swap) # Load numpy array (.npy), directory glob (*.jpg), or image file. args.input_file = os.path.expanduser(args.input_file) if args.input_file.endswith('npy'): print("Loading file: %s" % args.input_file) inputs = np.load(args.input_file) elif os.path.isdir(args.input_file): print("Loading folder: %s" % args.input_file) inputs =[caffe.io.load_image(im_f) for im_f in glob.glob(args.input_file + '/*.' + args.ext)] else: print("Loading file: %s" % args.input_file) inputs = [caffe.io.load_image(args.input_file)] print("Classifying %d inputs." % len(inputs)) # Classify. start = time.time() predictions = classifier.predict(inputs, not args.center_only) print("Done in %.2f s." % (time.time() - start)) # Save print("Saving results into %s" % args.output_file) np.save(args.output_file, predictions) if __name__ == '__main__': main(sys.argv)
4,262
29.669065
88
py
bottom-up-attention
bottom-up-attention-master/caffe/python/train.py
#!/usr/bin/env python """ Trains a model using one or more GPUs. """ from multiprocessing import Process import caffe def train( solver, # solver proto definition snapshot, # solver snapshot to restore gpus, # list of device ids timing=False, # show timing info for compute and communications ): # NCCL uses a uid to identify a session uid = caffe.NCCL.new_uid() caffe.init_log() caffe.log('Using devices %s' % str(gpus)) procs = [] for rank in range(len(gpus)): p = Process(target=solve, args=(solver, snapshot, gpus, timing, uid, rank)) p.daemon = True p.start() procs.append(p) for p in procs: p.join() def time(solver, nccl): fprop = [] bprop = [] total = caffe.Timer() allrd = caffe.Timer() for _ in range(len(solver.net.layers)): fprop.append(caffe.Timer()) bprop.append(caffe.Timer()) display = solver.param.display def show_time(): if solver.iter % display == 0: s = '\n' for i in range(len(solver.net.layers)): s += 'forw %3d %8s ' % (i, solver.net._layer_names[i]) s += ': %.2f\n' % fprop[i].ms for i in range(len(solver.net.layers) - 1, -1, -1): s += 'back %3d %8s ' % (i, solver.net._layer_names[i]) s += ': %.2f\n' % bprop[i].ms s += 'solver total: %.2f\n' % total.ms s += 'allreduce: %.2f\n' % allrd.ms caffe.log(s) solver.net.before_forward(lambda layer: fprop[layer].start()) solver.net.after_forward(lambda layer: fprop[layer].stop()) solver.net.before_backward(lambda layer: bprop[layer].start()) solver.net.after_backward(lambda layer: bprop[layer].stop()) solver.add_callback(lambda: total.start(), lambda: (total.stop(), allrd.start())) solver.add_callback(nccl) solver.add_callback(lambda: '', lambda: (allrd.stop(), show_time())) def solve(proto, snapshot, gpus, timing, uid, rank): caffe.set_mode_gpu() caffe.set_device(gpus[rank]) caffe.set_solver_count(len(gpus)) caffe.set_solver_rank(rank) caffe.set_multiprocess(True) solver = caffe.SGDSolver(proto) if snapshot and len(snapshot) != 0: solver.restore(snapshot) nccl = caffe.NCCL(solver, uid) nccl.bcast() if timing and rank == 0: time(solver, nccl) else: solver.add_callback(nccl) if solver.param.layer_wise_reduce: solver.net.after_backward(nccl) solver.step(solver.param.max_iter) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("--solver", required=True, help="Solver proto definition.") parser.add_argument("--snapshot", help="Solver snapshot to restore.") parser.add_argument("--gpus", type=int, nargs='+', default=[0], help="List of device ids.") parser.add_argument("--timing", action='store_true', help="Show timing info.") args = parser.parse_args() train(args.solver, args.snapshot, args.gpus, args.timing)
3,145
30.148515
85
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/net_spec.py
"""Python net specification. This module provides a way to write nets directly in Python, using a natural, functional style. See examples/pycaffe/caffenet.py for an example. Currently this works as a thin wrapper around the Python protobuf interface, with layers and parameters automatically generated for the "layers" and "params" pseudo-modules, which are actually objects using __getattr__ magic to generate protobuf messages. Note that when using to_proto or Top.to_proto, names of intermediate blobs will be automatically generated. To explicitly specify blob names, use the NetSpec class -- assign to its attributes directly to name layers, and call NetSpec.to_proto to serialize all assigned layers. This interface is expected to continue to evolve as Caffe gains new capabilities for specifying nets. In particular, the automatically generated layer names are not guaranteed to be forward-compatible. """ from collections import OrderedDict, Counter from .proto import caffe_pb2 from google import protobuf import six def param_name_dict(): """Find out the correspondence between layer names and parameter names.""" layer = caffe_pb2.LayerParameter() # get all parameter names (typically underscore case) and corresponding # type names (typically camel case), which contain the layer names # (note that not all parameters correspond to layers, but we'll ignore that) param_names = [f.name for f in layer.DESCRIPTOR.fields if f.name.endswith('_param')] param_type_names = [type(getattr(layer, s)).__name__ for s in param_names] # strip the final '_param' or 'Parameter' param_names = [s[:-len('_param')] for s in param_names] param_type_names = [s[:-len('Parameter')] for s in param_type_names] return dict(zip(param_type_names, param_names)) def to_proto(*tops): """Generate a NetParameter that contains all layers needed to compute all arguments.""" layers = OrderedDict() autonames = Counter() for top in tops: top.fn._to_proto(layers, {}, autonames) net = caffe_pb2.NetParameter() net.layer.extend(layers.values()) return net def assign_proto(proto, name, val): """Assign a Python object to a protobuf message, based on the Python type (in recursive fashion). Lists become repeated fields/messages, dicts become messages, and other types are assigned directly. For convenience, repeated fields whose values are not lists are converted to single-element lists; e.g., `my_repeated_int_field=3` is converted to `my_repeated_int_field=[3]`.""" is_repeated_field = hasattr(getattr(proto, name), 'extend') if is_repeated_field and not isinstance(val, list): val = [val] if isinstance(val, list): if isinstance(val[0], dict): for item in val: proto_item = getattr(proto, name).add() for k, v in six.iteritems(item): assign_proto(proto_item, k, v) else: getattr(proto, name).extend(val) elif isinstance(val, dict): for k, v in six.iteritems(val): assign_proto(getattr(proto, name), k, v) else: setattr(proto, name, val) class Top(object): """A Top specifies a single output blob (which could be one of several produced by a layer.)""" def __init__(self, fn, n): self.fn = fn self.n = n def to_proto(self): """Generate a NetParameter that contains all layers needed to compute this top.""" return to_proto(self) def _to_proto(self, layers, names, autonames): return self.fn._to_proto(layers, names, autonames) class Function(object): """A Function specifies a layer, its parameters, and its inputs (which are Tops from other layers).""" def __init__(self, type_name, inputs, params): self.type_name = type_name self.inputs = inputs self.params = params self.ntop = self.params.get('ntop', 1) # use del to make sure kwargs are not double-processed as layer params if 'ntop' in self.params: del self.params['ntop'] self.in_place = self.params.get('in_place', False) if 'in_place' in self.params: del self.params['in_place'] self.tops = tuple(Top(self, n) for n in range(self.ntop)) def _get_name(self, names, autonames): if self not in names and self.ntop > 0: names[self] = self._get_top_name(self.tops[0], names, autonames) elif self not in names: autonames[self.type_name] += 1 names[self] = self.type_name + str(autonames[self.type_name]) return names[self] def _get_top_name(self, top, names, autonames): if top not in names: autonames[top.fn.type_name] += 1 names[top] = top.fn.type_name + str(autonames[top.fn.type_name]) return names[top] def _to_proto(self, layers, names, autonames): if self in layers: return bottom_names = [] for inp in self.inputs: inp._to_proto(layers, names, autonames) bottom_names.append(layers[inp.fn].top[inp.n]) layer = caffe_pb2.LayerParameter() layer.type = self.type_name layer.bottom.extend(bottom_names) if self.in_place: layer.top.extend(layer.bottom) else: for top in self.tops: layer.top.append(self._get_top_name(top, names, autonames)) layer.name = self._get_name(names, autonames) for k, v in six.iteritems(self.params): # special case to handle generic *params if k.endswith('param'): assign_proto(layer, k, v) else: try: assign_proto(getattr(layer, _param_names[self.type_name] + '_param'), k, v) except (AttributeError, KeyError): assign_proto(layer, k, v) layers[self] = layer class NetSpec(object): """A NetSpec contains a set of Tops (assigned directly as attributes). Calling NetSpec.to_proto generates a NetParameter containing all of the layers needed to produce all of the assigned Tops, using the assigned names.""" def __init__(self): super(NetSpec, self).__setattr__('tops', OrderedDict()) def __setattr__(self, name, value): self.tops[name] = value def __getattr__(self, name): return self.tops[name] def __setitem__(self, key, value): self.__setattr__(key, value) def __getitem__(self, item): return self.__getattr__(item) def to_proto(self): names = {v: k for k, v in six.iteritems(self.tops)} autonames = Counter() layers = OrderedDict() for name, top in six.iteritems(self.tops): top._to_proto(layers, names, autonames) net = caffe_pb2.NetParameter() net.layer.extend(layers.values()) return net class Layers(object): """A Layers object is a pseudo-module which generates functions that specify layers; e.g., Layers().Convolution(bottom, kernel_size=3) will produce a Top specifying a 3x3 convolution applied to bottom.""" def __getattr__(self, name): def layer_fn(*args, **kwargs): fn = Function(name, args, kwargs) if fn.ntop == 0: return fn elif fn.ntop == 1: return fn.tops[0] else: return fn.tops return layer_fn class Parameters(object): """A Parameters object is a pseudo-module which generates constants used in layer parameters; e.g., Parameters().Pooling.MAX is the value used to specify max pooling.""" def __getattr__(self, name): class Param: def __getattr__(self, param_name): return getattr(getattr(caffe_pb2, name + 'Parameter'), param_name) return Param() _param_names = param_name_dict() layers = Layers() params = Parameters()
8,048
34.45815
88
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/classifier.py
#!/usr/bin/env python """ Classifier is an image classifier specialization of Net. """ import numpy as np import caffe class Classifier(caffe.Net): """ Classifier extends Net for image class prediction by scaling, center cropping, or oversampling. Parameters ---------- image_dims : dimensions to scale input for cropping/sampling. Default is to scale to net input size for whole-image crop. mean, input_scale, raw_scale, channel_swap: params for preprocessing options. """ def __init__(self, model_file, pretrained_file, image_dims=None, mean=None, input_scale=None, raw_scale=None, channel_swap=None): caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST) # configure pre-processing in_ = self.inputs[0] self.transformer = caffe.io.Transformer( {in_: self.blobs[in_].data.shape}) self.transformer.set_transpose(in_, (2, 0, 1)) if mean is not None: self.transformer.set_mean(in_, mean) if input_scale is not None: self.transformer.set_input_scale(in_, input_scale) if raw_scale is not None: self.transformer.set_raw_scale(in_, raw_scale) if channel_swap is not None: self.transformer.set_channel_swap(in_, channel_swap) self.crop_dims = np.array(self.blobs[in_].data.shape[2:]) if not image_dims: image_dims = self.crop_dims self.image_dims = image_dims def predict(self, inputs, oversample=True): """ Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes. """ # Scale to standardize input dimensions. input_ = np.zeros((len(inputs), self.image_dims[0], self.image_dims[1], inputs[0].shape[2]), dtype=np.float32) for ix, in_ in enumerate(inputs): input_[ix] = caffe.io.resize_image(in_, self.image_dims) if oversample: # Generate center, corner, and mirrored crops. input_ = caffe.io.oversample(input_, self.crop_dims) else: # Take center crop. center = np.array(self.image_dims) / 2.0 crop = np.tile(center, (1, 2))[0] + np.concatenate([ -self.crop_dims / 2.0, self.crop_dims / 2.0 ]) crop = crop.astype(int) input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :] # Classify caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]], dtype=np.float32) for ix, in_ in enumerate(input_): caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_) out = self.forward_all(**{self.inputs[0]: caffe_in}) predictions = out[self.outputs[0]] # For oversampling, average predictions across crops. if oversample: predictions = predictions.reshape((len(predictions) / 10, 10, -1)) predictions = predictions.mean(1) return predictions
3,537
34.737374
78
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/coord_map.py
""" Determine spatial relationships between layers to relate their coordinates. Coordinates are mapped from input-to-output (forward), but can be mapped output-to-input (backward) by the inverse mapping too. This helps crop and align feature maps among other uses. """ from __future__ import division import numpy as np from caffe import layers as L PASS_THROUGH_LAYERS = ['AbsVal', 'BatchNorm', 'Bias', 'BNLL', 'Dropout', 'Eltwise', 'ELU', 'Log', 'LRN', 'Exp', 'MVN', 'Power', 'ReLU', 'PReLU', 'Scale', 'Sigmoid', 'Split', 'TanH', 'Threshold'] def conv_params(fn): """ Extract the spatial parameters that determine the coordinate mapping: kernel size, stride, padding, and dilation. Implementation detail: Convolution, Deconvolution, and Im2col layers define these in the convolution_param message, while Pooling has its own fields in pooling_param. This method deals with these details to extract canonical parameters. """ params = fn.params.get('convolution_param', fn.params) axis = params.get('axis', 1) ks = np.array(params['kernel_size'], ndmin=1) dilation = np.array(params.get('dilation', 1), ndmin=1) assert len({'pad_h', 'pad_w', 'kernel_h', 'kernel_w', 'stride_h', 'stride_w'} & set(fn.params)) == 0, \ 'cropping does not support legacy _h/_w params' return (axis, np.array(params.get('stride', 1), ndmin=1), (ks - 1) * dilation + 1, np.array(params.get('pad', 0), ndmin=1)) def crop_params(fn): """ Extract the crop layer parameters with defaults. """ params = fn.params.get('crop_param', fn.params) axis = params.get('axis', 2) # default to spatial crop for N, C, H, W offset = np.array(params.get('offset', 0), ndmin=1) return (axis, offset) class UndefinedMapException(Exception): """ Exception raised for layers that do not have a defined coordinate mapping. """ pass def coord_map(fn): """ Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords. """ if fn.type_name in ['Convolution', 'Pooling', 'Im2col']: axis, stride, ks, pad = conv_params(fn) return axis, 1 / stride, (pad - (ks - 1) / 2) / stride elif fn.type_name == 'Deconvolution': axis, stride, ks, pad = conv_params(fn) return axis, stride, (ks - 1) / 2 - pad elif fn.type_name in PASS_THROUGH_LAYERS: return None, 1, 0 elif fn.type_name == 'Crop': axis, offset = crop_params(fn) axis -= 1 # -1 for last non-coordinate dim. return axis, 1, - offset else: raise UndefinedMapException class AxisMismatchException(Exception): """ Exception raised for mappings with incompatible axes. """ pass def compose(base_map, next_map): """ Compose a base coord map with scale a1, shift b1 with a further coord map with scale a2, shift b2. The scales multiply and the further shift, b2, is scaled by base coord scale a1. """ ax1, a1, b1 = base_map ax2, a2, b2 = next_map if ax1 is None: ax = ax2 elif ax2 is None or ax1 == ax2: ax = ax1 else: raise AxisMismatchException return ax, a1 * a2, a1 * b2 + b1 def inverse(coord_map): """ Invert a coord map by de-scaling and un-shifting; this gives the backward mapping for the gradient. """ ax, a, b = coord_map return ax, 1 / a, -b / a def coord_map_from_to(top_from, top_to): """ Determine the coordinate mapping betweeen a top (from) and a top (to). Walk the graph to find a common ancestor while composing the coord maps for from and to until they meet. As a last step the from map is inverted. """ # We need to find a common ancestor of top_from and top_to. # We'll assume that all ancestors are equivalent here (otherwise the graph # is an inconsistent state (which we could improve this to check for)). # For now use a brute-force algorithm. def collect_bottoms(top): """ Collect the bottoms to walk for the coordinate mapping. The general rule is that all the bottoms of a layer can be mapped, as most layers have the same coordinate mapping for each bottom. Crop layer is a notable exception. Only the first/cropped bottom is mappable; the second/dimensions bottom is excluded from the walk. """ bottoms = top.fn.inputs if top.fn.type_name == 'Crop': bottoms = bottoms[:1] return bottoms # walk back from top_from, keeping the coord map as we go from_maps = {top_from: (None, 1, 0)} frontier = {top_from} while frontier: top = frontier.pop() try: bottoms = collect_bottoms(top) for bottom in bottoms: from_maps[bottom] = compose(from_maps[top], coord_map(top.fn)) frontier.add(bottom) except UndefinedMapException: pass # now walk back from top_to until we hit a common blob to_maps = {top_to: (None, 1, 0)} frontier = {top_to} while frontier: top = frontier.pop() if top in from_maps: return compose(to_maps[top], inverse(from_maps[top])) try: bottoms = collect_bottoms(top) for bottom in bottoms: to_maps[bottom] = compose(to_maps[top], coord_map(top.fn)) frontier.add(bottom) except UndefinedMapException: continue # if we got here, we did not find a blob in common raise RuntimeError('Could not compute map between tops; are they ' 'connected by spatial layers?') def crop(top_from, top_to): """ Define a Crop layer to crop a top (from) to another top (to) by determining the coordinate mapping between the two and net spec'ing the axis and shift parameters of the crop. """ ax, a, b = coord_map_from_to(top_from, top_to) assert (a == 1).all(), 'scale mismatch on crop (a = {})'.format(a) assert (b <= 0).all(), 'cannot crop negative offset (b = {})'.format(b) assert (np.round(b) == b).all(), 'cannot crop noninteger offset ' \ '(b = {})'.format(b) return L.Crop(top_from, top_to, crop_param=dict(axis=ax + 1, # +1 for first cropping dim. offset=list(-np.round(b).astype(int))))
6,721
35.139785
79
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/detector.py
#!/usr/bin/env python """ Do windowed detection by classifying a number of images/crops at once, optionally using the selective search window proposal method. This implementation follows ideas in Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra Malik. Rich feature hierarchies for accurate object detection and semantic segmentation. http://arxiv.org/abs/1311.2524 The selective_search_ijcv_with_python code required for the selective search proposal mode is available at https://github.com/sergeyk/selective_search_ijcv_with_python """ import numpy as np import os import caffe class Detector(caffe.Net): """ Detector extends Net for windowed detection by a list of crops or selective search proposals. Parameters ---------- mean, input_scale, raw_scale, channel_swap : params for preprocessing options. context_pad : amount of surrounding context to take s.t. a `context_pad` sized border of pixels in the network input image is context, as in R-CNN feature extraction. """ def __init__(self, model_file, pretrained_file, mean=None, input_scale=None, raw_scale=None, channel_swap=None, context_pad=None): caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST) # configure pre-processing in_ = self.inputs[0] self.transformer = caffe.io.Transformer( {in_: self.blobs[in_].data.shape}) self.transformer.set_transpose(in_, (2, 0, 1)) if mean is not None: self.transformer.set_mean(in_, mean) if input_scale is not None: self.transformer.set_input_scale(in_, input_scale) if raw_scale is not None: self.transformer.set_raw_scale(in_, raw_scale) if channel_swap is not None: self.transformer.set_channel_swap(in_, channel_swap) self.configure_crop(context_pad) def detect_windows(self, images_windows): """ Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ # Extract windows. window_inputs = [] for image_fname, windows in images_windows: image = caffe.io.load_image(image_fname).astype(np.float32) for window in windows: window_inputs.append(self.crop(image, window)) # Run through the net (warping windows to input dimensions). in_ = self.inputs[0] caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2]) + self.blobs[in_].data.shape[2:], dtype=np.float32) for ix, window_in in enumerate(window_inputs): caffe_in[ix] = self.transformer.preprocess(in_, window_in) out = self.forward_all(**{in_: caffe_in}) predictions = out[self.outputs[0]] # Package predictions with images and windows. detections = [] ix = 0 for image_fname, windows in images_windows: for window in windows: detections.append({ 'window': window, 'prediction': predictions[ix], 'filename': image_fname }) ix += 1 return detections def detect_selective_search(self, image_fnames): """ Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net. Parameters ---------- image_fnames: list Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ import selective_search_ijcv_with_python as selective_search # Make absolute paths so MATLAB can find the files. image_fnames = [os.path.abspath(f) for f in image_fnames] windows_list = selective_search.get_windows( image_fnames, cmd='selective_search_rcnn' ) # Run windowed detection on the selective search list. return self.detect_windows(zip(image_fnames, windows_list)) def crop(self, im, window): """ Crop a window from the image for detection. Include surrounding context according to the `context_pad` configuration. Parameters ---------- im: H x W x K image ndarray to crop. window: bounding box coordinates as ymin, xmin, ymax, xmax. Returns ------- crop: cropped window. """ # Crop window from the image. crop = im[window[0]:window[2], window[1]:window[3]] if self.context_pad: box = window.copy() crop_size = self.blobs[self.inputs[0]].width # assumes square scale = crop_size / (1. * crop_size - self.context_pad * 2) # Crop a box + surrounding context. half_h = (box[2] - box[0] + 1) / 2. half_w = (box[3] - box[1] + 1) / 2. center = (box[0] + half_h, box[1] + half_w) scaled_dims = scale * np.array((-half_h, -half_w, half_h, half_w)) box = np.round(np.tile(center, 2) + scaled_dims) full_h = box[2] - box[0] + 1 full_w = box[3] - box[1] + 1 scale_h = crop_size / full_h scale_w = crop_size / full_w pad_y = round(max(0, -box[0]) * scale_h) # amount out-of-bounds pad_x = round(max(0, -box[1]) * scale_w) # Clip box to image dimensions. im_h, im_w = im.shape[:2] box = np.clip(box, 0., [im_h, im_w, im_h, im_w]) clip_h = box[2] - box[0] + 1 clip_w = box[3] - box[1] + 1 assert(clip_h > 0 and clip_w > 0) crop_h = round(clip_h * scale_h) crop_w = round(clip_w * scale_w) if pad_y + crop_h > crop_size: crop_h = crop_size - pad_y if pad_x + crop_w > crop_size: crop_w = crop_size - pad_x # collect with context padding and place in input # with mean padding context_crop = im[box[0]:box[2], box[1]:box[3]] context_crop = caffe.io.resize_image(context_crop, (crop_h, crop_w)) crop = np.ones(self.crop_dims, dtype=np.float32) * self.crop_mean crop[pad_y:(pad_y + crop_h), pad_x:(pad_x + crop_w)] = context_crop return crop def configure_crop(self, context_pad): """ Configure crop dimensions and amount of context for cropping. If context is included, make the special input mean for context padding. Parameters ---------- context_pad : amount of context for cropping. """ # crop dimensions in_ = self.inputs[0] tpose = self.transformer.transpose[in_] inv_tpose = [tpose[t] for t in tpose] self.crop_dims = np.array(self.blobs[in_].data.shape[1:])[inv_tpose] #.transpose(inv_tpose) # context padding self.context_pad = context_pad if self.context_pad: in_ = self.inputs[0] transpose = self.transformer.transpose.get(in_) channel_order = self.transformer.channel_swap.get(in_) raw_scale = self.transformer.raw_scale.get(in_) # Padding context crops needs the mean in unprocessed input space. mean = self.transformer.mean.get(in_) if mean is not None: inv_transpose = [transpose[t] for t in transpose] crop_mean = mean.copy().transpose(inv_transpose) if channel_order is not None: channel_order_inverse = [channel_order.index(i) for i in range(crop_mean.shape[2])] crop_mean = crop_mean[:, :, channel_order_inverse] if raw_scale is not None: crop_mean /= raw_scale self.crop_mean = crop_mean else: self.crop_mean = np.zeros(self.crop_dims, dtype=np.float32)
8,541
38.364055
80
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/__init__.py
from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver, NCCL, Timer from ._caffe import init_log, log, set_mode_cpu, set_mode_gpu, set_device, Layer, get_solver, layer_type_list, set_random_seed, solver_count, set_solver_count, solver_rank, set_solver_rank, set_multiprocess, Layer, get_solver from ._caffe import __version__ from .proto.caffe_pb2 import TRAIN, TEST from .classifier import Classifier from .detector import Detector from . import io from .net_spec import layers, params, NetSpec, to_proto
561
61.444444
225
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/pycaffe.py
""" Wrap the internal caffe C++ module (_caffe.so) with a clean, Pythonic interface. """ from collections import OrderedDict try: from itertools import izip_longest except: from itertools import zip_longest as izip_longest import numpy as np from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, \ RMSPropSolver, AdaDeltaSolver, AdamSolver, NCCL, Timer import caffe.io import six # We directly update methods from Net here (rather than using composition or # inheritance) so that nets created by caffe (e.g., by SGDSolver) will # automatically have the improved interface. @property def _Net_blobs(self): """ An OrderedDict (bottom to top, i.e., input to output) of network blobs indexed by name """ if not hasattr(self, '_blobs_dict'): self._blobs_dict = OrderedDict(zip(self._blob_names, self._blobs)) return self._blobs_dict @property def _Net_blob_loss_weights(self): """ An OrderedDict (bottom to top, i.e., input to output) of network blob loss weights indexed by name """ if not hasattr(self, '_blobs_loss_weights_dict'): self._blob_loss_weights_dict = OrderedDict(zip(self._blob_names, self._blob_loss_weights)) return self._blob_loss_weights_dict @property def _Net_params(self): """ An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases) """ if not hasattr(self, '_params_dict'): self._params_dict = OrderedDict([(name, lr.blobs) for name, lr in zip( self._layer_names, self.layers) if len(lr.blobs) > 0]) return self._params_dict @property def _Net_inputs(self): if not hasattr(self, '_input_list'): keys = list(self.blobs.keys()) self._input_list = [keys[i] for i in self._inputs] return self._input_list @property def _Net_outputs(self): if not hasattr(self, '_output_list'): keys = list(self.blobs.keys()) self._output_list = [keys[i] for i in self._outputs] return self._output_list def _Net_forward(self, blobs=None, start=None, end=None, **kwargs): """ Forward pass: prepare inputs and run the net forward. Parameters ---------- blobs : list of blobs to return in addition to output blobs. kwargs : Keys are input blob names and values are blob ndarrays. For formatting inputs for Caffe, see Net.preprocess(). If None, input is taken from data layers. start : optional name of layer at which to begin the forward pass end : optional name of layer at which to finish the forward pass (inclusive) Returns ------- outs : {blob name: blob ndarray} dict. """ if blobs is None: blobs = [] if start is not None: start_ind = list(self._layer_names).index(start) else: start_ind = 0 if end is not None: end_ind = list(self._layer_names).index(end) outputs = set([end] + blobs) else: end_ind = len(self.layers) - 1 outputs = set(self.outputs + blobs) if kwargs: if set(kwargs.keys()) != set(self.inputs): raise Exception('Input blob arguments do not match net inputs.') # Set input according to defined shapes and make arrays single and # C-contiguous as Caffe expects. for in_, blob in six.iteritems(kwargs): if blob.shape[0] != self.blobs[in_].shape[0]: raise Exception('Input is not batch sized') self.blobs[in_].data[...] = blob self._forward(start_ind, end_ind) # Unpack blobs to extract return {out: self.blobs[out].data for out in outputs} def _Net_backward(self, diffs=None, start=None, end=None, **kwargs): """ Backward pass: prepare diffs and run the net backward. Parameters ---------- diffs : list of diffs to return in addition to bottom diffs. kwargs : Keys are output blob names and values are diff ndarrays. If None, top diffs are taken from forward loss. start : optional name of layer at which to begin the backward pass end : optional name of layer at which to finish the backward pass (inclusive) Returns ------- outs: {blob name: diff ndarray} dict. """ if diffs is None: diffs = [] if start is not None: start_ind = list(self._layer_names).index(start) else: start_ind = len(self.layers) - 1 if end is not None: end_ind = list(self._layer_names).index(end) outputs = set([end] + diffs) else: end_ind = 0 outputs = set(self.inputs + diffs) if kwargs: if set(kwargs.keys()) != set(self.outputs): raise Exception('Top diff arguments do not match net outputs.') # Set top diffs according to defined shapes and make arrays single and # C-contiguous as Caffe expects. for top, diff in six.iteritems(kwargs): if diff.shape[0] != self.blobs[top].shape[0]: raise Exception('Diff is not batch sized') self.blobs[top].diff[...] = diff self._backward(start_ind, end_ind) # Unpack diffs to extract return {out: self.blobs[out].diff for out in outputs} def _Net_forward_all(self, blobs=None, **kwargs): """ Run net forward in batches. Parameters ---------- blobs : list of blobs to extract as in forward() kwargs : Keys are input blob names and values are blob ndarrays. Refer to forward(). Returns ------- all_outs : {blob name: list of blobs} dict. """ # Collect outputs from batches all_outs = {out: [] for out in set(self.outputs + (blobs or []))} for batch in self._batch(kwargs): outs = self.forward(blobs=blobs, **batch) for out, out_blob in six.iteritems(outs): all_outs[out].extend(out_blob.copy()) # Package in ndarray. for out in all_outs: all_outs[out] = np.asarray(all_outs[out]) # Discard padding. pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs))) if pad: for out in all_outs: all_outs[out] = all_outs[out][:-pad] return all_outs def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs): """ Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict. """ # Batch blobs and diffs. all_outs = {out: [] for out in set(self.outputs + (blobs or []))} all_diffs = {diff: [] for diff in set(self.inputs + (diffs or []))} forward_batches = self._batch({in_: kwargs[in_] for in_ in self.inputs if in_ in kwargs}) backward_batches = self._batch({out: kwargs[out] for out in self.outputs if out in kwargs}) # Collect outputs from batches (and heed lack of forward/backward batches). for fb, bb in izip_longest(forward_batches, backward_batches, fillvalue={}): batch_blobs = self.forward(blobs=blobs, **fb) batch_diffs = self.backward(diffs=diffs, **bb) for out, out_blobs in six.iteritems(batch_blobs): all_outs[out].extend(out_blobs.copy()) for diff, out_diffs in six.iteritems(batch_diffs): all_diffs[diff].extend(out_diffs.copy()) # Package in ndarray. for out, diff in zip(all_outs, all_diffs): all_outs[out] = np.asarray(all_outs[out]) all_diffs[diff] = np.asarray(all_diffs[diff]) # Discard padding at the end and package in ndarray. pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs))) if pad: for out, diff in zip(all_outs, all_diffs): all_outs[out] = all_outs[out][:-pad] all_diffs[diff] = all_diffs[diff][:-pad] return all_outs, all_diffs def _Net_set_input_arrays(self, data, labels): """ Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.) """ if labels.ndim == 1: labels = np.ascontiguousarray(labels[:, np.newaxis, np.newaxis, np.newaxis]) return self._set_input_arrays(data, labels) def _Net_batch(self, blobs): """ Batch blob lists according to net's batch size. Parameters ---------- blobs: Keys blob names and values are lists of blobs (of any length). Naturally, all the lists should have the same length. Yields ------ batch: {blob name: list of blobs} dict for a single batch. """ num = len(six.next(six.itervalues(blobs))) batch_size = six.next(six.itervalues(self.blobs)).shape[0] remainder = num % batch_size num_batches = num // batch_size # Yield full batches. for b in range(num_batches): i = b * batch_size yield {name: blobs[name][i:i + batch_size] for name in blobs} # Yield last padded batch, if any. if remainder > 0: padded_batch = {} for name in blobs: padding = np.zeros((batch_size - remainder,) + blobs[name].shape[1:]) padded_batch[name] = np.concatenate([blobs[name][-remainder:], padding]) yield padded_batch def _Net_get_id_name(func, field): """ Generic property that maps func to the layer names into an OrderedDict. Used for top_names and bottom_names. Parameters ---------- func: function id -> [id] field: implementation field name (cache) Returns ------ A one-parameter function that can be set as a property. """ @property def get_id_name(self): if not hasattr(self, field): id_to_name = list(self.blobs) res = OrderedDict([(self._layer_names[i], [id_to_name[j] for j in func(self, i)]) for i in range(len(self.layers))]) setattr(self, field, res) return getattr(self, field) return get_id_name # Attach methods to Net. Net.blobs = _Net_blobs Net.blob_loss_weights = _Net_blob_loss_weights Net.params = _Net_params Net.forward = _Net_forward Net.backward = _Net_backward Net.forward_all = _Net_forward_all Net.forward_backward_all = _Net_forward_backward_all Net.set_input_arrays = _Net_set_input_arrays Net._batch = _Net_batch Net.inputs = _Net_inputs Net.outputs = _Net_outputs Net.top_names = _Net_get_id_name(Net._top_ids, "_top_names") Net.bottom_names = _Net_get_id_name(Net._bottom_ids, "_bottom_names")
11,256
32.602985
89
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/draw.py
""" Caffe network visualization: draw the NetParameter protobuffer. .. note:: This requires pydot>=1.0.2, which is not included in requirements.txt since it requires graphviz and other prerequisites outside the scope of the Caffe. """ from caffe.proto import caffe_pb2 """ pydot is not supported under python 3 and pydot2 doesn't work properly. pydotplus works nicely (pip install pydotplus) """ try: # Try to load pydotplus import pydotplus as pydot except ImportError: import pydot # Internal layer and blob styles. LAYER_STYLE_DEFAULT = {'shape': 'record', 'fillcolor': '#6495ED', 'style': 'filled'} NEURON_LAYER_STYLE = {'shape': 'record', 'fillcolor': '#90EE90', 'style': 'filled'} BLOB_STYLE = {'shape': 'octagon', 'fillcolor': '#E0E0E0', 'style': 'filled'} def get_pooling_types_dict(): """Get dictionary mapping pooling type number to type name """ desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR d = {} for k, v in desc.values_by_name.items(): d[v.number] = k return d def get_edge_label(layer): """Define edge label based on layer type. """ if layer.type == 'Data': edge_label = 'Batch ' + str(layer.data_param.batch_size) elif layer.type == 'Convolution' or layer.type == 'Deconvolution': edge_label = str(layer.convolution_param.num_output) elif layer.type == 'InnerProduct': edge_label = str(layer.inner_product_param.num_output) else: edge_label = '""' return edge_label def get_layer_label(layer, rankdir): """Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer """ if rankdir in ('TB', 'BT'): # If graph orientation is vertical, horizontal space is free and # vertical space is not; separate words with spaces separator = ' ' else: # If graph orientation is horizontal, vertical space is free and # horizontal space is not; separate words with newlines separator = '\\n' if layer.type == 'Convolution' or layer.type == 'Deconvolution': # Outer double quotes needed or else colon characters don't parse # properly node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, layer.type, separator, layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size._values) else 1, separator, layer.convolution_param.stride[0] if len(layer.convolution_param.stride._values) else 1, separator, layer.convolution_param.pad[0] if len(layer.convolution_param.pad._values) else 0) elif layer.type == 'Pooling': pooling_types_dict = get_pooling_types_dict() node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, pooling_types_dict[layer.pooling_param.pool], layer.type, separator, layer.pooling_param.kernel_size, separator, layer.pooling_param.stride, separator, layer.pooling_param.pad) else: node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type) return node_label def choose_color_by_layertype(layertype): """Define colors for nodes based on the layer type. """ color = '#6495ED' # Default if layertype == 'Convolution' or layertype == 'Deconvolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF' return color def get_pydot_graph(caffe_net, rankdir, label_edges=True, phase=None): """Create a data structure which represents the `caffe_net`. Parameters ---------- caffe_net : object rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. label_edges : boolean, optional Label the edges (default is True). phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional Include layers from this network phase. If None, include all layers. (the default is None) Returns ------- pydot graph object """ pydot_graph = pydot.Dot(caffe_net.name if caffe_net.name else 'Net', graph_type='digraph', rankdir=rankdir) pydot_nodes = {} pydot_edges = [] for layer in caffe_net.layer: if phase is not None: included = False if len(layer.include) == 0: included = True if len(layer.include) > 0 and len(layer.exclude) > 0: raise ValueError('layer ' + layer.name + ' has both include ' 'and exclude specified.') for layer_phase in layer.include: included = included or layer_phase.phase == phase for layer_phase in layer.exclude: included = included and not layer_phase.phase == phase if not included: continue node_label = get_layer_label(layer, rankdir) node_name = "%s_%s" % (layer.name, layer.type) if (len(layer.bottom) == 1 and len(layer.top) == 1 and layer.bottom[0] == layer.top[0]): # We have an in-place neuron layer. pydot_nodes[node_name] = pydot.Node(node_label, **NEURON_LAYER_STYLE) else: layer_style = LAYER_STYLE_DEFAULT layer_style['fillcolor'] = choose_color_by_layertype(layer.type) pydot_nodes[node_name] = pydot.Node(node_label, **layer_style) for bottom_blob in layer.bottom: pydot_nodes[bottom_blob + '_blob'] = pydot.Node('%s' % bottom_blob, **BLOB_STYLE) edge_label = '""' pydot_edges.append({'src': bottom_blob + '_blob', 'dst': node_name, 'label': edge_label}) for top_blob in layer.top: pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob)) if label_edges: edge_label = get_edge_label(layer) else: edge_label = '""' pydot_edges.append({'src': node_name, 'dst': top_blob + '_blob', 'label': edge_label}) # Now, add the nodes and edges to the graph. for node in pydot_nodes.values(): pydot_graph.add_node(node) for edge in pydot_edges: pydot_graph.add_edge( pydot.Edge(pydot_nodes[edge['src']], pydot_nodes[edge['dst']], label=edge['label'])) return pydot_graph def draw_net(caffe_net, rankdir, ext='png', phase=None): """Draws a caffe net and returns the image string encoded using the given extension. Parameters ---------- caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer. ext : string, optional The image extension (the default is 'png'). phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional Include layers from this network phase. If None, include all layers. (the default is None) Returns ------- string : Postscript representation of the graph. """ return get_pydot_graph(caffe_net, rankdir, phase=phase).create(format=ext) def draw_net_to_file(caffe_net, filename, rankdir='LR', phase=None): """Draws a caffe net, and saves it to file using the format given as the file extension. Use '.raw' to output raw text that you can manually feed to graphviz to draw graphs. Parameters ---------- caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer. filename : string The path to a file where the networks visualization will be stored. rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional Include layers from this network phase. If None, include all layers. (the default is None) """ ext = filename[filename.rfind('.')+1:] with open(filename, 'wb') as fid: fid.write(draw_net(caffe_net, rankdir, ext, phase))
8,813
34.97551
120
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/io.py
import numpy as np import skimage.io from scipy.ndimage import zoom from skimage.transform import resize try: # Python3 will most likely not be able to load protobuf from caffe.proto import caffe_pb2 except: import sys if sys.version_info >= (3, 0): print("Failed to include caffe_pb2, things might go wrong!") else: raise ## proto / datum / ndarray conversion def blobproto_to_array(blob, return_diff=False): """ Convert a blob proto to an array. In default, we will just return the data, unless return_diff is True, in which case we will return the diff. """ # Read the data into an array if return_diff: data = np.array(blob.diff) else: data = np.array(blob.data) # Reshape the array if blob.HasField('num') or blob.HasField('channels') or blob.HasField('height') or blob.HasField('width'): # Use legacy 4D shape return data.reshape(blob.num, blob.channels, blob.height, blob.width) else: return data.reshape(blob.shape.dim) def array_to_blobproto(arr, diff=None): """Converts a N-dimensional array to blob proto. If diff is given, also convert the diff. You need to make sure that arr and diff have the same shape, and this function does not do sanity check. """ blob = caffe_pb2.BlobProto() blob.shape.dim.extend(arr.shape) blob.data.extend(arr.astype(float).flat) if diff is not None: blob.diff.extend(diff.astype(float).flat) return blob def arraylist_to_blobprotovector_str(arraylist): """Converts a list of arrays to a serialized blobprotovec, which could be then passed to a network for processing. """ vec = caffe_pb2.BlobProtoVector() vec.blobs.extend([array_to_blobproto(arr) for arr in arraylist]) return vec.SerializeToString() def blobprotovector_str_to_arraylist(str): """Converts a serialized blobprotovec to a list of arrays. """ vec = caffe_pb2.BlobProtoVector() vec.ParseFromString(str) return [blobproto_to_array(blob) for blob in vec.blobs] def array_to_datum(arr, label=None): """Converts a 3-dimensional array to datum. If the array has dtype uint8, the output data will be encoded as a string. Otherwise, the output data will be stored in float format. """ if arr.ndim != 3: raise ValueError('Incorrect array shape.') datum = caffe_pb2.Datum() datum.channels, datum.height, datum.width = arr.shape if arr.dtype == np.uint8: datum.data = arr.tostring() else: datum.float_data.extend(arr.flat) if label is not None: datum.label = label return datum def datum_to_array(datum): """Converts a datum to an array. Note that the label is not returned, as one can easily get it by calling datum.label. """ if len(datum.data): return np.fromstring(datum.data, dtype=np.uint8).reshape( datum.channels, datum.height, datum.width) else: return np.array(datum.float_data).astype(float).reshape( datum.channels, datum.height, datum.width) ## Pre-processing class Transformer: """ Transform input for feeding into a Net. Note: this is mostly for illustrative purposes and it is likely better to define your own input preprocessing routine for your needs. Parameters ---------- net : a Net for which the input should be prepared """ def __init__(self, inputs): self.inputs = inputs self.transpose = {} self.channel_swap = {} self.raw_scale = {} self.mean = {} self.input_scale = {} def __check_input(self, in_): if in_ not in self.inputs: raise Exception('{} is not one of the net inputs: {}'.format( in_, self.inputs)) def preprocess(self, in_, data): """ Format input for Caffe: - convert to single - resize to input dimensions (preserving number of channels) - transpose dimensions to K x H x W - reorder channels (for instance color to BGR) - scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models) - subtract mean - scale feature Parameters ---------- in_ : name of input blob to preprocess for data : (H' x W' x K) ndarray Returns ------- caffe_in : (K x H x W) ndarray for input to a Net """ self.__check_input(in_) caffe_in = data.astype(np.float32, copy=False) transpose = self.transpose.get(in_) channel_swap = self.channel_swap.get(in_) raw_scale = self.raw_scale.get(in_) mean = self.mean.get(in_) input_scale = self.input_scale.get(in_) in_dims = self.inputs[in_][2:] if caffe_in.shape[:2] != in_dims: caffe_in = resize_image(caffe_in, in_dims) if transpose is not None: caffe_in = caffe_in.transpose(transpose) if channel_swap is not None: caffe_in = caffe_in[channel_swap, :, :] if raw_scale is not None: caffe_in *= raw_scale if mean is not None: caffe_in -= mean if input_scale is not None: caffe_in *= input_scale return caffe_in def deprocess(self, in_, data): """ Invert Caffe formatting; see preprocess(). """ self.__check_input(in_) decaf_in = data.copy().squeeze() transpose = self.transpose.get(in_) channel_swap = self.channel_swap.get(in_) raw_scale = self.raw_scale.get(in_) mean = self.mean.get(in_) input_scale = self.input_scale.get(in_) if input_scale is not None: decaf_in /= input_scale if mean is not None: decaf_in += mean if raw_scale is not None: decaf_in /= raw_scale if channel_swap is not None: decaf_in = decaf_in[np.argsort(channel_swap), :, :] if transpose is not None: decaf_in = decaf_in.transpose(np.argsort(transpose)) return decaf_in def set_transpose(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. Parameters ---------- in_ : which input to assign this channel order order : the order to transpose the dimensions """ self.__check_input(in_) if len(order) != len(self.inputs[in_]) - 1: raise Exception('Transpose order needs to have the same number of ' 'dimensions as the input.') self.transpose[in_] = order def set_channel_swap(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example. """ self.__check_input(in_) if len(order) != self.inputs[in_][1]: raise Exception('Channel swap needs to have the same number of ' 'dimensions as the input channels.') self.channel_swap[in_] = order def set_raw_scale(self, in_, scale): """ Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient """ self.__check_input(in_) self.raw_scale[in_] = scale def set_mean(self, in_, mean): """ Set the mean to subtract for centering the data. Parameters ---------- in_ : which input to assign this mean. mean : mean ndarray (input dimensional or broadcastable) """ self.__check_input(in_) ms = mean.shape if mean.ndim == 1: # broadcast channels if ms[0] != self.inputs[in_][1]: raise ValueError('Mean channels incompatible with input.') mean = mean[:, np.newaxis, np.newaxis] else: # elementwise mean if len(ms) == 2: ms = (1,) + ms if len(ms) != 3: raise ValueError('Mean shape invalid') if ms != self.inputs[in_][1:]: raise ValueError('Mean shape incompatible with input shape.') self.mean[in_] = mean def set_input_scale(self, in_, scale): """ Set the scale of preprocessed inputs s.t. the blob = blob * scale. N.B. input_scale is done AFTER mean subtraction and other preprocessing while raw_scale is done BEFORE. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient """ self.__check_input(in_) self.input_scale[in_] = scale ## Image IO def load_image(filename, color=True): """ Load an image converting from grayscale or alpha as needed. Parameters ---------- filename : string color : boolean flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Returns ------- image : an image with type np.float32 in range [0, 1] of size (H x W x 3) in RGB or of size (H x W x 1) in grayscale. """ img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32) if img.ndim == 2: img = img[:, :, np.newaxis] if color: img = np.tile(img, (1, 1, 3)) elif img.shape[2] == 4: img = img[:, :, :3] return img def resize_image(im, new_dims, interp_order=1): """ Resize an image array with interpolation. Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K) """ if im.shape[-1] == 1 or im.shape[-1] == 3: im_min, im_max = im.min(), im.max() if im_max > im_min: # skimage is fast but only understands {1,3} channel images # in [0, 1]. im_std = (im - im_min) / (im_max - im_min) resized_std = resize(im_std, new_dims, order=interp_order) resized_im = resized_std * (im_max - im_min) + im_min else: # the image is a constant -- avoid divide by 0 ret = np.empty((new_dims[0], new_dims[1], im.shape[-1]), dtype=np.float32) ret.fill(im_min) return ret else: # ndimage interpolates anything but more slowly. scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2])) resized_im = zoom(im, scale + (1,), order=interp_order) return resized_im.astype(np.float32) def oversample(images, crop_dims): """ Crop images into the four corners, center, and their mirrored versions. Parameters ---------- image : iterable of (H x W x K) ndarrays crop_dims : (height, width) tuple for the crops. Returns ------- crops : (10*N x H x W x K) ndarray of crops for number of inputs N. """ # Dimensions and center. im_shape = np.array(images[0].shape) crop_dims = np.array(crop_dims) im_center = im_shape[:2] / 2.0 # Make crop coordinates h_indices = (0, im_shape[0] - crop_dims[0]) w_indices = (0, im_shape[1] - crop_dims[1]) crops_ix = np.empty((5, 4), dtype=int) curr = 0 for i in h_indices: for j in w_indices: crops_ix[curr] = (i, j, i + crop_dims[0], j + crop_dims[1]) curr += 1 crops_ix[4] = np.tile(im_center, (1, 2)) + np.concatenate([ -crop_dims / 2.0, crop_dims / 2.0 ]) crops_ix = np.tile(crops_ix, (2, 1)) # Extract crops crops = np.empty((10 * len(images), crop_dims[0], crop_dims[1], im_shape[-1]), dtype=np.float32) ix = 0 for im in images: for crop in crops_ix: crops[ix] = im[crop[0]:crop[2], crop[1]:crop[3], :] ix += 1 crops[ix-5:ix] = crops[ix-5:ix, :, ::-1, :] # flip for mirrors return crops
12,729
32.151042
110
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/test/test_coord_map.py
import unittest import numpy as np import random import caffe from caffe import layers as L from caffe import params as P from caffe.coord_map import coord_map_from_to, crop def coord_net_spec(ks=3, stride=1, pad=0, pool=2, dstride=2, dpad=0): """ Define net spec for simple conv-pool-deconv pattern common to all coordinate mapping tests. """ n = caffe.NetSpec() n.data = L.Input(shape=dict(dim=[2, 1, 100, 100])) n.aux = L.Input(shape=dict(dim=[2, 1, 20, 20])) n.conv = L.Convolution( n.data, num_output=10, kernel_size=ks, stride=stride, pad=pad) n.pool = L.Pooling( n.conv, pool=P.Pooling.MAX, kernel_size=pool, stride=pool, pad=0) # for upsampling kernel size is 2x stride try: deconv_ks = [s*2 for s in dstride] except: deconv_ks = dstride*2 n.deconv = L.Deconvolution( n.pool, num_output=10, kernel_size=deconv_ks, stride=dstride, pad=dpad) return n class TestCoordMap(unittest.TestCase): def setUp(self): pass def test_conv_pool_deconv(self): """ Map through conv, pool, and deconv. """ n = coord_net_spec() # identity for 2x pool, 2x deconv ax, a, b = coord_map_from_to(n.deconv, n.data) self.assertEquals(ax, 1) self.assertEquals(a, 1) self.assertEquals(b, 0) # shift-by-one for 4x pool, 4x deconv n = coord_net_spec(pool=4, dstride=4) ax, a, b = coord_map_from_to(n.deconv, n.data) self.assertEquals(ax, 1) self.assertEquals(a, 1) self.assertEquals(b, -1) def test_pass(self): """ A pass-through layer (ReLU) and conv (1x1, stride 1, pad 0) both do identity mapping. """ n = coord_net_spec() ax, a, b = coord_map_from_to(n.deconv, n.data) n.relu = L.ReLU(n.deconv) n.conv1x1 = L.Convolution( n.relu, num_output=10, kernel_size=1, stride=1, pad=0) for top in [n.relu, n.conv1x1]: ax_pass, a_pass, b_pass = coord_map_from_to(top, n.data) self.assertEquals(ax, ax_pass) self.assertEquals(a, a_pass) self.assertEquals(b, b_pass) def test_padding(self): """ Padding conv adds offset while padding deconv subtracts offset. """ n = coord_net_spec() ax, a, b = coord_map_from_to(n.deconv, n.data) pad = random.randint(0, 10) # conv padding n = coord_net_spec(pad=pad) _, a_pad, b_pad = coord_map_from_to(n.deconv, n.data) self.assertEquals(a, a_pad) self.assertEquals(b - pad, b_pad) # deconv padding n = coord_net_spec(dpad=pad) _, a_pad, b_pad = coord_map_from_to(n.deconv, n.data) self.assertEquals(a, a_pad) self.assertEquals(b + pad, b_pad) # pad both to cancel out n = coord_net_spec(pad=pad, dpad=pad) _, a_pad, b_pad = coord_map_from_to(n.deconv, n.data) self.assertEquals(a, a_pad) self.assertEquals(b, b_pad) def test_multi_conv(self): """ Multiple bottoms/tops of a layer are identically mapped. """ n = coord_net_spec() # multi bottom/top n.conv_data, n.conv_aux = L.Convolution( n.data, n.aux, ntop=2, num_output=10, kernel_size=5, stride=2, pad=0) ax1, a1, b1 = coord_map_from_to(n.conv_data, n.data) ax2, a2, b2 = coord_map_from_to(n.conv_aux, n.aux) self.assertEquals(ax1, ax2) self.assertEquals(a1, a2) self.assertEquals(b1, b2) def test_rect(self): """ Anisotropic mapping is equivalent to its isotropic parts. """ n3x3 = coord_net_spec(ks=3, stride=1, pad=0) n5x5 = coord_net_spec(ks=5, stride=2, pad=10) n3x5 = coord_net_spec(ks=[3, 5], stride=[1, 2], pad=[0, 10]) ax_3x3, a_3x3, b_3x3 = coord_map_from_to(n3x3.deconv, n3x3.data) ax_5x5, a_5x5, b_5x5 = coord_map_from_to(n5x5.deconv, n5x5.data) ax_3x5, a_3x5, b_3x5 = coord_map_from_to(n3x5.deconv, n3x5.data) self.assertTrue(ax_3x3 == ax_5x5 == ax_3x5) self.assertEquals(a_3x3, a_3x5[0]) self.assertEquals(b_3x3, b_3x5[0]) self.assertEquals(a_5x5, a_3x5[1]) self.assertEquals(b_5x5, b_3x5[1]) def test_nd_conv(self): """ ND conv maps the same way in more dimensions. """ n = caffe.NetSpec() # define data with 3 spatial dimensions, otherwise the same net n.data = L.Input(shape=dict(dim=[2, 3, 100, 100, 100])) n.conv = L.Convolution( n.data, num_output=10, kernel_size=[3, 3, 3], stride=[1, 1, 1], pad=[0, 1, 2]) n.pool = L.Pooling( n.conv, pool=P.Pooling.MAX, kernel_size=2, stride=2, pad=0) n.deconv = L.Deconvolution( n.pool, num_output=10, kernel_size=4, stride=2, pad=0) ax, a, b = coord_map_from_to(n.deconv, n.data) self.assertEquals(ax, 1) self.assertTrue(len(a) == len(b)) self.assertTrue(np.all(a == 1)) self.assertEquals(b[0] - 1, b[1]) self.assertEquals(b[1] - 1, b[2]) def test_crop_of_crop(self): """ Map coordinates through Crop layer: crop an already-cropped output to the input and check change in offset. """ n = coord_net_spec() offset = random.randint(0, 10) ax, a, b = coord_map_from_to(n.deconv, n.data) n.crop = L.Crop(n.deconv, n.data, axis=2, offset=offset) ax_crop, a_crop, b_crop = coord_map_from_to(n.crop, n.data) self.assertEquals(ax, ax_crop) self.assertEquals(a, a_crop) self.assertEquals(b + offset, b_crop) def test_crop_helper(self): """ Define Crop layer by crop(). """ n = coord_net_spec() crop(n.deconv, n.data) def test_catch_unconnected(self): """ Catch mapping spatially unconnected tops. """ n = coord_net_spec() n.ip = L.InnerProduct(n.deconv, num_output=10) with self.assertRaises(RuntimeError): coord_map_from_to(n.ip, n.data) def test_catch_scale_mismatch(self): """ Catch incompatible scales, such as when the top to be cropped is mapped to a differently strided reference top. """ n = coord_net_spec(pool=3, dstride=2) # pool 3x but deconv 2x with self.assertRaises(AssertionError): crop(n.deconv, n.data) def test_catch_negative_crop(self): """ Catch impossible offsets, such as when the top to be cropped is mapped to a larger reference top. """ n = coord_net_spec(dpad=10) # make output smaller than input with self.assertRaises(AssertionError): crop(n.deconv, n.data)
6,894
34.725389
79
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/test/test_python_layer_with_param_str.py
import unittest import tempfile import os import six import caffe class SimpleParamLayer(caffe.Layer): """A layer that just multiplies by the numeric value of its param string""" def setup(self, bottom, top): try: self.value = float(self.param_str) except ValueError: raise ValueError("Parameter string must be a legible float") def reshape(self, bottom, top): top[0].reshape(*bottom[0].data.shape) def forward(self, bottom, top): top[0].data[...] = self.value * bottom[0].data def backward(self, top, propagate_down, bottom): bottom[0].diff[...] = self.value * top[0].diff def python_param_net_file(): with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f: f.write("""name: 'pythonnet' force_backward: true input: 'data' input_shape { dim: 10 dim: 9 dim: 8 } layer { type: 'Python' name: 'mul10' bottom: 'data' top: 'mul10' python_param { module: 'test_python_layer_with_param_str' layer: 'SimpleParamLayer' param_str: '10' } } layer { type: 'Python' name: 'mul2' bottom: 'mul10' top: 'mul2' python_param { module: 'test_python_layer_with_param_str' layer: 'SimpleParamLayer' param_str: '2' } }""") return f.name @unittest.skipIf('Python' not in caffe.layer_type_list(), 'Caffe built without Python layer support') class TestLayerWithParam(unittest.TestCase): def setUp(self): net_file = python_param_net_file() self.net = caffe.Net(net_file, caffe.TRAIN) os.remove(net_file) def test_forward(self): x = 8 self.net.blobs['data'].data[...] = x self.net.forward() for y in self.net.blobs['mul2'].data.flat: self.assertEqual(y, 2 * 10 * x) def test_backward(self): x = 7 self.net.blobs['mul2'].diff[...] = x self.net.backward() for y in self.net.blobs['data'].diff.flat: self.assertEqual(y, 2 * 10 * x)
2,031
31.774194
79
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/test/test_io.py
import numpy as np import unittest import caffe class TestBlobProtoToArray(unittest.TestCase): def test_old_format(self): data = np.zeros((10,10)) blob = caffe.proto.caffe_pb2.BlobProto() blob.data.extend(list(data.flatten())) shape = (1,1,10,10) blob.num, blob.channels, blob.height, blob.width = shape arr = caffe.io.blobproto_to_array(blob) self.assertEqual(arr.shape, shape) def test_new_format(self): data = np.zeros((10,10)) blob = caffe.proto.caffe_pb2.BlobProto() blob.data.extend(list(data.flatten())) blob.shape.dim.extend(list(data.shape)) arr = caffe.io.blobproto_to_array(blob) self.assertEqual(arr.shape, data.shape) def test_no_shape(self): data = np.zeros((10,10)) blob = caffe.proto.caffe_pb2.BlobProto() blob.data.extend(list(data.flatten())) with self.assertRaises(ValueError): caffe.io.blobproto_to_array(blob) def test_scalar(self): data = np.ones((1)) * 123 blob = caffe.proto.caffe_pb2.BlobProto() blob.data.extend(list(data.flatten())) arr = caffe.io.blobproto_to_array(blob) self.assertEqual(arr, 123) class TestArrayToDatum(unittest.TestCase): def test_label_none_size(self): # Set label d1 = caffe.io.array_to_datum( np.ones((10,10,3)), label=1) # Don't set label d2 = caffe.io.array_to_datum( np.ones((10,10,3))) # Not setting the label should result in a smaller object self.assertGreater( len(d1.SerializeToString()), len(d2.SerializeToString()))
1,694
28.736842
65
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/test/test_solver.py
import unittest import tempfile import os import numpy as np import six import caffe from test_net import simple_net_file class TestSolver(unittest.TestCase): def setUp(self): self.num_output = 13 net_f = simple_net_file(self.num_output) f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.write("""net: '""" + net_f + """' test_iter: 10 test_interval: 10 base_lr: 0.01 momentum: 0.9 weight_decay: 0.0005 lr_policy: 'inv' gamma: 0.0001 power: 0.75 display: 100 max_iter: 100 snapshot_after_train: false snapshot_prefix: "model" """) f.close() self.solver = caffe.SGDSolver(f.name) # also make sure get_solver runs caffe.get_solver(f.name) caffe.set_mode_cpu() # fill in valid labels self.solver.net.blobs['label'].data[...] = \ np.random.randint(self.num_output, size=self.solver.net.blobs['label'].data.shape) self.solver.test_nets[0].blobs['label'].data[...] = \ np.random.randint(self.num_output, size=self.solver.test_nets[0].blobs['label'].data.shape) os.remove(f.name) os.remove(net_f) def test_solve(self): self.assertEqual(self.solver.iter, 0) self.solver.solve() self.assertEqual(self.solver.iter, 100) def test_net_memory(self): """Check that nets survive after the solver is destroyed.""" nets = [self.solver.net] + list(self.solver.test_nets) self.assertEqual(len(nets), 2) del self.solver total = 0 for net in nets: for ps in six.itervalues(net.params): for p in ps: total += p.data.sum() + p.diff.sum() for bl in six.itervalues(net.blobs): total += bl.data.sum() + bl.diff.sum() def test_snapshot(self): self.solver.snapshot() # Check that these files exist and then remove them files = ['model_iter_0.caffemodel', 'model_iter_0.solverstate'] for fn in files: assert os.path.isfile(fn) os.remove(fn)
2,165
33.380952
76
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/test/test_layer_type_list.py
import unittest import caffe class TestLayerTypeList(unittest.TestCase): def test_standard_types(self): #removing 'Data' from list for type_name in ['Data', 'Convolution', 'InnerProduct']: self.assertIn(type_name, caffe.layer_type_list(), '%s not in layer_type_list()' % type_name)
338
27.25
65
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/test/test_net.py
import unittest import tempfile import os import numpy as np import six from collections import OrderedDict import caffe def simple_net_file(num_output): """Make a simple net prototxt, based on test_net.cpp, returning the name of the (temporary) file.""" f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.write("""name: 'testnet' force_backward: true layer { type: 'DummyData' name: 'data' top: 'data' top: 'label' dummy_data_param { num: 5 channels: 2 height: 3 width: 4 num: 5 channels: 1 height: 1 width: 1 data_filler { type: 'gaussian' std: 1 } data_filler { type: 'constant' } } } layer { type: 'Convolution' name: 'conv' bottom: 'data' top: 'conv' convolution_param { num_output: 11 kernel_size: 2 pad: 3 weight_filler { type: 'gaussian' std: 1 } bias_filler { type: 'constant' value: 2 } } param { decay_mult: 1 } param { decay_mult: 0 } } layer { type: 'InnerProduct' name: 'ip' bottom: 'conv' top: 'ip' inner_product_param { num_output: """ + str(num_output) + """ weight_filler { type: 'gaussian' std: 2.5 } bias_filler { type: 'constant' value: -3 } } } layer { type: 'SoftmaxWithLoss' name: 'loss' bottom: 'ip' bottom: 'label' top: 'loss' }""") f.close() return f.name class TestNet(unittest.TestCase): def setUp(self): self.num_output = 13 net_file = simple_net_file(self.num_output) self.net = caffe.Net(net_file, caffe.TRAIN) # fill in valid labels self.net.blobs['label'].data[...] = \ np.random.randint(self.num_output, size=self.net.blobs['label'].data.shape) os.remove(net_file) def test_memory(self): """Check that holding onto blob data beyond the life of a Net is OK""" params = sum(map(list, six.itervalues(self.net.params)), []) blobs = self.net.blobs.values() del self.net # now sum everything (forcing all memory to be read) total = 0 for p in params: total += p.data.sum() + p.diff.sum() for bl in blobs: total += bl.data.sum() + bl.diff.sum() def test_forward_backward(self): self.net.forward() self.net.backward() def test_clear_param_diffs(self): # Run a forward/backward step to have non-zero diffs self.net.forward() self.net.backward() diff = self.net.params["conv"][0].diff # Check that we have non-zero diffs self.assertTrue(diff.max() > 0) self.net.clear_param_diffs() # Check that the diffs are now 0 self.assertTrue((diff == 0).all()) def test_inputs_outputs(self): self.assertEqual(self.net.inputs, []) self.assertEqual(self.net.outputs, ['loss']) def test_top_bottom_names(self): self.assertEqual(self.net.top_names, OrderedDict([('data', ['data', 'label']), ('conv', ['conv']), ('ip', ['ip']), ('loss', ['loss'])])) self.assertEqual(self.net.bottom_names, OrderedDict([('data', []), ('conv', ['data']), ('ip', ['conv']), ('loss', ['ip', 'label'])])) def test_save_and_read(self): f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.close() self.net.save(f.name) net_file = simple_net_file(self.num_output) # Test legacy constructor # should print deprecation warning caffe.Net(net_file, f.name, caffe.TRAIN) # Test named constructor net2 = caffe.Net(net_file, caffe.TRAIN, weights=f.name) os.remove(net_file) os.remove(f.name) for name in self.net.params: for i in range(len(self.net.params[name])): self.assertEqual(abs(self.net.params[name][i].data - net2.params[name][i].data).sum(), 0) def test_save_hdf5(self): f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.close() self.net.save_hdf5(f.name) net_file = simple_net_file(self.num_output) net2 = caffe.Net(net_file, caffe.TRAIN) net2.load_hdf5(f.name) os.remove(net_file) os.remove(f.name) for name in self.net.params: for i in range(len(self.net.params[name])): self.assertEqual(abs(self.net.params[name][i].data - net2.params[name][i].data).sum(), 0) class TestLevels(unittest.TestCase): TEST_NET = """ layer { name: "data" type: "DummyData" top: "data" dummy_data_param { shape { dim: 1 dim: 1 dim: 10 dim: 10 } } } layer { name: "NoLevel" type: "InnerProduct" bottom: "data" top: "NoLevel" inner_product_param { num_output: 1 } } layer { name: "Level0Only" type: "InnerProduct" bottom: "data" top: "Level0Only" include { min_level: 0 max_level: 0 } inner_product_param { num_output: 1 } } layer { name: "Level1Only" type: "InnerProduct" bottom: "data" top: "Level1Only" include { min_level: 1 max_level: 1 } inner_product_param { num_output: 1 } } layer { name: "Level>=0" type: "InnerProduct" bottom: "data" top: "Level>=0" include { min_level: 0 } inner_product_param { num_output: 1 } } layer { name: "Level>=1" type: "InnerProduct" bottom: "data" top: "Level>=1" include { min_level: 1 } inner_product_param { num_output: 1 } } """ def setUp(self): self.f = tempfile.NamedTemporaryFile(mode='w+', delete=False) self.f.write(self.TEST_NET) self.f.close() def tearDown(self): os.remove(self.f.name) def check_net(self, net, blobs): net_blobs = [b for b in net.blobs.keys() if 'data' not in b] self.assertEqual(net_blobs, blobs) def test_0(self): net = caffe.Net(self.f.name, caffe.TEST) self.check_net(net, ['NoLevel', 'Level0Only', 'Level>=0']) def test_1(self): net = caffe.Net(self.f.name, caffe.TEST, level=1) self.check_net(net, ['NoLevel', 'Level1Only', 'Level>=0', 'Level>=1']) class TestStages(unittest.TestCase): TEST_NET = """ layer { name: "data" type: "DummyData" top: "data" dummy_data_param { shape { dim: 1 dim: 1 dim: 10 dim: 10 } } } layer { name: "A" type: "InnerProduct" bottom: "data" top: "A" include { stage: "A" } inner_product_param { num_output: 1 } } layer { name: "B" type: "InnerProduct" bottom: "data" top: "B" include { stage: "B" } inner_product_param { num_output: 1 } } layer { name: "AorB" type: "InnerProduct" bottom: "data" top: "AorB" include { stage: "A" } include { stage: "B" } inner_product_param { num_output: 1 } } layer { name: "AandB" type: "InnerProduct" bottom: "data" top: "AandB" include { stage: "A" stage: "B" } inner_product_param { num_output: 1 } } """ def setUp(self): self.f = tempfile.NamedTemporaryFile(mode='w+', delete=False) self.f.write(self.TEST_NET) self.f.close() def tearDown(self): os.remove(self.f.name) def check_net(self, net, blobs): net_blobs = [b for b in net.blobs.keys() if 'data' not in b] self.assertEqual(net_blobs, blobs) def test_A(self): net = caffe.Net(self.f.name, caffe.TEST, stages=['A']) self.check_net(net, ['A', 'AorB']) def test_B(self): net = caffe.Net(self.f.name, caffe.TEST, stages=['B']) self.check_net(net, ['B', 'AorB']) def test_AandB(self): net = caffe.Net(self.f.name, caffe.TEST, stages=['A', 'B']) self.check_net(net, ['A', 'B', 'AorB', 'AandB']) class TestAllInOne(unittest.TestCase): TEST_NET = """ layer { name: "train_data" type: "DummyData" top: "data" top: "label" dummy_data_param { shape { dim: 1 dim: 1 dim: 10 dim: 10 } shape { dim: 1 dim: 1 dim: 1 dim: 1 } } include { phase: TRAIN stage: "train" } } layer { name: "val_data" type: "DummyData" top: "data" top: "label" dummy_data_param { shape { dim: 1 dim: 1 dim: 10 dim: 10 } shape { dim: 1 dim: 1 dim: 1 dim: 1 } } include { phase: TEST stage: "val" } } layer { name: "deploy_data" type: "Input" top: "data" input_param { shape { dim: 1 dim: 1 dim: 10 dim: 10 } } include { phase: TEST stage: "deploy" } } layer { name: "ip" type: "InnerProduct" bottom: "data" top: "ip" inner_product_param { num_output: 2 } } layer { name: "loss" type: "SoftmaxWithLoss" bottom: "ip" bottom: "label" top: "loss" include: { phase: TRAIN stage: "train" } include: { phase: TEST stage: "val" } } layer { name: "pred" type: "Softmax" bottom: "ip" top: "pred" include: { phase: TEST stage: "deploy" } } """ def setUp(self): self.f = tempfile.NamedTemporaryFile(mode='w+', delete=False) self.f.write(self.TEST_NET) self.f.close() def tearDown(self): os.remove(self.f.name) def check_net(self, net, outputs): self.assertEqual(list(net.blobs['data'].shape), [1,1,10,10]) self.assertEqual(net.outputs, outputs) def test_train(self): net = caffe.Net(self.f.name, caffe.TRAIN, stages=['train']) self.check_net(net, ['loss']) def test_val(self): net = caffe.Net(self.f.name, caffe.TEST, stages=['val']) self.check_net(net, ['loss']) def test_deploy(self): net = caffe.Net(self.f.name, caffe.TEST, stages=['deploy']) self.check_net(net, ['pred'])
9,722
27.101156
78
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/test/test_net_spec.py
import unittest import tempfile import caffe from caffe import layers as L from caffe import params as P def lenet(batch_size): n = caffe.NetSpec() n.data, n.label = L.DummyData(shape=[dict(dim=[batch_size, 1, 28, 28]), dict(dim=[batch_size, 1, 1, 1])], transform_param=dict(scale=1./255), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=5, num_output=20, weight_filler=dict(type='xavier')) n.pool1 = L.Pooling(n.conv1, kernel_size=2, stride=2, pool=P.Pooling.MAX) n.conv2 = L.Convolution(n.pool1, kernel_size=5, num_output=50, weight_filler=dict(type='xavier')) n.pool2 = L.Pooling(n.conv2, kernel_size=2, stride=2, pool=P.Pooling.MAX) n.ip1 = L.InnerProduct(n.pool2, num_output=500, weight_filler=dict(type='xavier')) n.relu1 = L.ReLU(n.ip1, in_place=True) n.ip2 = L.InnerProduct(n.relu1, num_output=10, weight_filler=dict(type='xavier')) n.loss = L.SoftmaxWithLoss(n.ip2, n.label) return n.to_proto() def anon_lenet(batch_size): data, label = L.DummyData(shape=[dict(dim=[batch_size, 1, 28, 28]), dict(dim=[batch_size, 1, 1, 1])], transform_param=dict(scale=1./255), ntop=2) conv1 = L.Convolution(data, kernel_size=5, num_output=20, weight_filler=dict(type='xavier')) pool1 = L.Pooling(conv1, kernel_size=2, stride=2, pool=P.Pooling.MAX) conv2 = L.Convolution(pool1, kernel_size=5, num_output=50, weight_filler=dict(type='xavier')) pool2 = L.Pooling(conv2, kernel_size=2, stride=2, pool=P.Pooling.MAX) ip1 = L.InnerProduct(pool2, num_output=500, weight_filler=dict(type='xavier')) relu1 = L.ReLU(ip1, in_place=True) ip2 = L.InnerProduct(relu1, num_output=10, weight_filler=dict(type='xavier')) loss = L.SoftmaxWithLoss(ip2, label) return loss.to_proto() def silent_net(): n = caffe.NetSpec() n.data, n.data2 = L.DummyData(shape=dict(dim=3), ntop=2) n.silence_data = L.Silence(n.data, ntop=0) n.silence_data2 = L.Silence(n.data2, ntop=0) return n.to_proto() class TestNetSpec(unittest.TestCase): def load_net(self, net_proto): f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.write(str(net_proto)) f.close() return caffe.Net(f.name, caffe.TEST) def test_lenet(self): """Construct and build the Caffe version of LeNet.""" net_proto = lenet(50) # check that relu is in-place self.assertEqual(net_proto.layer[6].bottom, net_proto.layer[6].top) net = self.load_net(net_proto) # check that all layers are present self.assertEqual(len(net.layers), 9) # now the check the version with automatically-generated layer names net_proto = anon_lenet(50) self.assertEqual(net_proto.layer[6].bottom, net_proto.layer[6].top) net = self.load_net(net_proto) self.assertEqual(len(net.layers), 9) def test_zero_tops(self): """Test net construction for top-less layers.""" net_proto = silent_net() net = self.load_net(net_proto) self.assertEqual(len(net.forward()), 0)
3,287
39.097561
77
py
bottom-up-attention
bottom-up-attention-master/caffe/python/caffe/test/test_python_layer.py
import unittest import tempfile import os import six import caffe class SimpleLayer(caffe.Layer): """A layer that just multiplies by ten""" def setup(self, bottom, top): pass def reshape(self, bottom, top): top[0].reshape(*bottom[0].data.shape) def forward(self, bottom, top): top[0].data[...] = 10 * bottom[0].data def backward(self, top, propagate_down, bottom): bottom[0].diff[...] = 10 * top[0].diff class ExceptionLayer(caffe.Layer): """A layer for checking exceptions from Python""" def setup(self, bottom, top): raise RuntimeError class ParameterLayer(caffe.Layer): """A layer that just multiplies by ten""" def setup(self, bottom, top): self.blobs.add_blob(1) self.blobs[0].data[0] = 0 def reshape(self, bottom, top): top[0].reshape(*bottom[0].data.shape) def forward(self, bottom, top): pass def backward(self, top, propagate_down, bottom): self.blobs[0].diff[0] = 1 class PhaseLayer(caffe.Layer): """A layer for checking attribute `phase`""" def setup(self, bottom, top): pass def reshape(self, bootom, top): top[0].reshape() def forward(self, bottom, top): top[0].data[()] = self.phase def python_net_file(): with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f: f.write("""name: 'pythonnet' force_backward: true input: 'data' input_shape { dim: 10 dim: 9 dim: 8 } layer { type: 'Python' name: 'one' bottom: 'data' top: 'one' python_param { module: 'test_python_layer' layer: 'SimpleLayer' } } layer { type: 'Python' name: 'two' bottom: 'one' top: 'two' python_param { module: 'test_python_layer' layer: 'SimpleLayer' } } layer { type: 'Python' name: 'three' bottom: 'two' top: 'three' python_param { module: 'test_python_layer' layer: 'SimpleLayer' } }""") return f.name def exception_net_file(): with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f: f.write("""name: 'pythonnet' force_backward: true input: 'data' input_shape { dim: 10 dim: 9 dim: 8 } layer { type: 'Python' name: 'layer' bottom: 'data' top: 'top' python_param { module: 'test_python_layer' layer: 'ExceptionLayer' } } """) return f.name def parameter_net_file(): with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f: f.write("""name: 'pythonnet' force_backward: true input: 'data' input_shape { dim: 10 dim: 9 dim: 8 } layer { type: 'Python' name: 'layer' bottom: 'data' top: 'top' python_param { module: 'test_python_layer' layer: 'ParameterLayer' } } """) return f.name def phase_net_file(): with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f: f.write("""name: 'pythonnet' force_backward: true layer { type: 'Python' name: 'layer' top: 'phase' python_param { module: 'test_python_layer' layer: 'PhaseLayer' } } """) return f.name @unittest.skipIf('Python' not in caffe.layer_type_list(), 'Caffe built without Python layer support') class TestPythonLayer(unittest.TestCase): def setUp(self): net_file = python_net_file() self.net = caffe.Net(net_file, caffe.TRAIN) os.remove(net_file) def test_forward(self): x = 8 self.net.blobs['data'].data[...] = x self.net.forward() for y in self.net.blobs['three'].data.flat: self.assertEqual(y, 10**3 * x) def test_backward(self): x = 7 self.net.blobs['three'].diff[...] = x self.net.backward() for y in self.net.blobs['data'].diff.flat: self.assertEqual(y, 10**3 * x) def test_reshape(self): s = 4 self.net.blobs['data'].reshape(s, s, s, s) self.net.forward() for blob in six.itervalues(self.net.blobs): for d in blob.data.shape: self.assertEqual(s, d) def test_exception(self): net_file = exception_net_file() self.assertRaises(RuntimeError, caffe.Net, net_file, caffe.TEST) os.remove(net_file) def test_parameter(self): net_file = parameter_net_file() net = caffe.Net(net_file, caffe.TRAIN) # Test forward and backward net.forward() net.backward() layer = net.layers[list(net._layer_names).index('layer')] self.assertEqual(layer.blobs[0].data[0], 0) self.assertEqual(layer.blobs[0].diff[0], 1) layer.blobs[0].data[0] += layer.blobs[0].diff[0] self.assertEqual(layer.blobs[0].data[0], 1) # Test saving and loading h, caffemodel_file = tempfile.mkstemp() net.save(caffemodel_file) layer.blobs[0].data[0] = -1 self.assertEqual(layer.blobs[0].data[0], -1) net.copy_from(caffemodel_file) self.assertEqual(layer.blobs[0].data[0], 1) os.remove(caffemodel_file) # Test weight sharing net2 = caffe.Net(net_file, caffe.TRAIN) net2.share_with(net) layer = net.layers[list(net2._layer_names).index('layer')] self.assertEqual(layer.blobs[0].data[0], 1) os.remove(net_file) def test_phase(self): net_file = phase_net_file() for phase in caffe.TRAIN, caffe.TEST: net = caffe.Net(net_file, phase) self.assertEqual(net.forward()['phase'], phase)
5,510
31.609467
81
py
bottom-up-attention
bottom-up-attention-master/caffe/scripts/cpp_lint.py
#!/usr/bin/python2 # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Does google-lint on c++ files. The goal of this script is to identify places in the code that *may* be in non-compliance with google style. It does not attempt to fix up these problems -- the point is to educate. It does also not attempt to find all problems, or to ensure that everything it does find is legitimately a problem. In particular, we can get very confused by /* and // inside strings! We do a small hack, which is to ignore //'s with "'s after them on the same line, but it is far from perfect (in either direction). """ import codecs import copy import getopt import math # for log import os import re import sre_compile import string import sys import unicodedata _USAGE = """ Syntax: cpp_lint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...] [--counting=total|toplevel|detailed] [--root=subdir] [--linelength=digits] <file> [file] ... The style guidelines this tries to follow are those in http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml Every problem is given a confidence score from 1-5, with 5 meaning we are certain of the problem, and 1 meaning it could be a legitimate construct. This will miss some errors, and is not a substitute for a code review. To suppress false-positive errors of a certain category, add a 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) suppresses errors of all categories on that line. The files passed in will be linted; at least one file must be provided. Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the extensions with the --extensions flag. Flags: output=vs7 By default, the output is formatted to ease emacs parsing. Visual Studio compatible output (vs7) may also be used. Other formats are unsupported. verbose=# Specify a number 0-5 to restrict errors to certain verbosity levels. filter=-x,+y,... Specify a comma-separated list of category-filters to apply: only error messages whose category names pass the filters will be printed. (Category names are printed with the message and look like "[whitespace/indent]".) Filters are evaluated left to right. "-FOO" and "FOO" means "do not print categories that start with FOO". "+FOO" means "do print categories that start with FOO". Examples: --filter=-whitespace,+whitespace/braces --filter=whitespace,runtime/printf,+runtime/printf_format --filter=-,+build/include_what_you_use To see a list of all the categories used in cpplint, pass no arg: --filter= counting=total|toplevel|detailed The total number of errors found is always printed. If 'toplevel' is provided, then the count of errors in each of the top-level categories like 'build' and 'whitespace' will also be printed. If 'detailed' is provided, then a count is provided for each category like 'build/class'. root=subdir The root directory used for deriving header guard CPP variable. By default, the header guard CPP variable is calculated as the relative path to the directory that contains .git, .hg, or .svn. When this flag is specified, the relative path is calculated from the specified directory. If the specified directory does not exist, this flag is ignored. Examples: Assuing that src/.git exists, the header guard CPP variables for src/chrome/browser/ui/browser.h are: No flag => CHROME_BROWSER_UI_BROWSER_H_ --root=chrome => BROWSER_UI_BROWSER_H_ --root=chrome/browser => UI_BROWSER_H_ linelength=digits This is the allowed line length for the project. The default value is 80 characters. Examples: --linelength=120 extensions=extension,extension,... The allowed file extensions that cpplint will check Examples: --extensions=hpp,cpp """ # We categorize each error message we print. Here are the categories. # We want an explicit list so we can list them all in cpplint --filter=. # If you add a new error message with a new category, add it to the list # here! cpplint_unittest.py should tell you if you forget to do this. _ERROR_CATEGORIES = [ 'build/class', 'build/deprecated', 'build/endif_comment', 'build/explicit_make_pair', 'build/forward_decl', 'build/header_guard', 'build/include', 'build/include_alpha', 'build/include_dir', 'build/include_order', 'build/include_what_you_use', 'build/namespaces', 'build/printf_format', 'build/storage_class', 'caffe/alt_fn', 'caffe/data_layer_setup', 'caffe/random_fn', 'legal/copyright', 'readability/alt_tokens', 'readability/braces', 'readability/casting', 'readability/check', 'readability/constructors', 'readability/fn_size', 'readability/function', 'readability/multiline_comment', 'readability/multiline_string', 'readability/namespace', 'readability/nolint', 'readability/nul', 'readability/streams', 'readability/todo', 'readability/utf8', 'runtime/arrays', 'runtime/casting', 'runtime/explicit', 'runtime/int', 'runtime/init', 'runtime/invalid_increment', 'runtime/member_string_references', 'runtime/memset', 'runtime/operator', 'runtime/printf', 'runtime/printf_format', 'runtime/references', 'runtime/string', 'runtime/threadsafe_fn', 'runtime/vlog', 'whitespace/blank_line', 'whitespace/braces', 'whitespace/comma', 'whitespace/comments', 'whitespace/empty_conditional_body', 'whitespace/empty_loop_body', 'whitespace/end_of_line', 'whitespace/ending_newline', 'whitespace/forcolon', 'whitespace/indent', 'whitespace/line_length', 'whitespace/newline', 'whitespace/operators', 'whitespace/parens', 'whitespace/semicolon', 'whitespace/tab', 'whitespace/todo' ] # The default state of the category filter. This is overrided by the --filter= # flag. By default all errors are on, so only add here categories that should be # off by default (i.e., categories that must be enabled by the --filter= flags). # All entries here should start with a '-' or '+', as in the --filter= flag. _DEFAULT_FILTERS = [ '-build/include_dir', '-readability/todo', ] # We used to check for high-bit characters, but after much discussion we # decided those were OK, as long as they were in UTF-8 and didn't represent # hard-coded international strings, which belong in a separate i18n file. # C++ headers _CPP_HEADERS = frozenset([ # Legacy 'algobase.h', 'algo.h', 'alloc.h', 'builtinbuf.h', 'bvector.h', 'complex.h', 'defalloc.h', 'deque.h', 'editbuf.h', 'fstream.h', 'function.h', 'hash_map', 'hash_map.h', 'hash_set', 'hash_set.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip.h', 'iostream.h', 'istream.h', 'iterator.h', 'list.h', 'map.h', 'multimap.h', 'multiset.h', 'ostream.h', 'pair.h', 'parsestream.h', 'pfstream.h', 'procbuf.h', 'pthread_alloc', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h', 'set.h', 'slist', 'slist.h', 'stack.h', 'stdiostream.h', 'stl_alloc.h', 'stl_relops.h', 'streambuf.h', 'stream.h', 'strfile.h', 'strstream.h', 'tempbuf.h', 'tree.h', 'type_traits.h', 'vector.h', # 17.6.1.2 C++ library headers 'algorithm', 'array', 'atomic', 'bitset', 'chrono', 'codecvt', 'complex', 'condition_variable', 'deque', 'exception', 'forward_list', 'fstream', 'functional', 'future', 'initializer_list', 'iomanip', 'ios', 'iosfwd', 'iostream', 'istream', 'iterator', 'limits', 'list', 'locale', 'map', 'memory', 'mutex', 'new', 'numeric', 'ostream', 'queue', 'random', 'ratio', 'regex', 'set', 'sstream', 'stack', 'stdexcept', 'streambuf', 'string', 'strstream', 'system_error', 'thread', 'tuple', 'typeindex', 'typeinfo', 'type_traits', 'unordered_map', 'unordered_set', 'utility', 'valarray', 'vector', # 17.6.1.2 C++ headers for C library facilities 'cassert', 'ccomplex', 'cctype', 'cerrno', 'cfenv', 'cfloat', 'cinttypes', 'ciso646', 'climits', 'clocale', 'cmath', 'csetjmp', 'csignal', 'cstdalign', 'cstdarg', 'cstdbool', 'cstddef', 'cstdint', 'cstdio', 'cstdlib', 'cstring', 'ctgmath', 'ctime', 'cuchar', 'cwchar', 'cwctype', ]) # Assertion macros. These are defined in base/logging.h and # testing/base/gunit.h. Note that the _M versions need to come first # for substring matching to work. _CHECK_MACROS = [ 'DCHECK', 'CHECK', 'EXPECT_TRUE_M', 'EXPECT_TRUE', 'ASSERT_TRUE_M', 'ASSERT_TRUE', 'EXPECT_FALSE_M', 'EXPECT_FALSE', 'ASSERT_FALSE_M', 'ASSERT_FALSE', ] # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS]) for op, replacement in [('==', 'EQ'), ('!=', 'NE'), ('>=', 'GE'), ('>', 'GT'), ('<=', 'LE'), ('<', 'LT')]: _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), ('>=', 'LT'), ('>', 'LE'), ('<=', 'GT'), ('<', 'GE')]: _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement # Alternative tokens and their replacements. For full list, see section 2.5 # Alternative tokens [lex.digraph] in the C++ standard. # # Digraphs (such as '%:') are not included here since it's a mess to # match those on a word boundary. _ALT_TOKEN_REPLACEMENT = { 'and': '&&', 'bitor': '|', 'or': '||', 'xor': '^', 'compl': '~', 'bitand': '&', 'and_eq': '&=', 'or_eq': '|=', 'xor_eq': '^=', 'not': '!', 'not_eq': '!=' } # Compile regular expression that matches all the above keywords. The "[ =()]" # bit is meant to avoid matching these keywords outside of boolean expressions. # # False positives include C-style multi-line comments and multi-line strings # but those have always been troublesome for cpplint. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') # These constants define types of headers for use with # _IncludeState.CheckNextIncludeOrder(). _C_SYS_HEADER = 1 _CPP_SYS_HEADER = 2 _LIKELY_MY_HEADER = 3 _POSSIBLE_MY_HEADER = 4 _OTHER_HEADER = 5 # These constants define the current inline assembly state _NO_ASM = 0 # Outside of inline assembly block _INSIDE_ASM = 1 # Inside inline assembly block _END_ASM = 2 # Last line of inline assembly block _BLOCK_ASM = 3 # The whole block is an inline assembly block # Match start of assembly blocks _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' r'(?:\s+(volatile|__volatile__))?' r'\s*[{(]') _regexp_compile_cache = {} # Finds occurrences of NOLINT[_NEXT_LINE] or NOLINT[_NEXT_LINE](...). _RE_SUPPRESSION = re.compile(r'\bNOLINT(_NEXT_LINE)?\b(\([^)]*\))?') # {str, set(int)}: a map from error categories to sets of linenumbers # on which those errors are expected and should be suppressed. _error_suppressions = {} # Finds Copyright. _RE_COPYRIGHT = re.compile(r'Copyright') # The root directory used for deriving header guard CPP variable. # This is set by --root flag. _root = None # The allowed line length of files. # This is set by --linelength flag. _line_length = 80 # The allowed extensions for file names # This is set by --extensions flag. _valid_extensions = set(['cc', 'h', 'cpp', 'hpp', 'cu', 'cuh']) def ParseNolintSuppressions(filename, raw_line, linenum, error): """Updates the global list of error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler. """ # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*). matched = _RE_SUPPRESSION.search(raw_line) if matched: if matched.group(1) == '_NEXT_LINE': linenum += 1 category = matched.group(2) if category in (None, '(*)'): # => "suppress all" _error_suppressions.setdefault(None, set()).add(linenum) else: if category.startswith('(') and category.endswith(')'): category = category[1:-1] if category in _ERROR_CATEGORIES: _error_suppressions.setdefault(category, set()).add(linenum) else: error(filename, linenum, 'readability/nolint', 5, 'Unknown NOLINT error category: %s' % category) def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear() def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment. """ return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set())) def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s) def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s) def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s) class _IncludeState(dict): """Tracks line numbers for includes, and the order in which includes appear. As a dict, an _IncludeState object serves as a mapping between include filename and line number on which that file was included. Call CheckNextIncludeOrder() once for each header in the file, passing in the type constants defined above. Calls in an illegal order will raise an _IncludeError with an appropriate error message. """ # self._section will move monotonically through this set. If it ever # needs to move backwards, CheckNextIncludeOrder will raise an error. _INITIAL_SECTION = 0 _MY_H_SECTION = 1 _C_SECTION = 2 _CPP_SECTION = 3 _OTHER_H_SECTION = 4 _TYPE_NAMES = { _C_SYS_HEADER: 'C system header', _CPP_SYS_HEADER: 'C++ system header', _LIKELY_MY_HEADER: 'header this file implements', _POSSIBLE_MY_HEADER: 'header this file may implement', _OTHER_HEADER: 'other header', } _SECTION_NAMES = { _INITIAL_SECTION: "... nothing. (This can't be an error.)", _MY_H_SECTION: 'a header this file implements', _C_SECTION: 'C system header', _CPP_SECTION: 'C++ system header', _OTHER_H_SECTION: 'other header', } def __init__(self): dict.__init__(self) self.ResetSection() def ResetSection(self): # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' def SetLastHeader(self, header_path): self._last_header = header_path def CanonicalizeAlphabeticalOrder(self, header_path): """Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path. """ return header_path.replace('-inl.h', '.h').replace('-', '_').lower() def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and not Match(r'^\s*$', clean_lines.elided[linenum - 1])): return False return True def CheckNextIncludeOrder(self, header_type): """Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong. """ error_message = ('Found %s after %s' % (self._TYPE_NAMES[header_type], self._SECTION_NAMES[self._section])) last_section = self._section if header_type == _C_SYS_HEADER: if self._section <= self._C_SECTION: self._section = self._C_SECTION else: self._last_header = '' return error_message elif header_type == _CPP_SYS_HEADER: if self._section <= self._CPP_SECTION: self._section = self._CPP_SECTION else: self._last_header = '' return error_message elif header_type == _LIKELY_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: self._section = self._OTHER_H_SECTION elif header_type == _POSSIBLE_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: # This will always be the fallback because we're not sure # enough that the header is associated with this file. self._section = self._OTHER_H_SECTION else: assert header_type == _OTHER_HEADER self._section = self._OTHER_H_SECTION if last_section != self._section: self._last_header = '' return '' class _CppLintState(object): """Maintains module-wide state..""" def __init__(self): self.verbose_level = 1 # global setting. self.error_count = 0 # global count of reported errors # filters to apply when emitting error messages self.filters = _DEFAULT_FILTERS[:] self.counting = 'total' # In what way are we counting errors? self.errors_by_category = {} # string to int dict storing error counts # output format: # "emacs" - format that emacs can parse (default) # "vs7" - format that Microsoft Visual Studio 7 can parse self.output_format = 'emacs' def SetOutputFormat(self, output_format): """Sets the output format for errors.""" self.output_format = output_format def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level def SetCountingStyle(self, counting_style): """Sets the module's counting options.""" self.counting = counting_style def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt) def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {} def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1 def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in self.errors_by_category.iteritems(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count) _cpplint_state = _CppLintState() def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format) def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level) def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level) def _Filters(): """Returns the module's list of output filters, as a list.""" return _cpplint_state.filters def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters) class _FunctionState(object): """Tracks current function name and the number of lines in its body.""" _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. def __init__(self): self.in_a_function = False self.lines_in_function = 0 self.current_function = '' def Begin(self, function_name): """Start analyzing function body. Args: function_name: The name of the function being tracked. """ self.in_a_function = True self.lines_in_function = 0 self.current_function = function_name def Count(self): """Count line in current function body.""" if self.in_a_function: self.lines_in_function += 1 def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger)) def End(self): """Stop analyzing function body.""" self.in_a_function = False class _IncludeError(Exception): """Indicates a problem with the include order in a file.""" pass class FileInfo: """Provides utility functions for filenames. FileInfo provides easy access to the components of a file's path relative to the project root. """ def __init__(self, filename): self._filename = filename def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/') def RepositoryName(self): """FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = os.path.dirname(fullname) while (root_dir != os.path.dirname(root_dir) and not os.path.exists(os.path.join(root_dir, ".git")) and not os.path.exists(os.path.join(root_dir, ".hg")) and not os.path.exists(os.path.join(root_dir, ".svn"))): root_dir = os.path.dirname(root_dir) if (os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname def Split(self): """Splits the file into the directory, basename, and extension. For 'chrome/browser/browser.cc', Split() would return ('chrome/browser', 'browser', '.cc') Returns: A tuple of (directory, basename, extension). """ googlename = self.RepositoryName() project, rest = os.path.split(googlename) return (project,) + os.path.splitext(rest) def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1] def Extension(self): """File extension - text following the final period.""" return self.Split()[2] def NoExtension(self): """File has no source file extension.""" return '/'.join(self.Split()[0:2]) def IsSource(self): """File has a source file extension.""" return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') # Matches strings. Escape codes should already be removed by ESCAPES. _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"') # Matches characters. Escape codes should already be removed by ESCAPES. _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'") # Matches multi-line C++ comments. # This RE is a little bit more complicated than one might expect, because we # have to take care of space removals tools so we can handle comments inside # statements better. # The current rule is: We only clear spaces from both sides when we're at the # end of the line. Otherwise, we try to remove spaces from the right side, # if this doesn't work we try on left side but only if there's a non-character # on the right. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( r"""(\s*/\*.*\*/\s*$| /\*.*\*/\s+| \s+/\*.*\*/(?=\W)| /\*.*\*/)""", re.VERBOSE) def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings. """ delimiter = None lines_without_raw_strings = [] for line in raw_lines: if delimiter: # Inside a raw string, look for the end end = line.find(delimiter) if end >= 0: # Found the end of the string, match leading space for this # line and resume copying the original lines, and also insert # a "" on the last line. leading_space = Match(r'^(\s*)\S', line) line = leading_space.group(1) + '""' + line[end + len(delimiter):] delimiter = None else: # Haven't found the end yet, append a blank line. line = '' else: # Look for beginning of a raw string. # See 2.14.15 [lex.string] for syntax. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) if matched: delimiter = ')' + matched.group(2) + '"' end = matched.group(3).find(delimiter) if end >= 0: # Raw string ended on same line line = (matched.group(1) + '""' + matched.group(3)[end + len(delimiter):]) delimiter = None else: # Start of a multi-line raw string line = matched.group(1) + '""' lines_without_raw_strings.append(line) # TODO(unknown): if delimiter is not None here, we might want to # emit a warning for unterminated string. return lines_without_raw_strings def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines) def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines) def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '// dummy' def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1 def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) class CleansedLines(object): """Holds 3 copies of all lines with different preprocessing applied to them. 1) elided member contains lines without strings and comments, 2) lines member contains lines without comments, and 3) raw_lines member contains all the lines without processing. All these three members are of <type 'list'>, and of the same length. """ def __init__(self, lines): self.elided = [] self.lines = [] self.raw_lines = lines self.num_lines = len(lines) self.lines_without_raw_strings = CleanseRawStrings(lines) for linenum in range(len(self.lines_without_raw_strings)): self.lines.append(CleanseComments( self.lines_without_raw_strings[linenum])) elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) self.elided.append(CleanseComments(elided)) def NumLines(self): """Returns the number of lines represented.""" return self.num_lines @staticmethod def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if not _RE_PATTERN_INCLUDE.match(elided): # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) return elided def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar): """Find the position just after the matching endchar. Args: line: a CleansedLines line. startpos: start searching at this position. depth: nesting level at startpos. startchar: expression opening character. endchar: expression closing character. Returns: On finding matching endchar: (index just after matching endchar, 0) Otherwise: (-1, new depth at end of this line) """ for i in xrange(startpos, len(line)): if line[i] == startchar: depth += 1 elif line[i] == endchar: depth -= 1 if depth == 0: return (i + 1, 0) return (-1, depth) def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] startchar = line[pos] if startchar not in '({[<': return (line, clean_lines.NumLines(), -1) if startchar == '(': endchar = ')' if startchar == '[': endchar = ']' if startchar == '{': endchar = '}' if startchar == '<': endchar = '>' # Check first line (end_pos, num_open) = FindEndOfExpressionInLine( line, pos, 0, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, num_open) = FindEndOfExpressionInLine( line, 0, num_open, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Did not find endchar before end of file, give up return (line, clean_lines.NumLines(), -1) def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar): """Find position at the matching startchar. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. depth: nesting level at endpos. startchar: expression opening character. endchar: expression closing character. Returns: On finding matching startchar: (index at matching startchar, 0) Otherwise: (-1, new depth at beginning of this line) """ for i in xrange(endpos, -1, -1): if line[i] == endchar: depth += 1 elif line[i] == startchar: depth -= 1 if depth == 0: return (i, 0) return (-1, depth) def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] endchar = line[pos] if endchar not in ')}]>': return (line, 0, -1) if endchar == ')': startchar = '(' if endchar == ']': startchar = '[' if endchar == '}': startchar = '{' if endchar == '>': startchar = '<' # Check last line (start_pos, num_open) = FindStartOfExpressionInLine( line, pos, 0, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, num_open) = FindStartOfExpressionInLine( line, len(line) - 1, num_open, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Did not find startchar before beginning of file, give up return (line, 0, -1) def CheckForCopyright(filename, lines, error): """Logs an error if a Copyright message appears at the top of the file.""" # We'll check up to line 10. Don't forget there's a # dummy line at the front. for line in xrange(1, min(len(lines), 11)): if _RE_COPYRIGHT.search(lines[line], re.I): error(filename, 0, 'legal/copyright', 5, 'Copyright message found. ' 'You should not include a copyright line.') def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' def CheckForHeaderGuard(filename, lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ cppvar = GetHeaderGuardCPPVariable(filename) ifndef = None ifndef_linenum = 0 define = None endif = None endif_linenum = 0 for linenum, line in enumerate(lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return if not define: error(filename, 0, 'build/header_guard', 5, 'No #define header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) if define != ifndef: error(filename, 0, 'build/header_guard', 5, '#ifndef and #define don\'t match, suggested CPP variable is: %s' % cppvar) return if endif != ('#endif // %s' % cppvar): error_level = 0 if endif != ('#endif // %s' % (cppvar + '_')): error_level = 5 ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, error) error(filename, endif_linenum, 'build/header_guard', error_level, '#endif line should be "#endif // %s"' % cppvar) def CheckForBadCharacters(filename, lines, error): """Logs an error for each line containing bad characters. Two kinds of bad characters: 1. Unicode replacement characters: These indicate that either the file contained invalid UTF-8 (likely) or Unicode replacement characters (which it shouldn't). Note that it's possible for this to throw off line numbering if the invalid UTF-8 occurred adjacent to a newline. 2. NUL bytes. These are problematic for some tools. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ for linenum, line in enumerate(lines): if u'\ufffd' in line: error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).') if '\0' in line: error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.') def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.') caffe_alt_function_list = ( ('memset', ['caffe_set', 'caffe_memset']), ('cudaMemset', ['caffe_gpu_set', 'caffe_gpu_memset']), ('memcpy', ['caffe_copy']), ('cudaMemcpy', ['caffe_copy', 'caffe_gpu_memcpy']), ) def CheckCaffeAlternatives(filename, clean_lines, linenum, error): """Checks for C(++) functions for which a Caffe substitute should be used. For certain native C functions (memset, memcpy), there is a Caffe alternative which should be used instead. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for function, alts in caffe_alt_function_list: ix = line.find(function + '(') if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): disp_alts = ['%s(...)' % alt for alt in alts] error(filename, linenum, 'caffe/alt_fn', 2, 'Use Caffe function %s instead of %s(...).' % (' or '.join(disp_alts), function)) def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error): """Except the base classes, Caffe DataLayer should define DataLayerSetUp instead of LayerSetUp. The base DataLayers define common SetUp steps, the subclasses should not override them. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] ix = line.find('DataLayer<Dtype>::LayerSetUp') if ix >= 0 and ( line.find('void DataLayer<Dtype>::LayerSetUp') != -1 or line.find('void ImageDataLayer<Dtype>::LayerSetUp') != -1 or line.find('void MemoryDataLayer<Dtype>::LayerSetUp') != -1 or line.find('void WindowDataLayer<Dtype>::LayerSetUp') != -1): error(filename, linenum, 'caffe/data_layer_setup', 2, 'Except the base classes, Caffe DataLayer should define' + ' DataLayerSetUp instead of LayerSetUp. The base DataLayers' + ' define common SetUp steps, the subclasses should' + ' not override them.') ix = line.find('DataLayer<Dtype>::DataLayerSetUp') if ix >= 0 and ( line.find('void Base') == -1 and line.find('void DataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void ImageDataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void MemoryDataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void WindowDataLayer<Dtype>::DataLayerSetUp') == -1): error(filename, linenum, 'caffe/data_layer_setup', 2, 'Except the base classes, Caffe DataLayer should define' + ' DataLayerSetUp instead of LayerSetUp. The base DataLayers' + ' define common SetUp steps, the subclasses should' + ' not override them.') c_random_function_list = ( 'rand(', 'rand_r(', 'random(', ) def CheckCaffeRandom(filename, clean_lines, linenum, error): """Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for function in c_random_function_list: ix = line.find(function) # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'caffe/random_fn', 2, 'Use caffe_rng_rand() (or other caffe_rng_* function) instead of ' + function + ') to ensure results are deterministic for a fixed Caffe seed.') threading_list = ( ('asctime(', 'asctime_r('), ('ctime(', 'ctime_r('), ('getgrgid(', 'getgrgid_r('), ('getgrnam(', 'getgrnam_r('), ('getlogin(', 'getlogin_r('), ('getpwnam(', 'getpwnam_r('), ('getpwuid(', 'getpwuid_r('), ('gmtime(', 'gmtime_r('), ('localtime(', 'localtime_r('), ('strtok(', 'strtok_r('), ('ttyname(', 'ttyname_r('), ) def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for single_thread_function, multithread_safe_function in threading_list: ix = line.find(single_thread_function) # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_function + '...) instead of ' + single_thread_function + '...) for improved thread safety.') def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.') # Matches invalid increment: *count++, which moves pointer instead of # incrementing a value. _RE_PATTERN_INVALID_INCREMENT = re.compile( r'^\s*\*\w+(\+\+|--);') def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).') class _BlockInfo(object): """Stores information about a generic block of code.""" def __init__(self, seen_open_brace): self.seen_open_brace = seen_open_brace self.open_parentheses = 0 self.inline_asm = _NO_ASM def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass class _ClassInfo(_BlockInfo): """Stores information about a class.""" def __init__(self, name, class_or_struct, clean_lines, linenum): _BlockInfo.__init__(self, False) self.name = name self.starting_linenum = linenum self.is_derived = False if class_or_struct == 'struct': self.access = 'public' self.is_struct = True else: self.access = 'private' self.is_struct = False # Remember initial indentation level for this class. Using raw_lines here # instead of elided to account for leading comments. initial_indent = Match(r'^( *)\S', clean_lines.raw_lines[linenum]) if initial_indent: self.class_indent = len(initial_indent.group(1)) else: self.class_indent = 0 # Try to find the end of the class. This will be confused by things like: # class A { # } *x = { ... # # But it's still good enough for CheckSectionSpacing. self.last_line = 0 depth = 0 for i in range(linenum, clean_lines.NumLines()): line = clean_lines.elided[i] depth += line.count('{') - line.count('}') if not depth: self.last_line = i break def CheckBegin(self, filename, clean_lines, linenum, error): # Look for a bare ':' if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): self.is_derived = True def CheckEnd(self, filename, clean_lines, linenum, error): # Check that closing brace is aligned with beginning of the class. # Only do this if the closing brace is indented by only whitespaces. # This means we will not check single-line class definitions. indent = Match(r'^( *)\}', clean_lines.elided[linenum]) if indent and len(indent.group(1)) != self.class_indent: if self.is_struct: parent = 'struct ' + self.name else: parent = 'class ' + self.name error(filename, linenum, 'whitespace/indent', 3, 'Closing brace should be aligned with beginning of %s' % parent) class _NamespaceInfo(_BlockInfo): """Stores information about a namespace.""" def __init__(self, name, linenum): _BlockInfo.__init__(self, False) self.name = name or '' self.starting_linenum = linenum def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace"') class _PreprocessorInfo(object): """Stores checkpoints of nesting stacks when #if/#else is seen.""" def __init__(self, stack_before_if): # The entire nesting stack before #if self.stack_before_if = stack_before_if # The entire nesting stack up to #else self.stack_before_else = [] # Whether we have already seen #else or #elif self.seen_else = False class _NestingState(object): """Holds states related to parsing braces.""" def __init__(self): # Stack for tracking all braces. An object is pushed whenever we # see a "{", and popped when we see a "}". Only 3 types of # objects are possible: # - _ClassInfo: a class or struct. # - _NamespaceInfo: a namespace. # - _BlockInfo: some other type of block. self.stack = [] # Stack of _PreprocessorInfo objects. self.pp_stack = [] def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo) def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Update pp_stack first self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; # # Templates with class arguments may confuse the parser, for example: # template <class T # class Comparator = less<T>, # class Vector = vector<T> > # class HeapQueue { # # Because this parser has no nesting state about templates, by the # time it saw "class Comparator", it may think that it's a new class. # Nested templates have a similar problem: # template < # typename ExportedType, # typename TupleType, # template <typename, typename> class ImplTemplate> # # To avoid these cases, we ignore classes that are followed by '=' or '>' class_decl_match = Match( r'\s*(template\s*<[\w\s<>,:]*>\s*)?' r'(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)' r'(([^=>]|<[^<>]*>|<[^<>]*<[^<>]*>\s*>)*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): self.stack.append(_ClassInfo( class_decl_match.group(4), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(5) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): classinfo = self.stack[-1] access_match = Match( r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' r':(?:[^:]|$)', line) if access_match: classinfo.access = access_match.group(2) # Check that access keywords are indented +1 space. Skip this # check if the keywords are not preceded by whitespaces. indent = access_match.group(1) if (len(indent) != classinfo.class_indent + 1 and Match(r'^\s*$', indent)): if classinfo.is_struct: parent = 'struct ' + classinfo.name else: parent = 'class ' + classinfo.name slots = '' if access_match.group(3): slots = access_match.group(3) error(filename, linenum, 'whitespace/indent', 3, '%s%s: should be indented +1 space inside %s' % ( access_match.group(2), slots, parent)) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True else: self.stack.append(_BlockInfo(True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2) def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name) def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)' % re.escape(base_classname), line) if (args and args.group(1) != 'void' and not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), args.group(1).strip())): error(filename, linenum, 'runtime/explicit', 5, 'Single-argument constructors should be marked explicit.') def CheckSpacingForFunctionCall(filename, line, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found. """ # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)): error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )') def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace() def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] raw = clean_lines.raw_lines raw_line = raw[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count() # Count non-blank/non-comment lines. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') def CheckComment(comment, filename, linenum, error): """Checks for common mistakes in TODO comments. Args: comment: The text of the comment from the line in question. filename: The name of the current file. linenum: The number of the line to check. error: The function to call with any errors found. """ match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_EVIL_CONSTRUCTORS|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): """Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists. """ line = init_suffix nesting_stack = ['<'] while True: # Find the next operator that can tell us whether < is used as an # opening bracket or as a less-than operator. We only want to # warn on the latter case. # # We could also check all other operators and terminate the search # early, e.g. if we got something like this "a<b+c", the "<" is # most likely a less-than operator, but then we will get false # positives for default arguments and other template expressions. match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line) if match: # Found an operator, update nesting stack operator = match.group(1) line = match.group(2) if nesting_stack[-1] == '<': # Expecting closing angle bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator == '>': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma after a bracket, this is most likely a template # argument. We have not seen a closing angle bracket yet, but # it's probably a few lines later if we look for it, so just # return early here. return True else: # Got some other operator. return False else: # Expecting closing parenthesis or closing bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator in (')', ']'): # We don't bother checking for matching () or []. If we got # something like (] or [), it would have been a syntax error. nesting_stack.pop() else: # Scan the next line linenum += 1 if linenum >= len(clean_lines.elided): break line = clean_lines.elided[linenum] # Exhausted all remaining lines and still no matching angle bracket. # Most likely the input was incomplete, otherwise we should have # seen a semicolon and returned early. return True def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix): """Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists. """ line = init_prefix nesting_stack = ['>'] while True: # Find the previous operator match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line) if match: # Found an operator, update nesting stack operator = match.group(2) line = match.group(1) if nesting_stack[-1] == '>': # Expecting opening angle bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator == '<': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma before a bracket, this is most likely a # template argument. The opening angle bracket is probably # there if we look for it, so just return early here. return True else: # Got some other operator. return False else: # Expecting opening parenthesis or opening bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator in ('(', '['): nesting_stack.pop() else: # Scan the previous line linenum -= 1 if linenum < 0: break line = clean_lines.elided[linenum] # Exhausted all earlier lines and still no matching angle bracket. return False def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw = clean_lines.lines_without_raw_strings line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. if IsBlankLine(line) and not nesting_state.InNamespaceBody(): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Redundant blank line at the start of a code block ' 'should be deleted.') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Redundant blank line at the end of a code block ' 'should be deleted.') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, we complain if there's a comment too near the text commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not Match(r'^\s*{ //', line) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # There should always be a space between the // and the comment commentend = commentpos + 2 if commentend < len(line) and not line[commentend] == ' ': # but some lines are exceptions -- e.g. if they're big # comment delimiters like: # //---------------------------------------------------------- # or are an empty C++ style Doxygen comment, like: # /// # or C++ style Doxygen comments placed after the variable: # ///< Header comment # //!< Header comment # or they begin with multiple slashes followed by a space: # //////// Header comment match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or Search(r'^/$', line[commentend:]) or Search(r'^!< ', line[commentend:]) or Search(r'^/< ', line[commentend:]) or Search(r'^/+ ', line[commentend:])) if not match: error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') CheckComment(line[commentpos:], filename, linenum, error) line = clean_lines.elided[linenum] # get rid of comments and strings # Don't try to do spacing checks for operator methods line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) # Also ignore using ns::operator<<; match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line) if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and not (match.group(1) == 'operator' and match.group(2) == ';')): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') elif not Match(r'#.*include', line): # Avoid false positives on -> reduced_line = line.replace('->', '') # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Search(r'[^\s<]<([^\s=<].*)', reduced_line) if (match and not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line) if (match and not FindPreviousMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) # A pet peeve of mine: no spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if len(match.group(2)) not in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) # You should always have a space after a comma (either as fn arg or operator) # # This does not apply when the non-space character following the # comma is another comma, since the only time when that happens is # for empty macro arguments. # # We run this check in two passes: first pass on elided lines to # verify that lines contain missing whitespaces, second pass on raw # lines to confirm that those missing whitespaces are not due to # elided comments. if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') # Next we will look for issues with function calls. CheckSpacingForFunctionCall(filename, line, linenum, error) # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. match = Match(r'^(.*[^ ({]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<]". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in xrange(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'new char * []'. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search('for *\(.*[^:]:[^: ]', line) or Search('for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop') def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1)) def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1) def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on compound # literals. closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or Search(r'\s+=\s*$', line_prefix)): match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }") def CheckEmptyBlockBody(filename, clean_lines, linenum, error): """Look for empty loop/conditional body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Search for loop keywords at the beginning of the line. Because only # whitespaces are allowed before the keywords, this will also ignore most # do-while-loops, since those lines should start with closing brace. # # We also check "if" blocks here, since an empty conditional block # is likely an error. line = clean_lines.elided[linenum] matched = Match(r'\s*(for|while|if)\s*\(', line) if matched: # Find the end of the conditional expression (end_line, end_linenum, end_pos) = CloseExpression( clean_lines, linenum, line.find('(')) # Output warning if what follows the condition expression is a semicolon. # No warning for all other cases, including whitespace or newline, since we # have a separate check for semicolons preceded by whitespace. if end_pos >= 0 and Match(r';', end_line[end_pos:]): if matched.group(1) == 'if': error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, 'Empty conditional bodies should use {}') else: error(filename, end_linenum, 'whitespace/empty_loop_body', 5, 'Empty loop bodies should use {} or continue') def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided check_macro = None start_pos = -1 for macro in _CHECK_MACROS: i = lines[linenum].find(macro) if i >= 0: check_macro = macro # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum]) if not matched: continue start_pos = len(matched.group(1)) break if not check_macro or start_pos < 0: # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')') if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator)) def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line) def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw_lines = clean_lines.lines_without_raw_strings line = raw_lines[linenum] if line.find('\t') != -1: error(filename, linenum, 'whitespace/tab', 1, 'Tab found; better to use spaces') # One or three blank spaces at the beginning of the line is weird; it's # hard to reconcile that with 2-space indents. # NOTE: here are the conditions rob pike used for his tests. Mine aren't # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces # if(RLENGTH > 20) complain = 0; # if(match($0, " +(error|private|public|protected):")) complain = 0; # if(match(prev, "&& *$")) complain = 0; # if(match(prev, "\\|\\| *$")) complain = 0; # if(match(prev, "[\",=><] *$")) complain = 0; # if(match($0, " <<")) complain = 0; # if(match(prev, " +for \\(")) complain = 0; # if(prevodd && match(prevprev, " +for \\(")) complain = 0; initial_spaces = 0 cleansed_line = clean_lines.elided[linenum] while initial_spaces < len(line) and line[initial_spaces] == ' ': initial_spaces += 1 if line and line[-1].isspace(): error(filename, linenum, 'whitespace/end_of_line', 4, 'Line ends in whitespace. Consider deleting these extra spaces.') # There are certain situations we allow one space, notably for section labels elif ((initial_spaces == 1 or initial_spaces == 3) and not Match(r'\s*\w+\s*:\s*$', cleansed_line)): error(filename, linenum, 'whitespace/indent', 3, 'Weird number of spaces at line-start. ' 'Are you using a 2-space indent?') # Check if the line is a header guard. is_header_guard = False if file_extension == 'h': cppvar = GetHeaderGuardCPPVariable(filename) if (line.startswith('#ifndef %s' % cppvar) or line.startswith('#define %s' % cppvar) or line.startswith('#endif // %s' % cppvar)): is_header_guard = True # #include lines and header guards can be long, since there's no clean way to # split them. # # URLs can be long too. It's possible to split these, but it makes them # harder to cut&paste. # # The "$Id:...$" comment may also get very long without it being the # developers fault. if (not line.startswith('#include') and not is_header_guard and not Match(r'^\s*//.*http(s?)://\S*$', line) and not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): line_width = GetLineWidth(line) extended_length = int((_line_length * 1.25)) if line_width > extended_length: error(filename, linenum, 'whitespace/line_length', 4, 'Lines should very rarely be longer than %i characters' % extended_length) elif line_width > _line_length: error(filename, linenum, 'whitespace/line_length', 2, 'Lines should be <= %i characters long' % _line_length) if (cleansed_line.count(';') > 1 and # for loops are allowed two ;'s (and may run over two lines). cleansed_line.find('for') == -1 and (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and # It's ok to have many commands in a switch case that fits in 1 line not ((cleansed_line.find('case ') != -1 or cleansed_line.find('default:') != -1) and cleansed_line.find('break;') != -1)): error(filename, linenum, 'whitespace/newline', 0, 'More than one command on the same line') # Some more style checks CheckBraces(filename, clean_lines, linenum, error) CheckEmptyBlockBody(filename, clean_lines, linenum, error) CheckAccess(filename, clean_lines, linenum, nesting_state, error) CheckSpacing(filename, clean_lines, linenum, nesting_state, error) CheckCheck(filename, clean_lines, linenum, error) CheckAltTokens(filename, clean_lines, linenum, error) classinfo = nesting_state.InnermostClass() if classinfo: CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"') _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') # Matches the first component of a filename delimited by -s and _s. That is: # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', 'inl.h', 'impl.h', 'internal.h'): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0] def _IsTestFilename(filename): """Determines if the given filename has a suffix that identifies it as a test. Args: filename: The input filename. Returns: True if 'filename' looks like a test, False otherwise. """ if (filename.endswith('_test.cc') or filename.endswith('_unittest.cc') or filename.endswith('_regtest.cc')): return True else: return False def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER """ # This is a list of all standard c++ header files, except # those already checked for above. is_cpp_h = include in _CPP_HEADERS if is_system: if is_cpp_h: return _CPP_SYS_HEADER else: return _C_SYS_HEADER # If the target file and the include we're checking share a # basename when we drop common extensions, and the include # lives in . , then it's likely to be owned by the target file. target_dir, target_base = ( os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) if target_base == include_base and ( include_dir == target_dir or include_dir == os.path.normpath(target_dir + '/../public')): return _LIKELY_MY_HEADER # If the target and include share some initial basename # component, it's possible the target is implementing the # include, so it's allowed to be first, but we'll never # complain if it's not there. target_first_component = _RE_FIRST_COMPONENT.match(target_base) include_first_component = _RE_FIRST_COMPONENT.match(include_base) if (target_first_component and include_first_component and target_first_component.group(0) == include_first_component.group(0)): return _POSSIBLE_MY_HEADER return _OTHER_HEADER def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): error(filename, linenum, 'build/include_dir', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') if include in include_state: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, include_state[include])) else: include_state[include] = linenum # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include) # Look for any of the stream classes that are part of standard C++. match = _RE_PATTERN_INCLUDE.match(line) if match: include = match.group(2) if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): # Many unit tests use cout, so we exempt them. if not _IsTestFilename(filename): error(filename, linenum, 'readability/streams', 3, 'Streams are highly discouraged.') def _GetTextInside(text, start_pattern): r"""Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found. """ # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably # rewritten to use _GetTextInside (and use inferior regexp matching today). # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} closing_punctuation = set(matching_punctuation.itervalues()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) if not match: # start_pattern not found in text. return None start_position = match.end(0) assert start_position > 0, ( 'start_pattern must ends with an opening punctuation.') assert text[start_position - 1] in matching_punctuation, ( 'start_pattern must ends with an opening punctuation.') # Stack of closing punctuations we expect to have in text after position. punctuation_stack = [matching_punctuation[text[start_position - 1]]] position = start_position while punctuation_stack and position < len(text): if text[position] == punctuation_stack[-1]: punctuation_stack.pop() elif text[position] in closing_punctuation: # A closing punctuation without matching opening punctuations. return None elif text[position] in matching_punctuation: punctuation_stack.append(matching_punctuation[text[position]]) position += 1 if punctuation_stack: # Opening punctuations left without matching close-punctuations. return None # punctuations match. return text[start_position:position - 1] # Patterns for matching call-by-reference parameters. # # Supports nested templates up to 2 levels deep using this messy pattern: # < (?: < (?: < [^<>]* # > # | [^<>] )* # > # | [^<>] )* # > _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]* _RE_PATTERN_TYPE = ( r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?' r'(?:\w|' r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|' r'::)+') # A call-by-reference parameter ends with '& identifier'. _RE_PATTERN_REF_PARAM = re.compile( r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*' r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]') # A call-by-const-reference parameter either ends with 'const& identifier' # or looks like 'const type& identifier' when 'type' is atomic. _RE_PATTERN_CONST_REF_PARAM = ( r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT + r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')') def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, nesting_state, error): """Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # If the line is empty or consists of entirely a comment, no need to # check it. line = clean_lines.elided[linenum] if not line: return match = _RE_PATTERN_INCLUDE.search(line) if match: CheckIncludeLine(filename, clean_lines, linenum, include_state, error) return # Reset include state across preprocessor directives. This is meant # to silence warnings for conditional includes. if Match(r'^\s*#\s*(?:ifdef|elif|else|endif)\b', line): include_state.ResetSection() # Make Windows paths like Unix. fullname = os.path.abspath(filename).replace('\\', '/') # TODO(unknown): figure out if they're using default arguments in fn proto. # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there r'(int|float|double|bool|char|int32|uint32|int64|uint64)' r'(\([^)].*)', line) if match: matched_new = match.group(1) matched_type = match.group(2) matched_funcptr = match.group(3) # gMock methods are defined using some variant of MOCK_METHODx(name, type) # where type may be float(), int(string), etc. Without context they are # virtually indistinguishable from int(x) casts. Likewise, gMock's # MockCallback takes a template parameter of the form return_type(arg_type), # which looks much like the cast we're trying to detect. # # std::function<> wrapper has a similar problem. # # Return types for function pointers also look like casts if they # don't have an extra space. if (matched_new is None and # If new operator, then this isn't a cast not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or Search(r'\bMockCallback<.*>', line) or Search(r'\bstd::function<.*>', line)) and not (matched_funcptr and Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', matched_funcptr))): # Try a bit harder to catch gmock lines: the only place where # something looks like an old-style cast is where we declare the # return type of the mocked method, and the only time when we # are missing context is if MOCK_METHOD was split across # multiple lines. The missing MOCK_METHOD is usually one or two # lines back, so scan back one or two lines. # # It's not possible for gmock macros to appear in the first 2 # lines, since the class head + section name takes up 2 lines. if (linenum < 2 or not (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', clean_lines.elided[linenum - 1]) or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', clean_lines.elided[linenum - 2]))): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % matched_type) CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. match = Search( r'(?:&\(([^)]+)\)[\w(])|' r'(?:&(static|dynamic|down|reinterpret)_cast\b)', line) if match and match.group(1) != '*': error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after')) # Create an extended_line, which is the concatenation of the current and # next lines, for more effective checking of code that may span more than one # line. if linenum + 1 < clean_lines.NumLines(): extended_line = line + clean_lines.elided[linenum + 1] else: extended_line = line # Check for people declaring static/global STL strings at the top level. # This is dangerous because the C++ language does not guarantee that # globals with constructors are initialized before the first access. match = Match( r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)', line) # Make sure it's not a function. # Function template specialization looks like: "string foo<Type>(...". # Class template definitions look like: "string Foo<Type>::Method(...". # # Also ignore things that look like operators. These are matched separately # because operator names cross non-word boundaries. If we change the pattern # above, we would decrease the accuracy of matching identifiers. if (match and not Search(r'\boperator\W', line) and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', match.group(3))): error(filename, linenum, 'runtime/string', 4, 'For a static/global string constant, use a C style string instead: ' '"%schar %s[]".' % (match.group(1), match.group(2))) if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line): error(filename, linenum, 'runtime/init', 4, 'You seem to be initializing a member variable with itself.') if file_extension == 'h': # TODO(unknown): check that 1-arg constructors are explicit. # How to tell it's a constructor? # (handled in CheckForNonStandardConstructs for now) # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS # (level 1 error) pass # Check if people are using the verboten C basic types. The only exception # we regularly allow is "unsigned short port" for port. if Search(r'\bshort port\b', line): if not Search(r'\bunsigned short port\b', line): error(filename, linenum, 'runtime/int', 4, 'Use "unsigned short" for ports, not "short"') else: match = Search(r'\b(short|long(?! +double)|long long)\b', line) if match: error(filename, linenum, 'runtime/int', 4, 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) # When snprintf is used, the second argument shouldn't be a literal. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) if match and match.group(2) != '0': # If 2nd arg is zero, snprintf is used to calculate size. error(filename, linenum, 'runtime/printf', 3, 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' 'to snprintf.' % (match.group(1), match.group(2))) # Check if some verboten C functions are being used. if Search(r'\bsprintf\b', line): error(filename, linenum, 'runtime/printf', 5, 'Never use sprintf. Use snprintf instead.') match = Search(r'\b(strcpy|strcat)\b', line) if match: error(filename, linenum, 'runtime/printf', 4, 'Almost always, snprintf is better than %s' % match.group(1)) # Check if some verboten operator overloading is going on # TODO(unknown): catch out-of-line unary operator&: # class X {}; # int operator&(const X& x) { return 42; } // unary operator& # The trick is it's hard to tell apart from binary operator&: # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& if Search(r'\boperator\s*&\s*\(\s*\)', line): error(filename, linenum, 'runtime/operator', 4, 'Unary operator& is dangerous. Do not use it.') # Check for suspicious usage of "if" like # } if (a == b) { if Search(r'\}\s*if\s*\(', line): error(filename, linenum, 'readability/braces', 4, 'Did you mean "else if"? If not, start a new line for "if".') # Check for potential format string bugs like printf(foo). # We constrain the pattern not to pick things like DocidForPrintf(foo). # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) # TODO(sugawarayu): Catch the following case. Need to change the calling # convention of the whole function to process multiple line to handle it. # printf( # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') if printf_args: match = Match(r'([\w.\->()]+)$', printf_args) if match and match.group(1) != '__VA_ARGS__': function_name = re.search(r'\b((?:string)?printf)\s*\(', line, re.I).group(1) error(filename, linenum, 'runtime/printf', 4, 'Potential format string bug. Do %s("%%s", %s) instead.' % (function_name, match.group(1))) # Check for potential memset bugs like memset(buf, sizeof(buf), 0). match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): error(filename, linenum, 'runtime/memset', 4, 'Did you mean "memset(%s, 0, %s)"?' % (match.group(1), match.group(2))) if Search(r'\busing namespace\b', line): error(filename, linenum, 'build/namespaces', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') # Detect variable-length arrays. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) if (match and match.group(2) != 'return' and match.group(2) != 'delete' and match.group(3).find(']') == -1): # Split the size using space and arithmetic operators as delimiters. # If any of the resulting tokens are not compile time constants then # report the error. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) is_const = True skip_next = False for tok in tokens: if skip_next: skip_next = False continue if Search(r'sizeof\(.+\)', tok): continue if Search(r'arraysize\(\w+\)', tok): continue tok = tok.lstrip('(') tok = tok.rstrip(')') if not tok: continue if Match(r'\d+', tok): continue if Match(r'0[xX][0-9a-fA-F]+', tok): continue if Match(r'k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue # A catch all for tricky sizeof cases, including 'sizeof expression', # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' # requires skipping the next token because we split on ' ' and '*'. if tok.startswith('sizeof'): skip_next = True continue is_const = False break if not is_const: error(filename, linenum, 'runtime/arrays', 1, 'Do not use variable-length arrays. Use an appropriately named ' "('k' followed by CamelCase) compile-time constant for the size.") # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing # in the class declaration. match = Match( (r'\s*' r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))' r'\(.*\);$'), line) if match and linenum + 1 < clean_lines.NumLines(): next_line = clean_lines.elided[linenum + 1] # We allow some, but not all, declarations of variables to be present # in the statement that defines the class. The [\w\*,\s]* fragment of # the regular expression below allows users to declare instances of # the class or pointers to instances, but not less common types such # as function pointers or arrays. It's a tradeoff between allowing # reasonable code and avoiding trying to parse more C++ using regexps. if not Search(r'^\s*}[\w\*,\s]*;', next_line): error(filename, linenum, 'readability/constructors', 3, match.group(1) + ' should be the last thing in the class') # Check for use of unnamed namespaces in header files. Registration # macros are typically OK, so we allow use of "namespace {" on lines # that end with backslashes. if (file_extension == 'h' and Search(r'\bnamespace\s*{', line) and line[-1] != '\\'): error(filename, linenum, 'build/namespaces', 4, 'Do not use unnamed namespaces in header files. See ' 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' ' for more information.') def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknwon): Doesn't account for preprocessor directives. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. check_params = False if not nesting_state.stack: check_params = True # top level elif (isinstance(nesting_state.stack[-1], _ClassInfo) or isinstance(nesting_state.stack[-1], _NamespaceInfo)): check_params = True # within class or namespace elif Match(r'.*{\s*$', line): if (len(nesting_state.stack) == 1 or isinstance(nesting_state.stack[-2], _ClassInfo) or isinstance(nesting_state.stack[-2], _NamespaceInfo)): check_params = True # just opened global/class/namespace block # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(whitelisted_functions, line): check_params = False elif not Search(r'\S+\([^)]*$', line): # Don't see a whitelisted function on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): check_params = False break if check_params: decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter)) def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ match = Search(pattern, line) if not match: return False # Exclude lines with sizeof, since sizeof looks like a cast. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) if sizeof_match: return False # operator++(int) and operator--(int) if (line[0:match.start(1) - 1].endswith(' operator++') or line[0:match.start(1) - 1].endswith(' operator--')): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True _HEADERS_CONTAINING_TEMPLATES = ( ('<deque>', ('deque',)), ('<functional>', ('unary_function', 'binary_function', 'plus', 'minus', 'multiplies', 'divides', 'modulus', 'negate', 'equal_to', 'not_equal_to', 'greater', 'less', 'greater_equal', 'less_equal', 'logical_and', 'logical_or', 'logical_not', 'unary_negate', 'not1', 'binary_negate', 'not2', 'bind1st', 'bind2nd', 'pointer_to_unary_function', 'pointer_to_binary_function', 'ptr_fun', 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', 'mem_fun_ref_t', 'const_mem_fun_t', 'const_mem_fun1_t', 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', 'mem_fun_ref', )), ('<limits>', ('numeric_limits',)), ('<list>', ('list',)), ('<map>', ('map', 'multimap',)), ('<memory>', ('allocator',)), ('<queue>', ('queue', 'priority_queue',)), ('<set>', ('set', 'multiset',)), ('<stack>', ('stack',)), ('<string>', ('char_traits', 'basic_string',)), ('<utility>', ('pair',)), ('<vector>', ('vector',)), # gcc extensions. # Note: std::hash is their hash, ::hash is our hash ('<hash_map>', ('hash_map', 'hash_multimap',)), ('<hash_set>', ('hash_set', 'hash_multiset',)), ('<slist>', ('slist',)), ) _RE_PATTERN_STRING = re.compile(r'\bstring\b') _re_pattern_algorithm_header = [] for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap', 'transform'): # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or # type::max(). _re_pattern_algorithm_header.append( (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), _template, '<algorithm>')) _re_pattern_templates = [] for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: for _template in _templates: _re_pattern_templates.append( (re.compile(r'(\<|\b)' + _template + r'\s*\<'), _template + '<>', _header)) def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ if not filename_cc.endswith('.cc'): return (False, '') filename_cc = filename_cc[:-len('.cc')] if filename_cc.endswith('_unittest'): filename_cc = filename_cc[:-len('_unittest')] elif filename_cc.endswith('_test'): filename_cc = filename_cc[:-len('_test')] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') if not filename_h.endswith('.h'): return (False, '') filename_h = filename_h[:-len('.h')] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path def UpdateIncludeState(filename, include_state, io=codecs): """Fill up the include_state with new includes found from the file. Args: filename: the name of the header to read. include_state: an _IncludeState instance in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was successfully added. False otherwise. """ headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _RE_PATTERN_INCLUDE.search(clean_line) if match: include = match.group(2) # The value formatting is cute, but not really used right now. # What matters here is that the key is in include_state. include_state.setdefault(include, '%s:%d' % (filename, linenum)) return True def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's copy the include_state so it is only messed up within this function. include_state = include_state.copy() # Did we find the header for this file (if any) and successfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_state is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_state.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_state, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_state: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template) _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly') def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM: return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckCaffeAlternatives(filename, clean_lines, line, error) CheckCaffeDataLayerSetUp(filename, clean_lines, line, error) CheckCaffeRandom(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error) def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=[]): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ lines = (['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way']) include_state = _IncludeState() function_state = _FunctionState() nesting_state = _NestingState() ResetNolintSuppressions() CheckForCopyright(filename, lines, error) if file_extension == 'h': CheckForHeaderGuard(filename, lines, error) RemoveMultiLineComments(filename, lines, error) clean_lines = CleansedLines(lines) for line in xrange(clean_lines.NumLines()): ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions) nesting_state.CheckCompletedBlocks(filename, error) CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) # We check here rather than inside ProcessLine so that we see raw # lines rather than "cleaned" lines. CheckForBadCharacters(filename, lines, error) CheckForNewlineAtEOF(filename, lines, error) def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. If it is not expected to be present (i.e. os.linesep != # '\r\n' as in Windows), a warning is issued below if this file # is processed. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') carriage_return_found = False # Remove trailing '\r'. for linenum in range(len(lines)): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') carriage_return_found = True except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in _valid_extensions: sys.stderr.write('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(_valid_extensions))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) if carriage_return_found and os.linesep != '\r\n': # Use 0 for linenum since outputting only one error for potentially # several lines. Error(filename, 0, 'whitespace/newline', 1, 'One or more unexpected \\r (^M) found;' 'better to use only a \\n') sys.stderr.write('Done processing %s\n' % filename) def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1) def PrintCategories(): """Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter. """ sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) sys.exit(0) def ParseArguments(args): """Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint. """ try: (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'counting=', 'filter=', 'root=', 'linelength=', 'extensions=']) except getopt.GetoptError: PrintUsage('Invalid arguments.') verbosity = _VerboseLevel() output_format = _OutputFormat() filters = '' counting_style = '' for (opt, val) in opts: if opt == '--help': PrintUsage(None) elif opt == '--output': if val not in ('emacs', 'vs7', 'eclipse'): PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') output_format = val elif opt == '--verbose': verbosity = int(val) elif opt == '--filter': filters = val if not filters: PrintCategories() elif opt == '--counting': if val not in ('total', 'toplevel', 'detailed'): PrintUsage('Valid counting options are total, toplevel, and detailed') counting_style = val elif opt == '--root': global _root _root = val elif opt == '--linelength': global _line_length try: _line_length = int(val) except ValueError: PrintUsage('Line length must be digits.') elif opt == '--extensions': global _valid_extensions try: _valid_extensions = set(val.split(',')) except ValueError: PrintUsage('Extensions must be comma separated list.') if not filenames: PrintUsage('No files were specified.') _SetOutputFormat(output_format) _SetVerboseLevel(verbosity) _SetFilters(filters) _SetCountingStyle(counting_style) return filenames def main(): filenames = ParseArguments(sys.argv[1:]) # Change stderr to write with replacement characters so we don't die # if we try to print something containing non-ASCII characters. sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') _cpplint_state.ResetErrorCounts() for filename in filenames: ProcessFile(filename, _cpplint_state.verbose_level) _cpplint_state.PrintErrorCounts() sys.exit(_cpplint_state.error_count > 0) if __name__ == '__main__': main()
187,450
37.49887
93
py
bottom-up-attention
bottom-up-attention-master/caffe/scripts/split_caffe_proto.py
#!/usr/bin/env python import mmap import re import os import errno script_path = os.path.dirname(os.path.realpath(__file__)) # a regex to match the parameter definitions in caffe.proto r = re.compile(r'(?://.*\n)*message ([^ ]*) \{\n(?: .*\n|\n)*\}') # create directory to put caffe.proto fragments try: os.mkdir( os.path.join(script_path, '../docs/_includes/')) os.mkdir( os.path.join(script_path, '../docs/_includes/proto/')) except OSError as exception: if exception.errno != errno.EEXIST: raise caffe_proto_fn = os.path.join( script_path, '../src/caffe/proto/caffe.proto') with open(caffe_proto_fn, 'r') as fin: for m in r.finditer(fin.read(), re.MULTILINE): fn = os.path.join( script_path, '../docs/_includes/proto/%s.txt' % m.group(1)) with open(fn, 'w') as fout: fout.write(m.group(0))
941
25.166667
65
py
bottom-up-attention
bottom-up-attention-master/caffe/scripts/download_model_binary.py
#!/usr/bin/env python import os import sys import time import yaml import hashlib import argparse from six.moves import urllib required_keys = ['caffemodel', 'caffemodel_url', 'sha1'] def reporthook(count, block_size, total_size): """ From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ """ global start_time if count == 0: start_time = time.time() return duration = (time.time() - start_time) or 0.01 progress_size = int(count * block_size) speed = int(progress_size / (1024 * duration)) percent = int(count * block_size * 100 / total_size) sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" % (percent, progress_size / (1024 * 1024), speed, duration)) sys.stdout.flush() def parse_readme_frontmatter(dirname): readme_filename = os.path.join(dirname, 'readme.md') with open(readme_filename) as f: lines = [line.strip() for line in f.readlines()] top = lines.index('---') bottom = lines.index('---', top + 1) frontmatter = yaml.load('\n'.join(lines[top + 1:bottom])) assert all(key in frontmatter for key in required_keys) return dirname, frontmatter def valid_dirname(dirname): try: return parse_readme_frontmatter(dirname) except Exception as e: print('ERROR: {}'.format(e)) raise argparse.ArgumentTypeError( 'Must be valid Caffe model directory with a correct readme.md') if __name__ == '__main__': parser = argparse.ArgumentParser( description='Download trained model binary.') parser.add_argument('dirname', type=valid_dirname) args = parser.parse_args() # A tiny hack: the dirname validator also returns readme YAML frontmatter. dirname = args.dirname[0] frontmatter = args.dirname[1] model_filename = os.path.join(dirname, frontmatter['caffemodel']) # Closure-d function for checking SHA1. def model_checks_out(filename=model_filename, sha1=frontmatter['sha1']): with open(filename, 'rb') as f: return hashlib.sha1(f.read()).hexdigest() == sha1 # Check if model exists. if os.path.exists(model_filename) and model_checks_out(): print("Model already exists.") sys.exit(0) # Download and verify model. urllib.request.urlretrieve( frontmatter['caffemodel_url'], model_filename, reporthook) if not model_checks_out(): print('ERROR: model did not download correctly! Run this again.') sys.exit(1)
2,531
31.461538
78
py
bottom-up-attention
bottom-up-attention-master/caffe/scripts/copy_notebook.py
#!/usr/bin/env python """ Takes as arguments: 1. the path to a JSON file (such as an IPython notebook). 2. the path to output file If 'metadata' dict in the JSON file contains 'include_in_docs': true, then copies the file to output file, appending the 'metadata' property as YAML front-matter, adding the field 'category' with value 'notebook'. """ import os import sys import json filename = sys.argv[1] output_filename = sys.argv[2] content = json.load(open(filename)) if 'include_in_docs' in content['metadata'] and content['metadata']['include_in_docs']: yaml_frontmatter = ['---'] for key, val in content['metadata'].iteritems(): if key == 'example_name': key = 'title' if val == '': val = os.path.basename(filename) yaml_frontmatter.append('{}: {}'.format(key, val)) yaml_frontmatter += ['category: notebook'] yaml_frontmatter += ['original_path: ' + filename] with open(output_filename, 'w') as fo: fo.write('\n'.join(yaml_frontmatter + ['---']) + '\n') fo.write(open(filename).read())
1,089
32.030303
87
py
bottom-up-attention
bottom-up-attention-master/lib/setup.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import os from os.path import join as pjoin from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import subprocess import numpy as np def find_in_path(name, path): "Find a file in a search path" # Adapted fom # http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/ for dir in path.split(os.pathsep): binpath = pjoin(dir, name) if os.path.exists(binpath): return os.path.abspath(binpath) return None def locate_cuda(): """Locate the CUDA environment on the system Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64' and values giving the absolute path to each directory. Starts by looking for the CUDAHOME env variable. If not found, everything is based on finding 'nvcc' in the PATH. """ # first check if the CUDAHOME env variable is in use if 'CUDAHOME' in os.environ: home = os.environ['CUDAHOME'] nvcc = pjoin(home, 'bin', 'nvcc') else: # otherwise, search the PATH for NVCC default_path = pjoin(os.sep, 'usr', 'local', 'cuda', 'bin') nvcc = find_in_path('nvcc', os.environ['PATH'] + os.pathsep + default_path) if nvcc is None: raise EnvironmentError('The nvcc binary could not be ' 'located in your $PATH. Either add it to your path, or set $CUDAHOME') home = os.path.dirname(os.path.dirname(nvcc)) cudaconfig = {'home':home, 'nvcc':nvcc, 'include': pjoin(home, 'include'), 'lib64': pjoin(home, 'lib64')} for k, v in cudaconfig.iteritems(): if not os.path.exists(v): raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v)) return cudaconfig CUDA = locate_cuda() # Obtain the numpy include directory. This logic works across numpy versions. try: numpy_include = np.get_include() except AttributeError: numpy_include = np.get_numpy_include() def customize_compiler_for_nvcc(self): """inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on.""" # tell the compiler it can processes .cu self.src_extensions.append('.cu') # save references to the default compiler_so and _comple methods default_compiler_so = self.compiler_so super = self._compile # now redefine the _compile method. This gets executed for each # object but distutils doesn't have the ability to change compilers # based on source extension: we add it. def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): if os.path.splitext(src)[1] == '.cu': # use the cuda for .cu files self.set_executable('compiler_so', CUDA['nvcc']) # use only a subset of the extra_postargs, which are 1-1 translated # from the extra_compile_args in the Extension class postargs = extra_postargs['nvcc'] else: postargs = extra_postargs['gcc'] super(obj, src, ext, cc_args, postargs, pp_opts) # reset the default compiler_so, which we might have changed for cuda self.compiler_so = default_compiler_so # inject our redefined _compile method into the class self._compile = _compile # run the customize_compiler class custom_build_ext(build_ext): def build_extensions(self): customize_compiler_for_nvcc(self.compiler) build_ext.build_extensions(self) ext_modules = [ Extension( "utils.cython_bbox", ["utils/bbox.pyx"], extra_compile_args={'gcc': ["-Wno-cpp", "-Wno-unused-function"]}, include_dirs = [numpy_include] ), Extension( "nms.cpu_nms", ["nms/cpu_nms.pyx"], extra_compile_args={'gcc': ["-Wno-cpp", "-Wno-unused-function"]}, include_dirs = [numpy_include] ), Extension('nms.gpu_nms', ['nms/nms_kernel.cu', 'nms/gpu_nms.pyx'], library_dirs=[CUDA['lib64']], libraries=['cudart'], language='c++', runtime_library_dirs=[CUDA['lib64']], # this syntax is specific to this build system # we're only going to use certain compiler args with nvcc and not with # gcc the implementation of this trick is in customize_compiler() below extra_compile_args={'gcc': ["-Wno-unused-function"], 'nvcc': ['-arch=sm_35', '--ptxas-options=-v', '-c', '--compiler-options', "'-fPIC'"]}, include_dirs = [numpy_include, CUDA['include']] ), Extension( 'pycocotools._mask', sources=['pycocotools/maskApi.c', 'pycocotools/_mask.pyx'], include_dirs = [numpy_include, 'pycocotools'], extra_compile_args={ 'gcc': ['-Wno-cpp', '-Wno-unused-function', '-std=c99']}, ), ] setup( name='fast_rcnn', ext_modules=ext_modules, # inject our custom trigger cmdclass={'build_ext': custom_build_ext}, )
5,665
35.089172
90
py
bottom-up-attention
bottom-up-attention-master/lib/roi_data_layer/layer.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """The data layer used during training to train a Fast R-CNN network. RoIDataLayer implements a Caffe Python layer. """ import caffe from fast_rcnn.config import cfg from roi_data_layer.minibatch import get_minibatch import numpy as np import yaml from multiprocessing import Process, Queue class RoIDataLayer(caffe.Layer): """Fast R-CNN data layer used for training.""" def _shuffle_roidb_inds(self, gpu_id=0): self.gpu_id = gpu_id """Randomly permute the training roidb.""" if cfg.TRAIN.ASPECT_GROUPING: widths = np.array([r['width'] for r in self._roidb]) heights = np.array([r['height'] for r in self._roidb]) horz = (widths >= heights) vert = np.logical_not(horz) horz_inds = np.where(horz)[0] vert_inds = np.where(vert)[0] inds = np.hstack(( np.random.permutation(horz_inds), np.random.permutation(vert_inds))) inds = np.reshape(inds, (-1, 2)) np.random.seed(gpu_id) row_perm = np.random.permutation(np.arange(inds.shape[0])) inds = np.reshape(inds[row_perm, :], (-1,)) self._perm = inds else: self._perm = np.random.permutation(np.arange(len(self._roidb))) self._cur = 0 def _get_next_minibatch_inds(self): """Return the roidb indices for the next minibatch.""" if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb): self._shuffle_roidb_inds(self.gpu_id) db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH] self._cur += cfg.TRAIN.IMS_PER_BATCH return db_inds def _get_next_minibatch(self): """Return the blobs to be used for the next minibatch. If cfg.TRAIN.USE_PREFETCH is True, then blobs will be computed in a separate process and made available through self._blob_queue. """ if cfg.TRAIN.USE_PREFETCH: return self._blob_queue.get() else: db_inds = self._get_next_minibatch_inds() minibatch_db = [self._roidb[i] for i in db_inds] return get_minibatch(minibatch_db, self._num_classes) def set_roidb(self, roidb, gpu_id=0): """Set the roidb to be used by this layer during training.""" self._roidb = roidb self._shuffle_roidb_inds(gpu_id) if cfg.TRAIN.USE_PREFETCH: self._blob_queue = Queue(10) self._prefetch_process = BlobFetcher(self._blob_queue, self._roidb, self._num_classes, gpu_id) self._prefetch_process.start() # Terminate the child process when the parent exists def cleanup(): print 'Terminating BlobFetcher' self._prefetch_process.terminate() self._prefetch_process.join() import atexit atexit.register(cleanup) def setup(self, bottom, top): """Setup the RoIDataLayer.""" # parse the layer parameter string, which must be valid YAML layer_params = yaml.load(self.param_str) self._num_classes = layer_params['num_classes'] self._name_to_top_map = {} # data blob: holds a batch of N images, each with 3 channels idx = 0 top[idx].reshape(cfg.TRAIN.IMS_PER_BATCH, 3, max(cfg.TRAIN.SCALES), cfg.TRAIN.MAX_SIZE) self._name_to_top_map['data'] = idx idx += 1 if cfg.TRAIN.HAS_RPN: top[idx].reshape(1, 3) self._name_to_top_map['im_info'] = idx idx += 1 top[idx].reshape(1, 4) self._name_to_top_map['gt_boxes'] = idx idx += 1 else: # not using RPN # rois blob: holds R regions of interest, each is a 5-tuple # (n, x1, y1, x2, y2) specifying an image batch index n and a # rectangle (x1, y1, x2, y2) top[idx].reshape(1, 5, 1, 1) self._name_to_top_map['rois'] = idx idx += 1 # labels blob: R categorical labels in [0, ..., K] for K foreground # classes plus background top[idx].reshape(1, 1, 1, 1) self._name_to_top_map['labels'] = idx idx += 1 if cfg.TRAIN.BBOX_REG: # bbox_targets blob: R bounding-box regression targets with 4 # targets per class num_reg_class = 2 if cfg.TRAIN.AGNOSTIC else self._num_classes top[idx].reshape(1, num_reg_class * 4, 1, 1) self._name_to_top_map['bbox_targets'] = idx idx += 1 # bbox_inside_weights blob: At most 4 targets per roi are active; # thisbinary vector sepcifies the subset of active targets top[idx].reshape(1, num_reg_class * 4, 1, 1) self._name_to_top_map['bbox_inside_weights'] = idx idx += 1 top[idx].reshape(1, num_reg_class * 4, 1, 1) self._name_to_top_map['bbox_outside_weights'] = idx idx += 1 print 'RoiDataLayer: name_to_top:', self._name_to_top_map assert len(top) == len(self._name_to_top_map) def forward(self, bottom, top): """Get blobs and copy them into this layer's top blob vector.""" blobs = self._get_next_minibatch() for blob_name, blob in blobs.iteritems(): top_ind = self._name_to_top_map[blob_name] shape = blob.shape if len(shape) == 1: blob = blob.reshape(blob.shape[0], 1, 1, 1) if len(shape) == 2 and blob_name != 'im_info': blob = blob.reshape(blob.shape[0], blob.shape[1], 1, 1) top[top_ind].reshape(*(blob.shape)) # Copy data into net's input blobs top[top_ind].data[...] = blob.astype(np.float32, copy=False) def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" pass def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass class BlobFetcher(Process): """Experimental class for prefetching blobs in a separate process.""" def __init__(self, queue, roidb, num_classes, gpu_id=0): super(BlobFetcher, self).__init__() self._queue = queue self._roidb = roidb self._num_classes = num_classes self._perm = None self._cur = 0 self.gpu_id = gpu_id np.random.seed(gpu_id) self._shuffle_roidb_inds() def _shuffle_roidb_inds(self): """Randomly permute the training roidb.""" # TODO(rbg): remove duplicated code self._perm = np.random.permutation(np.arange(len(self._roidb))) self._cur = 0 def _get_next_minibatch_inds(self): """Return the roidb indices for the next minibatch.""" # TODO(rbg): remove duplicated code if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb): self._shuffle_roidb_inds() db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH] self._cur += cfg.TRAIN.IMS_PER_BATCH return db_inds def run(self): print 'BlobFetcher started' while True: db_inds = self._get_next_minibatch_inds() minibatch_db = [self._roidb[i] for i in db_inds] blobs = get_minibatch(minibatch_db, self._num_classes) self._queue.put(blobs)
7,856
37.326829
81
py
bottom-up-attention
bottom-up-attention-master/lib/roi_data_layer/roidb.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Transform a roidb into a trainable roidb by adding a bunch of metadata.""" import numpy as np from fast_rcnn.config import cfg from fast_rcnn.bbox_transform import bbox_transform from utils.cython_bbox import bbox_overlaps import PIL def prepare_roidb(imdb): """Enrich the imdb's roidb by adding some derived quantities that are useful for training. This function precomputes the maximum overlap, taken over ground-truth boxes, between each ROI and each ground-truth box. The class with maximum overlap is also recorded. """ sizes = [PIL.Image.open(imdb.image_path_at(i)).size for i in xrange(imdb.num_images)] roidb = imdb.roidb for i in xrange(len(imdb.image_index)): roidb[i]['image'] = imdb.image_path_at(i) roidb[i]['width'] = sizes[i][0] roidb[i]['height'] = sizes[i][1] # need gt_overlaps as a dense array for argmax gt_overlaps = roidb[i]['gt_overlaps'].toarray() # max overlap with gt over classes (columns) max_overlaps = gt_overlaps.max(axis=1) # gt class that had the max overlap max_classes = gt_overlaps.argmax(axis=1) roidb[i]['max_classes'] = max_classes roidb[i]['max_overlaps'] = max_overlaps # sanity checks # max overlap of 0 => class should be zero (background) zero_inds = np.where(max_overlaps == 0)[0] assert all(max_classes[zero_inds] == 0) # max overlap > 0 => class should not be zero (must be a fg class) nonzero_inds = np.where(max_overlaps > 0)[0] assert all(max_classes[nonzero_inds] != 0) def add_bbox_regression_targets(roidb): """Add information needed to train bounding-box regressors.""" assert len(roidb) > 0 assert 'max_classes' in roidb[0], 'Did you call prepare_roidb first?' num_images = len(roidb) # Infer number of classes from the number of columns in gt_overlaps num_reg_classes = 2 if cfg.TRAIN.AGNOSTIC else roidb[0]['gt_overlaps'].shape[1] for im_i in xrange(num_images): rois = roidb[im_i]['boxes'] max_overlaps = roidb[im_i]['max_overlaps'] max_classes = roidb[im_i]['max_classes'] roidb[im_i]['bbox_targets'] = \ _compute_targets(rois, max_overlaps, max_classes) if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED: # Use fixed / precomputed "means" and "stds" instead of empirical values means = np.tile( np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS), (num_reg_classes, 1)) stds = np.tile( np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS), (num_reg_classes, 1)) else: # Compute values needed for means and stds # var(x) = E(x^2) - E(x)^2 class_counts = np.zeros((num_reg_classes, 1)) + cfg.EPS sums = np.zeros((num_reg_classes, 4)) squared_sums = np.zeros((num_reg_classes, 4)) for im_i in xrange(num_images): targets = roidb[im_i]['bbox_targets'] for cls in xrange(1, num_reg_classes): cls_inds = np.where(targets[:, 0] > 0)[0] if cfg.TRAIN.AGNOSTIC \ else np.where(targets[:, 0] == cls)[0] if cls_inds.size > 0: class_counts[cls] += cls_inds.size sums[cls, :] += targets[cls_inds, 1:].sum(axis=0) squared_sums[cls, :] += \ (targets[cls_inds, 1:] ** 2).sum(axis=0) means = sums / class_counts stds = np.sqrt(squared_sums / class_counts - means ** 2) print 'bbox target means:' print means print means[1:, :].mean(axis=0) # ignore bg class print 'bbox target stdevs:' print stds print stds[1:, :].mean(axis=0) # ignore bg class # Normalize targets if cfg.TRAIN.BBOX_NORMALIZE_TARGETS: print "Normalizing targets" for im_i in xrange(num_images): targets = roidb[im_i]['bbox_targets'] for cls in xrange(1, num_reg_classes): cls_inds = np.where(targets[:, 0] > 0) if cfg.TRAIN.AGNOSTIC \ else np.where(targets[:, 0] == cls)[0] roidb[im_i]['bbox_targets'][cls_inds, 1:] -= means[cls, :] roidb[im_i]['bbox_targets'][cls_inds, 1:] /= stds[cls, :] else: print "NOT normalizing targets" # These values will be needed for making predictions # (the predicts will need to be unnormalized and uncentered) return means.ravel(), stds.ravel() def _compute_targets(rois, overlaps, labels): """Compute bounding-box regression targets for an image.""" # Indices of ground-truth ROIs gt_inds = np.where(overlaps == 1)[0] if len(gt_inds) == 0: # Bail if the image has no ground-truth ROIs return np.zeros((rois.shape[0], 5), dtype=np.float32) # Indices of examples for which we try to make predictions ex_inds = np.where(overlaps >= cfg.TRAIN.BBOX_THRESH)[0] # Get IoU overlap between each ex ROI and gt ROI ex_gt_overlaps = bbox_overlaps( np.ascontiguousarray(rois[ex_inds, :], dtype=np.float), np.ascontiguousarray(rois[gt_inds, :], dtype=np.float)) # Find which gt ROI each ex ROI has max overlap with: # this will be the ex ROI's gt target gt_assignment = ex_gt_overlaps.argmax(axis=1) gt_rois = rois[gt_inds[gt_assignment], :] ex_rois = rois[ex_inds, :] targets = np.zeros((rois.shape[0], 5), dtype=np.float32) targets[ex_inds, 0] = labels[ex_inds] targets[ex_inds, 1:] = bbox_transform(ex_rois, gt_rois) return targets
5,818
40.863309
83
py
bottom-up-attention
bottom-up-attention-master/lib/roi_data_layer/minibatch.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Compute minibatch blobs for training a Fast R-CNN network.""" import numpy as np import numpy.random as npr import scipy.sparse as sparse import cv2 from fast_rcnn.config import cfg from utils.blob import prep_im_for_blob, im_list_to_blob def get_minibatch(roidb, num_classes): """Given a roidb, construct a minibatch sampled from it.""" num_images = len(roidb) num_reg_class = 2 if cfg.TRAIN.AGNOSTIC else num_classes # Sample random scales to use for each image in this batch random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES), size=num_images) assert(cfg.TRAIN.BATCH_SIZE % num_images == 0) or (cfg.TRAIN.BATCH_SIZE == -1), \ 'num_images ({}) must divide BATCH_SIZE ({})'. \ format(num_images, cfg.TRAIN.BATCH_SIZE) rois_per_image = np.inf if cfg.TRAIN.BATCH_SIZE == -1 else cfg.TRAIN.BATCH_SIZE / num_images fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image) # Get the input image blob, formatted for caffe im_blob, im_scales = _get_image_blob(roidb, random_scale_inds) blobs = {'data': im_blob} if cfg.TRAIN.HAS_RPN: assert len(im_scales) == 1, "Single batch only" assert len(roidb) == 1, "Single batch only" # gt boxes: (x1, y1, x2, y2, cls) gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0] num_gt = len(gt_inds) assert num_gt > 0, "gt must not be empty" if cfg.TRAIN.HAS_ATTRIBUTES: if cfg.TRAIN.HAS_RELATIONS: gt_boxes = np.zeros((num_gt, 21 + num_gt), dtype=np.float32) else: gt_boxes = np.zeros((num_gt, 21), dtype=np.float32) else: gt_boxes = np.zeros((num_gt, 5), dtype=np.float32) gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :] * im_scales[0] gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds] if cfg.TRAIN.HAS_ATTRIBUTES: gt_boxes[:, 5:21] = roidb[0]['gt_attributes'][gt_inds].toarray() if cfg.TRAIN.HAS_RELATIONS: assert num_gt == roidb[0]['gt_classes'].shape[0], \ "Generation of gt_relations doesn't accomodate dropping objects" coords = roidb[0]['gt_relations'] # i,relation,j if coords.size > 0: assert num_gt > coords.max(axis=0)[0], \ "gt_relations subject index exceeds number of objects" assert num_gt > coords.max(axis=0)[2], \ "gt_relations object index exceeds number of objects" np.random.shuffle(coords) # There may be multiple relations between same objects rel_matrix = gt_boxes[:, 21:] for r in range(coords.shape[0]): rel_matrix[coords[r,0],coords[r,2]] = coords[r,1] blobs['gt_boxes'] = gt_boxes blobs['im_info'] = np.array( [[im_blob.shape[2], im_blob.shape[3], im_scales[0]]], dtype=np.float32) else: # not using RPN # Now, build the region of interest and label blobs rois_blob = np.zeros((0, 5), dtype=np.float32) labels_blob = np.zeros((0), dtype=np.float32) bbox_targets_blob = np.zeros((0, 4 * num_reg_class), dtype=np.float32) bbox_inside_blob = np.zeros(bbox_targets_blob.shape, dtype=np.float32) # all_overlaps = [] for im_i in xrange(num_images): labels, overlaps, im_rois, bbox_targets, bbox_inside_weights \ = _sample_rois(roidb[im_i], fg_rois_per_image, rois_per_image, num_classes) # Add to RoIs blob rois = _project_im_rois(im_rois, im_scales[im_i]) batch_ind = im_i * np.ones((rois.shape[0], 1)) rois_blob_this_image = np.hstack((batch_ind, rois)) rois_blob = np.vstack((rois_blob, rois_blob_this_image)) # Add to labels, bbox targets, and bbox loss blobs labels_blob = np.hstack((labels_blob, labels)) bbox_targets_blob = np.vstack((bbox_targets_blob, bbox_targets)) bbox_inside_blob = np.vstack((bbox_inside_blob, bbox_inside_weights)) # all_overlaps = np.hstack((all_overlaps, overlaps)) # For debug visualizations # _vis_minibatch(im_blob, rois_blob, labels_blob, all_overlaps) blobs['rois'] = rois_blob blobs['labels'] = labels_blob if cfg.TRAIN.BBOX_REG: blobs['bbox_targets'] = bbox_targets_blob blobs['bbox_inside_weights'] = bbox_inside_blob blobs['bbox_outside_weights'] = \ np.array(bbox_inside_blob > 0).astype(np.float32) return blobs def _sample_rois(roidb, fg_rois_per_image, rois_per_image, num_classes): """Generate a random sample of RoIs comprising foreground and background examples. """ # label = class RoI has max overlap with labels = roidb['max_classes'] overlaps = roidb['max_overlaps'] rois = roidb['boxes'] # Select foreground RoIs as those with >= FG_THRESH overlap fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0] # Guard against the case when an image has fewer than fg_rois_per_image # foreground RoIs fg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_inds.size) # Sample foreground regions without replacement if fg_inds.size > 0: fg_inds = npr.choice( fg_inds, size=fg_rois_per_this_image, replace=False) # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO))[0] # Compute number of background RoIs to take from this image (guarding # against there being fewer than desired) bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image bg_rois_per_this_image = np.minimum(bg_rois_per_this_image, bg_inds.size) # Sample foreground regions without replacement if bg_inds.size > 0: bg_inds = npr.choice( bg_inds, size=bg_rois_per_this_image, replace=False) # The indices that we're selecting (both fg and bg) keep_inds = np.append(fg_inds, bg_inds) # Select sampled values from various arrays: labels = labels[keep_inds] # Clamp labels for the background RoIs to 0 labels[fg_rois_per_this_image:] = 0 overlaps = overlaps[keep_inds] rois = rois[keep_inds] bbox_targets, bbox_inside_weights = _get_bbox_regression_labels( roidb['bbox_targets'][keep_inds, :], num_classes) return labels, overlaps, rois, bbox_targets, bbox_inside_weights def _get_image_blob(roidb, scale_inds): """Builds an input blob from the images in the roidb at the specified scales. """ num_images = len(roidb) processed_ims = [] im_scales = [] for i in xrange(num_images): im = cv2.imread(roidb[i]['image']) if roidb[i]['flipped']: im = im[:, ::-1, :] target_size = cfg.TRAIN.SCALES[scale_inds[i]] im, im_scale = prep_im_for_blob(im, cfg.PIXEL_MEANS, target_size, cfg.TRAIN.MAX_SIZE) im_scales.append(im_scale) processed_ims.append(im) # Create a blob to hold the input images blob = im_list_to_blob(processed_ims) return blob, im_scales def _project_im_rois(im_rois, im_scale_factor): """Project image RoIs into the rescaled training image.""" rois = im_rois * im_scale_factor return rois def _get_bbox_regression_labels(bbox_target_data, num_classes): """Bounding-box regression targets are stored in a compact form in the roidb. This function expands those targets into the 4-of-4*K representation used by the network (i.e. only one class has non-zero targets). The loss weights are similarly expanded. Returns: bbox_target_data (ndarray): N x 4K blob of regression targets bbox_inside_weights (ndarray): N x 4K blob of loss weights """ clss = bbox_target_data[:, 0] num_reg_class = 2 if cfg.TRAIN.AGNOSTIC else num_classes bbox_targets = np.zeros((clss.size, 4 * num_reg_class), dtype=np.float32) bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32) inds = np.where(clss > 0)[0] if cfg.TRAIN.AGNOSTIC: for ind in inds: cls = clss[ind] start = 4 * (1 if cls > 0 else 0) end = start + 4 bbox_targets[ind, start:end] = bbox_target_data[ind, 1:] bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS else: for ind in inds: cls = clss[ind] start = 4 * cls end = start + 4 bbox_targets[ind, start:end] = bbox_target_data[ind, 1:] bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS return bbox_targets, bbox_inside_weights def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps): """Visualize a mini-batch for debugging.""" import matplotlib.pyplot as plt for i in xrange(rois_blob.shape[0]): rois = rois_blob[i, :] im_ind = rois[0] roi = rois[1:] im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy() im += cfg.PIXEL_MEANS im = im[:, :, (2, 1, 0)] im = im.astype(np.uint8) cls = labels_blob[i] plt.imshow(im) print 'class: ', cls, ' overlap: ', overlaps[i] plt.gca().add_patch( plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0], roi[3] - roi[1], fill=False, edgecolor='r', linewidth=3) ) plt.show()
10,006
41.046218
96
py
bottom-up-attention
bottom-up-attention-master/lib/roi_data_layer/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # --------------------------------------------------------
248
34.571429
58
py
bottom-up-attention
bottom-up-attention-master/lib/fast_rcnn/test.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Test a Fast R-CNN network on an imdb (image database).""" from fast_rcnn.config import cfg, get_output_dir from fast_rcnn.bbox_transform import clip_boxes, bbox_transform_inv import argparse from utils.timer import Timer import numpy as np import cv2 import caffe from fast_rcnn.nms_wrapper import nms, soft_nms import cPickle from utils.blob import im_list_to_blob import os from utils.cython_bbox import bbox_overlaps def _get_image_blob(im): """Converts an image into a network input. Arguments: im (ndarray): a color image in BGR order Returns: blob (ndarray): a data blob holding an image pyramid im_scale_factors (list): list of image scales (relative to im) used in the image pyramid """ im_orig = im.astype(np.float32, copy=True) im_orig -= cfg.PIXEL_MEANS im_shape = im_orig.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) processed_ims = [] im_scale_factors = [] for target_size in cfg.TEST.SCALES: im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE if np.round(im_scale * im_size_max) > cfg.TEST.MAX_SIZE: im_scale = float(cfg.TEST.MAX_SIZE) / float(im_size_max) im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) im_scale_factors.append(im_scale) processed_ims.append(im) # Create a blob to hold the input images blob = im_list_to_blob(processed_ims) return blob, np.array(im_scale_factors) def _get_rois_blob(im_rois, im_scale_factors): """Converts RoIs into network inputs. Arguments: im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates im_scale_factors (list): scale factors as returned by _get_image_blob Returns: blob (ndarray): R x 5 matrix of RoIs in the image pyramid """ rois, levels = _project_im_rois(im_rois, im_scale_factors) rois_blob = np.hstack((levels, rois)) return rois_blob.astype(np.float32, copy=False) def _project_im_rois(im_rois, scales): """Project image RoIs into the image pyramid built by _get_image_blob. Arguments: im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates scales (list): scale factors as returned by _get_image_blob Returns: rois (ndarray): R x 4 matrix of projected RoI coordinates levels (list): image pyramid levels used by each projected RoI """ im_rois = im_rois.astype(np.float, copy=False) if len(scales) > 1: widths = im_rois[:, 2] - im_rois[:, 0] + 1 heights = im_rois[:, 3] - im_rois[:, 1] + 1 areas = widths * heights scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2) diff_areas = np.abs(scaled_areas - 224 * 224) levels = diff_areas.argmin(axis=1)[:, np.newaxis] else: levels = np.zeros((im_rois.shape[0], 1), dtype=np.int) rois = im_rois * scales[levels] return rois, levels def _get_blobs(im, rois): """Convert an image and RoIs within that image into network inputs.""" blobs = {'data' : None, 'rois' : None} blobs['data'], im_scale_factors = _get_image_blob(im) if not cfg.TEST.HAS_RPN: blobs['rois'] = _get_rois_blob(rois, im_scale_factors) return blobs, im_scale_factors def im_detect(net, im, boxes=None, force_boxes=False): """Detect object classes in an image given object proposals. Arguments: net (caffe.Net): Fast R-CNN network to use im (ndarray): color image to test (in BGR order) boxes (ndarray): R x 4 array of object proposals or None (for RPN) Returns: scores (ndarray): R x K array of object class scores (K includes background as object category 0) boxes (ndarray): R x (4*K) array of predicted bounding boxes attr_scores (ndarray): R x M array of attribute class scores """ blobs, im_scales = _get_blobs(im, boxes) if force_boxes: blobs['rois'] = _get_rois_blob(boxes, im_scales) # When mapping from image ROIs to feature map ROIs, there's some aliasing # (some distinct image ROIs get mapped to the same feature ROI). # Here, we identify duplicate feature ROIs, so we only compute features # on the unique subset. if cfg.DEDUP_BOXES > 0 and not cfg.TEST.HAS_RPN: v = np.array([1, 1e3, 1e6, 1e9, 1e12]) hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v) _, index, inv_index = np.unique(hashes, return_index=True, return_inverse=True) blobs['rois'] = blobs['rois'][index, :] boxes = boxes[index, :] im_blob = blobs['data'] blobs['im_info'] = np.array( [[im_blob.shape[2], im_blob.shape[3], im_scales[0]]], dtype=np.float32) # reshape network inputs net.blobs['data'].reshape(*(blobs['data'].shape)) if 'im_info' in net.blobs: net.blobs['im_info'].reshape(*(blobs['im_info'].shape)) if force_boxes or not cfg.TEST.HAS_RPN: net.blobs['rois'].reshape(*(blobs['rois'].shape)) # do forward forward_kwargs = {'data': blobs['data'].astype(np.float32, copy=False)} if 'im_info' in net.blobs: forward_kwargs['im_info'] = blobs['im_info'].astype(np.float32, copy=False) if force_boxes or not cfg.TEST.HAS_RPN: forward_kwargs['rois'] = blobs['rois'].astype(np.float32, copy=False) blobs_out = net.forward(**forward_kwargs) if cfg.TEST.HAS_RPN and not force_boxes: assert len(im_scales) == 1, "Only single-image batch implemented" rois = net.blobs['rois'].data.copy() # unscale back to raw image space boxes = rois[:, 1:5] / im_scales[0] if cfg.TEST.SVM: # use the raw scores before softmax under the assumption they # were trained as linear SVMs scores = net.blobs['cls_score'].data else: # use softmax estimated probabilities scores = blobs_out['cls_prob'] if cfg.TEST.BBOX_REG: # Apply bounding-box regression deltas box_deltas = blobs_out['bbox_pred'] pred_boxes = bbox_transform_inv(boxes, box_deltas) pred_boxes = clip_boxes(pred_boxes, im.shape) else: # Simply repeat the boxes, once for each class pred_boxes = np.tile(boxes, (1, scores.shape[1])) if cfg.DEDUP_BOXES > 0 and not cfg.TEST.HAS_RPN: # Map scores and predictions back to the original set of boxes scores = scores[inv_index, :] pred_boxes = pred_boxes[inv_index, :] if 'attr_prob' in net.blobs: attr_scores = blobs_out['attr_prob'] else: attr_scores = None if 'rel_prob' in net.blobs: rel_scores = blobs_out['rel_prob'] else: rel_scores = None return scores, pred_boxes, attr_scores, rel_scores def vis_detections(im, class_name, dets, thresh=0.3, filename='vis.png'): """Visual debugging of detections.""" import matplotlib.pyplot as plt im = im[:, :, (2, 1, 0)] plt.cla() plt.imshow(im) for i in xrange(np.minimum(10, dets.shape[0])): bbox = dets[i, :4] score = dets[i, -1] if score > thresh: plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='g', linewidth=3) ) plt.title('{} {:.3f}'.format(class_name, score)) plt.show() plt.savefig('./data/vis/%s' % filename) def vis_multiple(im, class_names, all_boxes, filename='vis.png'): """Visual debugging of detections.""" print filename import matplotlib.pyplot as plt im = im[:, :, (2, 1, 0)] plt.cla() plt.imshow(im) max_boxes = 10 image_scores = np.hstack([all_boxes[j][:, 4] for j in xrange(1, len(class_names))]) if len(image_scores) > 10: image_thresh = np.sort(image_scores)[-max_boxes] else: image_thresh = -np.inf for j in xrange(1, len(class_names)): keep = np.where(all_boxes[j][:, 4] >= image_thresh)[0] dets = all_boxes[j][keep, :] for i in range(dets.shape[0]): bbox = dets[i, :4] score = dets[i, -1] plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=1) ) plt.gca().text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_names[j], score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=8, color='white') plt.title('Best %d Attributes using gt boxes' % max_boxes) plt.show() plt.savefig('./data/vis/%s' % filename) def vis_relations(im, class_names, box_proposals, scores, filename='vis.png'): n = box_proposals.shape[0] assert scores.shape[0] == n*n print filename import matplotlib.pyplot as plt im = im[:, :, (2, 1, 0)] plt.cla() plt.imshow(im) max_rels = 5 scores = scores[:, 1:] image_scores = scores.flatten() if len(image_scores) > 10: image_thresh = np.sort(image_scores)[-max_rels] else: image_thresh = -np.inf for i in xrange(n): for j in xrange(n): keep = np.where(scores[i*n+j] >= image_thresh)[0] for ix in keep: bbox = box_proposals[i] score = scores[i*n+j, ix] plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=1) ) plt.gca().text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_names[ix], score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=8, color='white') bbox = box_proposals[j] plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=1) ) plt.title('Best %d Relations using gt boxes' % max_rels) plt.show() plt.savefig('./data/vis/%s' % filename) def apply_nms(all_boxes, thresh): """Apply non-maximum suppression to all predicted boxes output by the test_net method. """ num_classes = len(all_boxes) num_images = len(all_boxes[0]) nms_boxes = [[[] for _ in xrange(num_images)] for _ in xrange(num_classes)] for cls_ind in xrange(num_classes): for im_ind in xrange(num_images): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # CPU NMS is much faster than GPU NMS when the number of boxes # is relative small (e.g., < 10k) # TODO(rbg): autotune NMS dispatch keep = nms(dets, thresh, force_cpu=True) if len(keep) == 0: continue nms_boxes[cls_ind][im_ind] = dets[keep, :].copy() return nms_boxes def test_net(net, imdb, max_per_image=400, thresh=-np.inf, vis=False, load_cache=False): """Test a Fast R-CNN network on an image database.""" num_images = len(imdb.image_index) # all detections are collected into: # all_boxes[cls][image] = N x 5 array of detections in # (x1, y1, x2, y2, score) all_boxes = [[[] for _ in xrange(num_images)] for _ in xrange(imdb.num_classes)] output_dir = get_output_dir(imdb, net) det_file = os.path.join(output_dir, 'detections.pkl') if load_cache and os.path.exists(det_file): print 'Loading pickled detections from %s' % det_file with open(det_file, 'rb') as f: all_boxes = cPickle.load(f) else: # timers _t = {'im_detect' : Timer(), 'misc' : Timer()} if not cfg.TEST.HAS_RPN: roidb = imdb.roidb for i in xrange(num_images): # filter out any ground truth boxes if cfg.TEST.HAS_RPN: box_proposals = None else: # The roidb may contain ground-truth rois (for example, if the roidb # comes from the training or val split). We only want to evaluate # detection on the *non*-ground-truth rois. We select those the rois # that have the gt_classes field set to 0, which means there's no # ground truth. box_proposals = roidb[i]['boxes'][roidb[i]['gt_classes'] == 0] im = cv2.imread(imdb.image_path_at(i)) _t['im_detect'].tic() scores, boxes, attr_scores, rel_scores = im_detect(net, im, box_proposals) _t['im_detect'].toc() _t['misc'].tic() # skip j = 0, because it's the background class for j in xrange(1, imdb.num_classes): inds = np.where(scores[:, j] > thresh)[0] cls_scores = scores[inds, j] if cfg.TEST.AGNOSTIC: cls_boxes = boxes[inds, 4:8] else: cls_boxes = boxes[inds, j*4:(j+1)*4] cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \ .astype(np.float32, copy=False) #keep = soft_nms(cls_dets, method=cfg.TEST.SOFT_NMS) keep = nms(cls_dets, cfg.TEST.NMS) cls_dets = cls_dets[keep, :] if vis: vis_detections(im, imdb.classes[j], cls_dets) all_boxes[j][i] = cls_dets # Limit to max_per_image detections *over all classes* if max_per_image > 0: image_scores = np.hstack([all_boxes[j][i][:, 4] for j in xrange(1, imdb.num_classes)]) if len(image_scores) > max_per_image: image_thresh = np.sort(image_scores)[-max_per_image] for j in xrange(1, imdb.num_classes): keep = np.where(all_boxes[j][i][:, 4] >= image_thresh)[0] all_boxes[j][i] = all_boxes[j][i][keep, :] _t['misc'].toc() print 'im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \ .format(i + 1, num_images, _t['im_detect'].average_time, _t['misc'].average_time) with open(det_file, 'wb') as f: cPickle.dump(all_boxes, f, cPickle.HIGHEST_PROTOCOL) print 'Evaluating detections' imdb.evaluate_detections(all_boxes, output_dir) def test_net_with_gt_boxes(net, imdb, max_per_image=400, thresh=-np.inf, vis=False, load_cache=False): """Test a Fast R-CNN network on an image database, evaluating attribute and relation detections given ground truth boxes.""" num_images = len(imdb.image_index) # all detections are collected into: # all_boxes[cls][image] = N x 5 array of detections in # (x1, y1, x2, y2, score) all_boxes = [[[] for _ in xrange(num_images)] for _ in xrange(imdb.num_attributes)] rel_boxes = [[[] for _ in xrange(num_images)] for _ in xrange(imdb.num_relations)] output_dir = get_output_dir(imdb, net, attributes=True) det_file = os.path.join(output_dir, 'attribute_detections.pkl') rel_file = os.path.join(output_dir, 'relation_detections.pkl') if load_cache and os.path.exists(det_file): print 'Loading pickled detections from %s' % det_file with open(det_file, 'rb') as f: all_boxes = cPickle.load(f) with open(rel_file, 'rb') as f: rel_boxes = cPickle.load(f) else: # timers _t = {'im_detect' : Timer(), 'misc' : Timer()} roidb = imdb.gt_roidb() for i in xrange(num_images): box_proposals = roidb[i]['boxes'] im = cv2.imread(imdb.image_path_at(i)) _t['im_detect'].tic() scores, boxes, attr_scores, rel_scores = im_detect(net, im, box_proposals, force_boxes=True) _t['im_detect'].toc() _t['misc'].tic() # skip j = 0, because it's the no attribute class if attr_scores.shape[1] < imdb.num_attributes: attr_scores = np.hstack((np.zeros((attr_scores.shape[0],1)),attr_scores)) if rel_scores and rel_scores.shape[1] < imdb.num_relations: rel_scores = np.hstack((np.zeros((rel_scores.shape[0],1)),rel_scores)) for j in xrange(1, imdb.num_attributes): inds = np.where(attr_scores[:, j] > thresh)[0] cls_scores = attr_scores[inds, j] cls_boxes = box_proposals[inds, :] cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \ .astype(np.float32, copy=False) all_boxes[j][i] = cls_dets # Limit to max_per_image detections *over all attributes* if max_per_image > 0: image_scores = np.hstack([all_boxes[j][i][:, 4] for j in xrange(1, imdb.num_attributes)]) if len(image_scores) > max_per_image: image_thresh = np.sort(image_scores)[-max_per_image] for j in xrange(1, imdb.num_attributes): keep = np.where(all_boxes[j][i][:, 4] >= image_thresh)[0] all_boxes[j][i] = all_boxes[j][i][keep, :] if vis: im_boxes = [all_boxes[j][i] for j in xrange(imdb.num_attributes)] vis_multiple(im, imdb.attributes, im_boxes, filename='attr_%d.png' % i) if rel_scores: vis_relations(im, imdb.relations, box_proposals, rel_scores, filename='rel_%d.png' % i) _t['misc'].toc() print 'im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \ .format(i + 1, num_images, _t['im_detect'].average_time, _t['misc'].average_time) with open(det_file, 'wb') as f: cPickle.dump(all_boxes, f, cPickle.HIGHEST_PROTOCOL) print 'Evaluating attribute and / or relation detections' imdb.evaluate_attributes(all_boxes, output_dir)
19,368
38.690574
123
py
bottom-up-attention
bottom-up-attention-master/lib/fast_rcnn/train_multi_gpu.py
# -------------------------------------------------------- # Written by Bharat Singh # Modified version of py-R-FCN # -------------------------------------------------------- """Train a Fast R-CNN network.""" import caffe from fast_rcnn.config import cfg import roi_data_layer.roidb as rdl_roidb from utils.timer import Timer import numpy as np import os from caffe.proto import caffe_pb2 import google.protobuf as pb2 import google.protobuf.text_format from multiprocessing import Process class SolverWrapper(object): """A simple wrapper around Caffe's solver. This wrapper gives us control over he snapshotting process, which we use to unnormalize the learned bounding-box regression weights. """ def __init__(self, solver_prototxt, roidb, output_dir, gpu_id, pretrained_model=None): """Initialize the SolverWrapper.""" self.output_dir = output_dir self.gpu_id = gpu_id if (cfg.TRAIN.HAS_RPN and cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS): # RPN can only use precomputed normalization because there are no # fixed statistics to compute a priori assert cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED if cfg.TRAIN.BBOX_REG: print 'Computing bounding-box regression targets...' self.bbox_means, self.bbox_stds = \ rdl_roidb.add_bbox_regression_targets(roidb) print 'done' self.solver = caffe.SGDSolver(solver_prototxt) if pretrained_model is not None: print ('Loading pretrained model ' 'weights from {:s}').format(pretrained_model) self.solver.net.copy_from(pretrained_model) self.solver_param = caffe_pb2.SolverParameter() with open(solver_prototxt, 'rt') as f: pb2.text_format.Merge(f.read(), self.solver_param) self.solver.net.layers[0].set_roidb(roidb, gpu_id) def snapshot(self): """Take a snapshot of the network after unnormalizing the learned bounding-box regression weights. This enables easy use at test-time. """ net = self.solver.net scale_bbox_params_faster_rcnn = (cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS and net.params.has_key('bbox_pred')) scale_bbox_params_rfcn = (cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS and net.params.has_key('rfcn_bbox')) scale_bbox_params_rpn = (cfg.TRAIN.RPN_NORMALIZE_TARGETS and net.params.has_key('rpn_bbox_pred')) if scale_bbox_params_faster_rcnn: # save original values orig_0 = net.params['bbox_pred'][0].data.copy() orig_1 = net.params['bbox_pred'][1].data.copy() # scale and shift with bbox reg unnormalization; then save snapshot net.params['bbox_pred'][0].data[...] = \ (net.params['bbox_pred'][0].data * self.bbox_stds[:, np.newaxis]) net.params['bbox_pred'][1].data[...] = \ (net.params['bbox_pred'][1].data * self.bbox_stds + self.bbox_means) if scale_bbox_params_rpn: rpn_orig_0 = net.params['rpn_bbox_pred'][0].data.copy() rpn_orig_1 = net.params['rpn_bbox_pred'][1].data.copy() num_anchor = rpn_orig_0.shape[0] / 4 # scale and shift with bbox reg unnormalization; then save snapshot self.rpn_means = np.tile(np.asarray(cfg.TRAIN.RPN_NORMALIZE_MEANS), num_anchor) self.rpn_stds = np.tile(np.asarray(cfg.TRAIN.RPN_NORMALIZE_STDS), num_anchor) net.params['rpn_bbox_pred'][0].data[...] = \ (net.params['rpn_bbox_pred'][0].data * self.rpn_stds[:, np.newaxis, np.newaxis, np.newaxis]) net.params['rpn_bbox_pred'][1].data[...] = \ (net.params['rpn_bbox_pred'][1].data * self.rpn_stds + self.rpn_means) if scale_bbox_params_rfcn: # save original values orig_0 = net.params['rfcn_bbox'][0].data.copy() orig_1 = net.params['rfcn_bbox'][1].data.copy() repeat = orig_1.shape[0] / self.bbox_means.shape[0] # scale and shift with bbox reg unnormalization; then save snapshot net.params['rfcn_bbox'][0].data[...] = \ (net.params['rfcn_bbox'][0].data * np.repeat(self.bbox_stds, repeat).reshape((orig_1.shape[0], 1, 1, 1))) net.params['rfcn_bbox'][1].data[...] = \ (net.params['rfcn_bbox'][1].data * np.repeat(self.bbox_stds, repeat) + np.repeat(self.bbox_means, repeat)) infix = ('_' + cfg.TRAIN.SNAPSHOT_INFIX if cfg.TRAIN.SNAPSHOT_INFIX != '' else '') filename = (self.solver_param.snapshot_prefix + infix + '_iter_{:d}'.format(self.solver.iter) + '.caffemodel') filename = os.path.join(self.output_dir, filename) if self.gpu_id == 0: net.save(str(filename)) print 'Wrote snapshot to: {:s}'.format(filename) if scale_bbox_params_faster_rcnn: # restore net to original state net.params['bbox_pred'][0].data[...] = orig_0 net.params['bbox_pred'][1].data[...] = orig_1 if scale_bbox_params_rfcn: # restore net to original state net.params['rfcn_bbox'][0].data[...] = orig_0 net.params['rfcn_bbox'][1].data[...] = orig_1 if scale_bbox_params_rpn: # restore net to original state net.params['rpn_bbox_pred'][0].data[...] = rpn_orig_0 net.params['rpn_bbox_pred'][1].data[...] = rpn_orig_1 return filename def track_memory(self): net = self.solver.net print 'Memory Usage:' total = 0.0 data = 0.0 params = 0.0 for k,v in net.blobs.iteritems(): gb = float(v.data.nbytes)/1024/1024/1024 print '%s : %.3f GB %s' % (k,gb,v.data.shape) total += gb data += gb print 'Memory Usage: Data %.3f GB' % data for k,v in net.params.iteritems(): for i,p in enumerate(v): gb = float(p.data.nbytes)/1024/1024/1024 total += gb params += gb print '%s[%d] : %.3f GB %s' % (k,i,gb,p.data.shape) print 'Memory Usage: Params %.3f GB' % params print 'Memory Usage: Total %.3f GB' % total def getSolver(self): return self.solver def solve(proto, roidb, pretrained_model, gpus, uid, rank, output_dir, max_iter): caffe.set_mode_gpu() caffe.set_device(gpus[rank]) caffe.set_solver_count(len(gpus)) caffe.set_solver_rank(rank) caffe.set_multiprocess(True) cfg.GPU_ID = gpus[rank] solverW = SolverWrapper(proto, roidb, output_dir,rank,pretrained_model) solver = solverW.getSolver() nccl = caffe.NCCL(solver, uid) nccl.bcast() solver.add_callback(nccl) if solver.param.layer_wise_reduce: solver.net.after_backward(nccl) count = 0 while count < max_iter: print 'Solver step' solver.step(cfg.TRAIN.SNAPSHOT_ITERS) if rank == 0: solverW.snapshot() #solverW.track_memory() count = count + cfg.TRAIN.SNAPSHOT_ITERS def get_training_roidb(imdb): """Returns a roidb (Region of Interest database) for use in training.""" if cfg.TRAIN.USE_FLIPPED: print 'Appending horizontally-flipped training examples...' imdb.append_flipped_images() print 'done' print 'Preparing training data...' rdl_roidb.prepare_roidb(imdb) print 'done' return imdb.roidb def filter_roidb(roidb): """Remove roidb entries that have no usable RoIs.""" def is_valid(entry): # Valid images have: # (1) At least one foreground RoI OR # (2) At least one background RoI overlaps = entry['max_overlaps'] # find boxes with sufficient overlap fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0] # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO))[0] # image is only valid if such boxes exist valid = len(fg_inds) > 0 or len(bg_inds) > 0 return valid num = len(roidb) filtered_roidb = [entry for entry in roidb if is_valid(entry)] num_after = len(filtered_roidb) print 'Filtered {} roidb entries: {} -> {}'.format(num - num_after, num, num_after) return filtered_roidb def train_net_multi_gpu(solver_prototxt, roidb, output_dir, pretrained_model, max_iter, gpus): """Train a Fast R-CNN network.""" uid = caffe.NCCL.new_uid() caffe.init_log() caffe.log('Using devices %s' % str(gpus)) procs = [] for rank in range(len(gpus)): p = Process(target=solve, args=(solver_prototxt, roidb, pretrained_model, gpus, uid, rank, output_dir, max_iter)) p.daemon = False p.start() procs.append(p) for p in procs: p.join()
9,558
37.857724
107
py
bottom-up-attention
bottom-up-attention-master/lib/fast_rcnn/bbox_transform.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import numpy as np def bbox_transform(ex_rois, gt_rois): ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0 ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0 ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0 gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0 gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights targets_dx = (gt_ctr_x - ex_ctr_x) / ex_widths targets_dy = (gt_ctr_y - ex_ctr_y) / ex_heights targets_dw = np.log(gt_widths / ex_widths) targets_dh = np.log(gt_heights / ex_heights) targets = np.vstack( (targets_dx, targets_dy, targets_dw, targets_dh)).transpose() return targets def bbox_transform_inv(boxes, deltas): if boxes.shape[0] == 0: return np.zeros((0, deltas.shape[1]), dtype=deltas.dtype) boxes = boxes.astype(deltas.dtype, copy=False) widths = boxes[:, 2] - boxes[:, 0] + 1.0 heights = boxes[:, 3] - boxes[:, 1] + 1.0 ctr_x = boxes[:, 0] + 0.5 * widths ctr_y = boxes[:, 1] + 0.5 * heights dx = deltas[:, 0::4] dy = deltas[:, 1::4] dw = deltas[:, 2::4] dh = deltas[:, 3::4] pred_ctr_x = dx * widths[:, np.newaxis] + ctr_x[:, np.newaxis] pred_ctr_y = dy * heights[:, np.newaxis] + ctr_y[:, np.newaxis] pred_w = np.exp(dw) * widths[:, np.newaxis] pred_h = np.exp(dh) * heights[:, np.newaxis] pred_boxes = np.zeros(deltas.shape, dtype=deltas.dtype) # x1 pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w # y1 pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h # x2 pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w # y2 pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h return pred_boxes def clip_boxes(boxes, im_shape): """ Clip boxes to image boundaries. """ # x1 >= 0 boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0) # y1 >= 0 boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0) # x2 < im_shape[1] boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0) # y2 < im_shape[0] boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0) return boxes
2,539
32.421053
79
py
bottom-up-attention
bottom-up-attention-master/lib/fast_rcnn/nms_wrapper.py
# ---------------------------------------------------------- # Soft-NMS: Improving Object Detection With One Line of Code # Copyright (c) University of Maryland, College Park # Licensed under The MIT License [see LICENSE for details] # Written by Navaneeth Bodla and Bharat Singh # ---------------------------------------------------------- from fast_rcnn.config import cfg from nms.gpu_nms import gpu_nms from nms.cpu_nms import cpu_nms, cpu_soft_nms import numpy as np def soft_nms(dets, sigma=0.5, Nt=0.3, threshold=0.001, method=1): keep = cpu_soft_nms(np.ascontiguousarray(dets, dtype=np.float32), np.float32(sigma), np.float32(Nt), np.float32(threshold), np.uint8(method)) return keep # Original NMS implementation def nms(dets, thresh, force_cpu=False): """Dispatch to either CPU or GPU NMS implementations.""" if dets.shape[0] == 0: return [] if cfg.USE_GPU_NMS and not force_cpu: return gpu_nms(dets, thresh, device_id=cfg.GPU_ID) else: return cpu_nms(dets, thresh)
1,101
33.4375
69
py
bottom-up-attention
bottom-up-attention-master/lib/fast_rcnn/config.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Fast R-CNN config system. This file specifies default config options for Fast R-CNN. You should not change values in this file. Instead, you should write a config file (in yaml) and use cfg_from_file(yaml_file) to load it and override the default options. Most tools in $ROOT/tools take a --cfg option to specify an override file. - See tools/{train,test}_net.py for example code that uses cfg_from_file() - See experiments/cfgs/*.yml for example YAML config override files """ import os import os.path as osp import numpy as np # `pip install easydict` if you don't have it from easydict import EasyDict as edict __C = edict() # Consumers can get config by: # from fast_rcnn_config import cfg cfg = __C # # Training options # __C.TRAIN = edict() # Scales to use during training (can list multiple scales) # Each scale is the pixel size of an image's shortest side __C.TRAIN.SCALES = (600,) # Max pixel size of the longest side of a scaled input image __C.TRAIN.MAX_SIZE = 1000 # Images to use per minibatch __C.TRAIN.IMS_PER_BATCH = 2 # Minibatch size (number of regions of interest [ROIs]) __C.TRAIN.BATCH_SIZE = 128 # Fraction of minibatch that is labeled foreground (i.e. class > 0) __C.TRAIN.FG_FRACTION = 0.25 # Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) __C.TRAIN.FG_THRESH = 0.5 # Overlap threshold for a ROI to be considered background (class = 0 if # overlap in [LO, HI)) __C.TRAIN.BG_THRESH_HI = 0.5 __C.TRAIN.BG_THRESH_LO = 0.1 # Use horizontally-flipped images during training? __C.TRAIN.USE_FLIPPED = True # Train bounding-box regressors __C.TRAIN.BBOX_REG = True # Overlap required between a ROI and ground-truth box in order for that ROI to # be used as a bounding-box regression training example __C.TRAIN.BBOX_THRESH = 0.5 # Iterations between snapshots __C.TRAIN.SNAPSHOT_ITERS = 10000 # solver.prototxt specifies the snapshot path prefix, this adds an optional # infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel __C.TRAIN.SNAPSHOT_INFIX = '' # Use a prefetch thread in roi_data_layer.layer # So far I haven't found this useful; likely more engineering work is required __C.TRAIN.USE_PREFETCH = False # Normalize the targets (subtract empirical mean, divide by empirical stddev) __C.TRAIN.BBOX_NORMALIZE_TARGETS = True # Deprecated (inside weights) __C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # Normalize the targets using "precomputed" (or made up) means and stdevs # (BBOX_NORMALIZE_TARGETS must also be True) __C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = False __C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0) __C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2) __C.TRAIN.RPN_NORMALIZE_TARGETS = False __C.TRAIN.RPN_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0) __C.TRAIN.RPN_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2) # Train using these proposals __C.TRAIN.PROPOSAL_METHOD = 'selective_search' # Make minibatches from images that have similar aspect ratios (i.e. both # tall and thin or both short and wide) in order to avoid wasting computation # on zero-padding. __C.TRAIN.ASPECT_GROUPING = True # Use RPN to detect objects __C.TRAIN.HAS_RPN = False # IOU >= thresh: positive example __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # IOU < thresh: negative example __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # If an anchor statisfied by positive and negative conditions set to negative __C.TRAIN.RPN_CLOBBER_POSITIVES = False # Max number of foreground examples __C.TRAIN.RPN_FG_FRACTION = 0.5 # Total number of examples __C.TRAIN.RPN_BATCHSIZE = 256 # NMS threshold used on RPN proposals __C.TRAIN.RPN_NMS_THRESH = 0.7 # Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TRAIN.RPN_MIN_SIZE = 16 # Deprecated (outside weights) __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # Give the positive RPN examples weight of p * 1 / {num positives} # and give negatives a weight of (1 - p) # Set to -1.0 to use uniform example weighting __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 # whether use class aware box or not __C.TRAIN.AGNOSTIC = False # Detect attributes of objects __C.TRAIN.HAS_ATTRIBUTES = False # Detect relations between objects __C.TRAIN.HAS_RELATIONS = False # Fraction of relation minibatch that is labeled with a relation (i.e. class > 0) __C.TRAIN.MIN_RELATION_FRACTION = 0.25 # # Testing options # __C.TEST = edict() # Scales to use during testing (can list multiple scales) # Each scale is the pixel size of an image's shortest side __C.TEST.SCALES = (600,) # Max pixel size of the longest side of a scaled input image __C.TEST.MAX_SIZE = 1000 # Overlap threshold used for non-maximum suppression (suppress boxes with # IoU >= this threshold) __C.TEST.NMS = 0.3 # Flag for soft-NMS method. 0 performs standard NMS, 1 performs soft-NMS with linear weighting and # 2 performs soft-NMS with Gaussian weighting __C.TEST.SOFT_NMS = 0 # Experimental: treat the (K+1) units in the cls_score layer as linear # predictors (trained, eg, with one-vs-rest SVMs). __C.TEST.SVM = False # Test using bounding-box regressors __C.TEST.BBOX_REG = True # Propose boxes __C.TEST.HAS_RPN = False # Test using these proposals __C.TEST.PROPOSAL_METHOD = 'selective_search' ## NMS threshold used on RPN proposals __C.TEST.RPN_NMS_THRESH = 0.7 ## Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TEST.RPN_PRE_NMS_TOP_N = 6000 ## Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TEST.RPN_POST_NMS_TOP_N = 300 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TEST.RPN_MIN_SIZE = 16 # whether use class aware box or not __C.TEST.AGNOSTIC = False # Detect attributes of objects __C.TEST.HAS_ATTRIBUTES = False # Detect relations between objects __C.TEST.HAS_RELATIONS = False # # MISC # # The mapping from image coordinates to feature map coordinates might cause # some boxes that are distinct in image space to become identical in feature # coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor # for identifying duplicate boxes. # 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16 __C.DEDUP_BOXES = 1./16. # Pixel mean values (BGR order) as a (1, 1, 3) array # We use the same pixel mean for all networks even though it's not exactly what # they were trained with __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # For reproducibility __C.RNG_SEED = 3 # A small number that's used many times __C.EPS = 1e-14 # Root directory of project __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # Data directory __C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data')) # Model directory __C.MODELS_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'models', 'pascal_voc')) # Name (or path to) the matlab executable __C.MATLAB = 'matlab' # Place outputs under an experiments directory __C.EXP_DIR = 'default' # Use GPU implementation of non-maximum suppression __C.USE_GPU_NMS = True # Default GPU device id __C.GPU_ID = 0 def get_output_dir(imdb, net=None, attributes=False): """Return the directory where experimental artifacts are placed. If the directory does not exist, it is created. A canonical path is built using the name from an imdb and a network (if not None). """ outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name)) if net is not None: outdir = osp.join(outdir, net.name) if attributes: outdir = osp.join(outdir, "attr") if not os.path.exists(outdir): os.makedirs(outdir) return outdir def _merge_a_into_b(a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k, v in a.iteritems(): # a must specify keys that are in b if not b.has_key(k): raise KeyError('{} is not a valid config key'.format(k)) # the types must match, too old_type = type(b[k]) if old_type is not type(v): if isinstance(b[k], np.ndarray): v = np.array(v, dtype=b[k].dtype) else: raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]), type(v), k)) # recursively merge dicts if type(v) is edict: try: _merge_a_into_b(a[k], b[k]) except: print('Error under config key: {}'.format(k)) raise else: b[k] = v def cfg_from_file(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C) def cfg_from_list(cfg_list): """Set config keys via list (e.g., from command line).""" from ast import literal_eval assert len(cfg_list) % 2 == 0 for k, v in zip(cfg_list[0::2], cfg_list[1::2]): key_list = k.split('.') d = __C for subkey in key_list[:-1]: assert d.has_key(subkey) d = d[subkey] subkey = key_list[-1] assert d.has_key(subkey) try: value = literal_eval(v) except: # handle the case when v is a string literal value = v assert type(value) == type(d[subkey]), \ 'type {} does not match original type {}'.format( type(value), type(d[subkey])) d[subkey] = value
10,118
31.329073
99
py
bottom-up-attention
bottom-up-attention-master/lib/fast_rcnn/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # --------------------------------------------------------
248
34.571429
58
py
bottom-up-attention
bottom-up-attention-master/lib/fast_rcnn/train.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Train a Fast R-CNN network.""" import caffe from fast_rcnn.config import cfg import roi_data_layer.roidb as rdl_roidb from utils.timer import Timer import numpy as np import os from caffe.proto import caffe_pb2 import google.protobuf as pb2 import google.protobuf.text_format as text_format class SolverWrapper(object): """A simple wrapper around Caffe's solver. This wrapper gives us control over he snapshotting process, which we use to unnormalize the learned bounding-box regression weights. """ def __init__(self, solver_prototxt, roidb, output_dir, pretrained_model=None): """Initialize the SolverWrapper.""" self.output_dir = output_dir if (cfg.TRAIN.HAS_RPN and cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS): # RPN can only use precomputed normalization because there are no # fixed statistics to compute a priori assert cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED if cfg.TRAIN.BBOX_REG: print 'Computing bounding-box regression targets...' self.bbox_means, self.bbox_stds = \ rdl_roidb.add_bbox_regression_targets(roidb) print 'done' self.solver = caffe.SGDSolver(solver_prototxt) if pretrained_model is not None: print ('Loading pretrained model ' 'weights from {:s}').format(pretrained_model) self.solver.net.copy_from(pretrained_model) self.solver_param = caffe_pb2.SolverParameter() with open(solver_prototxt, 'rt') as f: text_format.Merge(f.read(), self.solver_param) self.solver.net.layers[0].set_roidb(roidb, cfg.GPU_ID) def snapshot(self): """Take a snapshot of the network after unnormalizing the learned bounding-box regression weights. This enables easy use at test-time. """ net = self.solver.net scale_bbox_params_faster_rcnn = (cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS and net.params.has_key('bbox_pred')) scale_bbox_params_rfcn = (cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS and net.params.has_key('rfcn_bbox')) scale_bbox_params_rpn = (cfg.TRAIN.RPN_NORMALIZE_TARGETS and net.params.has_key('rpn_bbox_pred')) if scale_bbox_params_faster_rcnn: # save original values orig_0 = net.params['bbox_pred'][0].data.copy() orig_1 = net.params['bbox_pred'][1].data.copy() # scale and shift with bbox reg unnormalization; then save snapshot net.params['bbox_pred'][0].data[...] = \ (net.params['bbox_pred'][0].data * self.bbox_stds[:, np.newaxis]) net.params['bbox_pred'][1].data[...] = \ (net.params['bbox_pred'][1].data * self.bbox_stds + self.bbox_means) if scale_bbox_params_rpn: rpn_orig_0 = net.params['rpn_bbox_pred'][0].data.copy() rpn_orig_1 = net.params['rpn_bbox_pred'][1].data.copy() num_anchor = rpn_orig_0.shape[0] / 4 # scale and shift with bbox reg unnormalization; then save snapshot self.rpn_means = np.tile(np.asarray(cfg.TRAIN.RPN_NORMALIZE_MEANS), num_anchor) self.rpn_stds = np.tile(np.asarray(cfg.TRAIN.RPN_NORMALIZE_STDS), num_anchor) net.params['rpn_bbox_pred'][0].data[...] = \ (net.params['rpn_bbox_pred'][0].data * self.rpn_stds[:, np.newaxis, np.newaxis, np.newaxis]) net.params['rpn_bbox_pred'][1].data[...] = \ (net.params['rpn_bbox_pred'][1].data * self.rpn_stds + self.rpn_means) if scale_bbox_params_rfcn: # save original values orig_0 = net.params['rfcn_bbox'][0].data.copy() orig_1 = net.params['rfcn_bbox'][1].data.copy() repeat = orig_1.shape[0] / self.bbox_means.shape[0] # scale and shift with bbox reg unnormalization; then save snapshot net.params['rfcn_bbox'][0].data[...] = \ (net.params['rfcn_bbox'][0].data * np.repeat(self.bbox_stds, repeat).reshape((orig_1.shape[0], 1, 1, 1))) net.params['rfcn_bbox'][1].data[...] = \ (net.params['rfcn_bbox'][1].data * np.repeat(self.bbox_stds, repeat) + np.repeat(self.bbox_means, repeat)) infix = ('_' + cfg.TRAIN.SNAPSHOT_INFIX if cfg.TRAIN.SNAPSHOT_INFIX != '' else '') filename = (self.solver_param.snapshot_prefix + infix + '_iter_{:d}'.format(self.solver.iter) + '.caffemodel') filename = os.path.join(self.output_dir, filename) net.save(str(filename)) print 'Wrote snapshot to: {:s}'.format(filename) if scale_bbox_params_faster_rcnn: # restore net to original state net.params['bbox_pred'][0].data[...] = orig_0 net.params['bbox_pred'][1].data[...] = orig_1 if scale_bbox_params_rfcn: # restore net to original state net.params['rfcn_bbox'][0].data[...] = orig_0 net.params['rfcn_bbox'][1].data[...] = orig_1 if scale_bbox_params_rpn: # restore net to original state net.params['rpn_bbox_pred'][0].data[...] = rpn_orig_0 net.params['rpn_bbox_pred'][1].data[...] = rpn_orig_1 return filename def train_model(self, max_iters): """Network training loop.""" last_snapshot_iter = -1 timer = Timer() model_paths = [] while self.solver.iter < max_iters: # Make one SGD update timer.tic() self.solver.step(1) timer.toc() if self.solver.iter % (10 * self.solver_param.display) == 0: print 'speed: {:.3f}s / iter'.format(timer.average_time) if self.solver.iter % cfg.TRAIN.SNAPSHOT_ITERS == 0: last_snapshot_iter = self.solver.iter model_paths.append(self.snapshot()) if last_snapshot_iter != self.solver.iter: model_paths.append(self.snapshot()) return model_paths def get_training_roidb(imdb): """Returns a roidb (Region of Interest database) for use in training.""" if cfg.TRAIN.USE_FLIPPED: print 'Appending horizontally-flipped training examples...' imdb.append_flipped_images() print 'done' print 'Preparing training data...' rdl_roidb.prepare_roidb(imdb) print 'done' return imdb.roidb def filter_roidb(roidb): """Remove roidb entries that have no usable RoIs.""" def is_valid(entry): # Valid images have: # (1) At least one foreground RoI OR # (2) At least one background RoI overlaps = entry['max_overlaps'] # find boxes with sufficient overlap fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0] # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO))[0] # image is only valid if such boxes exist valid = len(fg_inds) > 0 or len(bg_inds) > 0 return valid num = len(roidb) filtered_roidb = [entry for entry in roidb if is_valid(entry)] num_after = len(filtered_roidb) print 'Filtered {} roidb entries: {} -> {}'.format(num - num_after, num, num_after) return filtered_roidb def train_net(solver_prototxt, roidb, output_dir, pretrained_model=None, max_iters=40000): """Train a Fast R-CNN network.""" roidb = filter_roidb(roidb) sw = SolverWrapper(solver_prototxt, roidb, output_dir, pretrained_model=pretrained_model) print 'Solving...' model_paths = sw.train_model(max_iters) print 'done solving' return model_paths
8,539
39.861244
92
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/voc_eval.py
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Bharath Hariharan # -------------------------------------------------------- import xml.etree.ElementTree as ET import os import cPickle import numpy as np def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.find('truncated').text) obj_struct['difficult'] = int(obj.find('difficult').text) bbox = obj.find('bndbox') obj_struct['bbox'] = [int(bbox.find('xmin').text), int(bbox.find('ymin').text), int(bbox.find('xmax').text), int(bbox.find('ymax').text)] objects.append(obj_struct) return objects def voc_ap(rec, prec, use_07_metric=False): """ ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False). """ if use_07_metric: # 11 point metric ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap = ap + p / 11. else: # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def voc_eval(detpath, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=False): """rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, classname, [ovthresh], [use_07_metric]) Top level function that does the PASCAL VOC evaluation. detpath: Path to detections detpath.format(classname) should produce the detection results file. annopath: Path to annotations annopath.format(imagename) should be the xml annotations file. imagesetfile: Text file containing the list of images, one image per line. classname: Category name (duh) cachedir: Directory for caching the annotations [ovthresh]: Overlap threshold (default = 0.5) [use_07_metric]: Whether to use VOC07's 11 point AP computation (default False) """ # assumes detections are in detpath.format(classname) # assumes annotations are in annopath.format(imagename) # assumes imagesetfile is a text file with each line an image name # cachedir caches the annotations in a pickle file # first load gt if not os.path.isdir(cachedir): os.mkdir(cachedir) cachefile = os.path.join(cachedir, 'annots.pkl') # read list of images with open(imagesetfile, 'r') as f: lines = f.readlines() imagenames = [x.strip() for x in lines] if not os.path.isfile(cachefile): # load annots recs = {} for i, imagename in enumerate(imagenames): recs[imagename] = parse_rec(annopath.format(imagename)) if i % 100 == 0: print 'Reading annotation for {:d}/{:d}'.format( i + 1, len(imagenames)) # save print 'Saving cached annotations to {:s}'.format(cachefile) with open(cachefile, 'w') as f: cPickle.dump(recs, f) else: # load with open(cachefile, 'r') as f: recs = cPickle.load(f) # extract gt objects for this class class_recs = {} npos = 0 for imagename in imagenames: R = [obj for obj in recs[imagename] if obj['name'] == classname] bbox = np.array([x['bbox'] for x in R]) difficult = np.array([x['difficult'] for x in R]).astype(np.bool) det = [False] * len(R) npos = npos + sum(~difficult) class_recs[imagename] = {'bbox': bbox, 'difficult': difficult, 'det': det} # read dets detfile = detpath.format(classname) with open(detfile, 'r') as f: lines = f.readlines() splitlines = [x.strip().split(' ') for x in lines] image_ids = [x[0] for x in splitlines] confidence = np.array([float(x[1]) for x in splitlines]) BB = np.array([[float(z) for z in x[2:]] for x in splitlines]) # sort by confidence sorted_ind = np.argsort(-confidence) sorted_scores = np.sort(-confidence) BB = BB[sorted_ind, :] image_ids = [image_ids[x] for x in sorted_ind] # go down dets and mark TPs and FPs nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) ovmax = -np.inf BBGT = R['bbox'].astype(float) if BBGT.size > 0: # compute overlaps # intersection ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin = np.maximum(BBGT[:, 1], bb[1]) ixmax = np.minimum(BBGT[:, 2], bb[2]) iymax = np.minimum(BBGT[:, 3], bb[3]) iw = np.maximum(ixmax - ixmin + 1., 0.) ih = np.maximum(iymax - iymin + 1., 0.) inters = iw * ih # union uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + (BBGT[:, 2] - BBGT[:, 0] + 1.) * (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters) overlaps = inters / uni ovmax = np.max(overlaps) jmax = np.argmax(overlaps) if ovmax > ovthresh: if not R['difficult'][jmax]: if not R['det'][jmax]: tp[d] = 1. R['det'][jmax] = 1 else: fp[d] = 1. else: fp[d] = 1. # compute precision recall fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / float(npos) # avoid divide by zero in case the first detection matches a difficult # ground truth prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = voc_ap(rec, prec, use_07_metric) return rec, prec, ap
6,937
33.69
78
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/vg.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import xml.etree.ElementTree as ET import numpy as np import scipy.sparse import utils.cython_bbox import cPickle import gzip import PIL import json from vg_eval import vg_eval from fast_rcnn.config import cfg class vg(imdb): def __init__(self, version, image_set, ): imdb.__init__(self, 'vg_' + version + '_' + image_set) self._version = version self._image_set = image_set self._data_path = os.path.join(cfg.DATA_DIR, 'genome') self._img_path = os.path.join(cfg.DATA_DIR, 'vg') # VG specific config options self.config = {'cleanup' : False} # Load classes self._classes = ['__background__'] self._class_to_ind = {} self._class_to_ind[self._classes[0]] = 0 with open(os.path.join(self._data_path, self._version, 'objects_vocab.txt')) as f: count = 1 for object in f.readlines(): names = [n.lower().strip() for n in object.split(',')] self._classes.append(names[0]) for n in names: self._class_to_ind[n] = count count += 1 # Load attributes self._attributes = ['__no_attribute__'] self._attribute_to_ind = {} self._attribute_to_ind[self._attributes[0]] = 0 with open(os.path.join(self._data_path, self._version, 'attributes_vocab.txt')) as f: count = 1 for att in f.readlines(): names = [n.lower().strip() for n in att.split(',')] self._attributes.append(names[0]) for n in names: self._attribute_to_ind[n] = count count += 1 # Load relations self._relations = ['__no_relation__'] self._relation_to_ind = {} self._relation_to_ind[self._relations[0]] = 0 with open(os.path.join(self._data_path, self._version, 'relations_vocab.txt')) as f: count = 1 for rel in f.readlines(): names = [n.lower().strip() for n in rel.split(',')] self._relations.append(names[0]) for n in names: self._relation_to_ind[n] = count count += 1 self._image_ext = '.jpg' self._image_index, self._id_to_dir = self._load_image_set_index() def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self._image_index[i]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ folder = self._id_to_dir[index] image_path = os.path.join(self._img_path, folder, str(index) + self._image_ext) assert os.path.exists(image_path), \ 'Path does not exist: {}'.format(image_path) return image_path def _image_split_path(self): if self._image_set == "minitrain": return os.path.join(self._data_path, 'train.txt') if self._image_set == "minival": return os.path.join(self._data_path, 'val.txt') else: return os.path.join(self._data_path, self._image_set+'.txt') def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ training_split_file = self._image_split_path() assert os.path.exists(training_split_file), \ 'Path does not exist: {}'.format(training_split_file) with open(training_split_file) as f: metadata = f.readlines() if self._image_set == "minitrain": metadata = metadata[:1000] elif self._image_set == "minival": metadata = metadata[:100] image_index = [] id_to_dir = {} for line in metadata: im_file,ann_file = line.split() image_id = int(ann_file.split('/')[-1].split('.')[0]) filename = self._annotation_path(image_id) if os.path.exists(filename): # Some images have no bboxes after object filtering, so there # is no xml annotation for these. tree = ET.parse(filename) for obj in tree.findall('object'): obj_name = obj.find('name').text.lower().strip() if obj_name in self._class_to_ind: # We have to actually load and check these to make sure they have # at least one object actually in vocab image_index.append(image_id) id_to_dir[image_id] = im_file.split('/')[0] break return image_index, id_to_dir def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): fid = gzip.open(cache_file,'rb') roidb = cPickle.load(fid) fid.close() print '{} gt roidb loaded from {}'.format(self.name, cache_file) return roidb gt_roidb = [self._load_vg_annotation(index) for index in self.image_index] fid = gzip.open(cache_file,'wb') cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL) fid.close() print 'wrote gt roidb to {}'.format(cache_file) return gt_roidb def _get_size(self, index): return PIL.Image.open(self.image_path_from_index(index)).size def _annotation_path(self, index): return os.path.join(self._data_path, 'xml', str(index) + '.xml') def _load_vg_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ width, height = self._get_size(index) filename = self._annotation_path(index) tree = ET.parse(filename) objs = tree.findall('object') num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) # Max of 16 attributes are observed in the data gt_attributes = np.zeros((num_objs, 16), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. obj_dict = {} ix = 0 for obj in objs: obj_name = obj.find('name').text.lower().strip() if obj_name in self._class_to_ind: bbox = obj.find('bndbox') x1 = max(0,float(bbox.find('xmin').text)) y1 = max(0,float(bbox.find('ymin').text)) x2 = min(width-1,float(bbox.find('xmax').text)) y2 = min(height-1,float(bbox.find('ymax').text)) # If bboxes are not positive, just give whole image coords (there are a few examples) if x2 < x1 or y2 < y1: print 'Failed bbox in %s, object %s' % (filename, obj_name) x1 = 0 y1 = 0 x2 = width-1 y2 = width-1 cls = self._class_to_ind[obj_name] obj_dict[obj.find('object_id').text] = ix atts = obj.findall('attribute') n = 0 for att in atts: att = att.text.lower().strip() if att in self._attribute_to_ind: gt_attributes[ix, n] = self._attribute_to_ind[att] n += 1 if n >= 16: break boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) ix += 1 overlaps = scipy.sparse.csr_matrix(overlaps) gt_attributes = scipy.sparse.csr_matrix(gt_attributes) rels = tree.findall('relation') num_rels = len(rels) gt_relations = set() # Avoid duplicates for rel in rels: pred = rel.find('predicate').text if pred: # One is empty pred = pred.lower().strip() if pred in self._relation_to_ind: try: triple = [] triple.append(obj_dict[rel.find('subject_id').text]) triple.append(self._relation_to_ind[pred]) triple.append(obj_dict[rel.find('object_id').text]) gt_relations.add(tuple(triple)) except: pass # Object not in dictionary gt_relations = np.array(list(gt_relations), dtype=np.int32) return {'boxes' : boxes, 'gt_classes': gt_classes, 'gt_attributes' : gt_attributes, 'gt_relations' : gt_relations, 'gt_overlaps' : overlaps, 'width' : width, 'height': height, 'flipped' : False, 'seg_areas' : seg_areas} def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(self.classes, all_boxes, output_dir) self._do_python_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__': continue filename = self._get_vg_results_file_template(output_dir).format(cls) os.remove(filename) def evaluate_attributes(self, all_boxes, output_dir): self._write_voc_results_file(self.attributes, all_boxes, output_dir) self._do_python_eval(output_dir, eval_attributes = True) if self.config['cleanup']: for cls in self._attributes: if cls == '__no_attribute__': continue filename = self._get_vg_results_file_template(output_dir).format(cls) os.remove(filename) def _get_vg_results_file_template(self, output_dir): filename = 'detections_' + self._image_set + '_{:s}.txt' path = os.path.join(output_dir, filename) return path def _write_voc_results_file(self, classes, all_boxes, output_dir): for cls_ind, cls in enumerate(classes): if cls == '__background__': continue print 'Writing "{}" vg results file'.format(cls) filename = self._get_vg_results_file_template(output_dir).format(cls) with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in xrange(dets.shape[0]): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(str(index), dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) def _do_python_eval(self, output_dir, pickle=True, eval_attributes = False): # We re-use parts of the pascal voc python code for visual genome aps = [] nposs = [] thresh = [] # The PASCAL VOC metric changed in 2010 use_07_metric = False print 'VOC07 metric? ' + ('Yes' if use_07_metric else 'No') if not os.path.isdir(output_dir): os.mkdir(output_dir) # Load ground truth gt_roidb = self.gt_roidb() if eval_attributes: classes = self._attributes else: classes = self._classes for i, cls in enumerate(classes): if cls == '__background__' or cls == '__no_attribute__': continue filename = self._get_vg_results_file_template(output_dir).format(cls) rec, prec, ap, scores, npos = vg_eval( filename, gt_roidb, self.image_index, i, ovthresh=0.5, use_07_metric=use_07_metric, eval_attributes=eval_attributes) # Determine per class detection thresholds that maximise f score if npos > 1: f = np.nan_to_num((prec*rec)/(prec+rec)) thresh += [scores[np.argmax(f)]] else: thresh += [0] aps += [ap] nposs += [float(npos)] print('AP for {} = {:.4f} (npos={:,})'.format(cls, ap, npos)) if pickle: with open(os.path.join(output_dir, cls + '_pr.pkl'), 'w') as f: cPickle.dump({'rec': rec, 'prec': prec, 'ap': ap, 'scores': scores, 'npos':npos}, f) # Set thresh to mean for classes with poor results thresh = np.array(thresh) avg_thresh = np.mean(thresh[thresh!=0]) thresh[thresh==0] = avg_thresh if eval_attributes: filename = 'attribute_thresholds_' + self._image_set + '.txt' else: filename = 'object_thresholds_' + self._image_set + '.txt' path = os.path.join(output_dir, filename) with open(path, 'wt') as f: for i, cls in enumerate(classes[1:]): f.write('{:s} {:.3f}\n'.format(cls, thresh[i])) weights = np.array(nposs) weights /= weights.sum() print('Mean AP = {:.4f}'.format(np.mean(aps))) print('Weighted Mean AP = {:.4f}'.format(np.average(aps, weights=weights))) print('Mean Detection Threshold = {:.3f}'.format(avg_thresh)) print('~~~~~~~~') print('Results:') for ap,npos in zip(aps,nposs): print('{:.3f}\t{:.3f}'.format(ap,npos)) print('{:.3f}'.format(np.mean(aps))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** PASCAL VOC Python eval code.') print('--------------------------------------------------------------') if __name__ == '__main__': d = datasets.vg('val') res = d.roidb from IPython import embed; embed()
15,143
40.719008
101
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/pascal_voc.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import xml.etree.ElementTree as ET import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import cPickle import subprocess import uuid from voc_eval import voc_eval from fast_rcnn.config import cfg class pascal_voc(imdb): def __init__(self, image_set, year, devkit_path=None): imdb.__init__(self, 'voc_' + year + '_' + image_set) self._year = year self._image_set = image_set self._devkit_path = self._get_default_path() if devkit_path is None \ else devkit_path self._data_path = os.path.join(self._devkit_path, 'VOC' + self._year) self._classes = ('__background__', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') self._class_to_ind = dict(zip(self.classes, xrange(self.num_classes))) self._image_ext = '.jpg' self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.selective_search_roidb self._salt = str(uuid.uuid4()) self._comp_id = 'comp4' # PASCAL specific config options self.config = {'cleanup' : True, 'use_salt' : True, 'use_diff' : False, 'matlab_eval' : False, 'rpn_file' : None, 'min_size' : 2} assert os.path.exists(self._devkit_path), \ 'VOCdevkit path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self._image_index[i]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ image_path = os.path.join(self._data_path, 'JPEGImages', index + self._image_ext) assert os.path.exists(image_path), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt image_set_file = os.path.join(self._data_path, 'ImageSets', 'Main', self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] return image_index def _get_default_path(self): """ Return the default path where PASCAL VOC is expected to be installed. """ return os.path.join(cfg.DATA_DIR, 'VOCdevkit' + self._year) def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} gt roidb loaded from {}'.format(self.name, cache_file) return roidb gt_roidb = [self._load_pascal_annotation(index) for index in self.image_index] with open(cache_file, 'wb') as fid: cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote gt roidb to {}'.format(cache_file) return gt_roidb def selective_search_roidb(self): """ Return the database of selective search regions of interest. Ground-truth ROIs are also included. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_selective_search_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} ss roidb loaded from {}'.format(self.name, cache_file) return roidb if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() ss_roidb = self._load_selective_search_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, ss_roidb) else: roidb = self._load_selective_search_roidb(None) with open(cache_file, 'wb') as fid: cPickle.dump(roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote ss roidb to {}'.format(cache_file) return roidb def rpn_roidb(self): if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print 'loading {}'.format(filename) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = cPickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_selective_search_roidb(self, gt_roidb): filename = os.path.abspath(os.path.join(cfg.DATA_DIR, 'selective_search_data', self.name + '.mat')) assert os.path.exists(filename), \ 'Selective search data not found at: {}'.format(filename) raw_data = sio.loadmat(filename)['boxes'].ravel() box_list = [] for i in xrange(raw_data.shape[0]): boxes = raw_data[i][:, (1, 0, 3, 2)] - 1 keep = ds_utils.unique_boxes(boxes) boxes = boxes[keep, :] keep = ds_utils.filter_small_boxes(boxes, self.config['min_size']) boxes = boxes[keep, :] box_list.append(boxes) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_pascal_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') if not self.config['use_diff']: # Exclude the samples labeled as difficult non_diff_objs = [ obj for obj in objs if int(obj.find('difficult').text) == 0] # if len(non_diff_objs) != len(objs): # print 'Removed {} difficult objects'.format( # len(objs) - len(non_diff_objs)) objs = non_diff_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) - 1 y1 = float(bbox.find('ymin').text) - 1 x2 = float(bbox.find('xmax').text) - 1 y2 = float(bbox.find('ymax').text) - 1 cls = self._class_to_ind[obj.find('name').text.lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes' : boxes, 'gt_classes': gt_classes, 'gt_overlaps' : overlaps, 'flipped' : False, 'seg_areas' : seg_areas} def _get_comp_id(self): comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt'] else self._comp_id) return comp_id def _get_voc_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = self._get_comp_id() + '_det_' + self._image_set + '_{:s}.txt' path = os.path.join( self._devkit_path, 'results', 'VOC' + self._year, 'Main', filename) return path def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print 'Writing {} VOC results file'.format(cls) filename = self._get_voc_results_file_template().format(cls) with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in xrange(dets.shape[0]): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(index, dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) def _do_python_eval(self, output_dir = 'output'): annopath = os.path.join( self._devkit_path, 'VOC' + self._year, 'Annotations', '{:s}.xml') imagesetfile = os.path.join( self._devkit_path, 'VOC' + self._year, 'ImageSets', 'Main', self._image_set + '.txt') cachedir = os.path.join(self._devkit_path, 'annotations_cache') aps = [] # The PASCAL VOC metric changed in 2010 use_07_metric = True if int(self._year) < 2010 else False print 'VOC07 metric? ' + ('Yes' if use_07_metric else 'No') if not os.path.isdir(output_dir): os.mkdir(output_dir) for i, cls in enumerate(self._classes): if cls == '__background__': continue filename = self._get_voc_results_file_template().format(cls) rec, prec, ap = voc_eval( filename, annopath, imagesetfile, cls, cachedir, ovthresh=0.5, use_07_metric=use_07_metric) aps += [ap] print('AP for {} = {:.4f}'.format(cls, ap)) with open(os.path.join(output_dir, cls + '_pr.pkl'), 'w') as f: cPickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f) print('Mean AP = {:.4f}'.format(np.mean(aps))) print('~~~~~~~~') print('Results:') for ap in aps: print('{:.3f}'.format(ap)) print('{:.3f}'.format(np.mean(aps))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** Python eval code.') print('Results should be very close to the official MATLAB eval code.') print('Recompute with `./tools/reval.py --matlab ...` for your paper.') print('-- Thanks, The Management') print('--------------------------------------------------------------') def _do_matlab_eval(self, output_dir='output'): print '-----------------------------------------------------' print 'Computing results with the official MATLAB eval code.' print '-----------------------------------------------------' path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\',\'{:s}\'); quit;"' \ .format(self._devkit_path, self._get_comp_id(), self._image_set, output_dir) print('Running:\n{}'.format(cmd)) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(all_boxes) self._do_python_eval(output_dir) if self.config['matlab_eval']: self._do_matlab_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__': continue filename = self._get_voc_results_file_template().format(cls) os.remove(filename) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True if __name__ == '__main__': from datasets.pascal_voc import pascal_voc d = pascal_voc('trainval', '2007') res = d.roidb from IPython import embed; embed()
14,217
40.211594
80
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/imdb.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import os import os.path as osp import PIL from utils.cython_bbox import bbox_overlaps import numpy as np import scipy.sparse from fast_rcnn.config import cfg class imdb(object): """Image database.""" def __init__(self, name): self._name = name self._classes = [] self._attributes = [] self._relations = [] self._image_index = [] self._obj_proposer = 'selective_search' self._roidb = None self._roidb_handler = self.default_roidb # Use this dict for storing dataset specific config options self.config = {} @property def name(self): return self._name @property def num_classes(self): return len(self._classes) @property def num_attributes(self): return len(self._attributes) @property def num_relations(self): return len(self._relations) @property def classes(self): return self._classes @property def attributes(self): return self._attributes @property def relations(self): return self._relations @property def image_index(self): return self._image_index @property def roidb_handler(self): return self._roidb_handler @roidb_handler.setter def roidb_handler(self, val): self._roidb_handler = val def set_proposal_method(self, method): method = eval('self.' + method + '_roidb') self.roidb_handler = method @property def roidb(self): # A roidb is a list of dictionaries, each with the following keys (at minimum): # boxes # gt_overlaps # gt_classes # flipped if self._roidb is not None: return self._roidb self._roidb = self.roidb_handler() return self._roidb @property def cache_path(self): cache_path = osp.abspath(osp.join(cfg.DATA_DIR, 'cache')) if not os.path.exists(cache_path): os.makedirs(cache_path) return cache_path @property def num_images(self): return len(self.image_index) def image_path_at(self, i): raise NotImplementedError def default_roidb(self): raise NotImplementedError def evaluate_detections(self, all_boxes, output_dir=None): """ all_boxes is a list of length number-of-classes. Each list element is a list of length number-of-images. Each of those list elements is either an empty list [] or a numpy array of detection. all_boxes[class][image] = [] or np.array of shape #dets x 5 """ raise NotImplementedError def evaluate_attributes(self, all_boxes, output_dir=None): """ all_boxes is a list of length number-of-classes. Each list element is a list of length number-of-images. Each of those list elements is either an empty list [] or a numpy array of detection. all_boxes[class][image] = [] or np.array of shape #dets x 5 """ raise NotImplementedError def evaluate_relations(self, all_boxes, output_dir=None): """ all_boxes is a list of length number-of-classes. Each list element is a list of length number-of-images. Each of those list elements is either an empty list [] or a numpy array of detection. all_boxes[class][image] = [] or np.array of shape #dets x 5 """ raise NotImplementedError def _get_widths(self): return [PIL.Image.open(self.image_path_at(i)).size[0] for i in xrange(self.num_images)] def append_flipped_images(self): num_images = self.num_images widths = None for i in xrange(num_images): entry = self.roidb[i].copy() if 'width' in entry: width = entry['width'] else: if not widths: widths = self._get_widths() width = widths[i] boxes = self.roidb[i]['boxes'].copy() oldx1 = boxes[:, 0].copy() oldx2 = boxes[:, 2].copy() boxes[:, 0] = width - oldx2 - 1 boxes[:, 2] = width - oldx1 - 1 assert (boxes[:, 2] >= boxes[:, 0]).all(), \ " image %d bounding boxes not positive, width %d:\n %s \n %s" \ % (i,width, entry['boxes'],boxes) entry['boxes'] = boxes entry['flipped'] = True self.roidb.append(entry) self._image_index = self._image_index * 2 def evaluate_recall(self, candidate_boxes=None, thresholds=None, area='all', limit=None): """Evaluate detection proposal recall metrics. Returns: results: dictionary of results with keys 'ar': average recall 'recalls': vector recalls at each IoU overlap threshold 'thresholds': vector of IoU overlap thresholds 'gt_overlaps': vector of all ground-truth overlaps """ # Record max overlap value for each gt box # Return vector of overlap values areas = { 'all': 0, 'small': 1, 'medium': 2, 'large': 3, '96-128': 4, '128-256': 5, '256-512': 6, '512-inf': 7} area_ranges = [ [0**2, 1e5**2], # all [0**2, 32**2], # small [32**2, 96**2], # medium [96**2, 1e5**2], # large [96**2, 128**2], # 96-128 [128**2, 256**2], # 128-256 [256**2, 512**2], # 256-512 [512**2, 1e5**2], # 512-inf ] assert areas.has_key(area), 'unknown area range: {}'.format(area) area_range = area_ranges[areas[area]] gt_overlaps = np.zeros(0) num_pos = 0 for i in xrange(self.num_images): # Checking for max_overlaps == 1 avoids including crowd annotations # (...pretty hacking :/) max_gt_overlaps = self.roidb[i]['gt_overlaps'].toarray().max(axis=1) gt_inds = np.where((self.roidb[i]['gt_classes'] > 0) & (max_gt_overlaps == 1))[0] gt_boxes = self.roidb[i]['boxes'][gt_inds, :] gt_areas = self.roidb[i]['seg_areas'][gt_inds] valid_gt_inds = np.where((gt_areas >= area_range[0]) & (gt_areas <= area_range[1]))[0] gt_boxes = gt_boxes[valid_gt_inds, :] num_pos += len(valid_gt_inds) if candidate_boxes is None: # If candidate_boxes is not supplied, the default is to use the # non-ground-truth boxes from this roidb non_gt_inds = np.where(self.roidb[i]['gt_classes'] == 0)[0] boxes = self.roidb[i]['boxes'][non_gt_inds, :] else: boxes = candidate_boxes[i] if boxes.shape[0] == 0: continue if limit is not None and boxes.shape[0] > limit: boxes = boxes[:limit, :] overlaps = bbox_overlaps(boxes.astype(np.float), gt_boxes.astype(np.float)) _gt_overlaps = np.zeros((gt_boxes.shape[0])) for j in xrange(gt_boxes.shape[0]): # find which proposal box maximally covers each gt box argmax_overlaps = overlaps.argmax(axis=0) # and get the iou amount of coverage for each gt box max_overlaps = overlaps.max(axis=0) # find which gt box is 'best' covered (i.e. 'best' = most iou) gt_ind = max_overlaps.argmax() gt_ovr = max_overlaps.max() assert(gt_ovr >= 0) # find the proposal box that covers the best covered gt box box_ind = argmax_overlaps[gt_ind] # record the iou coverage of this gt box _gt_overlaps[j] = overlaps[box_ind, gt_ind] assert(_gt_overlaps[j] == gt_ovr) # mark the proposal box and the gt box as used overlaps[box_ind, :] = -1 overlaps[:, gt_ind] = -1 # append recorded iou coverage level gt_overlaps = np.hstack((gt_overlaps, _gt_overlaps)) gt_overlaps = np.sort(gt_overlaps) if thresholds is None: step = 0.05 thresholds = np.arange(0.5, 0.95 + 1e-5, step) recalls = np.zeros_like(thresholds) # compute recall for each iou threshold for i, t in enumerate(thresholds): recalls[i] = (gt_overlaps >= t).sum() / float(num_pos) # ar = 2 * np.trapz(recalls, thresholds) ar = recalls.mean() return {'ar': ar, 'recalls': recalls, 'thresholds': thresholds, 'gt_overlaps': gt_overlaps} def create_roidb_from_box_list(self, box_list, gt_roidb): assert len(box_list) == self.num_images, \ 'Number of boxes must match number of ground-truth images' roidb = [] for i in xrange(self.num_images): boxes = box_list[i] num_boxes = boxes.shape[0] overlaps = np.zeros((num_boxes, self.num_classes), dtype=np.float32) if gt_roidb is not None and gt_roidb[i]['boxes'].size > 0: gt_boxes = gt_roidb[i]['boxes'] gt_classes = gt_roidb[i]['gt_classes'] gt_overlaps = bbox_overlaps(boxes.astype(np.float), gt_boxes.astype(np.float)) argmaxes = gt_overlaps.argmax(axis=1) maxes = gt_overlaps.max(axis=1) I = np.where(maxes > 0)[0] overlaps[I, gt_classes[argmaxes[I]]] = maxes[I] overlaps = scipy.sparse.csr_matrix(overlaps) roidb.append({ 'boxes' : boxes, 'gt_classes' : np.zeros((num_boxes,), dtype=np.int32), 'gt_overlaps' : overlaps, 'flipped' : False, 'seg_areas' : np.zeros((num_boxes,), dtype=np.float32), }) return roidb @staticmethod def merge_roidbs(a, b): assert len(a) == len(b) for i in xrange(len(a)): a[i]['boxes'] = np.vstack((a[i]['boxes'], b[i]['boxes'])) a[i]['gt_classes'] = np.hstack((a[i]['gt_classes'], b[i]['gt_classes'])) a[i]['gt_overlaps'] = scipy.sparse.vstack([a[i]['gt_overlaps'], b[i]['gt_overlaps']]) a[i]['seg_areas'] = np.hstack((a[i]['seg_areas'], b[i]['seg_areas'])) if 'gt_attributes' in a[i]: a[i]['gt_attributes'] = scipy.sparse.vstack((a[i]['gt_attributes'], b[i]['gt_attributes'])) if 'gt_relations' in a[i]: a[i]['gt_relations'] = np.vstack((a[i]['gt_relations'], b[i]['gt_relations'])) return a def competition_mode(self, on): """Turn competition mode on or off.""" pass
11,606
36.931373
87
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/factory.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Factory method for easily getting imdbs by name.""" __sets = {} from datasets.pascal_voc import pascal_voc from datasets.coco import coco from datasets.imagenet import imagenet from datasets.vg import vg import numpy as np # Set up voc_<year>_<split> using selective search "fast" mode for year in ['2007', '2012', '0712']: for split in ['train', 'val', 'trainval', 'test']: name = 'voc_{}_{}'.format(year, split) __sets[name] = (lambda split=split, year=year: pascal_voc(split, year)) for split in ['train', 'val']: name = 'imagenet_{}'.format(split) devkit_path = '/scratch0/ILSVRC/devkit/' data_path = '/scratch0/ILSVRC2015/' __sets[name] = (lambda split=split, devkit_path=devkit_path, data_path=data_path: imagenet(split, devkit_path, data_path)) print name print __sets[name] # Set up coco_2014_<split> for year in ['2014']: for split in ['train', 'val', 'minival', 'valminusminival']: name = 'coco_{}_{}'.format(year, split) __sets[name] = (lambda split=split, year=year: coco(split, year)) # Set up coco_2015_<split> for year in ['2015']: for split in ['test', 'test-dev']: name = 'coco_{}_{}'.format(year, split) __sets[name] = (lambda split=split, year=year: coco(split, year)) # Set up vg_<split> for version in ['1600-400-20']: for split in ['minitrain', 'train', 'minival', 'val', 'test']: name = 'vg_{}_{}'.format(version,split) __sets[name] = (lambda split=split, version=version: vg(version, split)) def get_imdb(name): """Get an imdb (image database) by name.""" if not __sets.has_key(name): raise KeyError('Unknown dataset: {}'.format(name)) return __sets[name]() def list_imdbs(): """List all registered imdbs.""" return __sets.keys()
2,055
33.847458
126
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/ds_utils.py
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import numpy as np def unique_boxes(boxes, scale=1.0): """Return indices of unique boxes.""" v = np.array([1, 1e3, 1e6, 1e9]) hashes = np.round(boxes * scale).dot(v) _, index = np.unique(hashes, return_index=True) return np.sort(index) def xywh_to_xyxy(boxes): """Convert [x y w h] box format to [x1 y1 x2 y2] format.""" return np.hstack((boxes[:, 0:2], boxes[:, 0:2] + boxes[:, 2:4] - 1)) def xyxy_to_xywh(boxes): """Convert [x1 y1 x2 y2] box format to [x y w h] format.""" return np.hstack((boxes[:, 0:2], boxes[:, 2:4] - boxes[:, 0:2] + 1)) def validate_boxes(boxes, width=0, height=0): """Check that a set of boxes are valid.""" x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] assert (x1 >= 0).all() assert (y1 >= 0).all() assert (x2 >= x1).all() assert (y2 >= y1).all() assert (x2 < width).all() assert (y2 < height).all() def filter_small_boxes(boxes, min_size): w = boxes[:, 2] - boxes[:, 0] h = boxes[:, 3] - boxes[:, 1] keep = np.where((w >= min_size) & (h > min_size))[0] return keep
1,336
30.833333
72
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # --------------------------------------------------------
248
34.571429
58
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/vg_eval.py
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Bharath Hariharan # -------------------------------------------------------- import xml.etree.ElementTree as ET import os import cPickle import numpy as np from voc_eval import voc_ap def vg_eval( detpath, gt_roidb, image_index, classindex, ovthresh=0.5, use_07_metric=False, eval_attributes=False): """rec, prec, ap, sorted_scores, npos = voc_eval( detpath, gt_roidb, image_index, classindex, [ovthresh], [use_07_metric]) Top level function that does the Visual Genome evaluation. detpath: Path to detections gt_roidb: List of ground truth structs. image_index: List of image ids. classindex: Category index [ovthresh]: Overlap threshold (default = 0.5) [use_07_metric]: Whether to use VOC07's 11 point AP computation (default False) """ # extract gt objects for this class class_recs = {} npos = 0 for item,imagename in zip(gt_roidb,image_index): if eval_attributes: bbox = item['boxes'][np.where(np.any(item['gt_attributes'].toarray() == classindex, axis=1))[0], :] else: bbox = item['boxes'][np.where(item['gt_classes'] == classindex)[0], :] difficult = np.zeros((bbox.shape[0],)).astype(np.bool) det = [False] * bbox.shape[0] npos = npos + sum(~difficult) class_recs[str(imagename)] = {'bbox': bbox, 'difficult': difficult, 'det': det} if npos == 0: # No ground truth examples return 0,0,0,0,npos # read dets with open(detpath, 'r') as f: lines = f.readlines() if len(lines) == 0: # No detection examples return 0,0,0,0,npos splitlines = [x.strip().split(' ') for x in lines] image_ids = [x[0] for x in splitlines] confidence = np.array([float(x[1]) for x in splitlines]) BB = np.array([[float(z) for z in x[2:]] for x in splitlines]) # sort by confidence sorted_ind = np.argsort(-confidence) sorted_scores = -np.sort(-confidence) BB = BB[sorted_ind, :] image_ids = [image_ids[x] for x in sorted_ind] # go down dets and mark TPs and FPs nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) ovmax = -np.inf BBGT = R['bbox'].astype(float) if BBGT.size > 0: # compute overlaps # intersection ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin = np.maximum(BBGT[:, 1], bb[1]) ixmax = np.minimum(BBGT[:, 2], bb[2]) iymax = np.minimum(BBGT[:, 3], bb[3]) iw = np.maximum(ixmax - ixmin + 1., 0.) ih = np.maximum(iymax - iymin + 1., 0.) inters = iw * ih # union uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + (BBGT[:, 2] - BBGT[:, 0] + 1.) * (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters) overlaps = inters / uni ovmax = np.max(overlaps) jmax = np.argmax(overlaps) if ovmax > ovthresh: if not R['difficult'][jmax]: if not R['det'][jmax]: tp[d] = 1. R['det'][jmax] = 1 else: fp[d] = 1. else: fp[d] = 1. # compute precision recall fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / float(npos) # avoid divide by zero in case the first detection matches a difficult # ground truth prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = voc_ap(rec, prec, use_07_metric) return rec, prec, ap, sorted_scores, npos
4,153
31.968254
111
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/imagenet.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import datasets import datasets.imagenet import os, sys from datasets.imdb import imdb import xml.dom.minidom as minidom import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import cPickle import subprocess class imagenet(imdb): def __init__(self, image_set, devkit_path, data_path): imdb.__init__(self, image_set) self._image_set = image_set self._devkit_path = devkit_path self._data_path = data_path synsets_image = sio.loadmat(os.path.join(self._devkit_path, 'data', 'meta_det.mat')) synsets_video = sio.loadmat(os.path.join(self._devkit_path, 'data', 'meta_vid.mat')) self._classes_image = ('__background__',) self._wnid_image = (0,) self._classes = ('__background__',) self._wnid = (0,) for i in xrange(200): self._classes_image = self._classes_image + (synsets_image['synsets'][0][i][2][0],) self._wnid_image = self._wnid_image + (synsets_image['synsets'][0][i][1][0],) for i in xrange(30): self._classes = self._classes + (synsets_video['synsets'][0][i][2][0],) self._wnid = self._wnid + (synsets_video['synsets'][0][i][1][0],) self._wnid_to_ind_image = dict(zip(self._wnid_image, xrange(201))) self._class_to_ind_image = dict(zip(self._classes_image, xrange(201))) self._wnid_to_ind = dict(zip(self._wnid, xrange(31))) self._class_to_ind = dict(zip(self._classes, xrange(31))) #check for valid intersection between video and image classes self._valid_image_flag = [0]*201 for i in range(1,201): if self._wnid_image[i] in self._wnid_to_ind: self._valid_image_flag[i] = 1 self._image_ext = ['.JPEG'] self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.gt_roidb # Specific config options self.config = {'cleanup' : True, 'use_salt' : True, 'top_k' : 2000} assert os.path.exists(self._devkit_path), 'Devkit path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self._image_index[i]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ image_path = os.path.join(self._data_path, 'Data', self._image_set, index + self._image_ext[0]) assert os.path.exists(image_path), 'path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._data_path + /ImageSets/val.txt if self._image_set == 'train': image_set_file = os.path.join(self._data_path, 'ImageSets', 'trainr.txt') image_index = [] if os.path.exists(image_set_file): f = open(image_set_file, 'r') data = f.read().split() for lines in data: if lines != '': image_index.append(lines) f.close() return image_index for i in range(1,31): print(i) image_set_file = os.path.join(self._data_path, 'ImageSets', 'train_' + str(i) + '.txt') with open(image_set_file) as f: tmp_index = [x.strip() for x in f.readlines()] vtmp_index = [] for line in tmp_index: image_list = os.popen('ls ' + self._data_path + '/Data/train/' + line + '/*.JPEG').read().split() tmp_list = [] for imgs in image_list: tmp_list.append(imgs[:-5]) vtmp_index = vtmp_index + tmp_list num_lines = len(vtmp_index) ids = np.random.permutation(num_lines) count = 0 while count < 2000: image_index.append(vtmp_index[ids[count % num_lines]]) count = count + 1 for i in range(1,201): if self._valid_image_flag[i] == 1: image_set_file = os.path.join(self._data_path, 'ImageSets', 'train_pos_' + str(i) + '.txt') with open(image_set_file) as f: tmp_index = [x.strip() for x in f.readlines()] num_lines = len(tmp_index) ids = np.random.permutation(num_lines) count = 0 while count < 2000: image_index.append(tmp_index[ids[count % num_lines]]) count = count + 1 image_set_file = os.path.join(self._data_path, 'ImageSets', 'trainr.txt') f = open(image_set_file, 'w') for lines in image_index: f.write(lines + '\n') f.close() else: image_set_file = os.path.join(self._data_path, 'ImageSets', 'val.txt') with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] return image_index def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} gt roidb loaded from {}'.format(self.name, cache_file) return roidb gt_roidb = [self._load_imagenet_annotation(index) for index in self.image_index] with open(cache_file, 'wb') as fid: cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote gt roidb to {}'.format(cache_file) return gt_roidb def _load_imagenet_annotation(self, index): """ Load image and bounding boxes info from txt files of imagenet. """ filename = os.path.join(self._data_path, 'Annotations', self._image_set, index + '.xml') # print 'Loading: {}'.format(filename) def get_data_from_tag(node, tag): return node.getElementsByTagName(tag)[0].childNodes[0].data with open(filename) as f: data = minidom.parseString(f.read()) objs = data.getElementsByTagName('object') num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): x1 = float(get_data_from_tag(obj, 'xmin')) y1 = float(get_data_from_tag(obj, 'ymin')) x2 = float(get_data_from_tag(obj, 'xmax')) y2 = float(get_data_from_tag(obj, 'ymax')) cls = self._wnid_to_ind[ str(get_data_from_tag(obj, "name")).lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes' : boxes, 'gt_classes': gt_classes, 'gt_overlaps' : overlaps, 'flipped' : False} if __name__ == '__main__': d = datasets.imagenet('val', '') res = d.roidb from IPython import embed; embed()
8,245
38.644231
121
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/coco.py
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from datasets.imdb import imdb import datasets.ds_utils as ds_utils from fast_rcnn.config import cfg import os.path as osp import sys import os import numpy as np import scipy.sparse import scipy.io as sio import cPickle import json import uuid # COCO API from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from pycocotools import mask as COCOmask def _filter_crowd_proposals(roidb, crowd_thresh): """ Finds proposals that are inside crowd regions and marks them with overlap = -1 (for all gt rois), which means they will be excluded from training. """ for ix, entry in enumerate(roidb): overlaps = entry['gt_overlaps'].toarray() crowd_inds = np.where(overlaps.max(axis=1) == -1)[0] non_gt_inds = np.where(entry['gt_classes'] == 0)[0] if len(crowd_inds) == 0 or len(non_gt_inds) == 0: continue iscrowd = [int(True) for _ in xrange(len(crowd_inds))] crowd_boxes = ds_utils.xyxy_to_xywh(entry['boxes'][crowd_inds, :]) non_gt_boxes = ds_utils.xyxy_to_xywh(entry['boxes'][non_gt_inds, :]) ious = COCOmask.iou(non_gt_boxes, crowd_boxes, iscrowd) bad_inds = np.where(ious.max(axis=1) > crowd_thresh)[0] overlaps[non_gt_inds[bad_inds], :] = -1 roidb[ix]['gt_overlaps'] = scipy.sparse.csr_matrix(overlaps) return roidb class coco(imdb): def __init__(self, image_set, year): imdb.__init__(self, 'coco_' + year + '_' + image_set) # COCO specific config options self.config = {'top_k' : 2000, 'use_salt' : True, 'cleanup' : True, 'crowd_thresh' : 0.7, 'rpn_file': None, 'min_size' : 2} # name, paths self._year = year self._image_set = image_set self._data_path = osp.join(cfg.DATA_DIR, 'coco') # load COCO API, classes, class <-> id mappings self._COCO = COCO(self._get_ann_file()) cats = self._COCO.loadCats(self._COCO.getCatIds()) self._classes = tuple(['__background__'] + [c['name'] for c in cats]) self._class_to_ind = dict(zip(self.classes, xrange(self.num_classes))) self._class_to_coco_cat_id = dict(zip([c['name'] for c in cats], self._COCO.getCatIds())) self._image_index = self._load_image_set_index() # Default to roidb handler self.set_proposal_method('selective_search') self.competition_mode(False) # Some image sets are "views" (i.e. subsets) into others. # For example, minival2014 is a random 5000 image subset of val2014. # This mapping tells us where the view's images and proposals come from. self._view_map = { 'minival2014' : 'val2014', # 5k val2014 subset 'valminusminival2014' : 'val2014', # val2014 \setminus minival2014 } coco_name = image_set + year # e.g., "val2014" self._data_name = (self._view_map[coco_name] if self._view_map.has_key(coco_name) else coco_name) # Dataset splits that have ground-truth annotations (test splits # do not have gt annotations) self._gt_splits = ('train', 'val', 'minival') def _get_ann_file(self): prefix = 'instances' if self._image_set.find('test') == -1 \ else 'image_info' return osp.join(self._data_path, 'annotations', prefix + '_' + self._image_set + self._year + '.json') def _load_image_set_index(self): """ Load image ids. """ image_ids = self._COCO.getImgIds() return image_ids def _get_widths(self): anns = self._COCO.loadImgs(self._image_index) widths = [ann['width'] for ann in anns] return widths def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self._image_index[i]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ # Example image path for index=119993: # images/train2014/COCO_train2014_000000119993.jpg file_name = ('COCO_' + self._data_name + '_' + str(index).zfill(12) + '.jpg') image_path = osp.join(self._data_path, 'images', self._data_name, file_name) assert osp.exists(image_path), \ 'Path does not exist: {}'.format(image_path) return image_path def selective_search_roidb(self): return self._roidb_from_proposals('selective_search') def edge_boxes_roidb(self): return self._roidb_from_proposals('edge_boxes_AR') def mcg_roidb(self): return self._roidb_from_proposals('MCG') def rpn_roidb(self): if (self._image_set != 'val') and ('test' not in self._image_set): gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print 'loading {}'.format(filename) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = cPickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _roidb_from_proposals(self, method): """ Creates a roidb from pre-computed proposals of a particular methods. """ top_k = self.config['top_k'] cache_file = osp.join(self.cache_path, self.name + '_{:s}_top{:d}'.format(method, top_k) + '_roidb.pkl') if osp.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{:s} {:s} roidb loaded from {:s}'.format(self.name, method, cache_file) return roidb if self._image_set in self._gt_splits: gt_roidb = self.gt_roidb() method_roidb = self._load_proposals(method, gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, method_roidb) # Make sure we don't use proposals that are contained in crowds roidb = _filter_crowd_proposals(roidb, self.config['crowd_thresh']) else: roidb = self._load_proposals(method, None) with open(cache_file, 'wb') as fid: cPickle.dump(roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote {:s} roidb to {:s}'.format(method, cache_file) return roidb def _load_proposals(self, method, gt_roidb): """ Load pre-computed proposals in the format provided by Jan Hosang: http://www.mpi-inf.mpg.de/departments/computer-vision-and-multimodal- computing/research/object-recognition-and-scene-understanding/how- good-are-detection-proposals-really/ For MCG, use boxes from http://www.eecs.berkeley.edu/Research/Projects/ CS/vision/grouping/mcg/ and convert the file layout using lib/datasets/tools/mcg_munge.py. """ box_list = [] top_k = self.config['top_k'] valid_methods = [ 'MCG', 'selective_search', 'edge_boxes_AR', 'edge_boxes_70'] assert method in valid_methods print 'Loading {} boxes'.format(method) for i, index in enumerate(self._image_index): if i % 1000 == 0: print '{:d} / {:d}'.format(i + 1, len(self._image_index)) box_file = osp.join( cfg.DATA_DIR, 'coco_proposals', method, 'mat', self._get_box_file(index)) raw_data = sio.loadmat(box_file)['boxes'] boxes = np.maximum(raw_data - 1, 0).astype(np.uint16) if method == 'MCG': # Boxes from the MCG website are in (y1, x1, y2, x2) order boxes = boxes[:, (1, 0, 3, 2)] # Remove duplicate boxes and very small boxes and then take top k keep = ds_utils.unique_boxes(boxes) boxes = boxes[keep, :] keep = ds_utils.filter_small_boxes(boxes, self.config['min_size']) boxes = boxes[keep, :] boxes = boxes[:top_k, :] box_list.append(boxes) # Sanity check im_ann = self._COCO.loadImgs(index)[0] width = im_ann['width'] height = im_ann['height'] ds_utils.validate_boxes(boxes, width=width, height=height) return self.create_roidb_from_box_list(box_list, gt_roidb) def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = osp.join(self.cache_path, self.name + '_gt_roidb.pkl') if osp.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} gt roidb loaded from {}'.format(self.name, cache_file) return roidb gt_roidb = [self._load_coco_annotation(index) for index in self._image_index] with open(cache_file, 'wb') as fid: cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote gt roidb to {}'.format(cache_file) return gt_roidb def _load_coco_annotation(self, index): """ Loads COCO bounding-box instance annotations. Crowd instances are handled by marking their overlaps (with all categories) to -1. This overlap value means that crowd "instances" are excluded from training. """ im_ann = self._COCO.loadImgs(index)[0] width = im_ann['width'] height = im_ann['height'] annIds = self._COCO.getAnnIds(imgIds=index, iscrowd=None) objs = self._COCO.loadAnns(annIds) # Sanitize bboxes -- some are invalid valid_objs = [] for obj in objs: x1 = np.max((0, obj['bbox'][0])) y1 = np.max((0, obj['bbox'][1])) x2 = np.min((width - 1, x1 + np.max((0, obj['bbox'][2] - 1)))) y2 = np.min((height - 1, y1 + np.max((0, obj['bbox'][3] - 1)))) if obj['area'] > 0 and x2 >= x1 and y2 >= y1: obj['clean_bbox'] = [x1, y1, x2, y2] valid_objs.append(obj) objs = valid_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) seg_areas = np.zeros((num_objs), dtype=np.float32) # Lookup table to map from COCO category ids to our internal class # indices coco_cat_id_to_class_ind = dict([(self._class_to_coco_cat_id[cls], self._class_to_ind[cls]) for cls in self._classes[1:]]) for ix, obj in enumerate(objs): cls = coco_cat_id_to_class_ind[obj['category_id']] boxes[ix, :] = obj['clean_bbox'] gt_classes[ix] = cls seg_areas[ix] = obj['area'] if obj['iscrowd']: # Set overlap to -1 for all classes for crowd objects # so they will be excluded during training overlaps[ix, :] = -1.0 else: overlaps[ix, cls] = 1.0 ds_utils.validate_boxes(boxes, width=width, height=height) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes' : boxes, 'gt_classes': gt_classes, 'gt_overlaps' : overlaps, 'flipped' : False, 'seg_areas' : seg_areas} def _get_box_file(self, index): # first 14 chars / first 22 chars / all chars + .mat # COCO_val2014_0/COCO_val2014_000000447/COCO_val2014_000000447991.mat file_name = ('COCO_' + self._data_name + '_' + str(index).zfill(12) + '.mat') return osp.join(file_name[:14], file_name[:22], file_name) def _print_detection_eval_metrics(self, coco_eval): IoU_lo_thresh = 0.5 IoU_hi_thresh = 0.95 def _get_thr_ind(coco_eval, thr): ind = np.where((coco_eval.params.iouThrs > thr - 1e-5) & (coco_eval.params.iouThrs < thr + 1e-5))[0][0] iou_thr = coco_eval.params.iouThrs[ind] assert np.isclose(iou_thr, thr) return ind ind_lo = _get_thr_ind(coco_eval, IoU_lo_thresh) ind_hi = _get_thr_ind(coco_eval, IoU_hi_thresh) # precision has dims (iou, recall, cls, area range, max dets) # area range index 0: all area ranges # max dets index 2: 100 per image precision = \ coco_eval.eval['precision'][ind_lo:(ind_hi + 1), :, :, 0, 2] ap_default = np.mean(precision[precision > -1]) print ('~~~~ Mean and per-category AP @ IoU=[{:.2f},{:.2f}] ' '~~~~').format(IoU_lo_thresh, IoU_hi_thresh) print '{:.1f}'.format(100 * ap_default) for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue # minus 1 because of __background__ precision = coco_eval.eval['precision'][ind_lo:(ind_hi + 1), :, cls_ind - 1, 0, 2] ap = np.mean(precision[precision > -1]) print '{:.1f}'.format(100 * ap) print '~~~~ Summary metrics ~~~~' coco_eval.summarize() def _do_detection_eval(self, res_file, output_dir): ann_type = 'bbox' coco_dt = self._COCO.loadRes(res_file) coco_eval = COCOeval(self._COCO, coco_dt) coco_eval.params.useSegm = (ann_type == 'segm') coco_eval.evaluate() coco_eval.accumulate() self._print_detection_eval_metrics(coco_eval) eval_file = osp.join(output_dir, 'detection_results.pkl') with open(eval_file, 'wb') as fid: cPickle.dump(coco_eval, fid, cPickle.HIGHEST_PROTOCOL) print 'Wrote COCO eval results to: {}'.format(eval_file) def _coco_results_one_category(self, boxes, cat_id): results = [] for im_ind, index in enumerate(self.image_index): dets = boxes[im_ind].astype(np.float) if dets == []: continue scores = dets[:, -1] xs = dets[:, 0] ys = dets[:, 1] ws = dets[:, 2] - xs + 1 hs = dets[:, 3] - ys + 1 results.extend( [{'image_id' : index, 'category_id' : cat_id, 'bbox' : [xs[k], ys[k], ws[k], hs[k]], 'score' : scores[k]} for k in xrange(dets.shape[0])]) return results def _write_coco_results_file(self, all_boxes, res_file): # [{"image_id": 42, # "category_id": 18, # "bbox": [258.15,41.29,348.26,243.78], # "score": 0.236}, ...] results = [] for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print 'Collecting {} results ({:d}/{:d})'.format(cls, cls_ind, self.num_classes - 1) coco_cat_id = self._class_to_coco_cat_id[cls] results.extend(self._coco_results_one_category(all_boxes[cls_ind], coco_cat_id)) print 'Writing results json to {}'.format(res_file) with open(res_file, 'w') as fid: json.dump(results, fid) def evaluate_detections(self, all_boxes, output_dir): res_file = osp.join(output_dir, ('detections_' + self._image_set + self._year + '_results')) if self.config['use_salt']: res_file += '_{}'.format(str(uuid.uuid4())) res_file += '.json' self._write_coco_results_file(all_boxes, res_file) # Only do evaluation on non-test sets if self._image_set.find('test') == -1: self._do_detection_eval(res_file, output_dir) # Optionally cleanup results json file if self.config['cleanup']: os.remove(res_file) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True
17,316
40.727711
94
py
bottom-up-attention
bottom-up-attention-master/lib/datasets/tools/mcg_munge.py
import os import sys """Hacky tool to convert file system layout of MCG boxes downloaded from http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/mcg/ so that it's consistent with those computed by Jan Hosang (see: http://www.mpi-inf.mpg.de/departments/computer-vision-and-multimodal- computing/research/object-recognition-and-scene-understanding/how- good-are-detection-proposals-really/) NB: Boxes from the MCG website are in (y1, x1, y2, x2) order. Boxes from Hosang et al. are in (x1, y1, x2, y2) order. """ def munge(src_dir): # stored as: ./MCG-COCO-val2014-boxes/COCO_val2014_000000193401.mat # want: ./MCG/mat/COCO_val2014_0/COCO_val2014_000000141/COCO_val2014_000000141334.mat files = os.listdir(src_dir) for fn in files: base, ext = os.path.splitext(fn) # first 14 chars / first 22 chars / all chars + .mat # COCO_val2014_0/COCO_val2014_000000447/COCO_val2014_000000447991.mat first = base[:14] second = base[:22] dst_dir = os.path.join('MCG', 'mat', first, second) if not os.path.exists(dst_dir): os.makedirs(dst_dir) src = os.path.join(src_dir, fn) dst = os.path.join(dst_dir, fn) print 'MV: {} -> {}'.format(src, dst) os.rename(src, dst) if __name__ == '__main__': # src_dir should look something like: # src_dir = 'MCG-COCO-val2014-boxes' src_dir = sys.argv[1] munge(src_dir)
1,451
36.230769
94
py
bottom-up-attention
bottom-up-attention-master/lib/rpn/proposal_layer.py
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- import caffe import numpy as np import yaml from fast_rcnn.config import cfg from generate_anchors import generate_anchors from fast_rcnn.bbox_transform import bbox_transform_inv, clip_boxes from fast_rcnn.nms_wrapper import nms DEBUG = False DEBUG_SHAPE = False class ProposalLayer(caffe.Layer): """ Outputs object detection proposals by applying estimated bounding-box transformations to a set of regular boxes (called "anchors"). """ def setup(self, bottom, top): # parse the layer parameter string, which must be valid YAML layer_params = yaml.load(self.param_str) self._feat_stride = layer_params['feat_stride'] anchor_scales = layer_params.get('scales', (8, 16, 32)) self._anchors = generate_anchors(scales=np.array(anchor_scales)) self._num_anchors = self._anchors.shape[0] if DEBUG: print 'feat_stride: {}'.format(self._feat_stride) print 'anchors:' print self._anchors # rois blob: holds R regions of interest, each is a 5-tuple # (n, x1, y1, x2, y2) specifying an image batch index n and a # rectangle (x1, y1, x2, y2) top[0].reshape(1, 5) # scores blob: holds scores for R regions of interest if len(top) > 1: top[1].reshape(1, 1, 1, 1) def forward(self, bottom, top): # Algorithm: # # for each (H, W) location i # generate A anchor boxes centered on cell i # apply predicted bbox deltas at cell i to each of the A anchors # clip predicted boxes to image # remove predicted boxes with either height or width < threshold # sort all (proposal, score) pairs by score from highest to lowest # take top pre_nms_topN proposals before NMS # apply NMS with threshold 0.7 to remaining proposals # take after_nms_topN proposals after NMS # return the top proposals (-> RoIs top, scores top) assert bottom[0].data.shape[0] == 1, \ 'Only single item batches are supported' cfg_key = str('TRAIN' if self.phase == 0 else 'TEST') # either 'TRAIN' or 'TEST' pre_nms_topN = cfg[cfg_key].RPN_PRE_NMS_TOP_N post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N nms_thresh = cfg[cfg_key].RPN_NMS_THRESH min_size = cfg[cfg_key].RPN_MIN_SIZE # the first set of _num_anchors channels are bg probs # the second set are the fg probs, which we want scores = bottom[0].data[:, self._num_anchors:, :, :] bbox_deltas = bottom[1].data im_info = bottom[2].data[0, :] if DEBUG: print 'im_size: ({}, {})'.format(im_info[0], im_info[1]) print 'scale: {}'.format(im_info[2]) # 1. Generate proposals from bbox deltas and shifted anchors height, width = scores.shape[-2:] if DEBUG: print 'score map size: {}'.format(scores.shape) # Enumerate all shifts shift_x = np.arange(0, width) * self._feat_stride shift_y = np.arange(0, height) * self._feat_stride shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() # Enumerate all shifted anchors: # # add A anchors (1, A, 4) to # cell K shifts (K, 1, 4) to get # shift anchors (K, A, 4) # reshape to (K*A, 4) shifted anchors A = self._num_anchors K = shifts.shape[0] anchors = self._anchors.reshape((1, A, 4)) + \ shifts.reshape((1, K, 4)).transpose((1, 0, 2)) anchors = anchors.reshape((K * A, 4)) # Transpose and reshape predicted bbox transformations to get them # into the same order as the anchors: # # bbox deltas will be (1, 4 * A, H, W) format # transpose to (1, H, W, 4 * A) # reshape to (1 * H * W * A, 4) where rows are ordered by (h, w, a) # in slowest to fastest order bbox_deltas = bbox_deltas.transpose((0, 2, 3, 1)).reshape((-1, 4)) if cfg_key == 'TRAIN' and cfg.TRAIN.RPN_NORMALIZE_TARGETS: bbox_deltas *= cfg.TRAIN.RPN_NORMALIZE_STDS bbox_deltas += cfg.TRAIN.RPN_NORMALIZE_MEANS # Same story for the scores: # # scores are (1, A, H, W) format # transpose to (1, H, W, A) # reshape to (1 * H * W * A, 1) where rows are ordered by (h, w, a) scores = scores.transpose((0, 2, 3, 1)).reshape((-1, 1)) # Convert anchors into proposals via bbox transformations proposals = bbox_transform_inv(anchors, bbox_deltas) # 2. clip predicted boxes to image proposals = clip_boxes(proposals, im_info[:2]) # 3. remove predicted boxes with either height or width < threshold # (NOTE: convert min_size to input image scale stored in im_info[2]) keep = _filter_boxes(proposals, min_size * im_info[2]) proposals = proposals[keep, :] scores = scores[keep] # 4. sort all (proposal, score) pairs by score from highest to lowest # 5. take top pre_nms_topN (e.g. 6000) order = scores.ravel().argsort()[::-1] if pre_nms_topN > 0: order = order[:pre_nms_topN] proposals = proposals[order, :] scores = scores[order] # 6. apply nms (e.g. threshold = 0.7) # 7. take after_nms_topN (e.g. 300) # 8. return the top proposals (-> RoIs top) keep = nms(np.hstack((proposals, scores)), nms_thresh) if post_nms_topN > 0: keep = keep[:post_nms_topN] proposals = proposals[keep, :] scores = scores[keep] # Output rois blob # Our RPN implementation only supports a single input image, so all # batch inds are 0 batch_inds = np.zeros((proposals.shape[0], 1), dtype=np.float32) blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False))) # print blob.shape top[0].reshape(*(blob.shape)) top[0].data[...] = blob if DEBUG_SHAPE: print 'ProposalLayer top[0] size: {}'.format(top[0].data.shape) # [Optional] output scores blob if len(top) > 1: top[1].reshape(*(scores.shape)) top[1].data[...] = scores if DEBUG_SHAPE: print 'ProposalLayer top[0] size: {}'.format(top[0].data.shape) def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" pass def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass def _filter_boxes(boxes, min_size): """Remove all boxes with any side smaller than min_size.""" ws = boxes[:, 2] - boxes[:, 0] + 1 hs = boxes[:, 3] - boxes[:, 1] + 1 keep = np.where((ws >= min_size) & (hs >= min_size))[0] return keep
7,265
38.064516
88
py
bottom-up-attention
bottom-up-attention-master/lib/rpn/generate_anchors.py
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- import numpy as np # Verify that we compute the same anchors as Shaoqing's matlab implementation: # # >> load output/rpn_cachedir/faster_rcnn_VOC2007_ZF_stage1_rpn/anchors.mat # >> anchors # # anchors = # # -83 -39 100 56 # -175 -87 192 104 # -359 -183 376 200 # -55 -55 72 72 # -119 -119 136 136 # -247 -247 264 264 # -35 -79 52 96 # -79 -167 96 184 # -167 -343 184 360 #array([[ -83., -39., 100., 56.], # [-175., -87., 192., 104.], # [-359., -183., 376., 200.], # [ -55., -55., 72., 72.], # [-119., -119., 136., 136.], # [-247., -247., 264., 264.], # [ -35., -79., 52., 96.], # [ -79., -167., 96., 184.], # [-167., -343., 184., 360.]]) def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=2**np.arange(3, 6)): """ Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. """ base_anchor = np.array([1, 1, base_size, base_size]) - 1 ratio_anchors = _ratio_enum(base_anchor, ratios) anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in xrange(ratio_anchors.shape[0])]) return anchors def _whctrs(anchor): """ Return width, height, x center, and y center for an anchor (window). """ w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr def _mkanchors(ws, hs, x_ctr, y_ctr): """ Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). """ ws = ws[:, np.newaxis] hs = hs[:, np.newaxis] anchors = np.hstack((x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1), x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1))) return anchors def _ratio_enum(anchor, ratios): """ Enumerate a set of anchors for each aspect ratio wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) size = w * h size_ratios = size / ratios ws = np.round(np.sqrt(size_ratios)) hs = np.round(ws * ratios) anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors def _scale_enum(anchor, scales): """ Enumerate a set of anchors for each scale wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) ws = w * scales hs = h * scales anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors if __name__ == '__main__': import time t = time.time() a = generate_anchors() print time.time() - t print a from IPython import embed; embed()
3,110
28.349057
78
py
bottom-up-attention
bottom-up-attention-master/lib/rpn/generate.py
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from fast_rcnn.config import cfg from fast_rcnn.train import filter_roidb from utils.blob import im_list_to_blob from utils.timer import Timer from generate_anchors import generate_anchors from utils.cython_bbox import bbox_overlaps from fast_rcnn.bbox_transform import bbox_transform import numpy as np import cv2 def _vis_proposals(im, dets, thresh=0.5): """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return class_name = 'obj' im = im[:, :, (2, 1, 0)] fig, ax = plt.subplots(figsize=(12, 12)) ax.imshow(im, aspect='equal') for i in inds: bbox = dets[i, :4] score = dets[i, -1] ax.add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=3.5) ) ax.text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') ax.set_title(('{} detections with ' 'p({} | box) >= {:.1f}').format(class_name, class_name, thresh), fontsize=14) plt.axis('off') plt.tight_layout() plt.draw() def _get_image_blob(im): """Converts an image into a network input. Arguments: im (ndarray): a color image in BGR order Returns: blob (ndarray): a data blob holding an image pyramid im_scale_factors (list): list of image scales (relative to im) used in the image pyramid """ im_orig = im.astype(np.float32, copy=True) im_orig -= cfg.PIXEL_MEANS im_shape = im_orig.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) processed_ims = [] assert len(cfg.TEST.SCALES) == 1 target_size = cfg.TEST.SCALES[0] im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE if np.round(im_scale * im_size_max) > cfg.TEST.MAX_SIZE: im_scale = float(cfg.TEST.MAX_SIZE) / float(im_size_max) im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) im_info = np.hstack((im.shape[:2], im_scale))[np.newaxis, :] processed_ims.append(im) # Create a blob to hold the input images blob = im_list_to_blob(processed_ims) return blob, im_info def im_proposals(net, im): """Generate RPN proposals on a single image.""" blobs = {} blobs['data'], blobs['im_info'] = _get_image_blob(im) net.blobs['data'].reshape(*(blobs['data'].shape)) net.blobs['im_info'].reshape(*(blobs['im_info'].shape)) blobs_out = net.forward( data=blobs['data'].astype(np.float32, copy=False), im_info=blobs['im_info'].astype(np.float32, copy=False)) scale = blobs['im_info'][0, 2] boxes = blobs_out['rois'][:, 1:].copy() / scale scores = blobs_out['scores'].copy() return boxes, scores def imdb_proposals(net, imdb): """Generate RPN proposals on all images in an imdb.""" _t = Timer() imdb_boxes = [[] for _ in xrange(imdb.num_images)] for i in xrange(imdb.num_images): im = cv2.imread(imdb.image_path_at(i)) _t.tic() imdb_boxes[i], scores = im_proposals(net, im) _t.toc() print 'im_proposals: {:d}/{:d} {:.3f}s' \ .format(i + 1, imdb.num_images, _t.average_time) if 0: dets = np.hstack((imdb_boxes[i], scores)) # from IPython import embed; embed() _vis_proposals(im, dets[:3, :], thresh=0.9) plt.show() return imdb_boxes def imdb_rpn_compute_stats(net, imdb, anchor_scales=(8,16,32), feature_stride=16): raw_anchors = generate_anchors(scales=np.array(anchor_scales)) print raw_anchors.shape sums = 0 squred_sums = 0 counts = 0 roidb = filter_roidb(imdb.roidb) # Compute a map of input image size and output feature map blob map_w = {} map_h = {} for i in xrange(50, cfg.TRAIN.MAX_SIZE + 10): blobs = { 'data': np.zeros((1, 3, i, i)), 'im_info': np.asarray([[i, i, 1.0]]) } net.blobs['data'].reshape(*(blobs['data'].shape)) net.blobs['im_info'].reshape(*(blobs['im_info'].shape)) blobs_out = net.forward( data=blobs['data'].astype(np.float32, copy=False), im_info=blobs['im_info'].astype(np.float32, copy=False)) height, width = net.blobs['rpn/output'].data.shape[-2:] map_w[i] = width map_h[i] = height for i in xrange(len(roidb)): if not i % 5000: print 'computing %d/%d' % (i, imdb.num_images) im = cv2.imread(roidb[i]['image']) im_data, im_info = _get_image_blob(im) gt_boxes = roidb[i]['boxes'] gt_boxes = gt_boxes * im_info[0, 2] height = map_h[im_data.shape[2]] width = map_w[im_data.shape[3]] # 1. Generate proposals from bbox deltas and shifted anchors shift_x = np.arange(0, width) * feature_stride shift_y = np.arange(0, height) * feature_stride shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() # add A anchors (1, A, 4) to # cell K shifts (K, 1, 4) to get # shift anchors (K, A, 4) # reshape to (K*A, 4) shifted anchors A = raw_anchors.shape[0] K = shifts.shape[0] all_anchors = (raw_anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2))) all_anchors = all_anchors.reshape((K * A, 4)) # only keep anchors inside the image inds_inside = np.where( (all_anchors[:, 0] >= 0) & (all_anchors[:, 1] >= 0) & (all_anchors[:, 2] < im_info[0, 1]) & # width (all_anchors[:, 3] < im_info[0, 0]) # height )[0] # keep only inside anchors anchors = all_anchors[inds_inside, :] overlaps = bbox_overlaps( np.ascontiguousarray(anchors, dtype=np.float), np.ascontiguousarray(gt_boxes, dtype=np.float)) # There are 2 types of bbox targets # 1. anchor whose overlaps with gt is greater than RPN_POSITIVE_OVERLAP argmax_overlaps = overlaps.argmax(axis=1) max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps] fg_inds = np.where(max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP)[0] # 2. anchors which best match certain gt gt_argmax_overlaps = overlaps.argmax(axis=0) gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])] gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0] fg_inds = np.unique(np.hstack((fg_inds, gt_argmax_overlaps))) gt_rois = gt_boxes[argmax_overlaps, :] anchors = anchors[fg_inds, :] gt_rois = gt_rois[fg_inds, :] targets = bbox_transform(anchors, gt_rois[:, :4]).astype(np.float32, copy=False) sums += targets.sum(axis=0) squred_sums += (targets ** 2).sum(axis=0) counts += targets.shape[0] means = sums / counts stds = np.sqrt(squred_sums / counts - means ** 2) print means print stds return means, stds
7,868
35.771028
88
py
bottom-up-attention
bottom-up-attention-master/lib/rpn/proposal_target_layer.py
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- import caffe import yaml import numpy as np import numpy.random as npr from fast_rcnn.config import cfg from fast_rcnn.bbox_transform import bbox_transform from utils.cython_bbox import bbox_overlaps DEBUG = False DEBUG_SHAPE = False class ProposalTargetLayer(caffe.Layer): """ Assign object detection proposals to ground-truth targets. Produces proposal classification labels and bounding-box regression targets. """ def setup(self, bottom, top): self._count = 0 self._fg_num = 0 self._bg_num = 0 layer_params = yaml.load(self.param_str) self._num_classes = layer_params['num_classes'] if 'num_attr_classes' in layer_params: self._num_attr_classes = layer_params['num_attr_classes'] else: self._num_attr_classes = 0 if 'num_rel_classes' in layer_params: self._num_rel_classes = layer_params['num_rel_classes'] else: self._num_rel_classes = 0 if 'ignore_label' in layer_params: self._ignore_label = layer_params['ignore_label'] else: self._ignore_label = -1 rois_per_image = 1 if cfg.TRAIN.BATCH_SIZE == -1 else cfg.TRAIN.BATCH_SIZE # sampled rois (0, x1, y1, x2, y2) top[0].reshape(rois_per_image, 5, 1, 1) # labels top[1].reshape(rois_per_image, 1, 1, 1) # bbox_targets top[2].reshape(rois_per_image, self._num_classes * 4, 1, 1) # bbox_inside_weights top[3].reshape(rois_per_image, self._num_classes * 4, 1, 1) # bbox_outside_weights top[4].reshape(rois_per_image, self._num_classes * 4, 1, 1) ix = 5 fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(int) if self._num_attr_classes > 0: # attribute labels top[ix].reshape(fg_rois_per_image, 16) ix += 1 if self._num_rel_classes > 0: # relation labels top[ix].reshape(fg_rois_per_image*fg_rois_per_image, 1, 1, 1) def forward(self, bottom, top): # Proposal ROIs (0, x1, y1, x2, y2) coming from RPN # (i.e., rpn.proposal_layer.ProposalLayer), or any other source all_rois = bottom[0].data # GT boxes (x1, y1, x2, y2, label, attributes[16], relations[num_objs]) # TODO(rbg): it's annoying that sometimes I have extra info before # and other times after box coordinates -- normalize to one format gt_boxes = bottom[1].data gt_boxes = gt_boxes.reshape(gt_boxes.shape[0], gt_boxes.shape[1]) # Include ground-truth boxes in the set of candidate rois zeros = np.zeros((gt_boxes.shape[0], 1), dtype=gt_boxes.dtype) all_rois = np.vstack( (all_rois, np.hstack((zeros, gt_boxes[:, :4]))) ) # Sanity check: single batch only assert np.all(all_rois[:, 0] == 0), \ 'Only single item batches are supported' rois_per_image = np.inf if cfg.TRAIN.BATCH_SIZE == -1 else cfg.TRAIN.BATCH_SIZE fg_rois_per_image = int(np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)) # Sample rois with classification labels and bounding box regression # targets # print 'proposal_target_layer:', fg_rois_per_image labels, rois, bbox_targets, bbox_inside_weights, attributes, relations = _sample_rois( all_rois, gt_boxes, fg_rois_per_image, rois_per_image, self._num_classes, self._num_attr_classes, self._num_rel_classes, self._ignore_label) if self._num_attr_classes > 0: assert attributes is not None if self._num_rel_classes > 0: assert relations is not None if DEBUG: print 'num fg: {}'.format((labels > 0).sum()) print 'num bg: {}'.format((labels == 0).sum()) self._count += 1 self._fg_num += (labels > 0).sum() self._bg_num += (labels == 0).sum() print 'num fg avg: {}'.format(self._fg_num / self._count) print 'num bg avg: {}'.format(self._bg_num / self._count) print 'ratio: {:.3f}'.format(float(self._fg_num) / float(self._bg_num)) # sampled rois # modified by ywxiong rois = rois.reshape((rois.shape[0], rois.shape[1], 1, 1)) top[0].reshape(*rois.shape) top[0].data[...] = rois # classification labels # modified by ywxiong labels = labels.reshape((labels.shape[0], 1, 1, 1)) top[1].reshape(*labels.shape) top[1].data[...] = labels # bbox_targets # modified by ywxiong bbox_targets = bbox_targets.reshape((bbox_targets.shape[0], bbox_targets.shape[1], 1, 1)) top[2].reshape(*bbox_targets.shape) top[2].data[...] = bbox_targets # bbox_inside_weights # modified by ywxiong bbox_inside_weights = bbox_inside_weights.reshape((bbox_inside_weights.shape[0], bbox_inside_weights.shape[1], 1, 1)) top[3].reshape(*bbox_inside_weights.shape) top[3].data[...] = bbox_inside_weights # bbox_outside_weights # modified by ywxiong bbox_inside_weights = bbox_inside_weights.reshape((bbox_inside_weights.shape[0], bbox_inside_weights.shape[1], 1, 1)) top[4].reshape(*bbox_inside_weights.shape) top[4].data[...] = np.array(bbox_inside_weights > 0).astype(np.float32) #attribute labels ix = 5 if self._num_attr_classes > 0: attributes[:,1:][attributes[:,1:]==0] = self._ignore_label top[ix].reshape(*attributes.shape) top[ix].data[...] = attributes ix += 1 # relation labels if self._num_rel_classes > 0: top[ix].reshape(*relations.shape) top[ix].data[...] = relations if DEBUG_SHAPE: for i in range(len(top)): print 'ProposalTargetLayer top[{}] size: {}'.format(i, top[i].data.shape) def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" pass def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass def _get_bbox_regression_labels(bbox_target_data, num_classes): """Bounding-box regression targets (bbox_target_data) are stored in a compact form N x (class, tx, ty, tw, th) This function expands those targets into the 4-of-4*K representation used by the network (i.e. only one class has non-zero targets). Returns: bbox_target (ndarray): N x 4K blob of regression targets bbox_inside_weights (ndarray): N x 4K blob of loss weights """ clss = bbox_target_data[:, 0] bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32) # print 'proposal_target_layer:', bbox_targets.shape bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32) inds = np.where(clss > 0)[0] if cfg.TRAIN.AGNOSTIC: for ind in inds: cls = clss[ind] start = 4 * (1 if cls > 0 else 0) end = start + 4 bbox_targets[ind, start:end] = bbox_target_data[ind, 1:] bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS else: for ind in inds: cls = clss[ind] start = int(4 * cls) end = int(start + 4) bbox_targets[ind, start:end] = bbox_target_data[ind, 1:] bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS return bbox_targets, bbox_inside_weights def _compute_targets(ex_rois, gt_rois, labels): """Compute bounding-box regression targets for an image.""" assert ex_rois.shape[0] == gt_rois.shape[0] assert ex_rois.shape[1] == 4 assert gt_rois.shape[1] == 4 targets = bbox_transform(ex_rois, gt_rois) if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED: # Optionally normalize targets by a precomputed mean and stdev targets = ((targets - np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS)) / np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS)) return np.hstack( (labels[:, np.newaxis], targets)).astype(np.float32, copy=False) def _sample_rois(all_rois, gt_boxes, fg_rois_per_image, rois_per_image, num_classes, num_attr_classes, num_rel_classes, ignore_label): """Generate a random sample of RoIs comprising foreground and background examples. """ # overlaps: (rois x gt_boxes) overlaps = bbox_overlaps( np.ascontiguousarray(all_rois[:, 1:5], dtype=np.float), np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float)) # GT boxes (x1, y1, x2, y2, label, attributes[16], relations[num_objs]) has_attributes = num_attr_classes > 0 if has_attributes: assert gt_boxes.shape[1] >= 21 has_relations = num_rel_classes > 0 if has_relations: assert gt_boxes.shape[0] == gt_boxes.shape[1]-21, \ 'relationships not found in gt_boxes, item length is only %d' % gt_boxes.shape[1] gt_assignment = overlaps.argmax(axis=1) max_overlaps = overlaps.max(axis=1) labels = gt_boxes[gt_assignment, 4] # Select foreground RoIs as those with >= FG_THRESH overlap fg_inds = np.where(max_overlaps >= cfg.TRAIN.FG_THRESH)[0] # Guard against the case when an image has fewer than fg_rois_per_image # foreground RoIs fg_rois_per_this_image = int(min(fg_rois_per_image, fg_inds.size)) # Sample foreground regions without replacement if fg_inds.size > 0: fg_inds = npr.choice(fg_inds, size=fg_rois_per_this_image, replace=False) # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((max_overlaps < cfg.TRAIN.BG_THRESH_HI) & (max_overlaps >= cfg.TRAIN.BG_THRESH_LO))[0] # Compute number of background RoIs to take from this image (guarding # against there being fewer than desired) bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image bg_rois_per_this_image = int(min(bg_rois_per_this_image, bg_inds.size)) # Sample background regions without replacement if bg_inds.size > 0: bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False) # The indices that we're selecting (both fg and bg) keep_inds = np.append(fg_inds, bg_inds) # print 'proposal_target_layer:', keep_inds # Select sampled values from various arrays: labels = labels[keep_inds] # Clamp labels for the background RoIs to 0 / ignore_label labels[fg_rois_per_this_image:] = 0 fg_gt = np.array(gt_assignment[fg_inds]) if has_attributes: attributes = np.ones((fg_rois_per_image,16))*ignore_label attributes[:fg_rois_per_this_image,:] = gt_boxes[fg_gt, 5:21] np.place(attributes[:,1:],attributes[:,1:] == 0, ignore_label) else: attributes = None if has_relations: expand_rels = gt_boxes[fg_gt, 21:].T[fg_gt].T num_relations_per_this_image = np.count_nonzero(expand_rels) # Keep an equal number of 'no relation' outputs, the rest can be ignore expand_rels = expand_rels.flatten() no_rel_inds = np.where(expand_rels==0)[0] if len(no_rel_inds) > num_relations_per_this_image: no_rel_inds = npr.choice(no_rel_inds, size=num_relations_per_this_image, replace=False) np.place(expand_rels,expand_rels==0,ignore_label) expand_rels[no_rel_inds] = 0 relations = np.ones((fg_rois_per_image,fg_rois_per_image),dtype=np.float)*ignore_label relations[:fg_rois_per_this_image,:fg_rois_per_this_image] = expand_rels.reshape((fg_rois_per_this_image,fg_rois_per_this_image)) relations = relations.reshape((relations.size, 1, 1, 1)) else: relations = None rois = all_rois[keep_inds] # print 'proposal_target_layer:', rois bbox_target_data = _compute_targets( rois[:, 1:5], gt_boxes[gt_assignment[keep_inds], :4], labels) # print 'proposal_target_layer:', bbox_target_data bbox_targets, bbox_inside_weights = \ _get_bbox_regression_labels(bbox_target_data, num_classes) return labels, rois, bbox_targets, bbox_inside_weights, attributes, relations
12,616
41.625
137
py
bottom-up-attention
bottom-up-attention-master/lib/rpn/anchor_target_layer.py
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- import os import caffe import yaml from fast_rcnn.config import cfg import numpy as np import numpy.random as npr from generate_anchors import generate_anchors from utils.cython_bbox import bbox_overlaps from fast_rcnn.bbox_transform import bbox_transform DEBUG = False class AnchorTargetLayer(caffe.Layer): """ Assign anchors to ground-truth targets. Produces anchor classification labels and bounding-box regression targets. """ def setup(self, bottom, top): layer_params = yaml.load(self.param_str) anchor_scales = layer_params.get('scales', (8, 16, 32)) self._anchors = generate_anchors(scales=np.array(anchor_scales)) self._num_anchors = self._anchors.shape[0] self._feat_stride = layer_params['feat_stride'] if DEBUG: print 'anchors:' print self._anchors print 'anchor shapes:' print np.hstack(( self._anchors[:, 2::4] - self._anchors[:, 0::4], self._anchors[:, 3::4] - self._anchors[:, 1::4], )) self._counts = cfg.EPS self._sums = np.zeros((1, 4)) self._squared_sums = np.zeros((1, 4)) self._fg_sum = 0 self._bg_sum = 0 self._count = 0 # allow boxes to sit over the edge by a small amount self._allowed_border = layer_params.get('allowed_border', 0) height, width = bottom[0].data.shape[-2:] if DEBUG: print 'AnchorTargetLayer: height', height, 'width', width A = self._num_anchors # labels top[0].reshape(1, 1, A * height, width) # bbox_targets top[1].reshape(1, A * 4, height, width) # bbox_inside_weights top[2].reshape(1, A * 4, height, width) # bbox_outside_weights top[3].reshape(1, A * 4, height, width) def forward(self, bottom, top): # Algorithm: # # for each (H, W) location i # generate 9 anchor boxes centered on cell i # apply predicted bbox deltas at cell i to each of the 9 anchors # filter out-of-image anchors # measure GT overlap assert bottom[0].data.shape[0] == 1, \ 'Only single item batches are supported' # map of shape (..., H, W) height, width = bottom[0].data.shape[-2:] # GT boxes (x1, y1, x2, y2, label, ...) gt_boxes = bottom[1].data[:,:5] # im_info im_info = bottom[2].data[0, :] if DEBUG: print '' print 'im_size: ({}, {})'.format(im_info[0], im_info[1]) print 'scale: {}'.format(im_info[2]) print 'height, width: ({}, {})'.format(height, width) print 'rpn: gt_boxes.shape', gt_boxes.shape print 'rpn: gt_boxes', gt_boxes # 1. Generate proposals from bbox deltas and shifted anchors shift_x = np.arange(0, width) * self._feat_stride shift_y = np.arange(0, height) * self._feat_stride shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() # add A anchors (1, A, 4) to # cell K shifts (K, 1, 4) to get # shift anchors (K, A, 4) # reshape to (K*A, 4) shifted anchors A = self._num_anchors K = shifts.shape[0] all_anchors = (self._anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2))) all_anchors = all_anchors.reshape((K * A, 4)) total_anchors = int(K * A) # only keep anchors inside the image inds_inside = np.where( (all_anchors[:, 0] >= -self._allowed_border) & (all_anchors[:, 1] >= -self._allowed_border) & (all_anchors[:, 2] < im_info[1] + self._allowed_border) & # width (all_anchors[:, 3] < im_info[0] + self._allowed_border) # height )[0] if DEBUG: print 'total_anchors', total_anchors print 'inds_inside', len(inds_inside) # keep only inside anchors anchors = all_anchors[inds_inside, :] if DEBUG: print 'anchors.shape', anchors.shape # label: 1 is positive, 0 is negative, -1 is dont care labels = np.empty((len(inds_inside), ), dtype=np.float32) labels.fill(-1) # overlaps between the anchors and the gt boxes # overlaps (ex, gt) gt_boxes = gt_boxes.reshape(gt_boxes.shape[0], gt_boxes.shape[1]) overlaps = bbox_overlaps( np.ascontiguousarray(anchors, dtype=np.float), np.ascontiguousarray(gt_boxes, dtype=np.float)) argmax_overlaps = overlaps.argmax(axis=1) max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps] gt_argmax_overlaps = overlaps.argmax(axis=0) gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])] gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0] if not cfg.TRAIN.RPN_CLOBBER_POSITIVES: # assign bg labels first so that positive labels can clobber them labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 # fg label: for each gt, anchor with highest overlap labels[gt_argmax_overlaps] = 1 # fg label: above threshold IOU labels[max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP] = 1 if cfg.TRAIN.RPN_CLOBBER_POSITIVES: # assign bg labels last so that negative labels can clobber positives labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 # subsample positive labels if we have too many num_fg = int(cfg.TRAIN.RPN_FG_FRACTION * cfg.TRAIN.RPN_BATCHSIZE) fg_inds = np.where(labels == 1)[0] if len(fg_inds) > num_fg: disable_inds = npr.choice( fg_inds, size=(len(fg_inds) - num_fg), replace=False) labels[disable_inds] = -1 # subsample negative labels if we have too many num_bg = cfg.TRAIN.RPN_BATCHSIZE - np.sum(labels == 1) bg_inds = np.where(labels == 0)[0] if len(bg_inds) > num_bg: disable_inds = npr.choice( bg_inds, size=(len(bg_inds) - num_bg), replace=False) labels[disable_inds] = -1 #print "was %s inds, disabling %s, now %s inds" % ( #len(bg_inds), len(disable_inds), np.sum(labels == 0)) bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32) bbox_targets = _compute_targets(anchors, gt_boxes[argmax_overlaps, :]) bbox_inside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) bbox_inside_weights[labels == 1, :] = np.array(cfg.TRAIN.RPN_BBOX_INSIDE_WEIGHTS) bbox_outside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) if cfg.TRAIN.RPN_POSITIVE_WEIGHT < 0: # uniform weighting of examples (given non-uniform sampling) num_examples = np.sum(labels >= 0) positive_weights = np.ones((1, 4)) * 1.0 / num_examples negative_weights = np.ones((1, 4)) * 1.0 / num_examples else: assert ((cfg.TRAIN.RPN_POSITIVE_WEIGHT > 0) & (cfg.TRAIN.RPN_POSITIVE_WEIGHT < 1)) positive_weights = (cfg.TRAIN.RPN_POSITIVE_WEIGHT / np.sum(labels == 1)) negative_weights = ((1.0 - cfg.TRAIN.RPN_POSITIVE_WEIGHT) / np.sum(labels == 0)) bbox_outside_weights[labels == 1, :] = positive_weights bbox_outside_weights[labels == 0, :] = negative_weights if DEBUG: self._sums += bbox_targets[labels == 1, :].sum(axis=0) self._squared_sums += (bbox_targets[labels == 1, :] ** 2).sum(axis=0) self._counts += np.sum(labels == 1) means = self._sums / self._counts stds = np.sqrt(self._squared_sums / self._counts - means ** 2) print 'means:' print means print 'stdevs:' print stds # map up to original set of anchors labels = _unmap(labels, total_anchors, inds_inside, fill=-1) bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0) bbox_inside_weights = _unmap(bbox_inside_weights, total_anchors, inds_inside, fill=0) bbox_outside_weights = _unmap(bbox_outside_weights, total_anchors, inds_inside, fill=0) if DEBUG: print 'rpn: max max_overlap', np.max(max_overlaps) print 'rpn: num_positive', np.sum(labels == 1) print 'rpn: num_negative', np.sum(labels == 0) self._fg_sum += np.sum(labels == 1) self._bg_sum += np.sum(labels == 0) self._count += 1 print 'rpn: num_positive avg', self._fg_sum / self._count print 'rpn: num_negative avg', self._bg_sum / self._count # labels labels = labels.reshape((1, height, width, A)).transpose(0, 3, 1, 2) labels = labels.reshape((1, 1, A * height, width)) top[0].reshape(*labels.shape) top[0].data[...] = labels # bbox_targets bbox_targets = bbox_targets \ .reshape((1, height, width, A * 4)).transpose(0, 3, 1, 2) top[1].reshape(*bbox_targets.shape) top[1].data[...] = bbox_targets # bbox_inside_weights bbox_inside_weights = bbox_inside_weights \ .reshape((1, height, width, A * 4)).transpose(0, 3, 1, 2) assert bbox_inside_weights.shape[2] == height assert bbox_inside_weights.shape[3] == width top[2].reshape(*bbox_inside_weights.shape) top[2].data[...] = bbox_inside_weights # bbox_outside_weights bbox_outside_weights = bbox_outside_weights \ .reshape((1, height, width, A * 4)).transpose(0, 3, 1, 2) assert bbox_outside_weights.shape[2] == height assert bbox_outside_weights.shape[3] == width top[3].reshape(*bbox_outside_weights.shape) top[3].data[...] = bbox_outside_weights def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" pass def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass def _unmap(data, count, inds, fill=0): """ Unmap a subset of item (data) back to the original set of items (of size count) """ if len(data.shape) == 1: ret = np.empty((count, ), dtype=np.float32) ret.fill(fill) ret[inds] = data else: ret = np.empty((count, ) + data.shape[1:], dtype=np.float32) ret.fill(fill) ret[inds, :] = data return ret def _compute_targets(ex_rois, gt_rois): """Compute bounding-box regression targets for an image.""" assert ex_rois.shape[0] == gt_rois.shape[0] assert ex_rois.shape[1] == 4 assert gt_rois.shape[1] == 5 targets = bbox_transform(ex_rois, gt_rois[:, :4]).astype(np.float32, copy=False) if cfg.TRAIN.RPN_NORMALIZE_TARGETS: assert cfg.TRAIN.RPN_NORMALIZE_MEANS is not None assert cfg.TRAIN.RPN_NORMALIZE_STDS is not None targets -= cfg.TRAIN.RPN_NORMALIZE_MEANS targets /= cfg.TRAIN.RPN_NORMALIZE_STDS return targets
11,700
39.487889
95
py
bottom-up-attention
bottom-up-attention-master/lib/rpn/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # --------------------------------------------------------
262
36.571429
58
py
bottom-up-attention
bottom-up-attention-master/lib/rpn/heatmap_layer.py
import caffe import yaml import numpy as np import numpy.random as npr from fast_rcnn.config import cfg from fast_rcnn.bbox_transform import bbox_transform from utils.cython_bbox import bbox_overlaps DEBUG = False class HeatmapLayer(caffe.Layer): """ Takes regions of interest (rois) and outputs heatmaps. """ def setup(self, bottom, top): layer_params = yaml.load(self.param_str) self._output_w = layer_params['output_w'] self._output_h = layer_params['output_h'] self._out_size = np.array([self._output_w, self._output_h, self._output_w, self._output_h],dtype=float) top[0].reshape(bottom[0].data.shape[0], 1, self._output_h, self._output_w) def forward(self, bottom, top): # im_info (height, width, scaling) assert bottom[1].data.shape[0] == 1, 'Batch size == 1 only' image_h = bottom[1].data[0][0] image_w = bottom[1].data[0][1] image_size = np.array([image_w, image_h, image_w, image_h],dtype=float) # Proposal ROIs (0, x1, y1, x2, y2) coming from RPN # (i.e., rpn.proposal_layer.ProposalLayer), or any other source rois = bottom[0].data rois = rois.reshape(rois.shape[0], rois.shape[1]) rois = rois[:,1:]*self._out_size/image_size # This will fill occupied pixels in an approximate (dilated) fashion rois_int = np.round(np.hstack(( np.floor(rois[:,[0]]), np.floor(rois[:,[1]]), np.minimum(self._output_w-1,np.ceil(rois[:,[2]])), np.minimum(self._output_h-1,np.ceil(rois[:,[3]])) ))).astype(int) top[0].reshape(bottom[0].data.shape[0], 1, self._output_h, self._output_w) top[0].data[...] = -1 for i in range(rois.shape[0]): top[0].data[i, 0, rois_int[i,1]:rois_int[i,3], rois_int[i,0]:rois_int[i,2]] = 1 def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" pass def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass
2,111
37.4
91
py
bottom-up-attention
bottom-up-attention-master/lib/pycocotools/cocoeval.py
__author__ = 'tsungyi' import numpy as np import datetime import time from collections import defaultdict import mask import copy class COCOeval: # Interface for evaluating detection on the Microsoft COCO dataset. # # The usage for CocoEval is as follows: # cocoGt=..., cocoDt=... # load dataset and results # E = CocoEval(cocoGt,cocoDt); # initialize CocoEval object # E.params.recThrs = ...; # set parameters as desired # E.evaluate(); # run per image evaluation # E.accumulate(); # accumulate per image results # E.summarize(); # display summary metrics of results # For example usage see evalDemo.m and http://mscoco.org/. # # The evaluation parameters are as follows (defaults in brackets): # imgIds - [all] N img ids to use for evaluation # catIds - [all] K cat ids to use for evaluation # iouThrs - [.5:.05:.95] T=10 IoU thresholds for evaluation # recThrs - [0:.01:1] R=101 recall thresholds for evaluation # areaRng - [...] A=4 object area ranges for evaluation # maxDets - [1 10 100] M=3 thresholds on max detections per image # useSegm - [1] if true evaluate against ground-truth segments # useCats - [1] if true use category labels for evaluation # Note: if useSegm=0 the evaluation is run on bounding boxes. # Note: if useCats=0 category labels are ignored as in proposal scoring. # Note: multiple areaRngs [Ax2] and maxDets [Mx1] can be specified. # # evaluate(): evaluates detections on every image and every category and # concats the results into the "evalImgs" with fields: # dtIds - [1xD] id for each of the D detections (dt) # gtIds - [1xG] id for each of the G ground truths (gt) # dtMatches - [TxD] matching gt id at each IoU or 0 # gtMatches - [TxG] matching dt id at each IoU or 0 # dtScores - [1xD] confidence of each dt # gtIgnore - [1xG] ignore flag for each gt # dtIgnore - [TxD] ignore flag for each dt at each IoU # # accumulate(): accumulates the per-image, per-category evaluation # results in "evalImgs" into the dictionary "eval" with fields: # params - parameters used for evaluation # date - date evaluation was performed # counts - [T,R,K,A,M] parameter dimensions (see above) # precision - [TxRxKxAxM] precision for every evaluation setting # recall - [TxKxAxM] max recall for every evaluation setting # Note: precision and recall==-1 for settings with no gt objects. # # See also coco, mask, pycocoDemo, pycocoEvalDemo # # Microsoft COCO Toolbox. version 2.0 # Data, paper, and tutorials available at: http://mscoco.org/ # Code written by Piotr Dollar and Tsung-Yi Lin, 2015. # Licensed under the Simplified BSD License [see coco/license.txt] def __init__(self, cocoGt=None, cocoDt=None): ''' Initialize CocoEval using coco APIs for gt and dt :param cocoGt: coco object with ground truth annotations :param cocoDt: coco object with detection results :return: None ''' self.cocoGt = cocoGt # ground truth COCO API self.cocoDt = cocoDt # detections COCO API self.params = {} # evaluation parameters self.evalImgs = defaultdict(list) # per-image per-category evaluation results [KxAxI] elements self.eval = {} # accumulated evaluation results self._gts = defaultdict(list) # gt for evaluation self._dts = defaultdict(list) # dt for evaluation self.params = Params() # parameters self._paramsEval = {} # parameters for evaluation self.stats = [] # result summarization self.ious = {} # ious between all gts and dts if not cocoGt is None: self.params.imgIds = sorted(cocoGt.getImgIds()) self.params.catIds = sorted(cocoGt.getCatIds()) def _prepare(self): ''' Prepare ._gts and ._dts for evaluation based on params :return: None ''' # def _toMask(objs, coco): # modify segmentation by reference for obj in objs: t = coco.imgs[obj['image_id']] if type(obj['segmentation']) == list: if type(obj['segmentation'][0]) == dict: print 'debug' obj['segmentation'] = mask.frPyObjects(obj['segmentation'],t['height'],t['width']) if len(obj['segmentation']) == 1: obj['segmentation'] = obj['segmentation'][0] else: # an object can have multiple polygon regions # merge them into one RLE mask obj['segmentation'] = mask.merge(obj['segmentation']) elif type(obj['segmentation']) == dict and type(obj['segmentation']['counts']) == list: obj['segmentation'] = mask.frPyObjects([obj['segmentation']],t['height'],t['width'])[0] elif type(obj['segmentation']) == dict and \ type(obj['segmentation']['counts'] == unicode or type(obj['segmentation']['counts']) == str): pass else: raise Exception('segmentation format not supported.') p = self.params if p.useCats: gts=self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)) dts=self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)) else: gts=self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds)) dts=self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds)) if p.useSegm: _toMask(gts, self.cocoGt) _toMask(dts, self.cocoDt) self._gts = defaultdict(list) # gt for evaluation self._dts = defaultdict(list) # dt for evaluation for gt in gts: self._gts[gt['image_id'], gt['category_id']].append(gt) for dt in dts: self._dts[dt['image_id'], dt['category_id']].append(dt) self.evalImgs = defaultdict(list) # per-image per-category evaluation results self.eval = {} # accumulated evaluation results def evaluate(self): ''' Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None ''' tic = time.time() print 'Running per image evaluation... ' p = self.params p.imgIds = list(np.unique(p.imgIds)) if p.useCats: p.catIds = list(np.unique(p.catIds)) p.maxDets = sorted(p.maxDets) self.params=p self._prepare() # loop through images, area range, max detection number catIds = p.catIds if p.useCats else [-1] computeIoU = self.computeIoU self.ious = {(imgId, catId): computeIoU(imgId, catId) \ for imgId in p.imgIds for catId in catIds} evaluateImg = self.evaluateImg maxDet = p.maxDets[-1] self.evalImgs = [evaluateImg(imgId, catId, areaRng, maxDet) for catId in catIds for areaRng in p.areaRng for imgId in p.imgIds ] self._paramsEval = copy.deepcopy(self.params) toc = time.time() print 'DONE (t=%0.2fs).'%(toc-tic) def computeIoU(self, imgId, catId): p = self.params if p.useCats: gt = self._gts[imgId,catId] dt = self._dts[imgId,catId] else: gt = [_ for cId in p.catIds for _ in self._gts[imgId,cId]] dt = [_ for cId in p.catIds for _ in self._dts[imgId,cId]] if len(gt) == 0 and len(dt) ==0: return [] dt = sorted(dt, key=lambda x: -x['score']) if len(dt) > p.maxDets[-1]: dt=dt[0:p.maxDets[-1]] if p.useSegm: g = [g['segmentation'] for g in gt] d = [d['segmentation'] for d in dt] else: g = [g['bbox'] for g in gt] d = [d['bbox'] for d in dt] # compute iou between each dt and gt region iscrowd = [int(o['iscrowd']) for o in gt] ious = mask.iou(d,g,iscrowd) return ious def evaluateImg(self, imgId, catId, aRng, maxDet): ''' perform evaluation for single category and image :return: dict (single image results) ''' # p = self.params if p.useCats: gt = self._gts[imgId,catId] dt = self._dts[imgId,catId] else: gt = [_ for cId in p.catIds for _ in self._gts[imgId,cId]] dt = [_ for cId in p.catIds for _ in self._dts[imgId,cId]] if len(gt) == 0 and len(dt) ==0: return None for g in gt: if 'ignore' not in g: g['ignore'] = 0 if g['iscrowd'] == 1 or g['ignore'] or (g['area']<aRng[0] or g['area']>aRng[1]): g['_ignore'] = 1 else: g['_ignore'] = 0 # sort dt highest score first, sort gt ignore last # gt = sorted(gt, key=lambda x: x['_ignore']) gtind = [ind for (ind, g) in sorted(enumerate(gt), key=lambda (ind, g): g['_ignore']) ] gt = [gt[ind] for ind in gtind] dt = sorted(dt, key=lambda x: -x['score'])[0:maxDet] iscrowd = [int(o['iscrowd']) for o in gt] # load computed ious N_iou = len(self.ious[imgId, catId]) ious = self.ious[imgId, catId][0:maxDet, np.array(gtind)] if N_iou >0 else self.ious[imgId, catId] T = len(p.iouThrs) G = len(gt) D = len(dt) gtm = np.zeros((T,G)) dtm = np.zeros((T,D)) gtIg = np.array([g['_ignore'] for g in gt]) dtIg = np.zeros((T,D)) if not len(ious)==0: for tind, t in enumerate(p.iouThrs): for dind, d in enumerate(dt): # information about best match so far (m=-1 -> unmatched) iou = min([t,1-1e-10]) m = -1 for gind, g in enumerate(gt): # if this gt already matched, and not a crowd, continue if gtm[tind,gind]>0 and not iscrowd[gind]: continue # if dt matched to reg gt, and on ignore gt, stop if m>-1 and gtIg[m]==0 and gtIg[gind]==1: break # continue to next gt unless better match made if ious[dind,gind] < iou: continue # match successful and best so far, store appropriately iou=ious[dind,gind] m=gind # if match made store id of match for both dt and gt if m ==-1: continue dtIg[tind,dind] = gtIg[m] dtm[tind,dind] = gt[m]['id'] gtm[tind,m] = d['id'] # set unmatched detections outside of area range to ignore a = np.array([d['area']<aRng[0] or d['area']>aRng[1] for d in dt]).reshape((1, len(dt))) dtIg = np.logical_or(dtIg, np.logical_and(dtm==0, np.repeat(a,T,0))) # store results for given image and category return { 'image_id': imgId, 'category_id': catId, 'aRng': aRng, 'maxDet': maxDet, 'dtIds': [d['id'] for d in dt], 'gtIds': [g['id'] for g in gt], 'dtMatches': dtm, 'gtMatches': gtm, 'dtScores': [d['score'] for d in dt], 'gtIgnore': gtIg, 'dtIgnore': dtIg, } def accumulate(self, p = None): ''' Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None ''' print 'Accumulating evaluation results... ' tic = time.time() if not self.evalImgs: print 'Please run evaluate() first' # allows input customized parameters if p is None: p = self.params p.catIds = p.catIds if p.useCats == 1 else [-1] T = len(p.iouThrs) R = len(p.recThrs) K = len(p.catIds) if p.useCats else 1 A = len(p.areaRng) M = len(p.maxDets) precision = -np.ones((T,R,K,A,M)) # -1 for the precision of absent categories recall = -np.ones((T,K,A,M)) # create dictionary for future indexing _pe = self._paramsEval catIds = _pe.catIds if _pe.useCats else [-1] setK = set(catIds) setA = set(map(tuple, _pe.areaRng)) setM = set(_pe.maxDets) setI = set(_pe.imgIds) # get inds to evaluate k_list = [n for n, k in enumerate(p.catIds) if k in setK] m_list = [m for n, m in enumerate(p.maxDets) if m in setM] a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA] i_list = [n for n, i in enumerate(p.imgIds) if i in setI] # K0 = len(_pe.catIds) I0 = len(_pe.imgIds) A0 = len(_pe.areaRng) # retrieve E at each category, area range, and max number of detections for k, k0 in enumerate(k_list): Nk = k0*A0*I0 for a, a0 in enumerate(a_list): Na = a0*I0 for m, maxDet in enumerate(m_list): E = [self.evalImgs[Nk+Na+i] for i in i_list] E = filter(None, E) if len(E) == 0: continue dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E]) # different sorting method generates slightly different results. # mergesort is used to be consistent as Matlab implementation. inds = np.argsort(-dtScores, kind='mergesort') dtm = np.concatenate([e['dtMatches'][:,0:maxDet] for e in E], axis=1)[:,inds] dtIg = np.concatenate([e['dtIgnore'][:,0:maxDet] for e in E], axis=1)[:,inds] gtIg = np.concatenate([e['gtIgnore'] for e in E]) npig = len([ig for ig in gtIg if ig == 0]) if npig == 0: continue tps = np.logical_and( dtm, np.logical_not(dtIg) ) fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg) ) tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float) fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float) for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)): tp = np.array(tp) fp = np.array(fp) nd = len(tp) rc = tp / npig pr = tp / (fp+tp+np.spacing(1)) q = np.zeros((R,)) if nd: recall[t,k,a,m] = rc[-1] else: recall[t,k,a,m] = 0 # numpy is slow without cython optimization for accessing elements # use python array gets significant speed improvement pr = pr.tolist(); q = q.tolist() for i in range(nd-1, 0, -1): if pr[i] > pr[i-1]: pr[i-1] = pr[i] inds = np.searchsorted(rc, p.recThrs) try: for ri, pi in enumerate(inds): q[ri] = pr[pi] except: pass precision[t,:,k,a,m] = np.array(q) self.eval = { 'params': p, 'counts': [T, R, K, A, M], 'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'precision': precision, 'recall': recall, } toc = time.time() print 'DONE (t=%0.2fs).'%( toc-tic ) def summarize(self): ''' Compute and display summary metrics for evaluation results. Note this functin can *only* be applied on the default parameter setting ''' def _summarize( ap=1, iouThr=None, areaRng='all', maxDets=100 ): p = self.params iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6} | maxDets={:>3} ] = {}' titleStr = 'Average Precision' if ap == 1 else 'Average Recall' typeStr = '(AP)' if ap==1 else '(AR)' iouStr = '%0.2f:%0.2f'%(p.iouThrs[0], p.iouThrs[-1]) if iouThr is None else '%0.2f'%(iouThr) areaStr = areaRng maxDetsStr = '%d'%(maxDets) aind = [i for i, aRng in enumerate(['all', 'small', 'medium', 'large']) if aRng == areaRng] mind = [i for i, mDet in enumerate([1, 10, 100]) if mDet == maxDets] if ap == 1: # dimension of precision: [TxRxKxAxM] s = self.eval['precision'] # IoU if iouThr is not None: t = np.where(iouThr == p.iouThrs)[0] s = s[t] # areaRng s = s[:,:,:,aind,mind] else: # dimension of recall: [TxKxAxM] s = self.eval['recall'] s = s[:,:,aind,mind] if len(s[s>-1])==0: mean_s = -1 else: mean_s = np.mean(s[s>-1]) print iStr.format(titleStr, typeStr, iouStr, areaStr, maxDetsStr, '%.3f'%(float(mean_s))) return mean_s if not self.eval: raise Exception('Please run accumulate() first') self.stats = np.zeros((12,)) self.stats[0] = _summarize(1) self.stats[1] = _summarize(1,iouThr=.5) self.stats[2] = _summarize(1,iouThr=.75) self.stats[3] = _summarize(1,areaRng='small') self.stats[4] = _summarize(1,areaRng='medium') self.stats[5] = _summarize(1,areaRng='large') self.stats[6] = _summarize(0,maxDets=1) self.stats[7] = _summarize(0,maxDets=10) self.stats[8] = _summarize(0,maxDets=100) self.stats[9] = _summarize(0,areaRng='small') self.stats[10] = _summarize(0,areaRng='medium') self.stats[11] = _summarize(0,areaRng='large') def __str__(self): self.summarize() class Params: ''' Params for coco evaluation api ''' def __init__(self): self.imgIds = [] self.catIds = [] # np.arange causes trouble. the data point on arange is slightly larger than the true value self.iouThrs = np.linspace(.5, 0.95, np.round((0.95-.5)/.05)+1, endpoint=True) self.recThrs = np.linspace(.0, 1.00, np.round((1.00-.0)/.01)+1, endpoint=True) self.maxDets = [1,10,100] self.areaRng = [ [0**2,1e5**2], [0**2, 32**2], [32**2, 96**2], [96**2, 1e5**2] ] self.useSegm = 0 self.useCats = 1
19,735
43.45045
131
py
bottom-up-attention
bottom-up-attention-master/lib/pycocotools/__init__.py
__author__ = 'tylin'
21
10
20
py
bottom-up-attention
bottom-up-attention-master/lib/pycocotools/coco.py
__author__ = 'tylin' __version__ = '1.0.1' # Interface for accessing the Microsoft COCO dataset. # Microsoft COCO is a large image dataset designed for object detection, # segmentation, and caption generation. pycocotools is a Python API that # assists in loading, parsing and visualizing the annotations in COCO. # Please visit http://mscoco.org/ for more information on COCO, including # for the data, paper, and tutorials. The exact format of the annotations # is also described on the COCO website. For example usage of the pycocotools # please see pycocotools_demo.ipynb. In addition to this API, please download both # the COCO images and annotations in order to run the demo. # An alternative to using the API is to load the annotations directly # into Python dictionary # Using the API provides additional utility functions. Note that this API # supports both *instance* and *caption* annotations. In the case of # captions not all functions are defined (e.g. categories are undefined). # The following API functions are defined: # COCO - COCO api class that loads COCO annotation file and prepare data structures. # decodeMask - Decode binary mask M encoded via run-length encoding. # encodeMask - Encode binary mask M using run-length encoding. # getAnnIds - Get ann ids that satisfy given filter conditions. # getCatIds - Get cat ids that satisfy given filter conditions. # getImgIds - Get img ids that satisfy given filter conditions. # loadAnns - Load anns with the specified ids. # loadCats - Load cats with the specified ids. # loadImgs - Load imgs with the specified ids. # segToMask - Convert polygon segmentation to binary mask. # showAnns - Display the specified annotations. # loadRes - Load algorithm results and create API for accessing them. # download - Download COCO images from mscoco.org server. # Throughout the API "ann"=annotation, "cat"=category, and "img"=image. # Help on each functions can be accessed by: "help COCO>function". # See also COCO>decodeMask, # COCO>encodeMask, COCO>getAnnIds, COCO>getCatIds, # COCO>getImgIds, COCO>loadAnns, COCO>loadCats, # COCO>loadImgs, COCO>segToMask, COCO>showAnns # Microsoft COCO Toolbox. version 2.0 # Data, paper, and tutorials available at: http://mscoco.org/ # Code written by Piotr Dollar and Tsung-Yi Lin, 2014. # Licensed under the Simplified BSD License [see bsd.txt] import json import datetime import time import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon import numpy as np from skimage.draw import polygon import urllib import copy import itertools import mask import os class COCO: def __init__(self, annotation_file=None): """ Constructor of Microsoft COCO helper class for reading and visualizing annotations. :param annotation_file (str): location of annotation file :param image_folder (str): location to the folder that hosts images. :return: """ # load dataset self.dataset = {} self.anns = [] self.imgToAnns = {} self.catToImgs = {} self.imgs = {} self.cats = {} if not annotation_file == None: print 'loading annotations into memory...' tic = time.time() dataset = json.load(open(annotation_file, 'r')) print 'Done (t=%0.2fs)'%(time.time()- tic) self.dataset = dataset self.createIndex() def createIndex(self): # create index print 'creating index...' anns = {} imgToAnns = {} catToImgs = {} cats = {} imgs = {} if 'annotations' in self.dataset: imgToAnns = {ann['image_id']: [] for ann in self.dataset['annotations']} anns = {ann['id']: [] for ann in self.dataset['annotations']} for ann in self.dataset['annotations']: imgToAnns[ann['image_id']] += [ann] anns[ann['id']] = ann if 'images' in self.dataset: imgs = {im['id']: {} for im in self.dataset['images']} for img in self.dataset['images']: imgs[img['id']] = img if 'categories' in self.dataset: cats = {cat['id']: [] for cat in self.dataset['categories']} for cat in self.dataset['categories']: cats[cat['id']] = cat catToImgs = {cat['id']: [] for cat in self.dataset['categories']} if 'annotations' in self.dataset: for ann in self.dataset['annotations']: catToImgs[ann['category_id']] += [ann['image_id']] print 'index created!' # create class members self.anns = anns self.imgToAnns = imgToAnns self.catToImgs = catToImgs self.imgs = imgs self.cats = cats def info(self): """ Print information about the annotation file. :return: """ for key, value in self.dataset['info'].items(): print '%s: %s'%(key, value) def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None): """ Get ann ids that satisfy given filter conditions. default skips that filter :param imgIds (int array) : get anns for given imgs catIds (int array) : get anns for given cats areaRng (float array) : get anns for given area range (e.g. [0 inf]) iscrowd (boolean) : get anns for given crowd label (False or True) :return: ids (int array) : integer array of ann ids """ imgIds = imgIds if type(imgIds) == list else [imgIds] catIds = catIds if type(catIds) == list else [catIds] if len(imgIds) == len(catIds) == len(areaRng) == 0: anns = self.dataset['annotations'] else: if not len(imgIds) == 0: # this can be changed by defaultdict lists = [self.imgToAnns[imgId] for imgId in imgIds if imgId in self.imgToAnns] anns = list(itertools.chain.from_iterable(lists)) else: anns = self.dataset['annotations'] anns = anns if len(catIds) == 0 else [ann for ann in anns if ann['category_id'] in catIds] anns = anns if len(areaRng) == 0 else [ann for ann in anns if ann['area'] > areaRng[0] and ann['area'] < areaRng[1]] if not iscrowd == None: ids = [ann['id'] for ann in anns if ann['iscrowd'] == iscrowd] else: ids = [ann['id'] for ann in anns] return ids def getCatIds(self, catNms=[], supNms=[], catIds=[]): """ filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given cat ids :return: ids (int array) : integer array of cat ids """ catNms = catNms if type(catNms) == list else [catNms] supNms = supNms if type(supNms) == list else [supNms] catIds = catIds if type(catIds) == list else [catIds] if len(catNms) == len(supNms) == len(catIds) == 0: cats = self.dataset['categories'] else: cats = self.dataset['categories'] cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name'] in catNms] cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms] cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id'] in catIds] ids = [cat['id'] for cat in cats] return ids def getImgIds(self, imgIds=[], catIds=[]): ''' Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids ''' imgIds = imgIds if type(imgIds) == list else [imgIds] catIds = catIds if type(catIds) == list else [catIds] if len(imgIds) == len(catIds) == 0: ids = self.imgs.keys() else: ids = set(imgIds) for i, catId in enumerate(catIds): if i == 0 and len(ids) == 0: ids = set(self.catToImgs[catId]) else: ids &= set(self.catToImgs[catId]) return list(ids) def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects """ if type(ids) == list: return [self.anns[id] for id in ids] elif type(ids) == int: return [self.anns[ids]] def loadCats(self, ids=[]): """ Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects """ if type(ids) == list: return [self.cats[id] for id in ids] elif type(ids) == int: return [self.cats[ids]] def loadImgs(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects """ if type(ids) == list: return [self.imgs[id] for id in ids] elif type(ids) == int: return [self.imgs[ids]] def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0]: datasetType = 'instances' elif 'caption' in anns[0]: datasetType = 'captions' if datasetType == 'instances': ax = plt.gca() polygons = [] color = [] for ann in anns: c = np.random.random((1, 3)).tolist()[0] if type(ann['segmentation']) == list: # polygon for seg in ann['segmentation']: poly = np.array(seg).reshape((len(seg)/2, 2)) polygons.append(Polygon(poly, True,alpha=0.4)) color.append(c) else: # mask t = self.imgs[ann['image_id']] if type(ann['segmentation']['counts']) == list: rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width']) else: rle = [ann['segmentation']] m = mask.decode(rle) img = np.ones( (m.shape[0], m.shape[1], 3) ) if ann['iscrowd'] == 1: color_mask = np.array([2.0,166.0,101.0])/255 if ann['iscrowd'] == 0: color_mask = np.random.random((1, 3)).tolist()[0] for i in range(3): img[:,:,i] = color_mask[i] ax.imshow(np.dstack( (img, m*0.5) )) p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4) ax.add_collection(p) elif datasetType == 'captions': for ann in anns: print ann['caption'] def loadRes(self, resFile): """ Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object """ res = COCO() res.dataset['images'] = [img for img in self.dataset['images']] # res.dataset['info'] = copy.deepcopy(self.dataset['info']) # res.dataset['licenses'] = copy.deepcopy(self.dataset['licenses']) print 'Loading and preparing results... ' tic = time.time() anns = json.load(open(resFile)) assert type(anns) == list, 'results in not an array of objects' annsImgIds = [ann['image_id'] for ann in anns] assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \ 'Results do not correspond to current coco set' if 'caption' in anns[0]: imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns]) res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds] for id, ann in enumerate(anns): ann['id'] = id+1 elif 'bbox' in anns[0] and not anns[0]['bbox'] == []: res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) for id, ann in enumerate(anns): bb = ann['bbox'] x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]] if not 'segmentation' in ann: ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]] ann['area'] = bb[2]*bb[3] ann['id'] = id+1 ann['iscrowd'] = 0 elif 'segmentation' in anns[0]: res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) for id, ann in enumerate(anns): # now only support compressed RLE format as segmentation results ann['area'] = mask.area([ann['segmentation']])[0] if not 'bbox' in ann: ann['bbox'] = mask.toBbox([ann['segmentation']])[0] ann['id'] = id+1 ann['iscrowd'] = 0 print 'DONE (t=%0.2fs)'%(time.time()- tic) res.dataset['annotations'] = anns res.createIndex() return res def download( self, tarDir = None, imgIds = [] ): ''' Download COCO images from mscoco.org server. :param tarDir (str): COCO results directory name imgIds (list): images to be downloaded :return: ''' if tarDir is None: print 'Please specify target directory' return -1 if len(imgIds) == 0: imgs = self.imgs.values() else: imgs = self.loadImgs(imgIds) N = len(imgs) if not os.path.exists(tarDir): os.makedirs(tarDir) for i, img in enumerate(imgs): tic = time.time() fname = os.path.join(tarDir, img['file_name']) if not os.path.exists(fname): urllib.urlretrieve(img['coco_url'], fname) print 'downloaded %d/%d images (t=%.1fs)'%(i, N, time.time()- tic)
14,881
41.278409
128
py
bottom-up-attention
bottom-up-attention-master/lib/pycocotools/mask.py
__author__ = 'tsungyi' import pycocotools._mask as _mask # Interface for manipulating masks stored in RLE format. # # RLE is a simple yet efficient format for storing binary masks. RLE # first divides a vector (or vectorized image) into a series of piecewise # constant regions and then for each piece simply stores the length of # that piece. For example, given M=[0 0 1 1 1 0 1] the RLE counts would # be [2 3 1 1], or for M=[1 1 1 1 1 1 0] the counts would be [0 6 1] # (note that the odd counts are always the numbers of zeros). Instead of # storing the counts directly, additional compression is achieved with a # variable bitrate representation based on a common scheme called LEB128. # # Compression is greatest given large piecewise constant regions. # Specifically, the size of the RLE is proportional to the number of # *boundaries* in M (or for an image the number of boundaries in the y # direction). Assuming fairly simple shapes, the RLE representation is # O(sqrt(n)) where n is number of pixels in the object. Hence space usage # is substantially lower, especially for large simple objects (large n). # # Many common operations on masks can be computed directly using the RLE # (without need for decoding). This includes computations such as area, # union, intersection, etc. All of these operations are linear in the # size of the RLE, in other words they are O(sqrt(n)) where n is the area # of the object. Computing these operations on the original mask is O(n). # Thus, using the RLE can result in substantial computational savings. # # The following API functions are defined: # encode - Encode binary masks using RLE. # decode - Decode binary masks encoded via RLE. # merge - Compute union or intersection of encoded masks. # iou - Compute intersection over union between masks. # area - Compute area of encoded masks. # toBbox - Get bounding boxes surrounding encoded masks. # frPyObjects - Convert polygon, bbox, and uncompressed RLE to encoded RLE mask. # # Usage: # Rs = encode( masks ) # masks = decode( Rs ) # R = merge( Rs, intersect=false ) # o = iou( dt, gt, iscrowd ) # a = area( Rs ) # bbs = toBbox( Rs ) # Rs = frPyObjects( [pyObjects], h, w ) # # In the API the following formats are used: # Rs - [dict] Run-length encoding of binary masks # R - dict Run-length encoding of binary mask # masks - [hxwxn] Binary mask(s) (must have type np.ndarray(dtype=uint8) in column-major order) # iscrowd - [nx1] list of np.ndarray. 1 indicates corresponding gt image has crowd region to ignore # bbs - [nx4] Bounding box(es) stored as [x y w h] # poly - Polygon stored as [[x1 y1 x2 y2...],[x1 y1 ...],...] (2D list) # dt,gt - May be either bounding boxes or encoded masks # Both poly and bbs are 0-indexed (bbox=[0 0 1 1] encloses first pixel). # # Finally, a note about the intersection over union (iou) computation. # The standard iou of a ground truth (gt) and detected (dt) object is # iou(gt,dt) = area(intersect(gt,dt)) / area(union(gt,dt)) # For "crowd" regions, we use a modified criteria. If a gt object is # marked as "iscrowd", we allow a dt to match any subregion of the gt. # Choosing gt' in the crowd gt that best matches the dt can be done using # gt'=intersect(dt,gt). Since by definition union(gt',dt)=dt, computing # iou(gt,dt,iscrowd) = iou(gt',dt) = area(intersect(gt,dt)) / area(dt) # For crowd gt regions we use this modified criteria above for the iou. # # To compile run "python setup.py build_ext --inplace" # Please do not contact us for help with compiling. # # Microsoft COCO Toolbox. version 2.0 # Data, paper, and tutorials available at: http://mscoco.org/ # Code written by Piotr Dollar and Tsung-Yi Lin, 2015. # Licensed under the Simplified BSD License [see coco/license.txt] encode = _mask.encode decode = _mask.decode iou = _mask.iou merge = _mask.merge area = _mask.area toBbox = _mask.toBbox frPyObjects = _mask.frPyObjects
4,058
48.5
100
py
bottom-up-attention
bottom-up-attention-master/lib/utils/timer.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import time class Timer(object): """A simple timer.""" def __init__(self): self.total_time = 0. self.calls = 0 self.start_time = 0. self.diff = 0. self.average_time = 0. def tic(self): # using time.time instead of time.clock because time time.clock # does not normalize for multithreading self.start_time = time.time() def toc(self, average=True): self.diff = time.time() - self.start_time self.total_time += self.diff self.calls += 1 self.average_time = self.total_time / self.calls if average: return self.average_time else: return self.diff
948
27.757576
71
py
bottom-up-attention
bottom-up-attention-master/lib/utils/blob.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Blob helper functions.""" import numpy as np import cv2 def im_list_to_blob(ims): """Convert a list of images into a network input. Assumes images are already prepared (means subtracted, BGR order, ...). """ max_shape = np.array([im.shape for im in ims]).max(axis=0) num_images = len(ims) blob = np.zeros((num_images, max_shape[0], max_shape[1], 3), dtype=np.float32) for i in xrange(num_images): im = ims[i] blob[i, 0:im.shape[0], 0:im.shape[1], :] = im # Move channels (axis 3) to axis 1 # Axis order will become: (batch elem, channel, height, width) channel_swap = (0, 3, 1, 2) blob = blob.transpose(channel_swap) return blob def prep_im_for_blob(im, pixel_means, target_size, max_size): """Mean subtract and scale an image for use in a blob.""" im = im.astype(np.float32, copy=False) im -= pixel_means im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE if np.round(im_scale * im_size_max) > max_size: im_scale = float(max_size) / float(im_size_max) im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) return im, im_scale
1,625
34.347826
75
py
bottom-up-attention
bottom-up-attention-master/lib/utils/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # --------------------------------------------------------
248
34.571429
58
py
bottom-up-attention
bottom-up-attention-master/lib/transform/__init__.py
0
0
0
py
bottom-up-attention
bottom-up-attention-master/lib/transform/torch_image_transform_layer.py
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # -------------------------------------------------------- """ Transform images for compatibility with models trained with https://github.com/facebook/fb.resnet.torch. Usage in model prototxt: layer { name: 'data_xform' type: 'Python' bottom: 'data_caffe' top: 'data' python_param { module: 'transform.torch_image_transform_layer' layer: 'TorchImageTransformLayer' } } """ import caffe from fast_rcnn.config import cfg import numpy as np class TorchImageTransformLayer(caffe.Layer): def setup(self, bottom, top): # (1, 3, 1, 1) shaped arrays self.PIXEL_MEANS = \ np.array([[[[0.48462227599918]], [[0.45624044862054]], [[0.40588363755159]]]]) self.PIXEL_STDS = \ np.array([[[[0.22889466674951]], [[0.22446679341259]], [[0.22495548344775]]]]) # The default ("old") pixel means that were already subtracted channel_swap = (0, 3, 1, 2) self.OLD_PIXEL_MEANS = \ cfg.PIXEL_MEANS[np.newaxis, :, :, :].transpose(channel_swap) top[0].reshape(*(bottom[0].shape)) def forward(self, bottom, top): ims = bottom[0].data # Invert the channel means that were already subtracted ims += self.OLD_PIXEL_MEANS # 1. Permute BGR to RGB and normalize to [0, 1] ims = ims[:, [2, 1, 0], :, :] / 255.0 # 2. Remove channel means ims -= self.PIXEL_MEANS # 3. Standardize channels ims /= self.PIXEL_STDS top[0].reshape(*(ims.shape)) top[0].data[...] = ims def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" pass def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass
2,000
29.784615
72
py
bottom-up-attention
bottom-up-attention-master/lib/nms/py_cpu_nms.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import numpy as np def py_cpu_nms(dets, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return keep
1,051
25.974359
59
py
bottom-up-attention
bottom-up-attention-master/lib/nms/__init__.py
0
0
0
py
XDF-GAN
XDF-GAN-master/run-sgan-tessellate.py
""" Script to create very large tessellated GDF Copyright 2019 Mike Smith Please see COPYING for licence details """ import matplotlib as mpl mpl.use("Agg") # General imports import numpy as np import h5py import os from time import time import argparse import astropy.io.fits as pyfits import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import imageio from skimage.util import view_as_windows # ML specific imports from keras.models import load_model def un_min_max_norm(ar, ar_max, ar_min): """ Reverse min max normalising carried out on the original UDF data. """ return ar*(ar_max - ar_min) + ar_min def find_nearest(ar, val): """ Get position in array of value nearest to 'val'. """ return np.argmin(np.abs(ar - val)) def get_sigma(hwhm): """ Given the half width at half maximum, find the standard deviation of a normal distribution. """ return (2*np.abs(hwhm))/(np.sqrt(8*np.log(2))) def apply_noise_low_vals(ar): """ Apply noise to low values given an array. """ hist = np.histogram(ar, 100000) maxpoint = np.max(hist[0]) negsx = hist[1][:-1][hist[1][:-1] <= 0] negsy = hist[0][hist[1][:-1] <= 0] hwhm = negsx[find_nearest(negsy, maxpoint/2)] sigma = get_sigma(hwhm) mu = 0 ar_replaced_noise = noise_replacement_low_vals(ar, sigma, mu) return ar_replaced_noise.astype(np.float32) def rescale(ar): """ Rescale so peak is at zero. """ hist = np.histogram(ar, 10000) delta = hist[1][hist[0].argmax()] return ar - delta def shuffle_noise_given_array(ar): """ Shuffle noise values given an array. """ hist = np.histogram(ar, 100000) maxpoint = np.max(hist[0]) negsx = hist[1][:-1][hist[1][:-1] <= 0] negsy = hist[0][hist[1][:-1] <= 0] hwhm = negsx[find_nearest(negsy, maxpoint/2)] sigma = get_sigma(hwhm) mu = 0 low_vals = np.random.permutation(ar[ar <= 2*sigma]) ar[np.where(ar <= 2*sigma)] = low_vals return ar.astype(np.float32) if __name__ == "__main__": # Argument parsing parser = argparse.ArgumentParser("Prorduce a fake xdf file.") # Args parser.add_argument("-m", "--model", help="Model file (h5).") parser.add_argument("-l", "--logdir", nargs="?", default="../big_ims", help="Logdir, default ../big_ims") parser.add_argument("-z", "--z_size", nargs="?", default=1024, type=int, help="Input noise array size (*16 for output size), default 1024. Must be a power of 2.") parser.add_argument("-o", "--overlap", nargs="?", default=32, type=int, help="Overlap between tiles in z space.") parser.add_argument("-f", "--fits", default=False, action="store_true", help="Output in FITS format.") parser.add_argument("-p", "--png", default=False, action="store_true", help="Output greyscale PNG images + histogram.") parser.add_argument("-n", "--numpy", default=False, action="store_true", help="Output numpy array.") args = parser.parse_args() dt = int(time()) model_file = args.model logdir = "{}/{}/".format(args.logdir, dt) os.mkdir(logdir) z_size = args.z_size overlap = args.overlap chunks = z_size//64 maxes = [0.5262004, 0.44799575, 0.62030375] mins = [-0.004748813, -0.0031752307, -0.011242471] # Load generator gen = load_model(model_file) big_z = np.random.randn(z_size+overlap, z_size+overlap, 50).astype(np.float32) mini_zs = np.squeeze(view_as_windows(big_z, ((z_size//chunks)+overlap, (z_size//chunks)+overlap, 50), step=(z_size//chunks, z_size//chunks, 1))) print(mini_zs.shape) z = np.reshape(mini_zs, (np.product(mini_zs.shape[0:2]), *mini_zs.shape[2:])) print(z.shape) print("Predicting imagery...") print("Batch size 4") ims = gen.predict(z, batch_size=4, verbose=1) # Batched for very large imagery print(logdir, ims.shape) ims = ims[:, (overlap*16)//2:-(overlap*16)//2, (overlap*16)//2:-(overlap*16)//2, :] # remove overlap ims = np.reshape(ims, (*mini_zs.shape[0:2], 1024, 1024, 3)) im = np.concatenate(np.split(ims, len(ims), axis=0), axis=2) # Stitch image back together im = np.squeeze(np.concatenate(np.split(im, len(ims), axis=1), axis=3)) # ditto... # Output values if args.numpy: # Output n-channel image in npy format print("Outputting as npy") np.save("{}array.npy".format(logdir), np.squeeze(im)) if args.png: # Output PNG images for each channel + a histogram for each (n-channel) image print("Outputting as PNG") hist = np.histogram(im, 10000) plt.yscale("log") plt.plot(hist[1][:-1], hist[0]) plt.savefig("{}hist.png".format(logdir)) plt.close() for channel in np.arange(ims.shape[-1]): plt.figure(figsize=(32, 32)) plt.tight_layout() plt.imshow(np.squeeze(im[..., channel])) plt.savefig("{}{}.png".format(logdir, channel)) plt.close() if args.fits: # Output as a separate FITS image for each channel print("Outputting as FITS") #im = un_min_max_norm(im, ar_max=0.4142234, ar_min=-0.011242471) # Uncomment for image wise norming for channel in np.arange(ims.shape[-1]): print("Channel:", channel) print("Before unnorming:", im[..., channel].max(), im[..., channel].min()) im[..., channel] = un_min_max_norm(im[..., channel], ar_max=maxes[channel], ar_min=mins[channel]) # For channel wise norming im[..., channel] = rescale(im[..., channel]) print("After unnorming:", im[..., channel].max(), im[..., channel].min()) #pyfits.writeto("{}{}.fits".format(logdir, channel), np.squeeze(shuffle_noise_given_array(im[..., channel])), overwrite=True) pyfits.writeto("{}{}.fits".format(logdir, channel), np.squeeze(im[..., channel]), overwrite=True)
5,897
35.8625
166
py
XDF-GAN
XDF-GAN-master/run-sgan.py
""" Script to run GDF generation Copyright 2019 Mike Smith Please see COPYING for licence details """ import matplotlib as mpl mpl.use("Agg") # General imports import numpy as np import h5py import os from time import time import argparse import astropy.io.fits as pyfits import matplotlib.pyplot as plt from matplotlib.colors import LogNorm # ML specific imports from keras.models import load_model def un_min_max_norm(ar, ar_max, ar_min): """ Reverse min max normalising carried out on the original UDF data. """ return ar*(ar_max - ar_min) + ar_min def find_nearest(ar, val): """ Get position in array of value nearest to 'val'. """ return np.argmin(np.abs(ar - val)) def get_sigma(hwhm): """ Given the half width at half maximum, find the standard deviation of a normal distribution. """ return (2*np.abs(hwhm))/(np.sqrt(8*np.log(2))) def noise_replacement_low_vals(x, sigma, mu): """ Replace low values with a random normal distribution """ return np.random.normal(mu, sigma) if np.abs(x) <= 2*sigma else x def apply_noise_low_vals(ar): """ Apply noise to low values given an array. """ hist = np.histogram(ar, 100000) maxpoint = np.max(hist[0]) negsx = hist[1][:-1][hist[1][:-1] <= 0] negsy = hist[0][hist[1][:-1] <= 0] hwhm = negsx[find_nearest(negsy, maxpoint/2)] sigma = get_sigma(hwhm) mu = 0 ar_replaced_noise = noise_replacement_low_vals(ar, sigma, mu) return ar_replaced_noise.astype(np.float32) def noise_replacement_all_vals(x, sigma, mu): """ Add a noise sampled from a gaussian to all values """ return x + np.random.normal(mu, sigma) def apply_noise_all_vals(ar): """ Apply additive noise to all values given an array. """ hist = np.histogram(ar, 100000) maxpoint = np.max(hist[0]) negsx = hist[1][:-1][hist[1][:-1] <= 0] negsy = hist[0][hist[1][:-1] <= 0] hwhm = negsx[find_nearest(negsy, maxpoint/2)] sigma = get_sigma(hwhm) mu = 0 ar_replaced_noise = noise_replacement_all_vals(ar, sigma, mu) return ar_replaced_noise.astype(np.float32) def rescale(ar): """ Rescale so peak is at zero. """ hist = np.histogram(ar, 10000) delta = hist[1][hist[0].argmax()] return ar - delta def shuffle_noise_given_array(ar): """ Shuffle noise values given an array. """ hist = np.histogram(ar, 100000) maxpoint = np.max(hist[0]) negsx = hist[1][:-1][hist[1][:-1] <= 0] negsy = hist[0][hist[1][:-1] <= 0] hwhm = negsx[find_nearest(negsy, maxpoint/2)] sigma = get_sigma(hwhm) mu = 0 low_vals = np.random.permutation(ar[ar <= 1*sigma]) ar[np.where(ar <= 1*sigma)] = low_vals return ar.astype(np.float32) if __name__ == "__main__": # Argument parsing parser = argparse.ArgumentParser("Produce a fake xdf file.") # Args parser.add_argument("-m", "--model", help="Model file (h5).") parser.add_argument("-l", "--logdir", nargs="?", default="../logs/outs", help="Logdir, default ../logs/outs/$UNIXTIME") parser.add_argument("-z", "--z_size", nargs="?", default=64, type=int, help="Input noise array size (*16 for output size), default 64.") parser.add_argument("-n", "--images", nargs="?", default=10, type=int, help="Number of images to generate.") parser.add_argument("-f", "--fits", default=False, action="store_true", help="Output in FITS format.") parser.add_argument("-p", "--png", default=False, action="store_true", help="Output greyscale PNG images + histogram.") parser.add_argument("--numpy", default=False, action="store_true", help="Output numpy array.") parser.add_argument("-s", "--shuffle", default=False, action="store_true", help="Shuffle output to mitigate noise waffling in FITS output.") parser.add_argument("--seed", nargs="?", default=42, type=int, help="A seed for np.random.seed") args = parser.parse_args() np.random.seed(args.seed) dt = int(time()) model_file = args.model n_images = args.images logdir = "{}/{}/".format(args.logdir, dt) os.mkdir(logdir) z_size = args.z_size test_batch_size = 100 # These are the original image maxima and minima for each channel maxes = [0.5262004, 0.44799575, 0.62030375] mins = [-0.004748813, -0.0031752307, -0.011242471] noise_replacement_low_vals = np.vectorize(noise_replacement_low_vals) noise_replacement_all_vals = np.vectorize(noise_replacement_all_vals) # Load generator gen = load_model(model_file) z = np.random.randn(n_images, z_size, z_size, 50).astype(np.float32) ims = gen.predict(z, batch_size=1, verbose=1) # added dtype still needs testing print(logdir, ims.shape, ims.dtype) # Output values for i, im in enumerate(ims): if args.numpy: # Output n-channel image in npy format print("Outputting as npy") np.save("{}{}.npy".format(logdir, i), np.squeeze(im)) if args.png: # Output PNG images for each channel + a histogram for each (n-channel) image print("Outputting as PNG") hist = np.histogram(im, 10000) plt.yscale("log") plt.plot(hist[1][:-1], hist[0]) plt.savefig("{}{}-hist.png".format(logdir, i)) plt.close() for channel in np.arange(ims.shape[-1]): plt.figure(figsize=(16, 16)) plt.imshow(np.squeeze(im[..., channel]), norm=LogNorm()) plt.savefig("{}{}-{}.png".format(logdir, i, channel)) plt.close() if args.fits: # Output as a separate FITS image for each channel print("Outputting as FITS") #im = un_min_max_norm(im, ar_max=0.4142234, ar_min=-0.011242471) # Uncomment for image wide norming for channel in np.arange(ims.shape[-1]): print("Channel:", channel) print("Before unnorming:", im[..., channel].max(), im[..., channel].min()) im[..., channel] = un_min_max_norm(im[..., channel], ar_max=maxes[channel], ar_min=mins[channel]) # For channel wise norming im[..., channel] = rescale(im[..., channel]) print("After unnorming:", im[..., channel].max(), im[..., channel].min()) if args.shuffle: pyfits.writeto("{}{}-{}.fits".format(logdir, i, channel), np.squeeze(shuffle_noise_given_array(im[..., channel])), overwrite=True) else: pyfits.writeto("{}{}-{}.fits".format(logdir, i, channel), np.squeeze(im[..., channel]), overwrite=True)
6,620
35.379121
150
py
XDF-GAN
XDF-GAN-master/sgan.py
""" Script to train GDF-SGAN Copyright 2019 Mike Smith Please see COPYING for licence details """ import matplotlib as mpl mpl.use("Agg") # General imports import numpy as np import h5py import os from time import time import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import argparse # ML specific imports import tensorflow as tf import keras.backend as K from keras.models import Model from keras.layers import Input, Dense, Lambda, Conv2D, Conv2DTranspose, LeakyReLU, ELU, GlobalAveragePooling2D, Concatenate from keras.optimizers import Adam from keras.utils.generic_utils import Progbar from keras.preprocessing.image import ImageDataGenerator def get_images(file): """ Get XDF fits (np) file. """ im = np.load(file) print(im.shape) return im def random_crop(img, crop_size=128): """ Random crop big xdf image. """ height, width = img.shape[0], img.shape[1] x = np.random.randint(0, width - crop_size + 1) y = np.random.randint(0, height - crop_size + 1) return img[y:(y+crop_size), x:(x+crop_size), :] def gen(z_shape=(None, None, 50), num_layers=4): """ Model a spatial GAN generator with `num_layers` hidden layers. """ fs = [32*2**f for f in np.arange(num_layers)][::-1] # define filter sizes z = Input(shape=z_shape) # z ct = Conv2DTranspose(filters=fs[0], kernel_size=4, strides=2, padding="same")(z) ct = ELU()(ct) for f in fs[1:]: ct = Conv2DTranspose(filters=f, kernel_size=4, strides=2, padding="same")(ct) ct = ELU()(ct) ct = Conv2DTranspose(filters=f, kernel_size=4, strides=1, padding="same")(ct) ct = ELU()(ct) ct = Conv2DTranspose(filters=f, kernel_size=4, strides=1, padding="same")(ct) ct = ELU()(ct) G_z = Conv2DTranspose(filters=3, kernel_size=3, strides=1, padding="same", activation="sigmoid")(ct) model = Model(z, G_z, name="Generator") model.summary() return model def disc(x_shape=(None, None, 6), num_layers=4): """ Model a spatial GAN discriminator. """ fs = [32*2**f for f in np.arange(num_layers)] # define filter sizes x = Input(shape=x_shape) c = Conv2D(filters=fs[0], kernel_size=4, strides=2, padding="same")(x) c = LeakyReLU(0.1)(c) for f in fs[1:]: c = Conv2D(filters=f, kernel_size=4, strides=2, padding="same")(c) c = LeakyReLU(0.1)(c) gap = GlobalAveragePooling2D()(c) y = Dense(1)(gap) model = Model(x, y, name="Discriminator") model.summary() return model if __name__ == "__main__": # Argument parsing parser = argparse.ArgumentParser("Run a spatial GAN on XDF FITS data.") # Args parser.add_argument("-f", "--im_file", nargs="?", default="./data/mc_channelwise_clipping.npy", help="Numpy file containing image data.") parser.add_argument("-b", "--batch_size", type=int, default=32, help="Batch size, default 32.") parser.add_argument("-e", "--epochs", type=int, default=10001, help="Number of training epochs, default 301.") parser.add_argument("-l", "--logdir", nargs="?", default="./logs", help="Logdir, default ./logs") parser.add_argument("-r", "--learning_rate", nargs="?", type=float, default=0.0002, help="Learning rate for ADAM op") parser.add_argument("-d", "--debug", dest="debug", default=False, action="store_true", help="Print example images/histograms at every epoch") parser.add_argument("--gen_weights", nargs="?", help="File containing gen weights for continuation of training.") parser.add_argument("--disc_weights", nargs="?", help="File containing disc weights for continuation of training.") args = parser.parse_args() batch_size = args.batch_size epochs = args.epochs debug = args.debug disc_weights = args.disc_weights gen_weights = args.gen_weights dt = int(time()) logdir = "{}/{}/".format(args.logdir, dt) print("logdir:", logdir) os.mkdir(logdir) sizes = [(4, 64), (8, 128), (16, 256)] # Possible input and output sizes test_batch_size = (1, 32, 32, 50) # might want to alter learning rate... adam_op = Adam(lr=args.learning_rate, beta_1=0.5, beta_2=0.999) xdf = get_images(args.im_file)[..., 1:4] # take F606W, F775W and F814W channels og_histo = np.histogram(xdf, 10000) # Define generator and discriminator models gen = gen() disc = disc() if disc_weights is not None and gen_weights is not None: gen.load_weights(gen_weights) disc.load_weights(disc_weights) # Define real and fake images raw_reals = Input(shape=(None, None, 3)) reals = Lambda(lambda x: tf.split(x, num_or_size_splits=2, axis=0))(raw_reals) reals = Concatenate(axis=-1)([reals[0], reals[1]]) z = Input(shape=(None, None, 50)) fakes = Lambda(lambda x: tf.split(x, num_or_size_splits=2, axis=0))(gen(z)) fakes = Concatenate(axis=-1)([fakes[0], fakes[1]]) disc_r = disc(reals) # C(x_r) disc_f = disc(fakes) # C(x_f) # Define generator and discriminator losses according to RaGAN described in Jolicoeur-Martineau (2018). # Dummy predictions and trues are needed in Keras (see https://github.com/Smith42/keras-relativistic-gan). def rel_disc_loss(y_true, y_pred): epsilon = 1e-9 return K.abs(-(K.mean(K.log(K.sigmoid(disc_r - K.mean(disc_f, axis=0))+epsilon), axis=0)\ +K.mean(K.log(1-K.sigmoid(disc_f - K.mean(disc_r, axis=0))+epsilon), axis=0))) def rel_gen_loss(y_true, y_pred): epsilon = 1e-9 return K.abs(-(K.mean(K.log(K.sigmoid(disc_f - K.mean(disc_r, axis=0))+epsilon), axis=0)\ +K.mean(K.log(1-K.sigmoid(disc_r - K.mean(disc_f, axis=0))+epsilon), axis=0))) # Define trainable generator and discriminator gen_train = Model([z, raw_reals], [disc_r, disc_f]) disc.trainable = False gen_train.compile(adam_op, loss=[rel_gen_loss, None]) gen_train.summary() disc_train = Model([z, raw_reals], [disc_r, disc_f]) gen.trainable = False disc.trainable = True disc_train.compile(adam_op, loss=[rel_disc_loss, None]) disc_train.summary() # Train RaGAN gen_loss = [] disc_loss = [] dummy_y = np.zeros((batch_size, 1), dtype=np.float32) test_z = np.random.randn(test_batch_size[0],\ test_batch_size[1],\ test_batch_size[2],\ test_batch_size[3]).astype(np.float32) # Define batch flow batchflow = ImageDataGenerator(rotation_range=0,\ width_shift_range=0.0,\ height_shift_range=0.0,\ shear_range=0.0,\ zoom_range=0.0,\ channel_shift_range=0.0,\ fill_mode='reflect',\ horizontal_flip=True,\ vertical_flip=True,\ rescale=None) start_time = time() for epoch in np.arange(epochs): print(epoch, "/", epochs) n_batches = 30 # int(len(ims) // batch_size) prog_bar = Progbar(target=n_batches) batch_start_time = time() for index in np.arange(n_batches): size = sizes[np.random.randint(len(sizes))] prog_bar.update(index) # Update G image_batch = batchflow.flow(np.array([random_crop(xdf, size[1]) for i in np.arange(batch_size)]), batch_size=batch_size)[0] z = np.random.randn(batch_size, size[0], size[0], 50).astype(np.float32) disc.trainable = False gen.trainable = True gen_loss.append(gen_train.train_on_batch([z, image_batch], dummy_y)) # Update D image_batch = batchflow.flow(np.array([random_crop(xdf, size[1]) for i in np.arange(batch_size)]), batch_size=batch_size)[0] z = np.random.randn(batch_size, size[0], size[0], 50).astype(np.float32) disc.trainable = True gen.trainable = False disc_loss.append(disc_train.train_on_batch([z, image_batch], dummy_y)) print("\nEpoch time", int(time() - batch_start_time)) print("Total elapsed time", int(time() - start_time)) print("Gen, Disc losses", gen_loss[-1], disc_loss[-1]) ## Print out losses and pics of G(z) outputs ## if debug or epoch % 5 == 0: gen_image = gen.predict(test_z) print("OG im: max, min, mean, std", xdf.max(), xdf.min(), xdf.mean(), xdf.std()) print("Gen im: max, min, mean, std", gen_image.max(), gen_image.min(), gen_image.mean(), gen_image.std()) # Plot generated/real histo comparison gen_histo = np.histogram(gen_image, 10000) fig, axs = plt.subplots(nrows=1, ncols=1, figsize=(16, 16)) axs.set_yscale("log") axs.plot(og_histo[1][:-1], og_histo[0], label="Original") axs.plot(gen_histo[1][:-1], gen_histo[0], label="Generated") axs.legend() plt.savefig("{}/{:05d}-histogram.png".format(logdir, epoch)) plt.close(fig) # Plot generated image fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(30, 20)) axs[0, 0].imshow(gen_image[0, ..., 0], cmap="gray", norm=LogNorm()) axs[0, 1].imshow(gen_image[0, ..., 1], cmap="gray", norm=LogNorm()) axs[0, 2].imshow(gen_image[0, ..., 2], cmap="gray", norm=LogNorm()) #axs[1, 0].imshow(gen_image[0, ..., 3], cmap="gray", norm=LogNorm()) #axs[1, 1].imshow(gen_image[0, ..., 4], cmap="gray", norm=LogNorm()) axs[1, 0].imshow(gen_image[0], norm=LogNorm()) # was [1,2] and sliced [...,1:4] plt.tight_layout() plt.savefig("{}/{:05d}-example.png".format(logdir, epoch)) plt.close(fig) ## Save model ## if epoch % 10 == 0: gen.save("{}/{:05d}-gen-model.h5".format(logdir, epoch)) gen.save_weights("{}/{:05d}-gen-weights.h5".format(logdir, epoch)) disc.save_weights("{}/{:05d}-disc-weights.h5".format(logdir, epoch)) fig, axs = plt.subplots(nrows=1, ncols=1, figsize=(8, 4)) disc_loss_ar = np.array(disc_loss)[:, 0] gen_loss_ar = np.array(gen_loss)[:, 0] axs.set_title("Losses at epoch " + str(epoch)) axs.set_xlabel("Global step") axs.set_ylabel("Loss") axs.set_yscale("log") axs.plot(disc_loss_ar, label="disc loss") axs.plot(gen_loss_ar, label="gen loss") axs.legend() plt.savefig("{}/{:05d}-loss.png".format(logdir, epoch)) plt.close(fig)
10,761
39.920152
145
py
rlmeta
rlmeta-main/setup.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import multiprocessing import os import re import subprocess import sys from distutils.version import LooseVersion from setuptools import Extension, setup from setuptools.command.build_ext import build_ext # Reference: # https://www.benjack.io/2017/06/12/python-cpp-tests.html class CMakeExtension(Extension): def __init__(self, name, src_dir=""): Extension.__init__(self, name, sources=[]) self.src_dir = os.path.abspath(src_dir) class CMakeBuild(build_ext): def run(self): try: cmake_version = subprocess.check_output(["cmake", "--version"]) except OSError: raise RuntimeError( "CMake must be installed to build the following extensions: " + ", ".join(e.name for e in self.extensions)) cmake_version = LooseVersion( re.search(r"version\s*([\d.]+)", cmake_version.decode()).group(1)) if cmake_version < "3.14": raise RuntimeError("CMake >= 3.14 is required.") for ext in self.extensions: self.build_extension(ext) def build_extension(self, ext): ext_dir = os.path.abspath( os.path.dirname(self.get_ext_fullpath(ext.name))) cmake_args = [ "-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=" + ext_dir, "-DPYTHON_EXECUTABLE=" + sys.executable ] cfg = "Debug" if self.debug else "Release" build_args = ["--config", cfg] cmake_args += ["-DCMAKE_BUILD_TYPE=" + cfg] build_args += ["--", f"-j{multiprocessing.cpu_count()}"] env = os.environ.copy() env["CXXFLAGS"] = f'{env.get("CXXFLAGS", "")} \ -DVERSION_INFO="{self.distribution.get_version()}"' if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(["cmake", ext.src_dir] + cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(["cmake", "--build", "."] + build_args, cwd=self.build_temp) print() # Add an empty line for cleaner output def main(): with open("./requirements.txt", "r") as f: requires = f.read().splitlines() setup( name="rlmeta", version="0.1", description="A flexible and lightweight distributed RL framework", long_description="", license="MIT", install_requires=requires, ext_modules=[CMakeExtension("rlmeta", "./rlmeta")], cmdclass=dict(build_ext=CMakeBuild), zip_safe=False, ) if __name__ == "__main__": main()
2,829
28.789474
79
py
rlmeta
rlmeta-main/examples/plot.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import json import re from datetime import datetime from typing import Any, Dict, Optional, Union import matplotlib.pyplot as plt import numpy as np JSON_REGEX = re.compile("{.+}") def parse_json(line: str) -> Optional[Dict[str, Any]]: m = JSON_REGEX.search(line) return None if m is None else json.loads(m.group()) def get_value(val: Union[float, Dict[str, float]]) -> float: return val["mean"] if isinstance(val, dict) else val def plot(log_file: str, phase: str, xkey: str, ykey: str, fig_file: Optional[str] = None) -> None: x = [] y = [] with open(log_file, "r") as f: line = f.readline() cfg = parse_json(line) for line in f: stats = parse_json(line) if stats is None: continue cur_phase = stats.get("phase", None) if cur_phase == phase: x.append(get_value(stats[xkey])) y.append(get_value(stats[ykey])) x = np.array(x) y = np.array(y) plt.plot(x, y) plt.xlabel(xkey) plt.ylabel(ykey) if fig_file is not None: plt.savefig(fig_file) else: plt.show() def main(): parser = argparse.ArgumentParser() parser.add_argument("--log_file", type=str, help="log file to plot") parser.add_argument("--phase", default="Eval", type=str, help="phase to plot.") parser.add_argument("--xkey", default="epoch", type=str, help="x values to plot.") parser.add_argument("--ykey", default="episode_return", type=str, help="y values to plot.") parser.add_argument("--fig_file", default=None, type=str, help="figure file to save.") flags = parser.parse_intermixed_args() plot(flags.log_file, flags.phase, flags.xkey, flags.ykey, flags.fig_file) if __name__ == "__main__": main()
2,320
26.305882
77
py
rlmeta
rlmeta-main/examples/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
179
35
65
py
rlmeta
rlmeta-main/examples/atari/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
179
35
65
py
rlmeta
rlmeta-main/examples/atari/ppo/atari_ppo_rnd_model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F import rlmeta.core.remote as remote from rlmeta.agents.ppo import PPORNDModel from rlmeta.core.types import NestedTensor from rlmeta.models.actor_critic import DiscreteActorCriticRNDHead from rlmeta.models.atari import NatureCNNBackbone, ImpalaCNNBackbone class AtariPPORNDModel(PPORNDModel): def __init__(self, num_actions: int, network: str = "nature") -> None: super().__init__() self._num_actions = num_actions self._network = network.lower() if self._network == "nature": self._ppo_net = NatureCNNBackbone() self._tgt_net = NatureCNNBackbone() self._prd_net = NatureCNNBackbone() self._head = DiscreteActorCriticRNDHead(self._ppo_net.output_size, [512], num_actions) elif self._network == "impala": self._ppo_net = ImpalaCNNBackbone() self._tgt_net = ImpalaCNNBackbone() self._prd_net = ImpalaCNNBackbone() self._head = DiscreteActorCriticRNDHead(self._ppo_net.output_size, [256], num_actions) else: assert False, "Unsupported network." def forward( self, obs: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: x = obs.float() / 255.0 h = self._ppo_net(x) logpi, ext_v, int_v = self._head(h) return logpi, ext_v, int_v @remote.remote_method(batch_size=128) def act( self, obs: torch.Tensor, deterministic_policy: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: with torch.no_grad(): logpi, ext_v, int_v = self.forward(obs) greedy_action = logpi.argmax(-1, keepdim=True) sample_action = logpi.exp().multinomial(1, replacement=True) action = torch.where(deterministic_policy, greedy_action, sample_action) logpi = logpi.gather(dim=-1, index=action) return action, logpi, ext_v, int_v @remote.remote_method(batch_size=None) def intrinsic_reward(self, obs: torch.Tensor) -> torch.Tensor: return self._rnd_error(obs) def rnd_loss(self, obs: torch.Tensor) -> torch.Tensor: return self._rnd_error(obs).mean() * 0.5 def _rnd_error(self, obs: torch.Tensor) -> torch.Tensor: x = obs.float() / 255.0 with torch.no_grad(): tgt = self._tgt_net(x) prd = self._prd_net(x) err = (prd - tgt).square().mean(-1, keepdim=True) return err
2,889
35.125
78
py
rlmeta
rlmeta-main/examples/atari/ppo/atari_ppo_model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Tuple import torch import torch.nn as nn import rlmeta.core.remote as remote from rlmeta.agents.ppo import PPOModel from rlmeta.models.actor_critic import DiscreteActorCriticHead from rlmeta.models.atari import NatureCNNBackbone, ImpalaCNNBackbone class AtariPPOModel(PPOModel): def __init__(self, num_actions: int, network: str = "nature") -> None: super().__init__() self._num_actions = num_actions self._network = network.lower() if self._network == "nature": self._backbone = NatureCNNBackbone() self._head = DiscreteActorCriticHead(self._backbone.output_size, [512], num_actions) elif self._network == "impala": self._backbone = ImpalaCNNBackbone() self._head = DiscreteActorCriticHead(self._backbone.output_size, [256], num_actions) else: assert False, "Unsupported network." def forward(self, obs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: x = obs.float() / 255.0 h = self._backbone(x) logpi, v = self._head(h) return logpi, v @remote.remote_method(batch_size=128) def act( self, obs: torch.Tensor, deterministic_policy: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: with torch.no_grad(): logpi, v = self.forward(obs) greedy_action = logpi.argmax(-1, keepdim=True) sample_action = logpi.exp().multinomial(1, replacement=True) action = torch.where(deterministic_policy, greedy_action, sample_action) logpi = logpi.gather(dim=-1, index=action) return action, logpi, v
1,988
35.163636
78
py
rlmeta
rlmeta-main/examples/atari/ppo/atari_ppo.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy import json import logging import time import hydra import torch import torch.multiprocessing as mp import rlmeta.envs.atari_wrapper as atari_wrapper import rlmeta.utils.hydra_utils as hydra_utils import rlmeta.utils.random_utils as random_utils import rlmeta.utils.remote_utils as remote_utils from examples.atari.ppo.atari_ppo_model import AtariPPOModel from rlmeta.agents.agent import AgentFactory from rlmeta.agents.ppo import PPOAgent from rlmeta.core.controller import Phase, Controller from rlmeta.core.loop import LoopList, ParallelLoop from rlmeta.core.model import ModelVersion, RemotableModelPool from rlmeta.core.model import make_remote_model, wrap_downstream_model from rlmeta.core.replay_buffer import ReplayBuffer, make_remote_replay_buffer from rlmeta.core.server import Server, ServerList from rlmeta.samplers import UniformSampler from rlmeta.storage import TensorCircularBuffer from rlmeta.utils.optimizer_utils import make_optimizer @hydra.main(config_path="./conf", config_name="conf_ppo") def main(cfg): if cfg.seed is not None: random_utils.manual_seed(cfg.seed) logging.info(hydra_utils.config_to_json(cfg)) env = atari_wrapper.make_atari_env(**cfg.env) model = AtariPPOModel(env.action_space.n, network=cfg.network).to(cfg.train_device) model_pool = RemotableModelPool(copy.deepcopy(model).to(cfg.infer_device), seed=cfg.seed) optimizer = make_optimizer(model.parameters(), **cfg.optimizer) replay_buffer = ReplayBuffer(TensorCircularBuffer(cfg.replay_buffer_size), UniformSampler()) ctrl = Controller() m_server = Server(cfg.m_server_name, cfg.m_server_addr) r_server = Server(cfg.r_server_name, cfg.r_server_addr) c_server = Server(cfg.c_server_name, cfg.c_server_addr) m_server.add_service(model_pool) r_server.add_service(replay_buffer) c_server.add_service(ctrl) servers = ServerList([m_server, r_server, c_server]) learner_model = wrap_downstream_model(model, m_server) t_actor_model = make_remote_model(model, m_server, version=ModelVersion.LATEST) # During blocking evaluation we have STABLE is LATEST e_actor_model = make_remote_model(model, m_server, version=ModelVersion.LATEST) learner_ctrl = remote_utils.make_remote(ctrl, c_server) t_actor_ctrl = remote_utils.make_remote(ctrl, c_server) e_actor_ctrl = remote_utils.make_remote(ctrl, c_server) learner_replay_buffer = make_remote_replay_buffer(replay_buffer, r_server, prefetch=cfg.prefetch) t_actor_replay_buffer = make_remote_replay_buffer(replay_buffer, r_server) env_fac = atari_wrapper.AtariWrapperFactory(**cfg.env) t_agent_fac = AgentFactory(PPOAgent, t_actor_model, replay_buffer=t_actor_replay_buffer, gamma=cfg.gamma) e_agent_fac = AgentFactory( PPOAgent, e_actor_model, deterministic_policy=cfg.deterministic_evaluation) t_loop = ParallelLoop(env_fac, t_agent_fac, t_actor_ctrl, running_phase=Phase.TRAIN, should_update=True, num_rollouts=cfg.num_training_rollouts, num_workers=cfg.num_training_workers, seed=cfg.seed) e_loop = ParallelLoop(env_fac, e_agent_fac, e_actor_ctrl, running_phase=Phase.EVAL, should_update=False, num_rollouts=cfg.num_evaluation_rollouts, num_workers=cfg.num_evaluation_workers, seed=(None if cfg.seed is None else cfg.seed + cfg.num_training_rollouts)) loops = LoopList([t_loop, e_loop]) learner = PPOAgent(learner_model, replay_buffer=learner_replay_buffer, controller=learner_ctrl, optimizer=optimizer, batch_size=cfg.batch_size, gamma=cfg.gamma, learning_starts=cfg.learning_starts, model_push_period=cfg.model_push_period) servers.start() loops.start() learner.connect() start_time = time.perf_counter() for epoch in range(cfg.num_epochs): stats = learner.train(cfg.steps_per_epoch) cur_time = time.perf_counter() - start_time info = f"T Epoch {epoch}" if cfg.table_view: logging.info("\n\n" + stats.table(info, time=cur_time) + "\n") else: logging.info( stats.json(info, phase="Train", epoch=epoch, time=cur_time)) time.sleep(1) stats = learner.eval(cfg.num_evaluation_episodes, keep_training_loops=True) cur_time = time.perf_counter() - start_time info = f"E Epoch {epoch}" if cfg.table_view: logging.info("\n\n" + stats.table(info, time=cur_time) + "\n") else: logging.info( stats.json(info, phase="Eval", epoch=epoch, time=cur_time)) torch.save(model.state_dict(), f"ppo_agent-{epoch}.pth") time.sleep(1) loops.terminate() servers.terminate() if __name__ == "__main__": mp.set_start_method("spawn") main()
5,968
38.013072
78
py
rlmeta
rlmeta-main/examples/atari/ppo/atari_ppo_rnd.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy import json import logging import time import hydra import torch import torch.multiprocessing as mp import rlmeta.envs.atari_wrapper as atari_wrapper import rlmeta.utils.hydra_utils as hydra_utils import rlmeta.utils.random_utils as random_utils import rlmeta.utils.remote_utils as remote_utils from examples.atari.ppo.atari_ppo_rnd_model import AtariPPORNDModel from rlmeta.agents.agent import AgentFactory from rlmeta.agents.ppo import PPORNDAgent from rlmeta.core.controller import Phase, Controller from rlmeta.core.loop import LoopList, ParallelLoop from rlmeta.core.model import ModelVersion, RemotableModelPool from rlmeta.core.model import make_remote_model, wrap_downstream_model from rlmeta.core.replay_buffer import ReplayBuffer, make_remote_replay_buffer from rlmeta.core.server import Server, ServerList from rlmeta.samplers import UniformSampler from rlmeta.storage import TensorCircularBuffer from rlmeta.utils.optimizer_utils import make_optimizer @hydra.main(config_path="./conf", config_name="conf_ppo") def main(cfg): if cfg.seed is not None: random_utils.manual_seed(cfg.seed) logging.info(hydra_utils.config_to_json(cfg)) env = atari_wrapper.make_atari_env(**cfg.env) model = AtariPPORNDModel(env.action_space.n, network=cfg.network).to(cfg.train_device) model_pool = RemotableModelPool(copy.deepcopy(model).to(cfg.infer_device), seed=cfg.seed) optimizer = make_optimizer(model.parameters(), **cfg.optimizer) ctrl = Controller() replay_buffer = ReplayBuffer(TensorCircularBuffer(cfg.replay_buffer_size), UniformSampler()) m_server = Server(cfg.m_server_name, cfg.m_server_addr) r_server = Server(cfg.r_server_name, cfg.r_server_addr) c_server = Server(cfg.c_server_name, cfg.c_server_addr) m_server.add_service(model_pool) r_server.add_service(replay_buffer) c_server.add_service(ctrl) servers = ServerList([m_server, r_server, c_server]) learner_model = wrap_downstream_model(model, m_server) t_actor_model = make_remote_model(model, m_server, version=ModelVersion.LATEST) # During blocking evaluation we have STABLE is LATEST e_actor_model = make_remote_model(model, m_server, version=ModelVersion.LATEST) a_ctrl = remote_utils.make_remote(ctrl, c_server) t_ctrl = remote_utils.make_remote(ctrl, c_server) e_ctrl = remote_utils.make_remote(ctrl, c_server) learner_replay_buffer = make_remote_replay_buffer(replay_buffer, r_server, prefetch=cfg.prefetch) t_actor_replay_buffer = make_remote_replay_buffer(replay_buffer, r_server) env_fac = atari_wrapper.AtariWrapperFactory(**cfg.env) t_agent_fac = AgentFactory(PPORNDAgent, t_actor_model, replay_buffer=t_actor_replay_buffer) e_agent_fac = AgentFactory( PPORNDAgent, e_actor_model, deterministic_policy=cfg.deterministic_evaluation) t_loop = ParallelLoop(env_fac, t_agent_fac, t_ctrl, running_phase=Phase.TRAIN, should_update=True, num_rollouts=cfg.num_training_rollouts, num_workers=cfg.num_training_workers, seed=cfg.seed) e_loop = ParallelLoop(env_fac, e_agent_fac, e_ctrl, running_phase=Phase.EVAL, should_update=False, num_rollouts=cfg.num_evaluation_rollouts, num_workers=cfg.num_evaluation_workers, seed=(None if cfg.seed is None else cfg.seed + cfg.num_training_rollouts)) loops = LoopList([t_loop, e_loop]) learner = PPORNDAgent(learner_model, replay_buffer=learner_replay_buffer, controller=a_ctrl, optimizer=optimizer, batch_size=cfg.batch_size, learning_starts=cfg.get("learning_starts", None), model_push_period=cfg.model_push_period) servers.start() loops.start() learner.connect() start_time = time.perf_counter() for epoch in range(cfg.num_epochs): stats = learner.train(cfg.steps_per_epoch) cur_time = time.perf_counter() - start_time info = f"T Epoch {epoch}" if cfg.table_view: logging.info("\n\n" + stats.table(info, time=cur_time) + "\n") else: logging.info( stats.json(info, phase="Train", epoch=epoch, time=cur_time)) time.sleep(1) stats = learner.eval(cfg.num_evaluation_episodes, keep_training_loops=True) cur_time = time.perf_counter() - start_time info = f"E Epoch {epoch}" if cfg.table_view: logging.info("\n\n" + stats.table(info, time=cur_time) + "\n") else: logging.info( stats.json(info, phase="Eval", epoch=epoch, time=cur_time)) torch.save(model.state_dict(), f"ppo_rnd_agent-{epoch}.pth") time.sleep(1) loops.terminate() servers.terminate() if __name__ == "__main__": mp.set_start_method("spawn") main()
5,904
38.10596
78
py
rlmeta
rlmeta-main/examples/atari/dqn/atari_dqn_model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy from typing import Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F import rlmeta.core.remote as remote import rlmeta.utils.nested_utils as nested_utils from rlmeta.agents.dqn import DQNModel from rlmeta.core.types import NestedTensor from rlmeta.models.atari import NatureCNNBackbone, ImpalaCNNBackbone from rlmeta.models.dqn import DQNHead, DuelingDQNHead class AtariDQNNet(nn.Module): def __init__(self, num_actions: int, network="nature", dueling_dqn: bool = True, spectral_norm: bool = True) -> None: super().__init__() self._num_actions = num_actions self._network = network.lower() self._dueling_dqn = dueling_dqn self._spectral_norm = spectral_norm head_cls = DuelingDQNHead if dueling_dqn else DQNHead if self._network == "nature": self._backbone = NatureCNNBackbone() self._head = head_cls(self._backbone.output_size, [512], num_actions) elif self._network == "impala": self._backbone = ImpalaCNNBackbone() self._head = head_cls(self._backbone.output_size, [256], num_actions) else: assert False, "Unsupported network." def init_model(self) -> None: if self._spectral_norm: # Apply SN[-2] in https://arxiv.org/abs/2105.05246 if self._dueling_dqn: nn.utils.parametrizations.spectral_norm( self._head._mlp_a._layers[-3]) nn.utils.parametrizations.spectral_norm( self._head._mlp_v._layers[-3]) else: nn.utils.parametrizations.spectral_norm( self._head._mlp._layers[-3]) def forward(self, observation: torch.Tensor) -> torch.Tensor: x = observation.float() / 255.0 h = self._backbone(x) a = self._head(h) return a class AtariDQNModel(DQNModel): def __init__(self, num_actions: int, network: str = "nature", dueling_dqn: bool = True, spectral_norm: bool = True, double_dqn: bool = False) -> None: super().__init__() self._num_actions = num_actions self._network = network.lower() self._dueling_dqn = dueling_dqn self._spectral_norm = spectral_norm self._double_dqn = double_dqn # Bootstrapping with online network when double_dqn = False. # https://arxiv.org/pdf/2209.07550.pdf self._online_net = AtariDQNNet(num_actions, network=network, dueling_dqn=dueling_dqn, spectral_norm=spectral_norm) self._target_net = copy.deepcopy( self._online_net) if double_dqn else None def init_model(self) -> None: self._online_net.init_model() if self._target_net is not None: self._target_net.init_model() def forward(self, observation: torch.Tensor) -> torch.Tensor: return self._online_net(observation) def q(self, s: torch.Tensor, a: torch.Tensor) -> torch.Tensor: q = self._online_net(s) q = q.gather(dim=-1, index=a) return q @remote.remote_method(batch_size=256) def act(self, observation: torch.Tensor, eps: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: with torch.no_grad(): q = self._online_net(observation) # size = (batch_size, action_dim) _, action_dim = q.size() greedy_action = q.argmax(-1, keepdim=True) pi = torch.ones_like(q) * (eps / action_dim) pi.scatter_(dim=-1, index=greedy_action, src=1.0 - eps * (action_dim - 1) / action_dim) action = pi.multinomial(1) v = self._value(observation, q) q = q.gather(dim=-1, index=action) return action, q, v def sync_target_net(self) -> None: if self._target_net is not None: self._target_net.load_state_dict(self._online_net.state_dict()) def _value(self, observation: torch.Tensor, q: Optional[torch.Tensor] = None) -> torch.Tensor: if q is None: q = self._online_net(observation) if not self._double_dqn: v = q.max(-1, keepdim=True)[0] else: a = q.argmax(-1, keepdim=True) q = self._target_net(observation) v = q.gather(dim=-1, index=a) return v
4,918
34.388489
80
py
rlmeta
rlmeta-main/examples/atari/dqn/atari_apex_dqn.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy import logging import time import hydra import torch import torch.multiprocessing as mp import rlmeta.envs.atari_wrapper as atari_wrapper import rlmeta.utils.hydra_utils as hydra_utils import rlmeta.utils.random_utils as random_utils import rlmeta.utils.remote_utils as remote_utils from examples.atari.dqn.atari_dqn_model import AtariDQNModel from rlmeta.agents.dqn import (ApexDQNAgent, ApexDQNAgentFactory, ConstantEpsFunc, FlexibleEpsFunc) from rlmeta.core.controller import Phase, Controller from rlmeta.core.loop import LoopList, ParallelLoop from rlmeta.core.model import ModelVersion, RemotableModelPool from rlmeta.core.model import make_remote_model, wrap_downstream_model from rlmeta.core.replay_buffer import ReplayBuffer, make_remote_replay_buffer from rlmeta.core.server import Server, ServerList from rlmeta.samplers import PrioritizedSampler from rlmeta.storage import TensorCircularBuffer from rlmeta.utils.optimizer_utils import make_optimizer @hydra.main(config_path="./conf", config_name="conf_apex_dqn") def main(cfg): if cfg.seed is not None: random_utils.manual_seed(cfg.seed) logging.info(hydra_utils.config_to_json(cfg)) env = atari_wrapper.make_atari_env(**cfg.env) model = AtariDQNModel(env.action_space.n, network=cfg.network, dueling_dqn=cfg.dueling_dqn, spectral_norm=cfg.spectral_norm, double_dqn=cfg.double_dqn).to(cfg.train_device) infer_model = copy.deepcopy(model).to(cfg.infer_device) infer_model.eval() model_pool = RemotableModelPool(infer_model, seed=cfg.seed) optimizer = make_optimizer(model.parameters(), **cfg.optimizer) replay_buffer = ReplayBuffer( TensorCircularBuffer(cfg.replay_buffer_size), PrioritizedSampler(priority_exponent=cfg.priority_exponent)) ctrl = Controller() m_server = Server(cfg.m_server_name, cfg.m_server_addr) r_server = Server(cfg.r_server_name, cfg.r_server_addr) c_server = Server(cfg.c_server_name, cfg.c_server_addr) m_server.add_service(model_pool) r_server.add_service(replay_buffer) c_server.add_service(ctrl) servers = ServerList([m_server, r_server, c_server]) learner_model = wrap_downstream_model(model, m_server) t_actor_model = make_remote_model(model, m_server, version=ModelVersion.LATEST) # During blocking evaluation we have STABLE is LATEST e_actor_model = make_remote_model(model, m_server, version=ModelVersion.LATEST) learner_ctrl = remote_utils.make_remote(ctrl, c_server) t_actor_ctrl = remote_utils.make_remote(ctrl, c_server) e_actor_ctrl = remote_utils.make_remote(ctrl, c_server) learner_replay_buffer = make_remote_replay_buffer(replay_buffer, r_server, prefetch=cfg.prefetch) t_actor_replay_buffer = make_remote_replay_buffer(replay_buffer, r_server) env_fac = atari_wrapper.AtariWrapperFactory(**cfg.env) t_agent_fac = ApexDQNAgentFactory(t_actor_model, FlexibleEpsFunc( cfg.eps, cfg.num_training_rollouts), replay_buffer=t_actor_replay_buffer, n_step=cfg.n_step, gamma=cfg.gamma, max_abs_reward=cfg.max_abs_reward, rescale_value=cfg.rescale_value) e_agent_fac = ApexDQNAgentFactory(e_actor_model, ConstantEpsFunc(cfg.evaluation_eps)) t_loop = ParallelLoop(env_fac, t_agent_fac, t_actor_ctrl, running_phase=Phase.TRAIN, should_update=True, num_rollouts=cfg.num_training_rollouts, num_workers=cfg.num_training_workers, seed=cfg.seed) e_loop = ParallelLoop(env_fac, e_agent_fac, e_actor_ctrl, running_phase=Phase.EVAL, should_update=False, num_rollouts=cfg.num_evaluation_rollouts, num_workers=cfg.num_evaluation_workers, seed=(None if cfg.seed is None else cfg.seed + cfg.num_training_rollouts)) loops = LoopList([t_loop, e_loop]) learner = ApexDQNAgent( learner_model, replay_buffer=learner_replay_buffer, controller=learner_ctrl, optimizer=optimizer, batch_size=cfg.batch_size, max_grad_norm=cfg.max_grad_norm, n_step=cfg.n_step, gamma=cfg.gamma, importance_sampling_exponent=cfg.importance_sampling_exponent, value_clipping_eps=cfg.value_clipping_eps, fr_kappa=cfg.fr_kappa, target_sync_period=cfg.target_sync_period, learning_starts=cfg.learning_starts, model_push_period=cfg.model_push_period) servers.start() loops.start() learner.connect() learner_model.init_model() learner_model.push() start_time = time.perf_counter() for epoch in range(cfg.num_epochs): stats = learner.train(cfg.steps_per_epoch) cur_time = time.perf_counter() - start_time info = f"T Epoch {epoch}" if cfg.table_view: logging.info("\n\n" + stats.table(info, time=cur_time) + "\n") else: logging.info( stats.json(info, phase="Train", epoch=epoch, time=cur_time)) time.sleep(1) stats = learner.eval(cfg.num_evaluation_episodes, keep_training_loops=True) cur_time = time.perf_counter() - start_time info = f"E Epoch {epoch}" if cfg.table_view: logging.info("\n\n" + stats.table(info, time=cur_time) + "\n") else: logging.info( stats.json(info, phase="Eval", epoch=epoch, time=cur_time)) torch.save(model.state_dict(), f"dqn_agent-{epoch}.pth") time.sleep(1) loops.terminate() servers.terminate() if __name__ == "__main__": mp.set_start_method("spawn") main()
6,771
39.071006
78
py
rlmeta
rlmeta-main/examples/tutorials/loop_example.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import asyncio import time from typing import Optional import numpy as np import torch import torch.multiprocessing as mp import rlmeta.utils.remote_utils as remote_utils from rlmeta.agents.agent import Agent from rlmeta.core.controller import Controller, Phase from rlmeta.core.loop import ParallelLoop from rlmeta.core.server import Server from rlmeta.core.types import Action, TimeStep from rlmeta.envs.env import Env, EnvFactory class MockEnv(Env): def __init__(self, index: int, observation_space: int = 4, action_space: int = 4, episode_length: int = 10) -> None: self.index = index self.observation_space = observation_space self.action_space = action_space self.episode_length = episode_length self.step_counter = 0 def reset(self, *args, **kwargs) -> TimeStep: print(f"[Env {self.index}] reset") print("") self.step_counter = 0 obs = torch.randn(self.observation_space) info = {"step_counter": 0} return TimeStep(obs, done=False, info=info) def step(self, action: Action) -> TimeStep: self.step_counter += 1 time.sleep(1.0) obs = torch.randn(self.observation_space) reward = np.random.randn() done = self.step_counter == self.episode_length info = {"step_counter": self.step_counter} print( f"[Env {self.index}] step = {self.step_counter}, reward = {reward}") print("") return TimeStep(obs, reward, done, info) def close(self) -> None: pass def seed(self, seed: Optional[int] = None) -> None: pass class MockAgent(Agent): def __init__(self, index: int, action_space: int = 4) -> None: self.index = index self.action_space = action_space async def async_act(self, timestep: TimeStep) -> Action: _, reward, _, info = timestep step_counter = info["step_counter"] await asyncio.sleep(1.0) act = np.random.randint(self.action_space) print(f"[Agent {self.index}] step = {step_counter}, action = {act}") return Action(act) async def async_observe_init(self, timestep: TimeStep) -> None: pass async def async_observe(self, action: Action, next_timestep: TimeStep) -> None: pass async def async_update(self) -> None: pass def env_factory(index: int) -> MockEnv: return MockEnv(index) def agent_factory(index: int) -> MockAgent: return MockAgent(index) def main() -> None: server = Server("server", "127.0.0.1:4411") ctrl = Controller() server.add_service(ctrl) loop_ctrl = remote_utils.make_remote(ctrl, server) main_ctrl = remote_utils.make_remote(ctrl, server) loop = ParallelLoop(env_factory, agent_factory, loop_ctrl, running_phase=Phase.EVAL, num_rollouts=2, num_workers=1) server.start() loop.start() main_ctrl.connect() main_ctrl.set_phase(Phase.EVAL, reset=True) time.sleep(30) loop.terminate() server.terminate() if __name__ == "__main__": mp.set_start_method("spawn") main()
3,493
27.177419
80
py
rlmeta
rlmeta-main/examples/tutorials/remote_example.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import asyncio import torch import torch.multiprocessing as mp import rlmeta.core.remote as remote import rlmeta.utils.remote_utils as remote_utils from rlmeta.core.server import Server class Adder(remote.Remotable): @remote.remote_method() def add(self, a, b): print(f"[Adder.add] a = {a}") print(f"[Adder.add] b = {b}") return a + b @remote.remote_method(batch_size=10) def batch_add(self, a, b): print(f"[Adder.batch_add] a = {a}") print(f"[Adder.batch_add] b = {b}") if not isinstance(a, tuple) and not isinstance(b, tuple): return a + b else: return tuple(sum(x) for x in zip(a, b)) async def run_batch(adder_client, send_tensor=False): futs = [] for i in range(20): if send_tensor: a = torch.tensor([i]) b = torch.tensor([i + 1]) else: a = i b = i + 1 fut = adder_client.async_batch_add(a, b) futs.append(fut) await asyncio.sleep(1.0) for i, fut in enumerate(futs): if send_tensor: a = torch.tensor([i]) b = torch.tensor([i + 1]) else: a = i b = i + 1 c = await fut print(f"{a} + {b} = {c}") def main(): adder = Adder() adder_server = Server(name="adder_server", addr="127.0.0.1:4411") adder_server.add_service(adder) adder_client = remote_utils.make_remote(adder, adder_server) adder_server.start() adder_client.connect() a = 1 b = 2 c = adder_client.add(a, b) print(f"{a} + {b} = {c}") print("") asyncio.run(run_batch(adder_client, send_tensor=False)) print("") asyncio.run(run_batch(adder_client, send_tensor=True)) adder_server.terminate() if __name__ == "__main__": mp.set_start_method("spawn") main()
2,053
22.883721
69
py
rlmeta
rlmeta-main/examples/tutorials/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
179
35
65
py
rlmeta
rlmeta-main/tests/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
179
35
65
py
rlmeta
rlmeta-main/tests/test_utils.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import numpy as np import torch import rlmeta.utils.data_utils as data_utils class TestCaseBase(unittest.TestCase): def assert_tensor_equal(self, x, y): self.assertTrue(isinstance(x, type(y))) x = data_utils.to_numpy(x) y = data_utils.to_numpy(y) np.testing.assert_array_equal(x, y) def assert_tensor_close(self, x, y, rtol=1e-7, atol=0): self.assertTrue(isinstance(x, type(y))) x = data_utils.to_numpy(x) y = data_utils.to_numpy(y) np.testing.assert_allclose(x, y, rtol, atol)
752
26.888889
65
py
rlmeta
rlmeta-main/tests/core/replay_buffer_test.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import torch import rlmeta.utils.data_utils as data_utils from rlmeta.core.replay_buffer import ReplayBuffer from rlmeta.samplers import UniformSampler, PrioritizedSampler from rlmeta.storage import CircularBuffer, TensorCircularBuffer from tests.test_utils import TestCaseBase class ReplayBufferTest(TestCaseBase): def setUp(self) -> None: self.size = 8 self.batch_size = 5 self.hidden_dim = 4 self.replay_buffer = ReplayBuffer( CircularBuffer(self.size, collate_fn=torch.stack), UniformSampler()) self.flatten_data = dict(obs=torch.randn(self.batch_size, self.hidden_dim), rew=torch.randn(self.batch_size)) self.data = data_utils.unstack_fields(self.flatten_data, self.batch_size) def test_extend(self) -> None: self.replay_buffer.reset() keys = self.replay_buffer.extend(self.data) expected_keys = torch.arange(self.batch_size) self.assertEqual(len(self.replay_buffer), self.batch_size) self.assert_tensor_equal(keys, expected_keys) data = self.replay_buffer.get(keys) self.assertEqual(data.keys(), self.flatten_data.keys()) for k, v in data.items(): self.assert_tensor_equal(v, self.flatten_data[k]) keys = self.replay_buffer.extend(self.data) self.assertEqual(len(self.replay_buffer), self.size) self.assert_tensor_equal(keys, expected_keys + self.batch_size) data = self.replay_buffer.get(keys) self.assertEqual(data.keys(), self.flatten_data.keys()) for k, v in data.items(): self.assert_tensor_equal(v, self.flatten_data[k]) def test_extend_stacked(self) -> None: self.replay_buffer.reset() keys = self.replay_buffer.extend(self.flatten_data, stacked=True) expected_keys = torch.arange(self.batch_size) self.assertEqual(len(self.replay_buffer), self.batch_size) self.assert_tensor_equal(keys, expected_keys) data = self.replay_buffer.get(keys) self.assertEqual(data.keys(), self.flatten_data.keys()) for k, v in data.items(): self.assert_tensor_equal(v, self.flatten_data[k]) keys = self.replay_buffer.extend(self.flatten_data, stacked=True) self.assertEqual(len(self.replay_buffer), self.size) self.assert_tensor_equal(keys, expected_keys + self.batch_size) data = self.replay_buffer.get(keys) self.assertEqual(data.keys(), self.flatten_data.keys()) for k, v in data.items(): self.assert_tensor_equal(v, self.flatten_data[k]) def test_sample(self) -> None: self.replay_buffer.reset() self.replay_buffer.extend(self.data) prob = 1.0 / self.batch_size num_samples = self.batch_size keys, _, probs = self.replay_buffer.sample(num_samples) expected_probs = torch.full_like(probs, prob) self.assert_tensor_equal(probs, expected_probs) count = torch.bincount(keys) self.assertEqual(count.max().item(), 1) count = torch.zeros(self.batch_size, dtype=torch.int64) for _ in range(20000): keys, _, _ = self.replay_buffer.sample(3) count[keys] += 1 actual_probs = count / count.sum() expected_probs = torch.full_like(actual_probs, prob) self.assert_tensor_close(actual_probs, expected_probs, atol=0.05) # Test sample with replacement. num_samples = 20000 keys, _, probs = self.replay_buffer.sample(num_samples, replacement=True) self.assert_tensor_equal( probs, torch.full((num_samples,), prob, dtype=torch.float64)) actual_probs = torch.bincount(keys).float() / num_samples expected_probs = torch.full_like(actual_probs, prob) self.assert_tensor_close(actual_probs, expected_probs, atol=0.05) def test_clear(self) -> None: self.replay_buffer.reset() self.replay_buffer.extend(self.data) self.assertEqual(len(self.replay_buffer), len(self.data)) self.replay_buffer.clear() self.assertEqual(len(self.replay_buffer), 0) self.replay_buffer.extend(self.data) self.assertEqual(len(self.replay_buffer), len(self.data)) class PrioritizedReplayBufferTest(TestCaseBase): def setUp(self): self.size = 8 self.batch_size = 5 self.hidden_dim = 4 self.flatten_data = dict(obs=torch.randn(self.batch_size, self.hidden_dim), rew=torch.randn(self.batch_size)) self.data = data_utils.unstack_fields(self.flatten_data, self.batch_size) def test_extend(self): replay_buffer = ReplayBuffer(TensorCircularBuffer(self.size), PrioritizedSampler(priority_exponent=0.6)) keys = replay_buffer.extend(self.data) expected_keys = torch.arange(self.batch_size) self.assertEqual(len(replay_buffer), self.batch_size) self.assert_tensor_equal(keys, expected_keys) data = replay_buffer.get(keys) self.assertEqual(data.keys(), self.flatten_data.keys()) for k, v in data.items(): self.assert_tensor_equal(v, self.flatten_data[k]) keys = replay_buffer.extend(self.data) self.assertEqual(len(replay_buffer), self.size) self.assert_tensor_equal(keys, expected_keys + self.batch_size) data = replay_buffer.get(keys) self.assertEqual(data.keys(), self.flatten_data.keys()) for k, v in data.items(): self.assert_tensor_equal(v, self.flatten_data[k]) def test_extend_stacked(self): replay_buffer = ReplayBuffer(TensorCircularBuffer(self.size), PrioritizedSampler(priority_exponent=0.6)) keys = replay_buffer.extend(self.flatten_data, stacked=True) expected_keys = torch.arange(self.batch_size) self.assertEqual(len(replay_buffer), self.batch_size) self.assert_tensor_equal(keys, expected_keys) data = replay_buffer.get(keys) self.assertEqual(data.keys(), self.flatten_data.keys()) for k, v in data.items(): self.assert_tensor_equal(v, self.flatten_data[k]) keys = replay_buffer.extend(self.flatten_data, stacked=True) self.assertEqual(len(replay_buffer), self.size) self.assert_tensor_equal(keys, expected_keys + self.batch_size) data = replay_buffer.get(keys) self.assertEqual(data.keys(), self.flatten_data.keys()) for k, v in data.items(): self.assert_tensor_equal(v, self.flatten_data[k]) def test_sample(self): replay_buffer = ReplayBuffer(TensorCircularBuffer(self.size), PrioritizedSampler(priority_exponent=1.0)) priorities = torch.rand((self.batch_size,)) * 10 expected_probs = priorities / priorities.sum() replay_buffer.extend(self.data, priorities=priorities) # Test sample without replacement. # Disable this test because of stability. # num_samples = self.batch_size # keys, _, probs = replay_buffer.sample(num_samples) # self.assert_tensor_close(probs, # expected_probs[keys], # rtol=1e-6, # atol=1e-6) # count = torch.bincount(keys) # self.assertEqual(count.max().item(), 1) # count = torch.zeros(self.batch_size, dtype=torch.int64) # for _ in range(100000): # keys, _, _ = replay_buffer.sample(3) # count[keys] += 1 # actual_probs = count / count.sum() # self.assert_tensor_close(actual_probs, expected_probs, atol=0.1) # Test sample with replacement. num_samples = 100000 keys, _, probs = replay_buffer.sample(num_samples, replacement=True) actual_probs = torch.bincount(keys).float() / num_samples self.assert_tensor_close(probs, expected_probs[keys], rtol=1e-6) self.assert_tensor_close(actual_probs, expected_probs, atol=0.05) def test_update(self): alpha = 0.6 replay_buffer = ReplayBuffer( TensorCircularBuffer(self.size), PrioritizedSampler(priority_exponent=alpha)) priorities = torch.rand((self.batch_size,)) * 10 keys = replay_buffer.extend(self.data, priorities=priorities) priorities = torch.rand((self.batch_size,)) * 10 expected_probs = priorities.pow(alpha) expected_probs.div_(expected_probs.sum()) replay_buffer.update(keys, priorities) num_samples = 100 keys, _, probs = replay_buffer.sample(num_samples, replacement=True) self.assert_tensor_close(probs, expected_probs[keys], rtol=1e-6) def test_reset(self) -> None: replay_buffer = ReplayBuffer(TensorCircularBuffer(self.size), PrioritizedSampler(priority_exponent=0.6)) replay_buffer.extend(self.data) self.assertEqual(len(replay_buffer), len(self.data)) replay_buffer.reset() self.assertEqual(len(replay_buffer), 0) self.assertFalse(replay_buffer._storage._impl.initialized) replay_buffer.extend(self.data) self.assertEqual(len(replay_buffer), len(self.data)) def test_clear(self) -> None: replay_buffer = ReplayBuffer(TensorCircularBuffer(self.size), PrioritizedSampler(priority_exponent=0.6)) replay_buffer.extend(self.data) self.assertEqual(len(replay_buffer), len(self.data)) replay_buffer.clear() self.assertEqual(len(replay_buffer), 0) self.assertTrue(replay_buffer._storage._impl.initialized) replay_buffer.extend(self.data) self.assertEqual(len(replay_buffer), len(self.data)) if __name__ == "__main__": unittest.main()
10,383
42.087137
80
py
rlmeta
rlmeta-main/tests/core/remotable_test.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import numpy as np import torch import rlmeta.core.remote as remote import rlmeta.utils.remote_utils as remote_utils from rlmeta.core.server import Server class RemotableAdder(remote.Remotable): @remote.remote_method() def add(self, a, b): return a + b class ReplayBufferTest(unittest.TestCase): def test_add_multiple(self): server = Server(name="adder_server", addr="127.0.0.1:4412") adder1 = RemotableAdder('a') adder2 = RemotableAdder('b') self.assertEqual(adder1.identifier, 'a') self.assertEqual(adder2.identifier, 'b') server.add_service([adder1, adder2]) adder_client1 = remote_utils.make_remote(adder1, server) adder_client2 = remote_utils.make_remote(adder2, server) server.start() adder_client1.connect() c = adder_client1.add(1, 1) self.assertEqual(c, 2) adder_client2.connect() c = adder_client2.add(1, 1) self.assertEqual(c, 2) server.terminate() if __name__ == "__main__": unittest.main()
1,261
26.434783
67
py
rlmeta
rlmeta-main/tests/core/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
179
35
65
py
rlmeta
rlmeta-main/tests/core/rescalers_test.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import numpy as np import torch from rlmeta.core.rescalers import MomentsRescaler, RMSRescaler, SqrtRescaler from tests.test_utils import TestCaseBase class RescalerTest(TestCaseBase): def setUp(self) -> None: self.size = (4, 5) self.rtol = 1e-5 self.atol = 1e-5 def test_rms_rescaler(self) -> None: rms_rescaler = RMSRescaler(self.size) batch_size = np.random.randint(low=1, high=10) data = torch.rand(batch_size, *self.size) for x in torch.unbind(data): rms_rescaler.update(x) x = torch.rand(*self.size) y = rms_rescaler.rescale(x) y_expected = x / data.square().mean(dim=0).sqrt() self.assert_tensor_close(y, y_expected, rtol=self.rtol, atol=self.atol) self.assert_tensor_close(rms_rescaler.recover(y), x, rtol=self.rtol, atol=self.atol) def test_norm_rescaler(self) -> None: norm_rescaler = MomentsRescaler(self.size) batch_size = np.random.randint(low=1, high=10) data = torch.rand(batch_size, *self.size) for x in torch.unbind(data): norm_rescaler.update(x) x = torch.rand(*self.size) y = norm_rescaler.rescale(x) if batch_size == 1: y_expected = x else: y_expected = (x - data.mean(dim=0)) / data.std(dim=0, unbiased=False) self.assert_tensor_close(y, y_expected, rtol=self.rtol, atol=self.atol) self.assert_tensor_close(norm_rescaler.recover(y), x, rtol=self.rtol, atol=self.atol) def test_sqrt_rescaler(self) -> None: eps = np.random.choice([0.0, 1e-5, 1e-3, 2e-2, 0.5]) sqrt_rescaler = SqrtRescaler(eps) x = torch.randn(*self.size, dtype=torch.float64) y = sqrt_rescaler.rescale(x) y_expected = x.sign() * ((x.abs() + 1).sqrt() - 1) + eps * x self.assert_tensor_close(y, y_expected, rtol=self.rtol, atol=self.atol) self.assert_tensor_close(sqrt_rescaler.recover(y), x, rtol=self.rtol, atol=self.atol) if __name__ == "__main__": unittest.main()
2,621
33.5
79
py
rlmeta
rlmeta-main/tests/utils/running_stats_test.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import torch from rlmeta.utils.running_stats import RunningMoments, RunningRMS from tests.test_utils import TestCaseBase class RunningRMSTest(TestCaseBase): def setUp(self) -> None: self.outer_size = 10 self.inner_size = (4, 5) self.running_rms = RunningRMS(self.inner_size) self.rtol = 1e-6 self.atol = 1e-6 def test_single_update(self) -> None: input = torch.rand(self.outer_size, *self.inner_size) self.running_rms.reset() for x in torch.unbind(input): self.running_rms.update(x) self._verify_running_rms(input) def test_batch_update(self) -> None: input = torch.rand(self.outer_size, *self.inner_size) split_size = [1, 2, 3, 4] self.running_rms.reset() for x in torch.split(input, split_size): self.running_rms.update(x) self._verify_running_rms(input) def _verify_running_rms(self, input: torch.Tensor) -> None: self.assert_tensor_equal(self.running_rms.count(), torch.tensor([self.outer_size])) self.assert_tensor_close(self.running_rms.mean_square(), input.square().mean(dim=0), rtol=self.rtol, atol=self.atol) self.assert_tensor_close(self.running_rms.rms(), input.square().mean(dim=0).sqrt(), rtol=self.rtol, atol=self.atol) self.assert_tensor_close(self.running_rms.rrms(), input.square().mean(dim=0).rsqrt(), rtol=self.rtol, atol=self.atol) class RunningMomentsTest(TestCaseBase): def setUp(self) -> None: self.outer_size = 10 self.inner_size = (4, 5) self.running_moments = RunningMoments(self.inner_size) self.rtol = 1e-6 self.atol = 1e-6 def test_single_update(self) -> None: input = torch.rand(self.outer_size, *self.inner_size) self.running_moments.reset() for x in torch.unbind(input): self.running_moments.update(x) self._verify_running_moments(input) def test_batch_update(self) -> None: input = torch.rand(self.outer_size, *self.inner_size) split_size = [1, 2, 3, 4] self.running_moments.reset() for x in torch.split(input, split_size): self.running_moments.update(x) self._verify_running_moments(input) def _verify_running_moments(self, input: torch.Tensor) -> None: self.assert_tensor_equal(self.running_moments.count(), torch.tensor([self.outer_size])) self.assert_tensor_close(self.running_moments.mean(), input.mean(dim=0), rtol=self.rtol, atol=self.atol) self.assert_tensor_close(self.running_moments.var(), input.var(dim=0, unbiased=False), rtol=self.rtol, atol=self.atol) self.assert_tensor_close(self.running_moments.var(ddof=1), input.var(dim=0, unbiased=True), rtol=self.rtol, atol=self.atol) self.assert_tensor_close(self.running_moments.std(), input.std(dim=0, unbiased=False), rtol=self.rtol, atol=self.atol) self.assert_tensor_close(self.running_moments.std(ddof=1), input.std(dim=0, unbiased=True), rtol=self.rtol, atol=self.atol) self.assert_tensor_close(self.running_moments.rstd(), input.std(dim=0, unbiased=False).reciprocal(), rtol=self.rtol, atol=self.atol) self.assert_tensor_close(self.running_moments.rstd(ddof=1), input.std(dim=0, unbiased=True).reciprocal(), rtol=self.rtol, atol=self.atol) if __name__ == "__main__": unittest.main()
4,653
39.824561
79
py
rlmeta
rlmeta-main/tests/utils/stats_dict_test.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import numpy as np from rlmeta.utils.stats_dict import StatsDict from tests.test_utils import TestCaseBase class StatsDictTest(TestCaseBase): def test_add(self) -> None: n = 10 a = np.random.rand(n) b = np.random.randn(n) d = StatsDict() for x, y in zip(a.tolist(), b.tolist()): d.add("a", x) d.add("b", y) self.assertEqual(d["a"].count(), n) self.assertEqual(d["a"].mean(), np.mean(a)) self.assertEqual(d["a"].var(ddof=0), np.var(a, ddof=0)) self.assertEqual(d["a"].std(ddof=0), np.std(a, ddof=0)) self.assertEqual(d["a"].min(), np.min(a)) self.assertEqual(d["a"].max(), np.max(a)) self.assertEqual(d["b"].count(), n) self.assertEqual(d["b"].mean(), np.mean(b)) self.assertEqual(d["b"].var(ddof=1), np.var(b, ddof=1)) self.assertEqual(d["b"].std(ddof=1), np.std(b, ddof=1)) self.assertEqual(d["b"].min(), np.min(b)) self.assertEqual(d["b"].max(), np.max(b)) def test_extend(self) -> None: n = 10 a = np.random.rand(n) b = np.random.randn(n) d = StatsDict() for x, y in zip(a.tolist(), b.tolist()): d.extend({"a": x, "b": y}) self.assertEqual(d["a"].count(), n) self.assertEqual(d["a"].mean(), np.mean(a)) self.assertEqual(d["a"].var(ddof=0), np.var(a, ddof=0)) self.assertEqual(d["a"].std(ddof=0), np.std(a, ddof=0)) self.assertEqual(d["a"].min(), np.min(a)) self.assertEqual(d["a"].max(), np.max(a)) self.assertEqual(d["b"].count(), n) self.assertEqual(d["b"].mean(), np.mean(b)) self.assertEqual(d["b"].var(ddof=1), np.var(b, ddof=1)) self.assertEqual(d["b"].std(ddof=1), np.std(b, ddof=1)) self.assertEqual(d["b"].min(), np.min(b)) self.assertEqual(d["b"].max(), np.max(b))
2,102
32.919355
65
py
rlmeta
rlmeta-main/tests/utils/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
179
35
65
py