repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
Attention-Gated-Networks
Attention-Gated-Networks-master/visualise_att_maps_epoch.py
from torch.utils.data import DataLoader from dataio.loader import get_dataset, get_dataset_path from dataio.transformation import get_dataset_transformation from utils.util import json_file_to_pyobj from models import get_model import matplotlib.cm as cm import matplotlib.pyplot as plt import math, numpy, os from dataio.loader.utils import write_nifti_img from torch.nn import functional as F def mkdirfun(directory): if not os.path.exists(directory): os.makedirs(directory) def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None): plt.ion() filters = units.shape[2] n_columns = round(math.sqrt(filters)) n_rows = math.ceil(filters / n_columns) + 1 fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3)) fig.clf() for i in range(filters): ax1 = plt.subplot(n_rows, n_columns, i+1) plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap) plt.axis('on') ax1.set_xticklabels([]) ax1.set_yticklabels([]) plt.colorbar() if colormap_lim: plt.clim(colormap_lim[0],colormap_lim[1]) plt.subplots_adjust(wspace=0, hspace=0) plt.tight_layout() # Epochs layer_name = 'attentionblock2' layer_save_directory = os.path.join('/vol/bitbucket/oo2113/tmp/attention_maps', layer_name); mkdirfun(layer_save_directory) epochs = range(225, 230, 3) att_maps = list() int_imgs = list() subject_id = int(2) for epoch in epochs: # Load options and replace the epoch attribute json_opts = json_file_to_pyobj('/vol/biomedic2/oo2113/projects/syntAI/ukbb_pytorch/configs_final/debug_ct.json') json_opts = json_opts._replace(model=json_opts.model._replace(which_epoch=epoch)) # Setup the NN Model model = get_model(json_opts.model) # Setup Dataset and Augmentation dataset_class = get_dataset('test_sax') dataset_path = get_dataset_path('test_sax', json_opts.data_path) dataset_transform = get_dataset_transformation('test_sax', json_opts.augmentation) # Setup Data Loader dataset = dataset_class(dataset_path, transform=dataset_transform['test']) data_loader = DataLoader(dataset=dataset, num_workers=1, batch_size=1, shuffle=False) # test for iteration, (input_arr, input_meta, _) in enumerate(data_loader, 1): # look for the subject_id if iteration == subject_id: # load the input image into the model model.set_input(input_arr) inp_fmap, out_fmap = model.get_feature_maps(layer_name=layer_name, upscale=False) # Display the input image and Down_sample the input image orig_input_img = model.input.permute(2, 3, 4, 1, 0).cpu().numpy() upsampled_attention = F.upsample(out_fmap[1], size=input_arr.size()[2:], mode='trilinear').data.squeeze().permute(1,2,3,0).cpu().numpy() # Append it to the list int_imgs.append(orig_input_img[:,:,:,0,0]) att_maps.append(upsampled_attention[:,:,:,1]) # return the model model.destructor() # Write the attentions to a nifti image input_meta['name'][0] = str(subject_id) + '_img_2.nii.gz' int_imgs = numpy.array(int_imgs).transpose([1,2,3,0]) write_nifti_img(int_imgs, input_meta, savedir=layer_save_directory) input_meta['name'][0] = str(subject_id) + '_att_2.nii.gz' att_maps = numpy.array(att_maps).transpose([1,2,3,0]) write_nifti_img(att_maps, input_meta, savedir=layer_save_directory)
3,482
36.451613
148
py
Attention-Gated-Networks
Attention-Gated-Networks-master/setup.py
#!/usr/bin/env python from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() setup(name='AttentionGatedNetworks', version='1.0', description='Pytorch library for Soft Attention', long_description=readme, author='Ozan Oktay & Jo Schlemper', install_requires=[ "numpy", "torch", "matplotlib", "scipy", "torchvision", "tqdm", "visdom", "nibabel", "scikit-image", "h5py", "pandas", "dominate", 'torchsample==0.1.3', ], dependency_links=[ 'https://github.com/ozan-oktay/torchsample/tarball/master#egg=torchsample-0.1.3' ], packages=find_packages(exclude=('tests', 'docs')) )
782
22.029412
90
py
Attention-Gated-Networks
Attention-Gated-Networks-master/train_segmentation.py
import numpy from torch.utils.data import DataLoader from tqdm import tqdm from dataio.loader import get_dataset, get_dataset_path from dataio.transformation import get_dataset_transformation from utils.util import json_file_to_pyobj from utils.visualiser import Visualiser from utils.error_logger import ErrorLogger from models import get_model def train(arguments): # Parse input arguments json_filename = arguments.config network_debug = arguments.debug # Load options json_opts = json_file_to_pyobj(json_filename) train_opts = json_opts.training # Architecture type arch_type = train_opts.arch_type # Setup Dataset and Augmentation ds_class = get_dataset(arch_type) ds_path = get_dataset_path(arch_type, json_opts.data_path) ds_transform = get_dataset_transformation(arch_type, opts=json_opts.augmentation) # Setup the NN Model model = get_model(json_opts.model) if network_debug: print('# of pars: ', model.get_number_parameters()) print('fp time: {0:.3f} sec\tbp time: {1:.3f} sec per sample'.format(*model.get_fp_bp_time())) exit() # Setup Data Loader train_dataset = ds_class(ds_path, split='train', transform=ds_transform['train'], preload_data=train_opts.preloadData) valid_dataset = ds_class(ds_path, split='validation', transform=ds_transform['valid'], preload_data=train_opts.preloadData) test_dataset = ds_class(ds_path, split='test', transform=ds_transform['valid'], preload_data=train_opts.preloadData) train_loader = DataLoader(dataset=train_dataset, num_workers=16, batch_size=train_opts.batchSize, shuffle=True) valid_loader = DataLoader(dataset=valid_dataset, num_workers=16, batch_size=train_opts.batchSize, shuffle=False) test_loader = DataLoader(dataset=test_dataset, num_workers=16, batch_size=train_opts.batchSize, shuffle=False) # Visualisation Parameters visualizer = Visualiser(json_opts.visualisation, save_dir=model.save_dir) error_logger = ErrorLogger() # Training Function model.set_scheduler(train_opts) for epoch in range(model.which_epoch, train_opts.n_epochs): print('(epoch: %d, total # iters: %d)' % (epoch, len(train_loader))) # Training Iterations for epoch_iter, (images, labels) in tqdm(enumerate(train_loader, 1), total=len(train_loader)): # Make a training update model.set_input(images, labels) model.optimize_parameters() #model.optimize_parameters_accumulate_grd(epoch_iter) # Error visualisation errors = model.get_current_errors() error_logger.update(errors, split='train') # Validation and Testing Iterations for loader, split in zip([valid_loader, test_loader], ['validation', 'test']): for epoch_iter, (images, labels) in tqdm(enumerate(loader, 1), total=len(loader)): # Make a forward pass with the model model.set_input(images, labels) model.validate() # Error visualisation errors = model.get_current_errors() stats = model.get_segmentation_stats() error_logger.update({**errors, **stats}, split=split) # Visualise predictions visuals = model.get_current_visuals() visualizer.display_current_results(visuals, epoch=epoch, save_result=False) # Update the plots for split in ['train', 'validation', 'test']: visualizer.plot_current_errors(epoch, error_logger.get_errors(split), split_name=split) visualizer.print_current_errors(epoch, error_logger.get_errors(split), split_name=split) error_logger.reset() # Save the model parameters if epoch % train_opts.save_epoch_freq == 0: model.save(epoch) # Update the model learning rate model.update_learning_rate() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='CNN Seg Training Function') parser.add_argument('-c', '--config', help='training config file', required=True) parser.add_argument('-d', '--debug', help='returns number of parameters and bp/fp runtime', action='store_true') args = parser.parse_args() train(args)
4,354
39.324074
127
py
Attention-Gated-Networks
Attention-Gated-Networks-master/visualise_attention.py
from torch.utils.data import DataLoader from dataio.loader import get_dataset, get_dataset_path from dataio.transformation import get_dataset_transformation from utils.util import json_file_to_pyobj from utils.visualiser import Visualiser from models import get_model import os, time # import matplotlib # matplotlib.use('Agg') import matplotlib.cm as cm import matplotlib.pyplot as plt import math, numpy import numpy as np from scipy.misc import imresize from skimage.transform import resize def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None, title=''): plt.ion() filters = units.shape[2] n_columns = round(math.sqrt(filters)) n_rows = math.ceil(filters / n_columns) + 1 fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3)) fig.clf() for i in range(filters): ax1 = plt.subplot(n_rows, n_columns, i+1) plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap) plt.axis('on') ax1.set_xticklabels([]) ax1.set_yticklabels([]) plt.colorbar() if colormap_lim: plt.clim(colormap_lim[0],colormap_lim[1]) plt.subplots_adjust(wspace=0, hspace=0) plt.tight_layout() plt.suptitle(title) def plotNNFilterOverlay(input_im, units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None, title='', alpha=0.8): plt.ion() filters = units.shape[2] fig = plt.figure(figure_id, figsize=(5,5)) fig.clf() for i in range(filters): plt.imshow(input_im[:,:,0], interpolation=interp, cmap='gray') plt.imshow(units[:,:,i], interpolation=interp, cmap=colormap, alpha=alpha) plt.axis('off') plt.colorbar() plt.title(title, fontsize='small') if colormap_lim: plt.clim(colormap_lim[0],colormap_lim[1]) plt.subplots_adjust(wspace=0, hspace=0) plt.tight_layout() # plt.savefig('{}/{}.png'.format(dir_name,time.time())) ## Load options PAUSE = .01 #config_name = 'config_sononet_attention_fs8_v6.json' #config_name = 'config_sononet_attention_fs8_v8.json' #config_name = 'config_sononet_attention_fs8_v9.json' #config_name = 'config_sononet_attention_fs8_v10.json' #config_name = 'config_sononet_attention_fs8_v11.json' #config_name = 'config_sononet_attention_fs8_v13.json' #config_name = 'config_sononet_attention_fs8_v14.json' #config_name = 'config_sononet_attention_fs8_v15.json' #config_name = 'config_sononet_attention_fs8_v16.json' #config_name = 'config_sononet_grid_attention_fs8_v1.json' config_name = 'config_sononet_grid_attention_fs8_deepsup_v1.json' config_name = 'config_sononet_grid_attention_fs8_deepsup_v2.json' config_name = 'config_sononet_grid_attention_fs8_deepsup_v3.json' config_name = 'config_sononet_grid_attention_fs8_deepsup_v4.json' # config_name = 'config_sononet_grid_att_fs8_avg.json' config_name = 'config_sononet_grid_att_fs8_avg_v2.json' # config_name = 'config_sononet_grid_att_fs8_avg_v3.json' #config_name = 'config_sononet_grid_att_fs8_avg_v4.json' #config_name = 'config_sononet_grid_att_fs8_avg_v5.json' #config_name = 'config_sononet_grid_att_fs8_avg_v5.json' #config_name = 'config_sononet_grid_att_fs8_avg_v6.json' #config_name = 'config_sononet_grid_att_fs8_avg_v7.json' #config_name = 'config_sononet_grid_att_fs8_avg_v8.json' #config_name = 'config_sononet_grid_att_fs8_avg_v9.json' #config_name = 'config_sononet_grid_att_fs8_avg_v10.json' #config_name = 'config_sononet_grid_att_fs8_avg_v11.json' #config_name = 'config_sononet_grid_att_fs8_avg_v12.json' config_name = 'config_sononet_grid_att_fs8_avg_v12_scratch.json' config_name = 'config_sononet_grid_att_fs4_avg_v12.json' #config_name = 'config_sononet_grid_attention_fs8_v3.json' json_opts = json_file_to_pyobj('/vol/bitbucket/js3611/projects/transfer_learning/ultrasound/configs_2/{}'.format(config_name)) train_opts = json_opts.training dir_name = os.path.join('visualisation_debug', config_name) if not os.path.isdir(dir_name): os.makedirs(dir_name) os.makedirs(os.path.join(dir_name,'pos')) os.makedirs(os.path.join(dir_name,'neg')) # Setup the NN Model model = get_model(json_opts.model) if hasattr(model.net, 'classification_mode'): model.net.classification_mode = 'attention' if hasattr(model.net, 'deep_supervised'): model.net.deep_supervised = False # Setup Dataset and Augmentation dataset_class = get_dataset(train_opts.arch_type) dataset_path = get_dataset_path(train_opts.arch_type, json_opts.data_path) dataset_transform = get_dataset_transformation(train_opts.arch_type, opts=json_opts.augmentation) # Setup Data Loader dataset = dataset_class(dataset_path, split='train', transform=dataset_transform['valid']) data_loader = DataLoader(dataset=dataset, num_workers=1, batch_size=1, shuffle=True) # test for iteration, data in enumerate(data_loader, 1): model.set_input(data[0], data[1]) cls = dataset.label_names[int(data[1])] model.validate() pred_class = model.pred[1] pred_cls = dataset.label_names[int(pred_class)] ######################################################### # Display the input image and Down_sample the input image input_img = model.input[0,0].cpu().numpy() #input_img = numpy.expand_dims(imresize(input_img, (fmap_size[0], fmap_size[1]), interp='bilinear'), axis=2) input_img = numpy.expand_dims(input_img, axis=2) # plotNNFilter(input_img, figure_id=0, colormap="gray") plotNNFilterOverlay(input_img, numpy.zeros_like(input_img), figure_id=0, interp='bilinear', colormap=cm.jet, title='[GT:{}|P:{}]'.format(cls, pred_cls),alpha=0) chance = np.random.random() < 0.01 if cls == "BACKGROUND" else 1 if cls != pred_cls: plt.savefig('{}/neg/{:03d}.png'.format(dir_name,iteration)) elif cls == pred_cls and chance: plt.savefig('{}/pos/{:03d}.png'.format(dir_name,iteration)) ######################################################### # Compatibility Scores overlay with input attentions = [] for i in [1,2]: fmap = model.get_feature_maps('compatibility_score%d'%i, upscale=False) if not fmap: continue # Output of the attention block fmap_0 = fmap[0].squeeze().permute(1,2,0).cpu().numpy() fmap_size = fmap_0.shape # Attention coefficient (b x c x w x h x s) attention = fmap[1].squeeze().cpu().numpy() attention = attention[:, :] #attention = numpy.expand_dims(resize(attention, (fmap_size[0], fmap_size[1]), mode='constant', preserve_range=True), axis=2) attention = numpy.expand_dims(resize(attention, (input_img.shape[0], input_img.shape[1]), mode='constant', preserve_range=True), axis=2) # this one is useless #plotNNFilter(fmap_0, figure_id=i+3, interp='bilinear', colormap=cm.jet, title='compat. feature %d' %i) plotNNFilterOverlay(input_img, attention, figure_id=i, interp='bilinear', colormap=cm.jet, title='[GT:{}|P:{}] compat. {}'.format(cls,pred_cls,i), alpha=0.5) attentions.append(attention) #plotNNFilterOverlay(input_img, attentions[0], figure_id=4, interp='bilinear', colormap=cm.jet, title='[GT:{}|P:{}] compat. (all)'.format(cls, pred_cls), alpha=0.5) plotNNFilterOverlay(input_img, numpy.mean(attentions,0), figure_id=4, interp='bilinear', colormap=cm.jet, title='[GT:{}|P:{}] compat. (all)'.format(cls, pred_cls), alpha=0.5) if cls != pred_cls: plt.savefig('{}/neg/{:03d}_hm.png'.format(dir_name,iteration)) elif cls == pred_cls and chance: plt.savefig('{}/pos/{:03d}_hm.png'.format(dir_name,iteration)) # Linear embedding g(x) # (b, c, h, w) #gx = fmap[2].squeeze().permute(1,2,0).cpu().numpy() #plotNNFilter(gx, figure_id=3, interp='nearest', colormap=cm.jet) plt.show() plt.pause(PAUSE) model.destructor() #if iteration == 1: break
7,900
39.937824
178
py
Attention-Gated-Networks
Attention-Gated-Networks-master/test_classification.py
import os, sys, numpy as np from torch.utils.data import DataLoader, sampler from tqdm import tqdm from dataio.loader import get_dataset, get_dataset_path from dataio.transformation import get_dataset_transformation from utils.util import json_file_to_pyobj from utils.visualiser import Visualiser from utils.error_logger import ErrorLogger from models.networks_other import adjust_learning_rate from models import get_model class HiddenPrints: def __enter__(self): self._original_stdout = sys.stdout sys.stdout = None def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout = self._original_stdout class StratifiedSampler(object): """Stratified Sampling Provides equal representation of target classes in each batch """ def __init__(self, class_vector, batch_size): """ Arguments --------- class_vector : torch tensor a vector of class labels batch_size : integer batch_size """ self.class_vector = class_vector self.batch_size = batch_size self.num_iter = len(class_vector) // 52 self.n_class = 14 self.sample_n = 2 # create pool of each vectors indices = {} for i in range(self.n_class): indices[i] = np.where(self.class_vector == i)[0] self.indices = indices self.background_index = np.argmax([ len(indices[i]) for i in range(self.n_class)]) def gen_sample_array(self): # sample 2 from each class sample_array = [] for i in range(self.num_iter): arrs = [] for i in range(self.n_class): n = self.sample_n if i == self.background_index: n = self.sample_n * (self.n_class-1) arr = np.random.choice(self.indices[i], n) arrs.append(arr) sample_array.append(np.hstack(arrs)) return np.hstack(sample_array) def __iter__(self): return iter(self.gen_sample_array()) def __len__(self): return len(self.class_vector) def test(arguments): # Parse input arguments json_filename = arguments.config network_debug = arguments.debug # Load options json_opts = json_file_to_pyobj(json_filename) train_opts = json_opts.training # Architecture type arch_type = train_opts.arch_type # Setup Dataset and Augmentation ds_class = get_dataset(arch_type) ds_path = get_dataset_path(arch_type, json_opts.data_path) ds_transform = get_dataset_transformation(arch_type, opts=json_opts.augmentation) # Setup the NN Model with HiddenPrints(): model = get_model(json_opts.model) if network_debug: print('# of pars: ', model.get_number_parameters()) print('fp time: {0:.8f} sec\tbp time: {1:.8f} sec per sample'.format(*model.get_fp_bp_time2((1,1,224,288)))) exit() # Setup Data Loader num_workers = train_opts.num_workers if hasattr(train_opts, 'num_workers') else 16 valid_dataset = ds_class(ds_path, split='val', transform=ds_transform['valid'], preload_data=train_opts.preloadData) test_dataset = ds_class(ds_path, split='test', transform=ds_transform['valid'], preload_data=train_opts.preloadData) # loader batch_size = train_opts.batchSize valid_loader = DataLoader(dataset=valid_dataset, num_workers=num_workers, batch_size=train_opts.batchSize, shuffle=False) test_loader = DataLoader(dataset=test_dataset, num_workers=0, batch_size=train_opts.batchSize, shuffle=False) # Visualisation Parameters filename = 'test_loss_log.txt' visualizer = Visualiser(json_opts.visualisation, save_dir=model.save_dir, filename=filename) error_logger = ErrorLogger() # Training Function track_labels = np.arange(len(valid_dataset.label_names)) model.set_labels(track_labels) model.set_scheduler(train_opts) if hasattr(model.net, 'deep_supervised'): model.net.deep_supervised = False # Validation and Testing Iterations pr_lbls = [] gt_lbls = [] for loader, split in zip([test_loader], ['test']): #for loader, split in zip([valid_loader, test_loader], ['validation', 'test']): model.reset_results() for epoch_iter, (images, labels) in tqdm(enumerate(loader, 1), total=len(loader)): # Make a forward pass with the model model.set_input(images, labels) model.validate() # Error visualisation errors = model.get_accumulated_errors() stats = model.get_classification_stats() error_logger.update({**errors, **stats}, split=split) # Update the plots # for split in ['train', 'validation', 'test']: for split in ['test']: # exclude bckground #track_labels = np.delete(track_labels, 3) #show_labels = train_dataset.label_names[:3] + train_dataset.label_names[4:] show_labels = valid_dataset.label_names visualizer.plot_current_errors(300, error_logger.get_errors(split), split_name=split, labels=show_labels) visualizer.print_current_errors(300, error_logger.get_errors(split), split_name=split) import pickle as pkl dst_file = os.path.join(model.save_dir, 'test_result.pkl') with open(dst_file, 'wb') as f: d = error_logger.get_errors(split) d['labels'] = valid_dataset.label_names d['pr_lbls'] = np.hstack(model.pr_lbls) d['gt_lbls'] = np.hstack(model.gt_lbls) pkl.dump(d, f) error_logger.reset() if arguments.time: print('# of pars: ', model.get_number_parameters()) print('fp time: {0:.8f} sec\tbp time: {1:.8f} sec per sample'.format(*model.get_fp_bp_time2((1,1,224,288)))) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='CNN Seg Training Function') parser.add_argument('-c', '--config', help='training config file', required=True) parser.add_argument('-d', '--debug', help='returns number of parameters and bp/fp runtime', action='store_true') parser.add_argument('-t', '--time', help='returns number of parameters and bp/fp runtime', action='store_true') args = parser.parse_args() test(args)
6,345
34.651685
125
py
Attention-Gated-Networks
Attention-Gated-Networks-master/validation.py
from torch.utils.data import DataLoader from dataio.loader import get_dataset, get_dataset_path from dataio.transformation import get_dataset_transformation from utils.util import json_file_to_pyobj from models import get_model import numpy as np import os from utils.metrics import dice_score, distance_metric, precision_and_recall from utils.error_logger import StatLogger def mkdirfun(directory): if not os.path.exists(directory): os.makedirs(directory) def validation(json_name): # Load options json_opts = json_file_to_pyobj(json_name) train_opts = json_opts.training # Setup the NN Model model = get_model(json_opts.model) save_directory = os.path.join(model.save_dir, train_opts.arch_type); mkdirfun(save_directory) # Setup Dataset and Augmentation dataset_class = get_dataset(train_opts.arch_type) dataset_path = get_dataset_path(train_opts.arch_type, json_opts.data_path) dataset_transform = get_dataset_transformation(train_opts.arch_type, opts=json_opts.augmentation) # Setup Data Loader dataset = dataset_class(dataset_path, split='validation', transform=dataset_transform['valid']) data_loader = DataLoader(dataset=dataset, num_workers=8, batch_size=1, shuffle=False) # Visualisation Parameters #visualizer = Visualiser(json_opts.visualisation, save_dir=model.save_dir) # Setup stats logger stat_logger = StatLogger() # test for iteration, data in enumerate(data_loader, 1): model.set_input(data[0], data[1]) model.test() input_arr = np.squeeze(data[0].cpu().numpy()).astype(np.float32) label_arr = np.squeeze(data[1].cpu().numpy()).astype(np.int16) output_arr = np.squeeze(model.pred_seg.cpu().byte().numpy()).astype(np.int16) # If there is a label image - compute statistics dice_vals = dice_score(label_arr, output_arr, n_class=int(4)) md, hd = distance_metric(label_arr, output_arr, dx=2.00, k=2) precision, recall = precision_and_recall(label_arr, output_arr, n_class=int(4)) stat_logger.update(split='test', input_dict={'img_name': '', 'dice_LV': dice_vals[1], 'dice_MY': dice_vals[2], 'dice_RV': dice_vals[3], 'prec_MYO':precision[2], 'reca_MYO':recall[2], 'md_MYO': md, 'hd_MYO': hd }) # Write a nifti image import SimpleITK as sitk input_img = sitk.GetImageFromArray(np.transpose(input_arr, (2, 1, 0))); input_img.SetDirection([-1,0,0,0,-1,0,0,0,1]) label_img = sitk.GetImageFromArray(np.transpose(label_arr, (2, 1, 0))); label_img.SetDirection([-1,0,0,0,-1,0,0,0,1]) predi_img = sitk.GetImageFromArray(np.transpose(output_arr,(2, 1, 0))); predi_img.SetDirection([-1,0,0,0,-1,0,0,0,1]) sitk.WriteImage(input_img, os.path.join(save_directory,'{}_img.nii.gz'.format(iteration))) sitk.WriteImage(label_img, os.path.join(save_directory,'{}_lbl.nii.gz'.format(iteration))) sitk.WriteImage(predi_img, os.path.join(save_directory,'{}_pred.nii.gz'.format(iteration))) stat_logger.statlogger2csv(split='test', out_csv_name=os.path.join(save_directory,'stats.csv')) for key, (mean_val, std_val) in stat_logger.get_errors(split='test').items(): print('-',key,': \t{0:.3f}+-{1:.3f}'.format(mean_val, std_val),'-') if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='CNN Seg Validation Function') parser.add_argument('-c', '--config', help='testing config file', required=True) args = parser.parse_args() validation(args.config)
3,992
43.366667
125
py
Attention-Gated-Networks
Attention-Gated-Networks-master/visualise_fmaps.py
from torch.utils.data import DataLoader from dataio.loader import get_dataset, get_dataset_path from dataio.transformation import get_dataset_transformation from utils.util import json_file_to_pyobj from models import get_model import matplotlib.cm as cm import matplotlib.pyplot as plt import math, numpy, os from scipy.misc import imresize from skimage.transform import resize from dataio.loader.utils import write_nifti_img from torch.nn import functional as F def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None): plt.ion() filters = units.shape[2] n_columns = round(math.sqrt(filters)) n_rows = math.ceil(filters / n_columns) + 1 fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3)) fig.clf() for i in range(filters): ax1 = plt.subplot(n_rows, n_columns, i+1) plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap) plt.axis('on') ax1.set_xticklabels([]) ax1.set_yticklabels([]) plt.colorbar() if colormap_lim: plt.clim(colormap_lim[0],colormap_lim[1]) plt.subplots_adjust(wspace=0, hspace=0) plt.tight_layout() # Load options json_opts = json_file_to_pyobj('/vol/biomedic2/oo2113/projects/syntAI/ukbb_pytorch/configs_final/debug_ct.json') # Setup the NN Model model = get_model(json_opts.model) # Setup Dataset and Augmentation dataset_class = get_dataset('test_sax') dataset_path = get_dataset_path('test_sax', json_opts.data_path) dataset_transform = get_dataset_transformation('test_sax', json_opts.augmentation) # Setup Data Loader dataset = dataset_class(dataset_path, transform=dataset_transform['test']) data_loader = DataLoader(dataset=dataset, num_workers=1, batch_size=1, shuffle=False) # test for iteration, (input_arr, input_meta, _) in enumerate(data_loader, 1): model.set_input(input_arr) layer_name = 'attentionblock1' inp_fmap, out_fmap = model.get_feature_maps(layer_name=layer_name, upscale=False) # Display the input image and Down_sample the input image orig_input_img = model.input.permute(2, 3, 4, 1, 0).cpu().numpy() upsampled_attention = F.upsample(out_fmap[1], size=input_arr.size()[2:], mode='trilinear').data.squeeze().permute(1,2,3,0).cpu().numpy() upsampled_fmap_before = F.upsample(inp_fmap[0], size=input_arr.size()[2:], mode='trilinear').data.squeeze().permute(1,2,3,0).cpu().numpy() upsampled_fmap_after = F.upsample(out_fmap[2], size=input_arr.size()[2:], mode='trilinear').data.squeeze().permute(1,2,3,0).cpu().numpy() # Define the directories save_directory = os.path.join('/vol/bitbucket/oo2113/tmp/feature_maps', layer_name) basename = input_meta['name'][0].split('.')[0] # Write the attentions to a nifti image input_meta['name'][0] = basename + '_img.nii.gz' write_nifti_img(orig_input_img, input_meta, savedir=save_directory) input_meta['name'][0] = basename + '_att.nii.gz' write_nifti_img(upsampled_attention, input_meta, savedir=save_directory) input_meta['name'][0] = basename + '_fmap_before.nii.gz' write_nifti_img(upsampled_fmap_before, input_meta, savedir=save_directory) input_meta['name'][0] = basename + '_fmap_after.nii.gz' write_nifti_img(upsampled_fmap_after, input_meta, savedir=save_directory) model.destructor() #if iteration == 1: break
3,357
39.95122
142
py
Attention-Gated-Networks
Attention-Gated-Networks-master/train_classifaction.py
import numpy as np from torch.utils.data import DataLoader, sampler from tqdm import tqdm from dataio.loader import get_dataset, get_dataset_path from dataio.transformation import get_dataset_transformation from utils.util import json_file_to_pyobj from utils.visualiser import Visualiser from utils.error_logger import ErrorLogger from models.networks_other import adjust_learning_rate from models import get_model class StratifiedSampler(object): """Stratified Sampling Provides equal representation of target classes in each batch """ def __init__(self, class_vector, batch_size): """ Arguments --------- class_vector : torch tensor a vector of class labels batch_size : integer batch_size """ self.class_vector = class_vector self.batch_size = batch_size self.num_iter = len(class_vector) // 52 self.n_class = 14 self.sample_n = 2 # create pool of each vectors indices = {} for i in range(self.n_class): indices[i] = np.where(self.class_vector == i)[0] self.indices = indices self.background_index = np.argmax([ len(indices[i]) for i in range(self.n_class)]) def gen_sample_array(self): # sample 2 from each class sample_array = [] for i in range(self.num_iter): arrs = [] for i in range(self.n_class): n = self.sample_n if i == self.background_index: n = self.sample_n * (self.n_class-1) arr = np.random.choice(self.indices[i], n) arrs.append(arr) sample_array.append(np.hstack(arrs)) return np.hstack(sample_array) def __iter__(self): return iter(self.gen_sample_array()) def __len__(self): return len(self.class_vector) # Not using anymore def check_warm_start(epoch, model, train_opts): if hasattr(train_opts, "warm_start_epoch"): if epoch < train_opts.warm_start_epoch: print('... warm_start: lr={}'.format(train_opts.warm_start_lr)) adjust_learning_rate(model.optimizers[0], train_opts.warm_start_lr) elif epoch == train_opts.warm_start_epoch: print('... warm_start ended: lr={}'.format(model.opts.lr_rate)) adjust_learning_rate(model.optimizers[0], model.opts.lr_rate) def train(arguments): # Parse input arguments json_filename = arguments.config network_debug = arguments.debug # Load options json_opts = json_file_to_pyobj(json_filename) train_opts = json_opts.training # Architecture type arch_type = train_opts.arch_type # Setup Dataset and Augmentation ds_class = get_dataset(arch_type) ds_path = get_dataset_path(arch_type, json_opts.data_path) ds_transform = get_dataset_transformation(arch_type, opts=json_opts.augmentation) # Setup the NN Model model = get_model(json_opts.model) if network_debug: print('# of pars: ', model.get_number_parameters()) print('fp time: {0:.3f} sec\tbp time: {1:.3f} sec per sample'.format(*model.get_fp_bp_time())) exit() # Setup Data Loader num_workers = train_opts.num_workers if hasattr(train_opts, 'num_workers') else 16 train_dataset = ds_class(ds_path, split='train', transform=ds_transform['train'], preload_data=train_opts.preloadData) valid_dataset = ds_class(ds_path, split='val', transform=ds_transform['valid'], preload_data=train_opts.preloadData) test_dataset = ds_class(ds_path, split='test', transform=ds_transform['valid'], preload_data=train_opts.preloadData) # create sampler if train_opts.sampler == 'stratified': print('stratified sampler') train_sampler = StratifiedSampler(train_dataset.labels, train_opts.batchSize) batch_size = 52 elif train_opts.sampler == 'weighted2': print('weighted sampler with background weight={}x'.format(train_opts.bgd_weight_multiplier)) # modify and increase background weight weight = train_dataset.weight bgd_weight = np.min(weight) weight[abs(weight - bgd_weight) < 1e-8] = bgd_weight * train_opts.bgd_weight_multiplier train_sampler = sampler.WeightedRandomSampler(weight, len(train_dataset.weight)) batch_size = train_opts.batchSize else: print('weighted sampler') train_sampler = sampler.WeightedRandomSampler(train_dataset.weight, len(train_dataset.weight)) batch_size = train_opts.batchSize # loader train_loader = DataLoader(dataset=train_dataset, num_workers=num_workers, batch_size=batch_size, sampler=train_sampler) valid_loader = DataLoader(dataset=valid_dataset, num_workers=num_workers, batch_size=train_opts.batchSize, shuffle=True) test_loader = DataLoader(dataset=test_dataset, num_workers=num_workers, batch_size=train_opts.batchSize, shuffle=True) # Visualisation Parameters visualizer = Visualiser(json_opts.visualisation, save_dir=model.save_dir) error_logger = ErrorLogger() # Training Function track_labels = np.arange(len(train_dataset.label_names)) model.set_labels(track_labels) model.set_scheduler(train_opts) if hasattr(model, 'update_state'): model.update_state(0) for epoch in range(model.which_epoch, train_opts.n_epochs): print('(epoch: %d, total # iters: %d)' % (epoch, len(train_loader))) # # # --- Start --- # import matplotlib.pyplot as plt # plt.ion() # plt.figure() # target_arr = np.zeros(14) # # # --- End --- # Training Iterations for epoch_iter, (images, labels) in tqdm(enumerate(train_loader, 1), total=len(train_loader)): # Make a training update model.set_input(images, labels) model.optimize_parameters() if epoch == (train_opts.n_epochs-1): import time time.sleep(36000) if train_opts.max_it == epoch_iter: break # # # --- visualise distribution --- # for lab in labels.numpy(): # target_arr[lab] += 1 # plt.clf(); plt.bar(train_dataset.label_names, target_arr); plt.pause(0.01) # # # --- End --- # Visualise predictions if epoch_iter <= 100: visuals = model.get_current_visuals() visualizer.display_current_results(visuals, epoch=epoch, save_result=False) # Error visualisation errors = model.get_current_errors() error_logger.update(errors, split='train') # Validation and Testing Iterations pr_lbls = [] gt_lbls = [] for loader, split in zip([valid_loader, test_loader], ['validation', 'test']): model.reset_results() for epoch_iter, (images, labels) in tqdm(enumerate(loader, 1), total=len(loader)): # Make a forward pass with the model model.set_input(images, labels) model.validate() # Visualise predictions visuals = model.get_current_visuals() visualizer.display_current_results(visuals, epoch=epoch, save_result=False) if train_opts.max_it == epoch_iter: break # Error visualisation errors = model.get_accumulated_errors() stats = model.get_classification_stats() error_logger.update({**errors, **stats}, split=split) # HACK save validation error if split == 'validation': valid_err = errors['CE'] # Update the plots for split in ['train', 'validation', 'test']: # exclude bckground #track_labels = np.delete(track_labels, 3) #show_labels = train_dataset.label_names[:3] + train_dataset.label_names[4:] show_labels = train_dataset.label_names visualizer.plot_current_errors(epoch, error_logger.get_errors(split), split_name=split, labels=show_labels) visualizer.print_current_errors(epoch, error_logger.get_errors(split), split_name=split) error_logger.reset() # Save the model parameters if epoch % train_opts.save_epoch_freq == 0: model.save(epoch) if hasattr(model, 'update_state'): model.update_state(epoch) # Update the model learning rate model.update_learning_rate(metric=valid_err, epoch=epoch) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='CNN Classification Training Function') parser.add_argument('-c', '--config', help='training config file', required=True) parser.add_argument('-d', '--debug', help='returns number of parameters and bp/fp runtime', action='store_true') args = parser.parse_args() train(args)
9,033
36.641667
124
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/base_model.py
import os import numpy import torch from utils.util import mkdir from .networks_other import get_n_parameters class BaseModel(): def __init__(self): self.input = None self.net = None self.isTrain = False self.use_cuda = True self.schedulers = [] self.optimizers = [] self.save_dir = None self.gpu_ids = [] self.which_epoch = int(0) self.path_pre_trained_model = None def name(self): return 'BaseModel' def initialize(self, opt, **kwargs): self.gpu_ids = opt.gpu_ids self.isTrain = opt.isTrain self.ImgTensor = torch.cuda.FloatTensor if self.gpu_ids else torch.Tensor self.LblTensor = torch.cuda.FloatTensor if self.gpu_ids else torch.Tensor self.save_dir = opt.save_dir; mkdir(self.save_dir) def set_input(self, input): self.input = input def set_scheduler(self, train_opt): pass def forward(self, split): pass # used in test time, no backprop def test(self): pass def get_image_paths(self): pass def optimize_parameters(self): pass def get_current_visuals(self): return self.input def get_current_errors(self): return {} def get_input_size(self): return self.input.size() if input else None def save(self, label): pass # helper saving function that can be used by subclasses def save_network(self, network, network_label, epoch_label, gpu_ids): print('Saving the model {0} at the end of epoch {1}'.format(network_label, epoch_label)) save_filename = '{0:03d}_net_{1}.pth'.format(epoch_label, network_label) save_path = os.path.join(self.save_dir, save_filename) torch.save(network.cpu().state_dict(), save_path) if len(gpu_ids) and torch.cuda.is_available(): network.cuda(gpu_ids[0]) # helper loading function that can be used by subclasses def load_network(self, network, network_label, epoch_label): print('Loading the model {0} - epoch {1}'.format(network_label, epoch_label)) save_filename = '{0:03d}_net_{1}.pth'.format(epoch_label, network_label) save_path = os.path.join(self.save_dir, save_filename) network.load_state_dict(torch.load(save_path)) def load_network_from_path(self, network, network_filepath, strict): network_label = os.path.basename(network_filepath) epoch_label = network_label.split('_')[0] print('Loading the model {0} - epoch {1}'.format(network_label, epoch_label)) network.load_state_dict(torch.load(network_filepath), strict=strict) # update learning rate (called once every epoch) def update_learning_rate(self, metric=None, epoch=None): for scheduler in self.schedulers: if isinstance(scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau): scheduler.step(metrics=metric) else: scheduler.step() lr = self.optimizers[0].param_groups[0]['lr'] print('current learning rate = %.7f' % lr) # returns the number of trainable parameters def get_number_parameters(self): return get_n_parameters(self.net) # clean up the GPU memory def destructor(self): del self.net del self.input
3,357
32.247525
96
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/utils.py
''' Misc Utility functions ''' import os import numpy as np import torch.optim as optim from torch.nn import CrossEntropyLoss from utils.metrics import segmentation_scores, dice_score_list from sklearn import metrics from .layers.loss import * def get_optimizer(option, params): opt_alg = 'sgd' if not hasattr(option, 'optim') else option.optim if opt_alg == 'sgd': optimizer = optim.SGD(params, lr=option.lr_rate, momentum=0.9, nesterov=True, weight_decay=option.l2_reg_weight) if opt_alg == 'adam': optimizer = optim.Adam(params, lr=option.lr_rate, betas=(0.9, 0.999), weight_decay=option.l2_reg_weight) return optimizer def get_criterion(opts): if opts.criterion == 'cross_entropy': if opts.type == 'seg': criterion = cross_entropy_2D if opts.tensor_dim == '2D' else cross_entropy_3D elif 'classifier' in opts.type: criterion = CrossEntropyLoss() elif opts.criterion == 'dice_loss': criterion = SoftDiceLoss(opts.output_nc) elif opts.criterion == 'dice_loss_pancreas_only': criterion = CustomSoftDiceLoss(opts.output_nc, class_ids=[0, 2]) return criterion def recursive_glob(rootdir='.', suffix=''): """Performs recursive glob with given suffix and rootdir :param rootdir is the root directory :param suffix is the suffix to be searched """ return [os.path.join(looproot, filename) for looproot, _, filenames in os.walk(rootdir) for filename in filenames if filename.endswith(suffix)] def poly_lr_scheduler(optimizer, init_lr, iter, lr_decay_iter=1, max_iter=30000, power=0.9,): """Polynomial decay of learning rate :param init_lr is base learning rate :param iter is a current iteration :param lr_decay_iter how frequently decay occurs, default is 1 :param max_iter is number of maximum iterations :param power is a polymomial power """ if iter % lr_decay_iter or iter > max_iter: return optimizer for param_group in optimizer.param_groups: param_group['lr'] = init_lr*(1 - iter/max_iter)**power def adjust_learning_rate(optimizer, init_lr, epoch): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = init_lr * (0.1 ** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr def segmentation_stats(pred_seg, target): n_classes = pred_seg.size(1) pred_lbls = pred_seg.data.max(1)[1].cpu().numpy() gt = np.squeeze(target.data.cpu().numpy(), axis=1) gts, preds = [], [] for gt_, pred_ in zip(gt, pred_lbls): gts.append(gt_) preds.append(pred_) iou = segmentation_scores(gts, preds, n_class=n_classes) dice = dice_score_list(gts, preds, n_class=n_classes) return iou, dice def classification_scores(gts, preds, labels): accuracy = metrics.accuracy_score(gts, preds) class_accuracies = [] for lab in labels: # TODO Fix class_accuracies.append(metrics.accuracy_score(gts[gts == lab], preds[gts == lab])) class_accuracies = np.array(class_accuracies) f1_micro = metrics.f1_score(gts, preds, average='micro') precision_micro = metrics.precision_score(gts, preds, average='micro') recall_micro = metrics.recall_score(gts, preds, average='micro') f1_macro = metrics.f1_score(gts, preds, average='macro') precision_macro = metrics.precision_score(gts, preds, average='macro') recall_macro = metrics.recall_score(gts, preds, average='macro') # class wise score f1s = metrics.f1_score(gts, preds, average=None) precisions = metrics.precision_score(gts, preds, average=None) recalls = metrics.recall_score(gts, preds, average=None) confusion = metrics.confusion_matrix(gts,preds, labels=labels) #TODO confusion matrix, recall, precision return accuracy, f1_micro, precision_micro, recall_micro, f1_macro, precision_macro, recall_macro, confusion, class_accuracies, f1s, precisions, recalls def classification_stats(pred_seg, target, labels): return classification_scores(target, pred_seg, labels)
4,417
36.440678
156
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/aggregated_classifier.py
import os, collections import numpy as np import torch from torch.autograd import Variable from .feedforward_classifier import FeedForwardClassifier class AggregatedClassifier(FeedForwardClassifier): def name(self): return 'AggregatedClassifier' def initialize(self, opts, **kwargs): FeedForwardClassifier.initialize(self, opts, **kwargs) weight = self.opts.raw.weight[:] # copy weight_t = torch.from_numpy(np.array(weight, dtype=np.float32)) self.weight = weight self.aggregation = opts.raw.aggregation self.aggregation_param = opts.raw.aggregation_param self.aggregation_weight = Variable(weight_t, volatile=True).view(-1,1,1).cuda() def compute_loss(self): """Compute loss function. Iterate over multiple output""" preds = self.predictions weights = self.weight if not isinstance(preds, collections.Sequence): preds = [preds] weights = [1] loss = 0 for lmda, prediction in zip(weights, preds): if lmda == 0: continue loss += lmda * self.criterion(prediction, self.target) self.loss = loss def aggregate_output(self): """Given a list of predictions from net, make a decision based on aggreagation rule""" if isinstance(self.predictions, collections.Sequence): logits = [] for pred in self.predictions: logit = self.net.apply_argmax_softmax(pred).unsqueeze(0) logits.append(logit) logits = torch.cat(logits, 0) if self.aggregation == 'max': self.pred = logits.data.max(0)[0].max(1) elif self.aggregation == 'mean': self.pred = logits.data.mean(0).max(1) elif self.aggregation == 'weighted_mean': self.pred = (self.aggregation_weight.expand_as(logits) * logits).data.mean(0).max(1) elif self.aggregation == 'idx': self.pred = logits[self.aggregation_param].data.max(1) else: # Apply a softmax and return a segmentation map self.logits = self.net.apply_argmax_softmax(self.predictions) self.pred = self.logits.data.max(1) def forward(self, split): if split == 'train': self.predictions = self.net(Variable(self.input)) elif split in ['validation', 'test']: self.predictions = self.net(Variable(self.input, volatile=True)) self.aggregate_output() def backward(self): self.compute_loss() self.loss.backward() def validate(self): self.net.eval() self.forward(split='test') self.compute_loss() self.accumulate_results() def update_state(self, epoch): """ A function that is called at the end of every epoch. Can adjust state of the network here. For example, if one wants to change the loss weights for prediction during training (e.g. deep supervision), """ if hasattr(self.opts.raw,'late_gate'): if epoch < self.opts.raw.late_gate: self.weight[0] = 0 self.weight[1] = 0 print('='*10,'weight={}'.format(self.weight), '='*10) if epoch == self.opts.raw.late_gate: self.weight = self.opts.raw.weight[:] weight_t = torch.from_numpy(np.array(self.weight, dtype=np.float32)) self.aggregation_weight = Variable(weight_t,volatile=True).view(-1,1,1).cuda() print('='*10,'weight={}'.format(self.weight), '='*10)
3,629
38.89011
120
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/feedforward_classifier.py
import os import numpy as np import utils.util as util from collections import OrderedDict import torch from torch.autograd import Variable from .base_model import BaseModel from .networks import get_network from .layers.loss import * from .networks_other import get_scheduler, print_network, benchmark_fp_bp_time from .utils import classification_stats, get_optimizer, get_criterion from .networks.utils import HookBasedFeatureExtractor class FeedForwardClassifier(BaseModel): def name(self): return 'FeedForwardClassifier' def initialize(self, opts, **kwargs): BaseModel.initialize(self, opts, **kwargs) self.opts = opts self.isTrain = opts.isTrain # define network input and output pars self.input = None self.target = None self.labels = None self.tensor_dim = opts.tensor_dim # load/define networks self.net = get_network(opts.model_type, n_classes=opts.output_nc, in_channels=opts.input_nc, nonlocal_mode=opts.nonlocal_mode, tensor_dim=opts.tensor_dim, feature_scale=opts.feature_scale, attention_dsample=opts.attention_dsample, aggregation_mode=opts.aggregation_mode) if self.use_cuda: self.net = self.net.cuda() # load the model if a path is specified or it is in inference mode if not self.isTrain or opts.continue_train: self.path_pre_trained_model = opts.path_pre_trained_model if self.path_pre_trained_model: self.load_network_from_path(self.net, self.path_pre_trained_model, strict=False) self.which_epoch = int(0) else: self.which_epoch = opts.which_epoch self.load_network(self.net, 'S', self.which_epoch) # training objective if self.isTrain: self.criterion = get_criterion(opts) # initialize optimizers self.schedulers = [] self.optimizers = [] self.optimizer = get_optimizer(opts, self.net.parameters()) self.optimizers.append(self.optimizer) # print the network details if kwargs.get('verbose', True): print('Network is initialized') print_network(self.net) # for accumulator self.reset_results() def set_scheduler(self, train_opt): for optimizer in self.optimizers: self.schedulers.append(get_scheduler(optimizer, train_opt)) print('Scheduler is added for optimiser {0}'.format(optimizer)) def set_input(self, *inputs): # self.input.resize_(inputs[0].size()).copy_(inputs[0]) for idx, _input in enumerate(inputs): # If it's a 5D array and 2D model then (B x C x H x W x Z) -> (BZ x C x H x W) bs = _input.size() if (self.tensor_dim == '2D') and (len(bs) > 4): _input = _input.permute(0,4,1,2,3).contiguous().view(bs[0]*bs[4], bs[1], bs[2], bs[3]) # Define that it's a cuda array if idx == 0: self.input = _input.cuda() if self.use_cuda else _input elif idx == 1: self.target = Variable(_input.cuda()) if self.use_cuda else Variable(_input) assert self.input.shape[0] == self.target.shape[0] def forward(self, split): if split == 'train': self.prediction = self.net(Variable(self.input)) elif split in ['validation', 'test']: self.prediction = self.net(Variable(self.input, volatile=True)) # Apply a softmax and return a segmentation map self.logits = self.net.apply_argmax_softmax(self.prediction) self.pred = self.logits.data.max(1) def backward(self): #print(self.net.apply_argmax_softmax(self.prediction), self.target) self.loss = self.criterion(self.prediction, self.target) self.loss.backward() def optimize_parameters(self): self.net.train() self.forward(split='train') self.optimizer.zero_grad() self.backward() self.optimizer.step() def test(self): self.net.eval() self.forward(split='test') self.accumulate_results() def validate(self): self.net.eval() self.forward(split='test') self.loss = self.criterion(self.prediction, self.target) self.accumulate_results() def reset_results(self): self.losses = [] self.pr_lbls = [] self.pr_probs = [] self.gt_lbls = [] def accumulate_results(self): self.losses.append(self.loss.data[0]) self.pr_probs.append(self.pred[0].cpu().numpy()) self.pr_lbls.append(self.pred[1].cpu().numpy()) self.gt_lbls.append(self.target.data.cpu().numpy()) def get_classification_stats(self): self.pr_lbls = np.concatenate(self.pr_lbls) self.gt_lbls = np.concatenate(self.gt_lbls) res = classification_stats(self.pr_lbls, self.gt_lbls, self.labels) (self.accuracy, self.f1_micro, self.precision_micro, self.recall_micro, self.f1_macro, self.precision_macro, self.recall_macro, self.confusion, self.class_accuracies, self.f1s, self.precisions,self.recalls) = res breakdown = dict(type='table', colnames=['|accuracy|',' precison|',' recall|',' f1_score|'], rownames=self.labels, data=[self.class_accuracies, self.precisions,self.recalls, self.f1s]) return OrderedDict([('accuracy', self.accuracy), ('confusion', self.confusion), ('f1', self.f1_macro), ('precision', self.precision_macro), ('recall', self.recall_macro), ('confusion', self.confusion), ('breakdown', breakdown)]) def get_current_errors(self): return OrderedDict([('CE', self.loss.data[0])]) def get_accumulated_errors(self): return OrderedDict([('CE', np.mean(self.losses))]) def get_current_visuals(self): inp_img = util.tensor2im(self.input, 'img') return OrderedDict([('inp_S', inp_img)]) def get_feature_maps(self, layer_name, upscale): feature_extractor = HookBasedFeatureExtractor(self.net, layer_name, upscale) return feature_extractor.forward(Variable(self.input)) def save(self, epoch_label): self.save_network(self.net, 'S', epoch_label, self.gpu_ids) def set_labels(self, labels): self.labels = labels def load_network_from_path(self, network, network_filepath, strict): network_label = os.path.basename(network_filepath) epoch_label = network_label.split('_')[0] print('Loading the model {0} - epoch {1}'.format(network_label, epoch_label)) network.load_state_dict(torch.load(network_filepath), strict=strict) def update_state(self, epoch): pass def get_fp_bp_time2(self, size=None): # returns the fp/bp times of the model if size is None: size = (8, 1, 192, 192) inp_array = Variable(torch.rand(*size)).cuda() out_array = Variable(torch.rand(*size)).cuda() fp, bp = benchmark_fp_bp_time(self.net, inp_array, out_array) bsize = size[0] return fp/float(bsize), bp/float(bsize)
7,536
37.258883
102
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks_other.py
import torch import torch.nn as nn from torch.nn import init import functools from torch.autograd import Variable from torch.optim import lr_scheduler import time import numpy as np ############################################################################### # Functions ############################################################################### def weights_init_normal(m): classname = m.__class__.__name__ #print(classname) if classname.find('Conv') != -1: init.normal(m.weight.data, 0.0, 0.02) elif classname.find('Linear') != -1: init.normal(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: init.normal(m.weight.data, 1.0, 0.02) init.constant(m.bias.data, 0.0) def weights_init_xavier(m): classname = m.__class__.__name__ #print(classname) if classname.find('Conv') != -1: init.xavier_normal(m.weight.data, gain=1) elif classname.find('Linear') != -1: init.xavier_normal(m.weight.data, gain=1) elif classname.find('BatchNorm') != -1: init.normal(m.weight.data, 1.0, 0.02) init.constant(m.bias.data, 0.0) def weights_init_kaiming(m): classname = m.__class__.__name__ #print(classname) if classname.find('Conv') != -1: init.kaiming_normal(m.weight.data, a=0, mode='fan_in') elif classname.find('Linear') != -1: init.kaiming_normal(m.weight.data, a=0, mode='fan_in') elif classname.find('BatchNorm') != -1: init.normal(m.weight.data, 1.0, 0.02) init.constant(m.bias.data, 0.0) def weights_init_orthogonal(m): classname = m.__class__.__name__ #print(classname) if classname.find('Conv') != -1: init.orthogonal(m.weight.data, gain=1) elif classname.find('Linear') != -1: init.orthogonal(m.weight.data, gain=1) elif classname.find('BatchNorm') != -1: init.normal(m.weight.data, 1.0, 0.02) init.constant(m.bias.data, 0.0) def init_weights(net, init_type='normal'): #print('initialization method [%s]' % init_type) if init_type == 'normal': net.apply(weights_init_normal) elif init_type == 'xavier': net.apply(weights_init_xavier) elif init_type == 'kaiming': net.apply(weights_init_kaiming) elif init_type == 'orthogonal': net.apply(weights_init_orthogonal) else: raise NotImplementedError('initialization method [%s] is not implemented' % init_type) def get_norm_layer(norm_type='instance'): if norm_type == 'batch': norm_layer = functools.partial(nn.BatchNorm2d, affine=True) elif norm_type == 'instance': norm_layer = functools.partial(nn.InstanceNorm2d, affine=False) elif norm_type == 'none': norm_layer = None else: raise NotImplementedError('normalization layer [%s] is not found' % norm_type) return norm_layer def adjust_learning_rate(optimizer, lr): """Sets the learning rate to a fixed number""" for param_group in optimizer.param_groups: param_group['lr'] = lr def get_scheduler(optimizer, opt): print('opt.lr_policy = [{}]'.format(opt.lr_policy)) if opt.lr_policy == 'lambda': def lambda_rule(epoch): lr_l = 1.0 - max(0, epoch + 1 + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif opt.lr_policy == 'step': scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.5) elif opt.lr_policy == 'step2': scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1) elif opt.lr_policy == 'plateau': print('schedular=plateau') scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, threshold=0.01, patience=5) elif opt.lr_policy == 'plateau2': scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5) elif opt.lr_policy == 'step_warmstart': def lambda_rule(epoch): #print(epoch) if epoch < 5: lr_l = 0.1 elif 5 <= epoch < 100: lr_l = 1 elif 100 <= epoch < 200: lr_l = 0.1 elif 200 <= epoch: lr_l = 0.01 return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif opt.lr_policy == 'step_warmstart2': def lambda_rule(epoch): #print(epoch) if epoch < 5: lr_l = 0.1 elif 5 <= epoch < 50: lr_l = 1 elif 50 <= epoch < 100: lr_l = 0.1 elif 100 <= epoch: lr_l = 0.01 return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) else: return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy) return scheduler def define_G(input_nc, output_nc, ngf, which_model_netG, norm='batch', use_dropout=False, init_type='normal', gpu_ids=[]): netG = None use_gpu = len(gpu_ids) > 0 norm_layer = get_norm_layer(norm_type=norm) if use_gpu: assert(torch.cuda.is_available()) if which_model_netG == 'resnet_9blocks': netG = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9, gpu_ids=gpu_ids) elif which_model_netG == 'resnet_6blocks': netG = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6, gpu_ids=gpu_ids) elif which_model_netG == 'unet_128': netG = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout, gpu_ids=gpu_ids) elif which_model_netG == 'unet_256': netG = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout, gpu_ids=gpu_ids) else: raise NotImplementedError('Generator model name [%s] is not recognized' % which_model_netG) if len(gpu_ids) > 0: netG.cuda(gpu_ids[0]) init_weights(netG, init_type=init_type) return netG def define_D(input_nc, ndf, which_model_netD, n_layers_D=3, norm='batch', use_sigmoid=False, init_type='normal', gpu_ids=[]): netD = None use_gpu = len(gpu_ids) > 0 norm_layer = get_norm_layer(norm_type=norm) if use_gpu: assert(torch.cuda.is_available()) if which_model_netD == 'basic': netD = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer, use_sigmoid=use_sigmoid, gpu_ids=gpu_ids) elif which_model_netD == 'n_layers': netD = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer, use_sigmoid=use_sigmoid, gpu_ids=gpu_ids) else: raise NotImplementedError('Discriminator model name [%s] is not recognized' % which_model_netD) if use_gpu: netD.cuda(gpu_ids[0]) init_weights(netD, init_type=init_type) return netD def print_network(net): num_params = 0 for param in net.parameters(): num_params += param.numel() print(net) print('Total number of parameters: %d' % num_params) def get_n_parameters(net): num_params = 0 for param in net.parameters(): num_params += param.numel() return num_params def measure_fp_bp_time(model, x, y): # synchronize gpu time and measure fp torch.cuda.synchronize() t0 = time.time() y_pred = model(x) torch.cuda.synchronize() elapsed_fp = time.time() - t0 if isinstance(y_pred, tuple): y_pred = sum(y_p.sum() for y_p in y_pred) else: y_pred = y_pred.sum() # zero gradients, synchronize time and measure model.zero_grad() t0 = time.time() #y_pred.backward(y) y_pred.backward() torch.cuda.synchronize() elapsed_bp = time.time() - t0 return elapsed_fp, elapsed_bp def benchmark_fp_bp_time(model, x, y, n_trial=1000): # transfer the model on GPU model.cuda() # DRY RUNS for i in range(10): _, _ = measure_fp_bp_time(model, x, y) print('DONE WITH DRY RUNS, NOW BENCHMARKING') # START BENCHMARKING t_forward = [] t_backward = [] print('trial: {}'.format(n_trial)) for i in range(n_trial): t_fp, t_bp = measure_fp_bp_time(model, x, y) t_forward.append(t_fp) t_backward.append(t_bp) # free memory del model return np.mean(t_forward), np.mean(t_backward) ############################################################################## # Classes ############################################################################## # Defines the GAN loss which uses either LSGAN or the regular GAN. # When LSGAN is used, it is basically same as MSELoss, # but it abstracts away the need to create the target label tensor # that has the same size as the input class GANLoss(nn.Module): def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor): super(GANLoss, self).__init__() self.real_label = target_real_label self.fake_label = target_fake_label self.real_label_var = None self.fake_label_var = None self.Tensor = tensor if use_lsgan: self.loss = nn.MSELoss() else: self.loss = nn.BCELoss() def get_target_tensor(self, input, target_is_real): target_tensor = None if target_is_real: create_label = ((self.real_label_var is None) or (self.real_label_var.numel() != input.numel())) if create_label: real_tensor = self.Tensor(input.size()).fill_(self.real_label) self.real_label_var = Variable(real_tensor, requires_grad=False) target_tensor = self.real_label_var else: create_label = ((self.fake_label_var is None) or (self.fake_label_var.numel() != input.numel())) if create_label: fake_tensor = self.Tensor(input.size()).fill_(self.fake_label) self.fake_label_var = Variable(fake_tensor, requires_grad=False) target_tensor = self.fake_label_var return target_tensor def __call__(self, input, target_is_real): target_tensor = self.get_target_tensor(input, target_is_real) return self.loss(input, target_tensor) # Defines the generator that consists of Resnet blocks between a few # downsampling/upsampling operations. # Code and idea originally from Justin Johnson's architecture. # https://github.com/jcjohnson/fast-neural-style/ class ResnetGenerator(nn.Module): def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, gpu_ids=[], padding_type='reflect'): assert(n_blocks >= 0) super(ResnetGenerator, self).__init__() self.input_nc = input_nc self.output_nc = output_nc self.ngf = ngf self.gpu_ids = gpu_ids if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True)] n_downsampling = 2 for i in range(n_downsampling): mult = 2**i model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias), norm_layer(ngf * mult * 2), nn.ReLU(True)] mult = 2**n_downsampling for i in range(n_blocks): model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)] for i in range(n_downsampling): mult = 2**(n_downsampling - i) model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias), norm_layer(int(ngf * mult / 2)), nn.ReLU(True)] model += [nn.ReflectionPad2d(3)] model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] model += [nn.Tanh()] self.model = nn.Sequential(*model) def forward(self, input): if self.gpu_ids and isinstance(input.data, torch.cuda.FloatTensor): return nn.parallel.data_parallel(self.model, input, self.gpu_ids) else: return self.model(input) # Define a resnet block class ResnetBlock(nn.Module): def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias): super(ResnetBlock, self).__init__() self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias) def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias): conv_block = [] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)] if use_dropout: conv_block += [nn.Dropout(0.5)] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)] return nn.Sequential(*conv_block) def forward(self, x): out = x + self.conv_block(x) return out # Defines the Unet generator. # |num_downs|: number of downsamplings in UNet. For example, # if |num_downs| == 7, image of size 128x128 will become of size 1x1 # at the bottleneck class UnetGenerator(nn.Module): def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, gpu_ids=[]): super(UnetGenerator, self).__init__() self.gpu_ids = gpu_ids # construct unet structure unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) for i in range(num_downs - 5): unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout) unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) self.model = unet_block def forward(self, input): if self.gpu_ids and isinstance(input.data, torch.cuda.FloatTensor): return nn.parallel.data_parallel(self.model, input, self.gpu_ids) else: return self.model(input) # Defines the submodule with skip connection. # X -------------------identity---------------------- X # |-- downsampling -- |submodule| -- upsampling --| class UnetSkipConnectionBlock(nn.Module): def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): super(UnetSkipConnectionBlock, self).__init__() self.outermost = outermost if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d if input_nc is None: input_nc = outer_nc downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) downrelu = nn.LeakyReLU(0.2, True) downnorm = norm_layer(inner_nc) uprelu = nn.ReLU(True) upnorm = norm_layer(outer_nc) if outermost: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1) down = [downconv] up = [uprelu, upconv, nn.Tanh()] model = down + [submodule] + up elif innermost: upconv = nn.ConvTranspose2d(inner_nc, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv] up = [uprelu, upconv, upnorm] model = down + up else: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv, downnorm] up = [uprelu, upconv, upnorm] if use_dropout: model = down + [submodule] + up + [nn.Dropout(0.5)] else: model = down + [submodule] + up self.model = nn.Sequential(*model) def forward(self, x): if self.outermost: return self.model(x) else: return torch.cat([x, self.model(x)], 1) # Defines the PatchGAN discriminator with the specified arguments. class NLayerDiscriminator(nn.Module): def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False, gpu_ids=[]): super(NLayerDiscriminator, self).__init__() self.gpu_ids = gpu_ids if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d kw = 4 padw = 1 sequence = [ nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True) ] nf_mult = 1 nf_mult_prev = 1 for n in range(1, n_layers): nf_mult_prev = nf_mult nf_mult = min(2**n, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ] nf_mult_prev = nf_mult nf_mult = min(2**n_layers, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ] sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] if use_sigmoid: sequence += [nn.Sigmoid()] self.model = nn.Sequential(*sequence) def forward(self, input): if len(self.gpu_ids) and isinstance(input.data, torch.cuda.FloatTensor): return nn.parallel.data_parallel(self.model, input, self.gpu_ids) else: return self.model(input)
20,196
37.251894
151
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/feedforward_seg_model.py
import torch from torch.autograd import Variable import torch.optim as optim from collections import OrderedDict import utils.util as util from .base_model import BaseModel from .networks import get_network from .layers.loss import * from .networks_other import get_scheduler, print_network, benchmark_fp_bp_time from .utils import segmentation_stats, get_optimizer, get_criterion from .networks.utils import HookBasedFeatureExtractor class FeedForwardSegmentation(BaseModel): def name(self): return 'FeedForwardSegmentation' def initialize(self, opts, **kwargs): BaseModel.initialize(self, opts, **kwargs) self.isTrain = opts.isTrain # define network input and output pars self.input = None self.target = None self.tensor_dim = opts.tensor_dim # load/define networks self.net = get_network(opts.model_type, n_classes=opts.output_nc, in_channels=opts.input_nc, nonlocal_mode=opts.nonlocal_mode, tensor_dim=opts.tensor_dim, feature_scale=opts.feature_scale, attention_dsample=opts.attention_dsample) if self.use_cuda: self.net = self.net.cuda() # load the model if a path is specified or it is in inference mode if not self.isTrain or opts.continue_train: self.path_pre_trained_model = opts.path_pre_trained_model if self.path_pre_trained_model: self.load_network_from_path(self.net, self.path_pre_trained_model, strict=False) self.which_epoch = int(0) else: self.which_epoch = opts.which_epoch self.load_network(self.net, 'S', self.which_epoch) # training objective if self.isTrain: self.criterion = get_criterion(opts) # initialize optimizers self.schedulers = [] self.optimizers = [] self.optimizer_S = get_optimizer(opts, self.net.parameters()) self.optimizers.append(self.optimizer_S) # print the network details # print the network details if kwargs.get('verbose', True): print('Network is initialized') print_network(self.net) def set_scheduler(self, train_opt): for optimizer in self.optimizers: self.schedulers.append(get_scheduler(optimizer, train_opt)) print('Scheduler is added for optimiser {0}'.format(optimizer)) def set_input(self, *inputs): # self.input.resize_(inputs[0].size()).copy_(inputs[0]) for idx, _input in enumerate(inputs): # If it's a 5D array and 2D model then (B x C x H x W x Z) -> (BZ x C x H x W) bs = _input.size() if (self.tensor_dim == '2D') and (len(bs) > 4): _input = _input.permute(0,4,1,2,3).contiguous().view(bs[0]*bs[4], bs[1], bs[2], bs[3]) # Define that it's a cuda array if idx == 0: self.input = _input.cuda() if self.use_cuda else _input elif idx == 1: self.target = Variable(_input.cuda()) if self.use_cuda else Variable(_input) assert self.input.size() == self.target.size() def forward(self, split): if split == 'train': self.prediction = self.net(Variable(self.input)) elif split == 'test': self.prediction = self.net(Variable(self.input, volatile=True)) # Apply a softmax and return a segmentation map self.logits = self.net.apply_argmax_softmax(self.prediction) self.pred_seg = self.logits.data.max(1)[1].unsqueeze(1) def backward(self): self.loss_S = self.criterion(self.prediction, self.target) self.loss_S.backward() def optimize_parameters(self): self.net.train() self.forward(split='train') self.optimizer_S.zero_grad() self.backward() self.optimizer_S.step() # This function updates the network parameters every "accumulate_iters" def optimize_parameters_accumulate_grd(self, iteration): accumulate_iters = int(2) if iteration == 0: self.optimizer_S.zero_grad() self.net.train() self.forward(split='train') self.backward() if iteration % accumulate_iters == 0: self.optimizer_S.step() self.optimizer_S.zero_grad() def test(self): self.net.eval() self.forward(split='test') def validate(self): self.net.eval() self.forward(split='test') self.loss_S = self.criterion(self.prediction, self.target) def get_segmentation_stats(self): self.seg_scores, self.dice_score = segmentation_stats(self.prediction, self.target) seg_stats = [('Overall_Acc', self.seg_scores['overall_acc']), ('Mean_IOU', self.seg_scores['mean_iou'])] for class_id in range(self.dice_score.size): seg_stats.append(('Class_{}'.format(class_id), self.dice_score[class_id])) return OrderedDict(seg_stats) def get_current_errors(self): return OrderedDict([('Seg_Loss', self.loss_S.data[0]) ]) def get_current_visuals(self): inp_img = util.tensor2im(self.input, 'img') seg_img = util.tensor2im(self.pred_seg, 'lbl') return OrderedDict([('out_S', seg_img), ('inp_S', inp_img)]) def get_feature_maps(self, layer_name, upscale): feature_extractor = HookBasedFeatureExtractor(self.net, layer_name, upscale) return feature_extractor.forward(Variable(self.input)) # returns the fp/bp times of the model def get_fp_bp_time (self, size=None): if size is None: size = (1, 1, 160, 160, 96) inp_array = Variable(torch.zeros(*size)).cuda() out_array = Variable(torch.zeros(*size)).cuda() fp, bp = benchmark_fp_bp_time(self.net, inp_array, out_array) bsize = size[0] return fp/float(bsize), bp/float(bsize) def save(self, epoch_label): self.save_network(self.net, 'S', epoch_label, self.gpu_ids)
6,177
38.350318
112
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/unet_nonlocal_2D.py
import math import torch.nn as nn from .utils import unetConv2, unetUp from models.layers.nonlocal_layer import NONLocalBlock2D import torch.nn.functional as F class unet_nonlocal_2D(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, is_batchnorm=True, nonlocal_mode='embedded_gaussian', nonlocal_sf=4): super(unet_nonlocal_2D, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale filters = [64, 128, 256, 512, 1024] filters = [int(x / self.feature_scale) for x in filters] # downsampling self.conv1 = unetConv2(self.in_channels, filters[0], self.is_batchnorm) self.maxpool1 = nn.MaxPool2d(kernel_size=2) self.nonlocal1 = NONLocalBlock2D(in_channels=filters[0], inter_channels=filters[0] // 4, sub_sample_factor=nonlocal_sf, mode=nonlocal_mode) self.conv2 = unetConv2(filters[0], filters[1], self.is_batchnorm) self.maxpool2 = nn.MaxPool2d(kernel_size=2) self.nonlocal2 = NONLocalBlock2D(in_channels=filters[1], inter_channels=filters[1] // 4, sub_sample_factor=nonlocal_sf, mode=nonlocal_mode) self.conv3 = unetConv2(filters[1], filters[2], self.is_batchnorm) self.maxpool3 = nn.MaxPool2d(kernel_size=2) self.conv4 = unetConv2(filters[2], filters[3], self.is_batchnorm) self.maxpool4 = nn.MaxPool2d(kernel_size=2) self.center = unetConv2(filters[3], filters[4], self.is_batchnorm) # upsampling self.up_concat4 = unetUp(filters[4], filters[3], self.is_deconv) self.up_concat3 = unetUp(filters[3], filters[2], self.is_deconv) self.up_concat2 = unetUp(filters[2], filters[1], self.is_deconv) self.up_concat1 = unetUp(filters[1], filters[0], self.is_deconv) # final conv (without any concat) self.final = nn.Conv2d(filters[0], n_classes, 1) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def forward(self, inputs): conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) nonlocal1 = self.nonlocal1(maxpool1) conv2 = self.conv2(nonlocal1) maxpool2 = self.maxpool2(conv2) nonlocal2 = self.nonlocal2(maxpool2) conv3 = self.conv3(nonlocal2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) center = self.center(maxpool4) up4 = self.up_concat4(conv4, center) up3 = self.up_concat3(conv3, up4) up2 = self.up_concat2(conv2, up3) up1 = self.up_concat1(conv1, up2) final = self.final(up1) return final @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p
3,267
36.136364
96
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/sononet.py
import numpy as np import math import torch.nn as nn from .utils import unetConv2, unetUp, conv2DBatchNormRelu, conv2DBatchNorm import torch.nn.functional as F from models.networks_other import init_weights class sononet(nn.Module): def __init__(self, feature_scale=4, n_classes=21, in_channels=3, is_batchnorm=True, n_convs=None): super(sononet, self).__init__() self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale self.n_classes= n_classes filters = [64, 128, 256, 512] filters = [int(x / self.feature_scale) for x in filters] if n_convs is None: n_convs = [2,2,3,3,3] # downsampling self.conv1 = unetConv2(self.in_channels, filters[0], self.is_batchnorm, n=n_convs[0]) self.maxpool1 = nn.MaxPool2d(kernel_size=2) self.conv2 = unetConv2(filters[0], filters[1], self.is_batchnorm, n=n_convs[1]) self.maxpool2 = nn.MaxPool2d(kernel_size=2) self.conv3 = unetConv2(filters[1], filters[2], self.is_batchnorm, n=n_convs[2]) self.maxpool3 = nn.MaxPool2d(kernel_size=2) self.conv4 = unetConv2(filters[2], filters[3], self.is_batchnorm, n=n_convs[3]) self.maxpool4 = nn.MaxPool2d(kernel_size=2) self.conv5 = unetConv2(filters[3], filters[3], self.is_batchnorm, n=n_convs[4]) # adaptation layer self.conv5_p = conv2DBatchNormRelu(filters[3], filters[2], 1, 1, 0) self.conv6_p = conv2DBatchNorm(filters[2], self.n_classes, 1, 1, 0) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv2d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm2d): init_weights(m, init_type='kaiming') def forward(self, inputs): # Feature Extraction conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) maxpool2 = self.maxpool2(conv2) conv3 = self.conv3(maxpool2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) conv5 = self.conv5(maxpool4) conv5_p = self.conv5_p(conv5) conv6_p = self.conv6_p(conv5_p) batch_size = inputs.shape[0] pooled = F.adaptive_avg_pool2d(conv6_p, (1, 1)).view(batch_size, -1) return pooled @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p def sononet2(feature_scale=4, n_classes=21, in_channels=3, is_batchnorm=True): return sononet(feature_scale, n_classes, in_channels, is_batchnorm, n_convs=[3,3,3,2,2])
2,761
31.494118
102
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/unet_2D.py
import math import torch.nn as nn from .utils import unetConv2, unetUp import torch.nn.functional as F from models.networks_other import init_weights class unet_2D(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, is_batchnorm=True): super(unet_2D, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale filters = [64, 128, 256, 512, 1024] filters = [int(x / self.feature_scale) for x in filters] # downsampling self.conv1 = unetConv2(self.in_channels, filters[0], self.is_batchnorm) self.maxpool1 = nn.MaxPool2d(kernel_size=2) self.conv2 = unetConv2(filters[0], filters[1], self.is_batchnorm) self.maxpool2 = nn.MaxPool2d(kernel_size=2) self.conv3 = unetConv2(filters[1], filters[2], self.is_batchnorm) self.maxpool3 = nn.MaxPool2d(kernel_size=2) self.conv4 = unetConv2(filters[2], filters[3], self.is_batchnorm) self.maxpool4 = nn.MaxPool2d(kernel_size=2) self.center = unetConv2(filters[3], filters[4], self.is_batchnorm) # upsampling self.up_concat4 = unetUp(filters[4], filters[3], self.is_deconv) self.up_concat3 = unetUp(filters[3], filters[2], self.is_deconv) self.up_concat2 = unetUp(filters[2], filters[1], self.is_deconv) self.up_concat1 = unetUp(filters[1], filters[0], self.is_deconv) # final conv (without any concat) self.final = nn.Conv2d(filters[0], n_classes, 1) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv2d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm2d): init_weights(m, init_type='kaiming') def forward(self, inputs): conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) maxpool2 = self.maxpool2(conv2) conv3 = self.conv3(maxpool2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) center = self.center(maxpool4) up4 = self.up_concat4(conv4, center) up3 = self.up_concat3(conv3, up4) up2 = self.up_concat2(conv2, up3) up1 = self.up_concat1(conv1, up2) final = self.final(up1) return final @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p
2,613
27.413043
104
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/utils.py
import torch import torch.nn as nn import torch.nn.functional as F from models.networks_other import init_weights class conv2DBatchNorm(nn.Module): def __init__(self, in_channels, n_filters, k_size, stride, padding, bias=True): super(conv2DBatchNorm, self).__init__() self.cb_unit = nn.Sequential(nn.Conv2d(int(in_channels), int(n_filters), kernel_size=k_size, padding=padding, stride=stride, bias=bias), nn.BatchNorm2d(int(n_filters)),) def forward(self, inputs): outputs = self.cb_unit(inputs) return outputs class deconv2DBatchNorm(nn.Module): def __init__(self, in_channels, n_filters, k_size, stride, padding, bias=True): super(deconv2DBatchNorm, self).__init__() self.dcb_unit = nn.Sequential(nn.ConvTranspose2d(int(in_channels), int(n_filters), kernel_size=k_size, padding=padding, stride=stride, bias=bias), nn.BatchNorm2d(int(n_filters)),) def forward(self, inputs): outputs = self.dcb_unit(inputs) return outputs class conv2DBatchNormRelu(nn.Module): def __init__(self, in_channels, n_filters, k_size, stride, padding, bias=True): super(conv2DBatchNormRelu, self).__init__() self.cbr_unit = nn.Sequential(nn.Conv2d(int(in_channels), int(n_filters), kernel_size=k_size, padding=padding, stride=stride, bias=bias), nn.BatchNorm2d(int(n_filters)), nn.ReLU(inplace=True),) def forward(self, inputs): outputs = self.cbr_unit(inputs) return outputs class deconv2DBatchNormRelu(nn.Module): def __init__(self, in_channels, n_filters, k_size, stride, padding, bias=True): super(deconv2DBatchNormRelu, self).__init__() self.dcbr_unit = nn.Sequential(nn.ConvTranspose2d(int(in_channels), int(n_filters), kernel_size=k_size, padding=padding, stride=stride, bias=bias), nn.BatchNorm2d(int(n_filters)), nn.ReLU(inplace=True),) def forward(self, inputs): outputs = self.dcbr_unit(inputs) return outputs class unetConv2(nn.Module): def __init__(self, in_size, out_size, is_batchnorm, n=2, ks=3, stride=1, padding=1): super(unetConv2, self).__init__() self.n = n self.ks = ks self.stride = stride self.padding = padding s = stride p = padding if is_batchnorm: for i in range(1, n+1): conv = nn.Sequential(nn.Conv2d(in_size, out_size, ks, s, p), nn.BatchNorm2d(out_size), nn.ReLU(inplace=True),) setattr(self, 'conv%d'%i, conv) in_size = out_size else: for i in range(1, n+1): conv = nn.Sequential(nn.Conv2d(in_size, out_size, ks, s, p), nn.ReLU(inplace=True),) setattr(self, 'conv%d'%i, conv) in_size = out_size # initialise the blocks for m in self.children(): init_weights(m, init_type='kaiming') def forward(self, inputs): x = inputs for i in range(1, self.n+1): conv = getattr(self, 'conv%d'%i) x = conv(x) return x class UnetConv3(nn.Module): def __init__(self, in_size, out_size, is_batchnorm, kernel_size=(3,3,1), padding_size=(1,1,0), init_stride=(1,1,1)): super(UnetConv3, self).__init__() if is_batchnorm: self.conv1 = nn.Sequential(nn.Conv3d(in_size, out_size, kernel_size, init_stride, padding_size), nn.BatchNorm3d(out_size), nn.ReLU(inplace=True),) self.conv2 = nn.Sequential(nn.Conv3d(out_size, out_size, kernel_size, 1, padding_size), nn.BatchNorm3d(out_size), nn.ReLU(inplace=True),) else: self.conv1 = nn.Sequential(nn.Conv3d(in_size, out_size, kernel_size, init_stride, padding_size), nn.ReLU(inplace=True),) self.conv2 = nn.Sequential(nn.Conv3d(out_size, out_size, kernel_size, 1, padding_size), nn.ReLU(inplace=True),) # initialise the blocks for m in self.children(): init_weights(m, init_type='kaiming') def forward(self, inputs): outputs = self.conv1(inputs) outputs = self.conv2(outputs) return outputs class FCNConv3(nn.Module): def __init__(self, in_size, out_size, is_batchnorm, kernel_size=(3,3,1), padding_size=(1,1,0), init_stride=(1,1,1)): super(FCNConv3, self).__init__() if is_batchnorm: self.conv1 = nn.Sequential(nn.Conv3d(in_size, out_size, kernel_size, init_stride, padding_size), nn.BatchNorm3d(out_size), nn.ReLU(inplace=True),) self.conv2 = nn.Sequential(nn.Conv3d(out_size, out_size, kernel_size, 1, padding_size), nn.BatchNorm3d(out_size), nn.ReLU(inplace=True),) self.conv3 = nn.Sequential(nn.Conv3d(out_size, out_size, kernel_size, 1, padding_size), nn.BatchNorm3d(out_size), nn.ReLU(inplace=True),) else: self.conv1 = nn.Sequential(nn.Conv3d(in_size, out_size, kernel_size, init_stride, padding_size), nn.ReLU(inplace=True),) self.conv2 = nn.Sequential(nn.Conv3d(out_size, out_size, kernel_size, 1, padding_size), nn.ReLU(inplace=True),) self.conv3 = nn.Sequential(nn.Conv3d(out_size, out_size, kernel_size, 1, padding_size), nn.ReLU(inplace=True),) # initialise the blocks for m in self.children(): init_weights(m, init_type='kaiming') def forward(self, inputs): outputs = self.conv1(inputs) outputs = self.conv2(outputs) outputs = self.conv3(outputs) return outputs class UnetGatingSignal3(nn.Module): def __init__(self, in_size, out_size, is_batchnorm): super(UnetGatingSignal3, self).__init__() self.fmap_size = (4, 4, 4) if is_batchnorm: self.conv1 = nn.Sequential(nn.Conv3d(in_size, in_size//2, (1,1,1), (1,1,1), (0,0,0)), nn.BatchNorm3d(in_size//2), nn.ReLU(inplace=True), nn.AdaptiveAvgPool3d(output_size=self.fmap_size), ) self.fc1 = nn.Linear(in_features=(in_size//2) * self.fmap_size[0] * self.fmap_size[1] * self.fmap_size[2], out_features=out_size, bias=True) else: self.conv1 = nn.Sequential(nn.Conv3d(in_size, in_size//2, (1,1,1), (1,1,1), (0,0,0)), nn.ReLU(inplace=True), nn.AdaptiveAvgPool3d(output_size=self.fmap_size), ) self.fc1 = nn.Linear(in_features=(in_size//2) * self.fmap_size[0] * self.fmap_size[1] * self.fmap_size[2], out_features=out_size, bias=True) # initialise the blocks for m in self.children(): init_weights(m, init_type='kaiming') def forward(self, inputs): batch_size = inputs.size(0) outputs = self.conv1(inputs) outputs = outputs.view(batch_size, -1) outputs = self.fc1(outputs) return outputs class UnetGridGatingSignal3(nn.Module): def __init__(self, in_size, out_size, kernel_size=(1,1,1), is_batchnorm=True): super(UnetGridGatingSignal3, self).__init__() if is_batchnorm: self.conv1 = nn.Sequential(nn.Conv3d(in_size, out_size, kernel_size, (1,1,1), (0,0,0)), nn.BatchNorm3d(out_size), nn.ReLU(inplace=True), ) else: self.conv1 = nn.Sequential(nn.Conv3d(in_size, out_size, kernel_size, (1,1,1), (0,0,0)), nn.ReLU(inplace=True), ) # initialise the blocks for m in self.children(): init_weights(m, init_type='kaiming') def forward(self, inputs): outputs = self.conv1(inputs) return outputs class unetUp(nn.Module): def __init__(self, in_size, out_size, is_deconv): super(unetUp, self).__init__() self.conv = unetConv2(in_size, out_size, False) if is_deconv: self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=4, stride=2, padding=1) else: self.up = nn.UpsamplingBilinear2d(scale_factor=2) # initialise the blocks for m in self.children(): if m.__class__.__name__.find('unetConv2') != -1: continue init_weights(m, init_type='kaiming') def forward(self, inputs1, inputs2): outputs2 = self.up(inputs2) offset = outputs2.size()[2] - inputs1.size()[2] padding = 2 * [offset // 2, offset // 2] outputs1 = F.pad(inputs1, padding) return self.conv(torch.cat([outputs1, outputs2], 1)) class UnetUp3(nn.Module): def __init__(self, in_size, out_size, is_deconv, is_batchnorm=True): super(UnetUp3, self).__init__() if is_deconv: self.conv = UnetConv3(in_size, out_size, is_batchnorm) self.up = nn.ConvTranspose3d(in_size, out_size, kernel_size=(4,4,1), stride=(2,2,1), padding=(1,1,0)) else: self.conv = UnetConv3(in_size+out_size, out_size, is_batchnorm) self.up = nn.Upsample(scale_factor=(2, 2, 1), mode='trilinear') # initialise the blocks for m in self.children(): if m.__class__.__name__.find('UnetConv3') != -1: continue init_weights(m, init_type='kaiming') def forward(self, inputs1, inputs2): outputs2 = self.up(inputs2) offset = outputs2.size()[2] - inputs1.size()[2] padding = 2 * [offset // 2, offset // 2, 0] outputs1 = F.pad(inputs1, padding) return self.conv(torch.cat([outputs1, outputs2], 1)) class UnetUp3_CT(nn.Module): def __init__(self, in_size, out_size, is_batchnorm=True): super(UnetUp3_CT, self).__init__() self.conv = UnetConv3(in_size + out_size, out_size, is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.up = nn.Upsample(scale_factor=(2, 2, 2), mode='trilinear') # initialise the blocks for m in self.children(): if m.__class__.__name__.find('UnetConv3') != -1: continue init_weights(m, init_type='kaiming') def forward(self, inputs1, inputs2): outputs2 = self.up(inputs2) offset = outputs2.size()[2] - inputs1.size()[2] padding = 2 * [offset // 2, offset // 2, 0] outputs1 = F.pad(inputs1, padding) return self.conv(torch.cat([outputs1, outputs2], 1)) # Squeeze-and-Excitation Network class SqEx(nn.Module): def __init__(self, n_features, reduction=6): super(SqEx, self).__init__() if n_features % reduction != 0: raise ValueError('n_features must be divisible by reduction (default = 4)') self.linear1 = nn.Linear(n_features, n_features // reduction, bias=False) self.nonlin1 = nn.ReLU(inplace=True) self.linear2 = nn.Linear(n_features // reduction, n_features, bias=False) self.nonlin2 = nn.Sigmoid() def forward(self, x): y = F.avg_pool3d(x, kernel_size=x.size()[2:5]) y = y.permute(0, 2, 3, 4, 1) y = self.nonlin1(self.linear1(y)) y = self.nonlin2(self.linear2(y)) y = y.permute(0, 4, 1, 2, 3) y = x * y return y class UnetUp3_SqEx(nn.Module): def __init__(self, in_size, out_size, is_deconv, is_batchnorm): super(UnetUp3_SqEx, self).__init__() if is_deconv: self.sqex = SqEx(n_features=in_size+out_size) self.conv = UnetConv3(in_size, out_size, is_batchnorm) self.up = nn.ConvTranspose3d(in_size, out_size, kernel_size=(4,4,1), stride=(2,2,1), padding=(1,1,0)) else: self.sqex = SqEx(n_features=in_size+out_size) self.conv = UnetConv3(in_size+out_size, out_size, is_batchnorm) self.up = nn.Upsample(scale_factor=(2, 2, 1), mode='trilinear') # initialise the blocks for m in self.children(): if m.__class__.__name__.find('UnetConv3') != -1: continue init_weights(m, init_type='kaiming') def forward(self, inputs1, inputs2): outputs2 = self.up(inputs2) offset = outputs2.size()[2] - inputs1.size()[2] padding = 2 * [offset // 2, offset // 2, 0] outputs1 = F.pad(inputs1, padding) concat = torch.cat([outputs1, outputs2], 1) gated = self.sqex(concat) return self.conv(gated) class residualBlock(nn.Module): expansion = 1 def __init__(self, in_channels, n_filters, stride=1, downsample=None): super(residualBlock, self).__init__() self.convbnrelu1 = conv2DBatchNormRelu(in_channels, n_filters, 3, stride, 1, bias=False) self.convbn2 = conv2DBatchNorm(n_filters, n_filters, 3, 1, 1, bias=False) self.downsample = downsample self.stride = stride self.relu = nn.ReLU(inplace=True) def forward(self, x): residual = x out = self.convbnrelu1(x) out = self.convbn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class residualBottleneck(nn.Module): expansion = 4 def __init__(self, in_channels, n_filters, stride=1, downsample=None): super(residualBottleneck, self).__init__() self.convbn1 = nn.Conv2DBatchNorm(in_channels, n_filters, k_size=1, bias=False) self.convbn2 = nn.Conv2DBatchNorm(n_filters, n_filters, k_size=3, padding=1, stride=stride, bias=False) self.convbn3 = nn.Conv2DBatchNorm(n_filters, n_filters * 4, k_size=1, bias=False) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.convbn1(x) out = self.convbn2(out) out = self.convbn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class SeqModelFeatureExtractor(nn.Module): def __init__(self, submodule, extracted_layers): super(SeqModelFeatureExtractor, self).__init__() self.submodule = submodule self.extracted_layers = extracted_layers def forward(self, x): outputs = [] for name, module in self.submodule._modules.items(): x = module(x) if name in self.extracted_layers: outputs += [x] return outputs + [x] class HookBasedFeatureExtractor(nn.Module): def __init__(self, submodule, layername, upscale=False): super(HookBasedFeatureExtractor, self).__init__() self.submodule = submodule self.submodule.eval() self.layername = layername self.outputs_size = None self.outputs = None self.inputs = None self.inputs_size = None self.upscale = upscale def get_input_array(self, m, i, o): if isinstance(i, tuple): self.inputs = [i[index].data.clone() for index in range(len(i))] self.inputs_size = [input.size() for input in self.inputs] else: self.inputs = i.data.clone() self.inputs_size = self.input.size() print('Input Array Size: ', self.inputs_size) def get_output_array(self, m, i, o): if isinstance(o, tuple): self.outputs = [o[index].data.clone() for index in range(len(o))] self.outputs_size = [output.size() for output in self.outputs] else: self.outputs = o.data.clone() self.outputs_size = self.outputs.size() print('Output Array Size: ', self.outputs_size) def rescale_output_array(self, newsize): us = nn.Upsample(size=newsize[2:], mode='bilinear') if isinstance(self.outputs, list): for index in range(len(self.outputs)): self.outputs[index] = us(self.outputs[index]).data() else: self.outputs = us(self.outputs).data() def forward(self, x): target_layer = self.submodule._modules.get(self.layername) # Collect the output tensor h_inp = target_layer.register_forward_hook(self.get_input_array) h_out = target_layer.register_forward_hook(self.get_output_array) self.submodule(x) h_inp.remove() h_out.remove() # Rescale the feature-map if it's required if self.upscale: self.rescale_output_array(x.size()) return self.inputs, self.outputs class UnetDsv3(nn.Module): def __init__(self, in_size, out_size, scale_factor): super(UnetDsv3, self).__init__() self.dsv = nn.Sequential(nn.Conv3d(in_size, out_size, kernel_size=1, stride=1, padding=0), nn.Upsample(scale_factor=scale_factor, mode='trilinear'), ) def forward(self, input): return self.dsv(input)
18,106
38.192641
120
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/unet_nonlocal_3D.py
import math import torch.nn as nn from .utils import UnetConv3, UnetUp3 import torch.nn.functional as F from models.layers.nonlocal_layer import NONLocalBlock3D from models.networks_other import init_weights class unet_nonlocal_3D(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, is_batchnorm=True, nonlocal_mode='embedded_gaussian', nonlocal_sf=4): super(unet_nonlocal_3D, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale filters = [64, 128, 256, 512, 1024] filters = [int(x / self.feature_scale) for x in filters] # downsampling self.conv1 = UnetConv3(self.in_channels, filters[0], self.is_batchnorm) self.maxpool1 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv2 = UnetConv3(filters[0], filters[1], self.is_batchnorm) self.nonlocal2 = NONLocalBlock3D(in_channels=filters[1], inter_channels=filters[1] // 4, sub_sample_factor=nonlocal_sf, mode=nonlocal_mode) self.maxpool2 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv3 = UnetConv3(filters[1], filters[2], self.is_batchnorm) self.nonlocal3 = NONLocalBlock3D(in_channels=filters[2], inter_channels=filters[2] // 4, sub_sample_factor=nonlocal_sf, mode=nonlocal_mode) self.maxpool3 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv4 = UnetConv3(filters[2], filters[3], self.is_batchnorm) self.maxpool4 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.center = UnetConv3(filters[3], filters[4], self.is_batchnorm) # upsampling self.up_concat4 = UnetUp3(filters[4], filters[3], self.is_deconv) self.up_concat3 = UnetUp3(filters[3], filters[2], self.is_deconv) self.up_concat2 = UnetUp3(filters[2], filters[1], self.is_deconv) self.up_concat1 = UnetUp3(filters[1], filters[0], self.is_deconv) # final conv (without any concat) self.final = nn.Conv3d(filters[0], n_classes, 1) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv3d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm3d): init_weights(m, init_type='kaiming') def forward(self, inputs): conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) nl2 = self.nonlocal2(conv2) maxpool2 = self.maxpool2(nl2) conv3 = self.conv3(maxpool2) nl3 = self.nonlocal3(conv3) maxpool3 = self.maxpool3(nl3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) center = self.center(maxpool4) up4 = self.up_concat4(conv4, center) up3 = self.up_concat3(nl3, up4) up2 = self.up_concat2(nl2, up3) up1 = self.up_concat1(conv1, up2) final = self.final(up1) return final @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p
3,237
31.707071
103
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/sononet_grid_attention.py
import numpy as np import math import torch.nn as nn from .utils import unetConv2, unetUp, conv2DBatchNormRelu, conv2DBatchNorm import torch import torch.nn.functional as F from models.layers.grid_attention_layer import GridAttentionBlock2D_TORR as AttentionBlock2D from models.networks_other import init_weights class sononet_grid_attention(nn.Module): def __init__(self, feature_scale=4, n_classes=21, in_channels=3, is_batchnorm=True, n_convs=None, nonlocal_mode='concatenation', aggregation_mode='concat'): super(sononet_grid_attention, self).__init__() self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale self.n_classes= n_classes self.aggregation_mode = aggregation_mode self.deep_supervised = True if n_convs is None: n_convs = [3, 3, 3, 2, 2] filters = [64, 128, 256, 512] filters = [int(x / self.feature_scale) for x in filters] #################### # Feature Extraction self.conv1 = unetConv2(self.in_channels, filters[0], self.is_batchnorm, n=n_convs[0]) self.maxpool1 = nn.MaxPool2d(kernel_size=2) self.conv2 = unetConv2(filters[0], filters[1], self.is_batchnorm, n=n_convs[1]) self.maxpool2 = nn.MaxPool2d(kernel_size=2) self.conv3 = unetConv2(filters[1], filters[2], self.is_batchnorm, n=n_convs[2]) self.maxpool3 = nn.MaxPool2d(kernel_size=2) self.conv4 = unetConv2(filters[2], filters[3], self.is_batchnorm, n=n_convs[3]) self.maxpool4 = nn.MaxPool2d(kernel_size=2) self.conv5 = unetConv2(filters[3], filters[3], self.is_batchnorm, n=n_convs[4]) ################ # Attention Maps self.compatibility_score1 = AttentionBlock2D(in_channels=filters[2], gating_channels=filters[3], inter_channels=filters[3], sub_sample_factor=(1,1), mode=nonlocal_mode, use_W=False, use_phi=True, use_theta=True, use_psi=True, nonlinearity1='relu') self.compatibility_score2 = AttentionBlock2D(in_channels=filters[3], gating_channels=filters[3], inter_channels=filters[3], sub_sample_factor=(1,1), mode=nonlocal_mode, use_W=False, use_phi=True, use_theta=True, use_psi=True, nonlinearity1='relu') ######################### # Aggreagation Strategies self.attention_filter_sizes = [filters[2], filters[3]] if aggregation_mode == 'concat': self.classifier = nn.Linear(filters[2]+filters[3]+filters[3], n_classes) self.aggregate = self.aggreagation_concat else: self.classifier1 = nn.Linear(filters[2], n_classes) self.classifier2 = nn.Linear(filters[3], n_classes) self.classifier3 = nn.Linear(filters[3], n_classes) self.classifiers = [self.classifier1, self.classifier2, self.classifier3] if aggregation_mode == 'mean': self.aggregate = self.aggregation_sep elif aggregation_mode == 'deep_sup': self.classifier = nn.Linear(filters[2] + filters[3] + filters[3], n_classes) self.aggregate = self.aggregation_ds elif aggregation_mode == 'ft': self.classifier = nn.Linear(n_classes*3, n_classes) self.aggregate = self.aggregation_ft else: raise NotImplementedError #################### # initialise weights for m in self.modules(): if isinstance(m, nn.Conv2d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm2d): init_weights(m, init_type='kaiming') def aggregation_sep(self, *attended_maps): return [ clf(att) for clf, att in zip(self.classifiers, attended_maps) ] def aggregation_ft(self, *attended_maps): preds = self.aggregation_sep(*attended_maps) return self.classifier(torch.cat(preds, dim=1)) def aggregation_ds(self, *attended_maps): preds_sep = self.aggregation_sep(*attended_maps) pred = self.aggregation_concat(*attended_maps) return [pred] + preds_sep def aggregation_concat(self, *attended_maps): return self.classifier(torch.cat(attended_maps, dim=1)) def forward(self, inputs): # Feature Extraction conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) maxpool2 = self.maxpool2(conv2) conv3 = self.conv3(maxpool2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) conv5 = self.conv5(maxpool4) batch_size = inputs.shape[0] pooled = F.adaptive_avg_pool2d(conv5, (1, 1)).view(batch_size, -1) # Attention Mechanism g_conv1, att1 = self.compatibility_score1(conv3, conv5) g_conv2, att2 = self.compatibility_score2(conv4, conv5) # flatten to get single feature vector fsizes = self.attention_filter_sizes g1 = torch.sum(g_conv1.view(batch_size, fsizes[0], -1), dim=-1) g2 = torch.sum(g_conv2.view(batch_size, fsizes[1], -1), dim=-1) return self.aggregate(g1, g2, pooled) @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p
5,710
38.659722
104
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/unet_CT_dsv_3D.py
import torch.nn as nn from .utils import UnetConv3, UnetUp3_CT, UnetDsv3 import torch.nn.functional as F from models.networks_other import init_weights import torch class unet_CT_dsv_3D(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, is_batchnorm=True): super(unet_CT_dsv_3D, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale filters = [64, 128, 256, 512, 1024] filters = [int(x / self.feature_scale) for x in filters] # downsampling self.conv1 = UnetConv3(self.in_channels, filters[0], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool1 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv2 = UnetConv3(filters[0], filters[1], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool2 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv3 = UnetConv3(filters[1], filters[2], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool3 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv4 = UnetConv3(filters[2], filters[3], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool4 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.center = UnetConv3(filters[3], filters[4], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) # upsampling self.up_concat4 = UnetUp3_CT(filters[4], filters[3], is_batchnorm) self.up_concat3 = UnetUp3_CT(filters[3], filters[2], is_batchnorm) self.up_concat2 = UnetUp3_CT(filters[2], filters[1], is_batchnorm) self.up_concat1 = UnetUp3_CT(filters[1], filters[0], is_batchnorm) # deep supervision self.dsv4 = UnetDsv3(in_size=filters[3], out_size=n_classes, scale_factor=8) self.dsv3 = UnetDsv3(in_size=filters[2], out_size=n_classes, scale_factor=4) self.dsv2 = UnetDsv3(in_size=filters[1], out_size=n_classes, scale_factor=2) self.dsv1 = nn.Conv3d(in_channels=filters[0], out_channels=n_classes, kernel_size=1) # final conv (without any concat) self.final = nn.Conv3d(n_classes*4, n_classes, 1) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv3d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm3d): init_weights(m, init_type='kaiming') def forward(self, inputs): conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) maxpool2 = self.maxpool2(conv2) conv3 = self.conv3(maxpool2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) center = self.center(maxpool4) up4 = self.up_concat4(conv4, center) up3 = self.up_concat3(conv3, up4) up2 = self.up_concat2(conv2, up3) up1 = self.up_concat1(conv1, up2) # Deep Supervision dsv4 = self.dsv4(up4) dsv3 = self.dsv3(up3) dsv2 = self.dsv2(up2) dsv1 = self.dsv1(up1) final = self.final(torch.cat([dsv1,dsv2,dsv3,dsv4], dim=1)) return final @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p
3,457
32.572816
122
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/unet_grid_attention_3D.py
import torch.nn as nn from .utils import UnetConv3, UnetUp3, UnetGridGatingSignal3 import torch.nn.functional as F from models.layers.grid_attention_layer import GridAttentionBlock3D from models.networks_other import init_weights class unet_grid_attention_3D(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, nonlocal_mode='concatenation', attention_dsample=(2,2,2), is_batchnorm=True): super(unet_grid_attention_3D, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale filters = [64, 128, 256, 512, 1024] filters = [int(x / self.feature_scale) for x in filters] # downsampling self.conv1 = UnetConv3(self.in_channels, filters[0], self.is_batchnorm) self.maxpool1 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv2 = UnetConv3(filters[0], filters[1], self.is_batchnorm) self.maxpool2 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv3 = UnetConv3(filters[1], filters[2], self.is_batchnorm) self.maxpool3 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv4 = UnetConv3(filters[2], filters[3], self.is_batchnorm) self.maxpool4 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.center = UnetConv3(filters[3], filters[4], self.is_batchnorm) self.gating = UnetGridGatingSignal3(filters[4], filters[3], kernel_size=(1, 1, 1), is_batchnorm=self.is_batchnorm) # attention blocks self.attentionblock2 = GridAttentionBlock3D(in_channels=filters[1], gating_channels=filters[3], inter_channels=filters[1], sub_sample_factor=attention_dsample, mode=nonlocal_mode) self.attentionblock3 = GridAttentionBlock3D(in_channels=filters[2], gating_channels=filters[3], inter_channels=filters[2], sub_sample_factor=attention_dsample, mode=nonlocal_mode) self.attentionblock4 = GridAttentionBlock3D(in_channels=filters[3], gating_channels=filters[3], inter_channels=filters[3], sub_sample_factor=attention_dsample, mode=nonlocal_mode) # upsampling self.up_concat4 = UnetUp3(filters[4], filters[3], self.is_deconv, self.is_batchnorm) self.up_concat3 = UnetUp3(filters[3], filters[2], self.is_deconv, self.is_batchnorm) self.up_concat2 = UnetUp3(filters[2], filters[1], self.is_deconv, self.is_batchnorm) self.up_concat1 = UnetUp3(filters[1], filters[0], self.is_deconv, self.is_batchnorm) # final conv (without any concat) self.final = nn.Conv3d(filters[0], n_classes, 1) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv3d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm3d): init_weights(m, init_type='kaiming') def forward(self, inputs): # Feature Extraction conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) maxpool2 = self.maxpool2(conv2) conv3 = self.conv3(maxpool2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) # Gating Signal Generation center = self.center(maxpool4) gating = self.gating(center) # Attention Mechanism g_conv4, att4 = self.attentionblock4(conv4, gating) g_conv3, att3 = self.attentionblock3(conv3, gating) g_conv2, att2 = self.attentionblock2(conv2, gating) # Upscaling Part (Decoder) up4 = self.up_concat4(g_conv4, center) up3 = self.up_concat3(g_conv3, up4) up2 = self.up_concat2(g_conv2, up3) up1 = self.up_concat1(conv1, up2) final = self.final(up1) return final @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p
4,134
36.252252
135
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/unet_CT_multi_att_dsv_3D.py
import torch.nn as nn import torch from .utils import UnetConv3, UnetUp3_CT, UnetGridGatingSignal3, UnetDsv3 import torch.nn.functional as F from models.networks_other import init_weights from models.layers.grid_attention_layer import GridAttentionBlock3D class unet_CT_multi_att_dsv_3D(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, nonlocal_mode='concatenation', attention_dsample=(2,2,2), is_batchnorm=True): super(unet_CT_multi_att_dsv_3D, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale filters = [64, 128, 256, 512, 1024] filters = [int(x / self.feature_scale) for x in filters] # downsampling self.conv1 = UnetConv3(self.in_channels, filters[0], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool1 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv2 = UnetConv3(filters[0], filters[1], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool2 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv3 = UnetConv3(filters[1], filters[2], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool3 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv4 = UnetConv3(filters[2], filters[3], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool4 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.center = UnetConv3(filters[3], filters[4], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.gating = UnetGridGatingSignal3(filters[4], filters[4], kernel_size=(1, 1, 1), is_batchnorm=self.is_batchnorm) # attention blocks self.attentionblock2 = MultiAttentionBlock(in_size=filters[1], gate_size=filters[2], inter_size=filters[1], nonlocal_mode=nonlocal_mode, sub_sample_factor= attention_dsample) self.attentionblock3 = MultiAttentionBlock(in_size=filters[2], gate_size=filters[3], inter_size=filters[2], nonlocal_mode=nonlocal_mode, sub_sample_factor= attention_dsample) self.attentionblock4 = MultiAttentionBlock(in_size=filters[3], gate_size=filters[4], inter_size=filters[3], nonlocal_mode=nonlocal_mode, sub_sample_factor= attention_dsample) # upsampling self.up_concat4 = UnetUp3_CT(filters[4], filters[3], is_batchnorm) self.up_concat3 = UnetUp3_CT(filters[3], filters[2], is_batchnorm) self.up_concat2 = UnetUp3_CT(filters[2], filters[1], is_batchnorm) self.up_concat1 = UnetUp3_CT(filters[1], filters[0], is_batchnorm) # deep supervision self.dsv4 = UnetDsv3(in_size=filters[3], out_size=n_classes, scale_factor=8) self.dsv3 = UnetDsv3(in_size=filters[2], out_size=n_classes, scale_factor=4) self.dsv2 = UnetDsv3(in_size=filters[1], out_size=n_classes, scale_factor=2) self.dsv1 = nn.Conv3d(in_channels=filters[0], out_channels=n_classes, kernel_size=1) # final conv (without any concat) self.final = nn.Conv3d(n_classes*4, n_classes, 1) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv3d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm3d): init_weights(m, init_type='kaiming') def forward(self, inputs): # Feature Extraction conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) maxpool2 = self.maxpool2(conv2) conv3 = self.conv3(maxpool2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) # Gating Signal Generation center = self.center(maxpool4) gating = self.gating(center) # Attention Mechanism # Upscaling Part (Decoder) g_conv4, att4 = self.attentionblock4(conv4, gating) up4 = self.up_concat4(g_conv4, center) g_conv3, att3 = self.attentionblock3(conv3, up4) up3 = self.up_concat3(g_conv3, up4) g_conv2, att2 = self.attentionblock2(conv2, up3) up2 = self.up_concat2(g_conv2, up3) up1 = self.up_concat1(conv1, up2) # Deep Supervision dsv4 = self.dsv4(up4) dsv3 = self.dsv3(up3) dsv2 = self.dsv2(up2) dsv1 = self.dsv1(up1) final = self.final(torch.cat([dsv1,dsv2,dsv3,dsv4], dim=1)) return final @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p class MultiAttentionBlock(nn.Module): def __init__(self, in_size, gate_size, inter_size, nonlocal_mode, sub_sample_factor): super(MultiAttentionBlock, self).__init__() self.gate_block_1 = GridAttentionBlock3D(in_channels=in_size, gating_channels=gate_size, inter_channels=inter_size, mode=nonlocal_mode, sub_sample_factor= sub_sample_factor) self.gate_block_2 = GridAttentionBlock3D(in_channels=in_size, gating_channels=gate_size, inter_channels=inter_size, mode=nonlocal_mode, sub_sample_factor=sub_sample_factor) self.combine_gates = nn.Sequential(nn.Conv3d(in_size*2, in_size, kernel_size=1, stride=1, padding=0), nn.BatchNorm3d(in_size), nn.ReLU(inplace=True) ) # initialise the blocks for m in self.children(): if m.__class__.__name__.find('GridAttentionBlock3D') != -1: continue init_weights(m, init_type='kaiming') def forward(self, input, gating_signal): gate_1, attention_1 = self.gate_block_1(input, gating_signal) gate_2, attention_2 = self.gate_block_2(input, gating_signal) return self.combine_gates(torch.cat([gate_1, gate_2], 1)), torch.cat([attention_1, attention_2], 1)
6,354
44.719424
122
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/unet_3D.py
import math import torch.nn as nn from .utils import UnetConv3, UnetUp3 import torch.nn.functional as F from models.networks_other import init_weights class unet_3D(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, is_batchnorm=True): super(unet_3D, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale filters = [64, 128, 256, 512, 1024] filters = [int(x / self.feature_scale) for x in filters] # downsampling self.conv1 = UnetConv3(self.in_channels, filters[0], self.is_batchnorm) self.maxpool1 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv2 = UnetConv3(filters[0], filters[1], self.is_batchnorm) self.maxpool2 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv3 = UnetConv3(filters[1], filters[2], self.is_batchnorm) self.maxpool3 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.conv4 = UnetConv3(filters[2], filters[3], self.is_batchnorm) self.maxpool4 = nn.MaxPool3d(kernel_size=(2, 2, 1)) self.center = UnetConv3(filters[3], filters[4], self.is_batchnorm) # upsampling self.up_concat4 = UnetUp3(filters[4], filters[3], self.is_deconv, is_batchnorm) self.up_concat3 = UnetUp3(filters[3], filters[2], self.is_deconv, is_batchnorm) self.up_concat2 = UnetUp3(filters[2], filters[1], self.is_deconv, is_batchnorm) self.up_concat1 = UnetUp3(filters[1], filters[0], self.is_deconv, is_batchnorm) # final conv (without any concat) self.final = nn.Conv3d(filters[0], n_classes, 1) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv3d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm3d): init_weights(m, init_type='kaiming') def forward(self, inputs): conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) maxpool2 = self.maxpool2(conv2) conv3 = self.conv3(maxpool2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) center = self.center(maxpool4) up4 = self.up_concat4(conv4, center) up3 = self.up_concat3(conv3, up4) up2 = self.up_concat2(conv2, up3) up1 = self.up_concat1(conv1, up2) final = self.final(up1) return final @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p
2,705
28.736264
104
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/networks/unet_CT_single_att_dsv_3D.py
import torch.nn as nn import torch from .utils import UnetConv3, UnetUp3_CT, UnetGridGatingSignal3, UnetDsv3 import torch.nn.functional as F from models.networks_other import init_weights from models.layers.grid_attention_layer import GridAttentionBlock3D class unet_CT_single_att_dsv_3D(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, nonlocal_mode='concatenation', attention_dsample=(2,2,2), is_batchnorm=True): super(unet_CT_single_att_dsv_3D, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale = feature_scale filters = [64, 128, 256, 512, 1024] filters = [int(x / self.feature_scale) for x in filters] # downsampling self.conv1 = UnetConv3(self.in_channels, filters[0], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool1 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv2 = UnetConv3(filters[0], filters[1], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool2 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv3 = UnetConv3(filters[1], filters[2], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool3 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.conv4 = UnetConv3(filters[2], filters[3], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.maxpool4 = nn.MaxPool3d(kernel_size=(2, 2, 2)) self.center = UnetConv3(filters[3], filters[4], self.is_batchnorm, kernel_size=(3,3,3), padding_size=(1,1,1)) self.gating = UnetGridGatingSignal3(filters[4], filters[4], kernel_size=(1, 1, 1), is_batchnorm=self.is_batchnorm) # attention blocks self.attentionblock2 = MultiAttentionBlock(in_size=filters[1], gate_size=filters[2], inter_size=filters[1], nonlocal_mode=nonlocal_mode, sub_sample_factor= attention_dsample) self.attentionblock3 = MultiAttentionBlock(in_size=filters[2], gate_size=filters[3], inter_size=filters[2], nonlocal_mode=nonlocal_mode, sub_sample_factor= attention_dsample) self.attentionblock4 = MultiAttentionBlock(in_size=filters[3], gate_size=filters[4], inter_size=filters[3], nonlocal_mode=nonlocal_mode, sub_sample_factor= attention_dsample) # upsampling self.up_concat4 = UnetUp3_CT(filters[4], filters[3], is_batchnorm) self.up_concat3 = UnetUp3_CT(filters[3], filters[2], is_batchnorm) self.up_concat2 = UnetUp3_CT(filters[2], filters[1], is_batchnorm) self.up_concat1 = UnetUp3_CT(filters[1], filters[0], is_batchnorm) # deep supervision self.dsv4 = UnetDsv3(in_size=filters[3], out_size=n_classes, scale_factor=8) self.dsv3 = UnetDsv3(in_size=filters[2], out_size=n_classes, scale_factor=4) self.dsv2 = UnetDsv3(in_size=filters[1], out_size=n_classes, scale_factor=2) self.dsv1 = nn.Conv3d(in_channels=filters[0], out_channels=n_classes, kernel_size=1) # final conv (without any concat) self.final = nn.Conv3d(n_classes*4, n_classes, 1) # initialise weights for m in self.modules(): if isinstance(m, nn.Conv3d): init_weights(m, init_type='kaiming') elif isinstance(m, nn.BatchNorm3d): init_weights(m, init_type='kaiming') def forward(self, inputs): # Feature Extraction conv1 = self.conv1(inputs) maxpool1 = self.maxpool1(conv1) conv2 = self.conv2(maxpool1) maxpool2 = self.maxpool2(conv2) conv3 = self.conv3(maxpool2) maxpool3 = self.maxpool3(conv3) conv4 = self.conv4(maxpool3) maxpool4 = self.maxpool4(conv4) # Gating Signal Generation center = self.center(maxpool4) gating = self.gating(center) # Attention Mechanism # Upscaling Part (Decoder) g_conv4, att4 = self.attentionblock4(conv4, gating) up4 = self.up_concat4(g_conv4, center) g_conv3, att3 = self.attentionblock3(conv3, up4) up3 = self.up_concat3(g_conv3, up4) g_conv2, att2 = self.attentionblock2(conv2, up3) up2 = self.up_concat2(g_conv2, up3) up1 = self.up_concat1(conv1, up2) # Deep Supervision dsv4 = self.dsv4(up4) dsv3 = self.dsv3(up3) dsv2 = self.dsv2(up2) dsv1 = self.dsv1(up1) final = self.final(torch.cat([dsv1,dsv2,dsv3,dsv4], dim=1)) return final @staticmethod def apply_argmax_softmax(pred): log_p = F.softmax(pred, dim=1) return log_p class MultiAttentionBlock(nn.Module): def __init__(self, in_size, gate_size, inter_size, nonlocal_mode, sub_sample_factor): super(MultiAttentionBlock, self).__init__() self.gate_block_1 = GridAttentionBlock3D(in_channels=in_size, gating_channels=gate_size, inter_channels=inter_size, mode=nonlocal_mode, sub_sample_factor= sub_sample_factor) self.combine_gates = nn.Sequential(nn.Conv3d(in_size, in_size, kernel_size=1, stride=1, padding=0), nn.BatchNorm3d(in_size), nn.ReLU(inplace=True) ) # initialise the blocks for m in self.children(): if m.__class__.__name__.find('GridAttentionBlock3D') != -1: continue init_weights(m, init_type='kaiming') def forward(self, input, gating_signal): gate_1, attention_1 = self.gate_block_1(input, gating_signal) return self.combine_gates(gate_1), attention_1
5,952
43.096296
122
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/layers/grid_attention_layer.py
import torch from torch import nn from torch.nn import functional as F from models.networks_other import init_weights class _GridAttentionBlockND(nn.Module): def __init__(self, in_channels, gating_channels, inter_channels=None, dimension=3, mode='concatenation', sub_sample_factor=(2,2,2)): super(_GridAttentionBlockND, self).__init__() assert dimension in [2, 3] assert mode in ['concatenation', 'concatenation_debug', 'concatenation_residual'] # Downsampling rate for the input featuremap if isinstance(sub_sample_factor, tuple): self.sub_sample_factor = sub_sample_factor elif isinstance(sub_sample_factor, list): self.sub_sample_factor = tuple(sub_sample_factor) else: self.sub_sample_factor = tuple([sub_sample_factor]) * dimension # Default parameter set self.mode = mode self.dimension = dimension self.sub_sample_kernel_size = self.sub_sample_factor # Number of channels (pixel dimensions) self.in_channels = in_channels self.gating_channels = gating_channels self.inter_channels = inter_channels if self.inter_channels is None: self.inter_channels = in_channels // 2 if self.inter_channels == 0: self.inter_channels = 1 if dimension == 3: conv_nd = nn.Conv3d bn = nn.BatchNorm3d self.upsample_mode = 'trilinear' elif dimension == 2: conv_nd = nn.Conv2d bn = nn.BatchNorm2d self.upsample_mode = 'bilinear' else: raise NotImplemented # Output transform self.W = nn.Sequential( conv_nd(in_channels=self.in_channels, out_channels=self.in_channels, kernel_size=1, stride=1, padding=0), bn(self.in_channels), ) # Theta^T * x_ij + Phi^T * gating_signal + bias self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, kernel_size=self.sub_sample_kernel_size, stride=self.sub_sample_factor, padding=0, bias=False) self.phi = conv_nd(in_channels=self.gating_channels, out_channels=self.inter_channels, kernel_size=1, stride=1, padding=0, bias=True) self.psi = conv_nd(in_channels=self.inter_channels, out_channels=1, kernel_size=1, stride=1, padding=0, bias=True) # Initialise weights for m in self.children(): init_weights(m, init_type='kaiming') # Define the operation if mode == 'concatenation': self.operation_function = self._concatenation elif mode == 'concatenation_debug': self.operation_function = self._concatenation_debug elif mode == 'concatenation_residual': self.operation_function = self._concatenation_residual else: raise NotImplementedError('Unknown operation function.') def forward(self, x, g): ''' :param x: (b, c, t, h, w) :param g: (b, g_d) :return: ''' output = self.operation_function(x, g) return output def _concatenation(self, x, g): input_size = x.size() batch_size = input_size[0] assert batch_size == g.size(0) # theta => (b, c, t, h, w) -> (b, i_c, t, h, w) -> (b, i_c, thw) # phi => (b, g_d) -> (b, i_c) theta_x = self.theta(x) theta_x_size = theta_x.size() # g (b, c, t', h', w') -> phi_g (b, i_c, t', h', w') # Relu(theta_x + phi_g + bias) -> f = (b, i_c, thw) -> (b, i_c, t/s1, h/s2, w/s3) phi_g = F.upsample(self.phi(g), size=theta_x_size[2:], mode=self.upsample_mode) f = F.relu(theta_x + phi_g, inplace=True) # psi^T * f -> (b, psi_i_c, t/s1, h/s2, w/s3) sigm_psi_f = F.sigmoid(self.psi(f)) # upsample the attentions and multiply sigm_psi_f = F.upsample(sigm_psi_f, size=input_size[2:], mode=self.upsample_mode) y = sigm_psi_f.expand_as(x) * x W_y = self.W(y) return W_y, sigm_psi_f def _concatenation_debug(self, x, g): input_size = x.size() batch_size = input_size[0] assert batch_size == g.size(0) # theta => (b, c, t, h, w) -> (b, i_c, t, h, w) -> (b, i_c, thw) # phi => (b, g_d) -> (b, i_c) theta_x = self.theta(x) theta_x_size = theta_x.size() # g (b, c, t', h', w') -> phi_g (b, i_c, t', h', w') # Relu(theta_x + phi_g + bias) -> f = (b, i_c, thw) -> (b, i_c, t/s1, h/s2, w/s3) phi_g = F.upsample(self.phi(g), size=theta_x_size[2:], mode=self.upsample_mode) f = F.softplus(theta_x + phi_g) # psi^T * f -> (b, psi_i_c, t/s1, h/s2, w/s3) sigm_psi_f = F.sigmoid(self.psi(f)) # upsample the attentions and multiply sigm_psi_f = F.upsample(sigm_psi_f, size=input_size[2:], mode=self.upsample_mode) y = sigm_psi_f.expand_as(x) * x W_y = self.W(y) return W_y, sigm_psi_f def _concatenation_residual(self, x, g): input_size = x.size() batch_size = input_size[0] assert batch_size == g.size(0) # theta => (b, c, t, h, w) -> (b, i_c, t, h, w) -> (b, i_c, thw) # phi => (b, g_d) -> (b, i_c) theta_x = self.theta(x) theta_x_size = theta_x.size() # g (b, c, t', h', w') -> phi_g (b, i_c, t', h', w') # Relu(theta_x + phi_g + bias) -> f = (b, i_c, thw) -> (b, i_c, t/s1, h/s2, w/s3) phi_g = F.upsample(self.phi(g), size=theta_x_size[2:], mode=self.upsample_mode) f = F.relu(theta_x + phi_g, inplace=True) # psi^T * f -> (b, psi_i_c, t/s1, h/s2, w/s3) f = self.psi(f).view(batch_size, 1, -1) sigm_psi_f = F.softmax(f, dim=2).view(batch_size, 1, *theta_x.size()[2:]) # upsample the attentions and multiply sigm_psi_f = F.upsample(sigm_psi_f, size=input_size[2:], mode=self.upsample_mode) y = sigm_psi_f.expand_as(x) * x W_y = self.W(y) return W_y, sigm_psi_f class GridAttentionBlock2D(_GridAttentionBlockND): def __init__(self, in_channels, gating_channels, inter_channels=None, mode='concatenation', sub_sample_factor=(2,2,2)): super(GridAttentionBlock2D, self).__init__(in_channels, inter_channels=inter_channels, gating_channels=gating_channels, dimension=2, mode=mode, sub_sample_factor=sub_sample_factor, ) class GridAttentionBlock3D(_GridAttentionBlockND): def __init__(self, in_channels, gating_channels, inter_channels=None, mode='concatenation', sub_sample_factor=(2,2,2)): super(GridAttentionBlock3D, self).__init__(in_channels, inter_channels=inter_channels, gating_channels=gating_channels, dimension=3, mode=mode, sub_sample_factor=sub_sample_factor, ) class _GridAttentionBlockND_TORR(nn.Module): def __init__(self, in_channels, gating_channels, inter_channels=None, dimension=3, mode='concatenation', sub_sample_factor=(1,1,1), bn_layer=True, use_W=True, use_phi=True, use_theta=True, use_psi=True, nonlinearity1='relu'): super(_GridAttentionBlockND_TORR, self).__init__() assert dimension in [2, 3] assert mode in ['concatenation', 'concatenation_softmax', 'concatenation_sigmoid', 'concatenation_mean', 'concatenation_range_normalise', 'concatenation_mean_flow'] # Default parameter set self.mode = mode self.dimension = dimension self.sub_sample_factor = sub_sample_factor if isinstance(sub_sample_factor, tuple) else tuple([sub_sample_factor])*dimension self.sub_sample_kernel_size = self.sub_sample_factor # Number of channels (pixel dimensions) self.in_channels = in_channels self.gating_channels = gating_channels self.inter_channels = inter_channels if self.inter_channels is None: self.inter_channels = in_channels // 2 if self.inter_channels == 0: self.inter_channels = 1 if dimension == 3: conv_nd = nn.Conv3d bn = nn.BatchNorm3d self.upsample_mode = 'trilinear' elif dimension == 2: conv_nd = nn.Conv2d bn = nn.BatchNorm2d self.upsample_mode = 'bilinear' else: raise NotImplemented # initialise id functions # Theta^T * x_ij + Phi^T * gating_signal + bias self.W = lambda x: x self.theta = lambda x: x self.psi = lambda x: x self.phi = lambda x: x self.nl1 = lambda x: x if use_W: if bn_layer: self.W = nn.Sequential( conv_nd(in_channels=self.in_channels, out_channels=self.in_channels, kernel_size=1, stride=1, padding=0), bn(self.in_channels), ) else: self.W = conv_nd(in_channels=self.in_channels, out_channels=self.in_channels, kernel_size=1, stride=1, padding=0) if use_theta: self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, kernel_size=self.sub_sample_kernel_size, stride=self.sub_sample_factor, padding=0, bias=False) if use_phi: self.phi = conv_nd(in_channels=self.gating_channels, out_channels=self.inter_channels, kernel_size=self.sub_sample_kernel_size, stride=self.sub_sample_factor, padding=0, bias=False) if use_psi: self.psi = conv_nd(in_channels=self.inter_channels, out_channels=1, kernel_size=1, stride=1, padding=0, bias=True) if nonlinearity1: if nonlinearity1 == 'relu': self.nl1 = lambda x: F.relu(x, inplace=True) if 'concatenation' in mode: self.operation_function = self._concatenation else: raise NotImplementedError('Unknown operation function.') # Initialise weights for m in self.children(): init_weights(m, init_type='kaiming') if use_psi and self.mode == 'concatenation_sigmoid': nn.init.constant(self.psi.bias.data, 3.0) if use_psi and self.mode == 'concatenation_softmax': nn.init.constant(self.psi.bias.data, 10.0) # if use_psi and self.mode == 'concatenation_mean': # nn.init.constant(self.psi.bias.data, 3.0) # if use_psi and self.mode == 'concatenation_range_normalise': # nn.init.constant(self.psi.bias.data, 3.0) parallel = False if parallel: if use_W: self.W = nn.DataParallel(self.W) if use_phi: self.phi = nn.DataParallel(self.phi) if use_psi: self.psi = nn.DataParallel(self.psi) if use_theta: self.theta = nn.DataParallel(self.theta) def forward(self, x, g): ''' :param x: (b, c, t, h, w) :param g: (b, g_d) :return: ''' output = self.operation_function(x, g) return output def _concatenation(self, x, g): input_size = x.size() batch_size = input_size[0] assert batch_size == g.size(0) ############################# # compute compatibility score # theta => (b, c, t, h, w) -> (b, i_c, t, h, w) # phi => (b, c, t, h, w) -> (b, i_c, t, h, w) theta_x = self.theta(x) theta_x_size = theta_x.size() # nl(theta.x + phi.g + bias) -> f = (b, i_c, t/s1, h/s2, w/s3) phi_g = F.upsample(self.phi(g), size=theta_x_size[2:], mode=self.upsample_mode) f = theta_x + phi_g f = self.nl1(f) psi_f = self.psi(f) ############################################ # normalisation -- scale compatibility score # psi^T . f -> (b, 1, t/s1, h/s2, w/s3) if self.mode == 'concatenation_softmax': sigm_psi_f = F.softmax(psi_f.view(batch_size, 1, -1), dim=2) sigm_psi_f = sigm_psi_f.view(batch_size, 1, *theta_x_size[2:]) elif self.mode == 'concatenation_mean': psi_f_flat = psi_f.view(batch_size, 1, -1) psi_f_sum = torch.sum(psi_f_flat, dim=2)#clamp(1e-6) psi_f_sum = psi_f_sum[:,:,None].expand_as(psi_f_flat) sigm_psi_f = psi_f_flat / psi_f_sum sigm_psi_f = sigm_psi_f.view(batch_size, 1, *theta_x_size[2:]) elif self.mode == 'concatenation_mean_flow': psi_f_flat = psi_f.view(batch_size, 1, -1) ss = psi_f_flat.shape psi_f_min = psi_f_flat.min(dim=2)[0].view(ss[0],ss[1],1) psi_f_flat = psi_f_flat - psi_f_min psi_f_sum = torch.sum(psi_f_flat, dim=2).view(ss[0],ss[1],1).expand_as(psi_f_flat) sigm_psi_f = psi_f_flat / psi_f_sum sigm_psi_f = sigm_psi_f.view(batch_size, 1, *theta_x_size[2:]) elif self.mode == 'concatenation_range_normalise': psi_f_flat = psi_f.view(batch_size, 1, -1) ss = psi_f_flat.shape psi_f_max = torch.max(psi_f_flat, dim=2)[0].view(ss[0], ss[1], 1) psi_f_min = torch.min(psi_f_flat, dim=2)[0].view(ss[0], ss[1], 1) sigm_psi_f = (psi_f_flat - psi_f_min) / (psi_f_max - psi_f_min).expand_as(psi_f_flat) sigm_psi_f = sigm_psi_f.view(batch_size, 1, *theta_x_size[2:]) elif self.mode == 'concatenation_sigmoid': sigm_psi_f = F.sigmoid(psi_f) else: raise NotImplementedError # sigm_psi_f is attention map! upsample the attentions and multiply sigm_psi_f = F.upsample(sigm_psi_f, size=input_size[2:], mode=self.upsample_mode) y = sigm_psi_f.expand_as(x) * x W_y = self.W(y) return W_y, sigm_psi_f class GridAttentionBlock2D_TORR(_GridAttentionBlockND_TORR): def __init__(self, in_channels, gating_channels, inter_channels=None, mode='concatenation', sub_sample_factor=(1,1), bn_layer=True, use_W=True, use_phi=True, use_theta=True, use_psi=True, nonlinearity1='relu'): super(GridAttentionBlock2D_TORR, self).__init__(in_channels, inter_channels=inter_channels, gating_channels=gating_channels, dimension=2, mode=mode, sub_sample_factor=sub_sample_factor, bn_layer=bn_layer, use_W=use_W, use_phi=use_phi, use_theta=use_theta, use_psi=use_psi, nonlinearity1=nonlinearity1) class GridAttentionBlock3D_TORR(_GridAttentionBlockND_TORR): def __init__(self, in_channels, gating_channels, inter_channels=None, mode='concatenation', sub_sample_factor=(1,1,1), bn_layer=True): super(GridAttentionBlock3D_TORR, self).__init__(in_channels, inter_channels=inter_channels, gating_channels=gating_channels, dimension=3, mode=mode, sub_sample_factor=sub_sample_factor, bn_layer=bn_layer) if __name__ == '__main__': from torch.autograd import Variable mode_list = ['concatenation'] for mode in mode_list: img = Variable(torch.rand(2, 16, 10, 10, 10)) gat = Variable(torch.rand(2, 64, 4, 4, 4)) net = GridAttentionBlock3D(in_channels=16, inter_channels=16, gating_channels=64, mode=mode, sub_sample_factor=(2,2,2)) out, sigma = net(img, gat) print(out.size())
16,617
40.441397
137
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/layers/nonlocal_layer.py
import torch from torch import nn from torch.nn import functional as F from models.networks_other import init_weights class _NonLocalBlockND(nn.Module): def __init__(self, in_channels, inter_channels=None, dimension=3, mode='embedded_gaussian', sub_sample_factor=4, bn_layer=True): super(_NonLocalBlockND, self).__init__() assert dimension in [1, 2, 3] assert mode in ['embedded_gaussian', 'gaussian', 'dot_product', 'concatenation', 'concat_proper', 'concat_proper_down'] # print('Dimension: %d, mode: %s' % (dimension, mode)) self.mode = mode self.dimension = dimension self.sub_sample_factor = sub_sample_factor if isinstance(sub_sample_factor, list) else [sub_sample_factor] self.in_channels = in_channels self.inter_channels = inter_channels if self.inter_channels is None: self.inter_channels = in_channels // 2 if self.inter_channels == 0: self.inter_channels = 1 if dimension == 3: conv_nd = nn.Conv3d max_pool = nn.MaxPool3d bn = nn.BatchNorm3d elif dimension == 2: conv_nd = nn.Conv2d max_pool = nn.MaxPool2d bn = nn.BatchNorm2d else: conv_nd = nn.Conv1d max_pool = nn.MaxPool1d bn = nn.BatchNorm1d self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, kernel_size=1, stride=1, padding=0) if bn_layer: self.W = nn.Sequential( conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, kernel_size=1, stride=1, padding=0), bn(self.in_channels) ) nn.init.constant(self.W[1].weight, 0) nn.init.constant(self.W[1].bias, 0) else: self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, kernel_size=1, stride=1, padding=0) nn.init.constant(self.W.weight, 0) nn.init.constant(self.W.bias, 0) self.theta = None self.phi = None if mode in ['embedded_gaussian', 'dot_product', 'concatenation', 'concat_proper', 'concat_proper_down']: self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, kernel_size=1, stride=1, padding=0) self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, kernel_size=1, stride=1, padding=0) if mode in ['concatenation']: self.wf_phi = nn.Linear(self.inter_channels, 1, bias=False) self.wf_theta = nn.Linear(self.inter_channels, 1, bias=False) elif mode in ['concat_proper', 'concat_proper_down']: self.psi = nn.Conv2d(in_channels=self.inter_channels, out_channels=1, kernel_size=1, stride=1, padding=0, bias=True) if mode == 'embedded_gaussian': self.operation_function = self._embedded_gaussian elif mode == 'dot_product': self.operation_function = self._dot_product elif mode == 'gaussian': self.operation_function = self._gaussian elif mode == 'concatenation': self.operation_function = self._concatenation elif mode == 'concat_proper': self.operation_function = self._concatenation_proper elif mode == 'concat_proper_down': self.operation_function = self._concatenation_proper_down else: raise NotImplementedError('Unknown operation function.') if any(ss > 1 for ss in self.sub_sample_factor): self.g = nn.Sequential(self.g, max_pool(kernel_size=sub_sample_factor)) if self.phi is None: self.phi = max_pool(kernel_size=sub_sample_factor) else: self.phi = nn.Sequential(self.phi, max_pool(kernel_size=sub_sample_factor)) if mode == 'concat_proper_down': self.theta = nn.Sequential(self.theta, max_pool(kernel_size=sub_sample_factor)) # Initialise weights for m in self.children(): init_weights(m, init_type='kaiming') def forward(self, x): ''' :param x: (b, c, t, h, w) :return: ''' output = self.operation_function(x) return output def _embedded_gaussian(self, x): batch_size = x.size(0) # g=>(b, c, t, h, w)->(b, 0.5c, t, h, w)->(b, thw, 0.5c) g_x = self.g(x).view(batch_size, self.inter_channels, -1) g_x = g_x.permute(0, 2, 1) # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, thw, 0.5c) # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw) # f=>(b, thw, 0.5c)dot(b, 0.5c, twh) = (b, thw, thw) theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) theta_x = theta_x.permute(0, 2, 1) phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) f = torch.matmul(theta_x, phi_x) f_div_C = F.softmax(f, dim=-1) # (b, thw, thw)dot(b, thw, 0.5c) = (b, thw, 0.5c)->(b, 0.5c, t, h, w)->(b, c, t, h, w) y = torch.matmul(f_div_C, g_x) y = y.permute(0, 2, 1).contiguous() y = y.view(batch_size, self.inter_channels, *x.size()[2:]) W_y = self.W(y) z = W_y + x return z def _gaussian(self, x): batch_size = x.size(0) g_x = self.g(x).view(batch_size, self.inter_channels, -1) g_x = g_x.permute(0, 2, 1) theta_x = x.view(batch_size, self.in_channels, -1) theta_x = theta_x.permute(0, 2, 1) if self.sub_sample_factor > 1: phi_x = self.phi(x).view(batch_size, self.in_channels, -1) else: phi_x = x.view(batch_size, self.in_channels, -1) f = torch.matmul(theta_x, phi_x) f_div_C = F.softmax(f, dim=-1) y = torch.matmul(f_div_C, g_x) y = y.permute(0, 2, 1).contiguous() y = y.view(batch_size, self.inter_channels, *x.size()[2:]) W_y = self.W(y) z = W_y + x return z def _dot_product(self, x): batch_size = x.size(0) g_x = self.g(x).view(batch_size, self.inter_channels, -1) g_x = g_x.permute(0, 2, 1) theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) theta_x = theta_x.permute(0, 2, 1) phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) f = torch.matmul(theta_x, phi_x) N = f.size(-1) f_div_C = f / N y = torch.matmul(f_div_C, g_x) y = y.permute(0, 2, 1).contiguous() y = y.view(batch_size, self.inter_channels, *x.size()[2:]) W_y = self.W(y) z = W_y + x return z def _concatenation(self, x): batch_size = x.size(0) # g=>(b, c, t, h, w)->(b, 0.5c, thw/s**2) g_x = self.g(x).view(batch_size, self.inter_channels, -1) # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, thw, 0.5c) # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, thw/s**2, 0.5c) theta_x = self.theta(x).view(batch_size, self.inter_channels, -1).permute(0, 2, 1) phi_x = self.phi(x).view(batch_size, self.inter_channels, -1).permute(0, 2, 1) # theta => (b, thw, 0.5c) -> (b, thw, 1) -> (b, 1, thw) -> (expand) (b, thw/s**2, thw) # phi => (b, thw/s**2, 0.5c) -> (b, thw/s**2, 1) -> (expand) (b, thw/s**2, thw) # f=> RELU[(b, thw/s**2, thw) + (b, thw/s**2, thw)] = (b, thw/s**2, thw) f = self.wf_theta(theta_x).permute(0, 2, 1).repeat(1, phi_x.size(1), 1) + \ self.wf_phi(phi_x).repeat(1, 1, theta_x.size(1)) f = F.relu(f, inplace=True) # Normalise the relations N = f.size(-1) f_div_c = f / N # g(x_j) * f(x_j, x_i) # (b, 0.5c, thw/s**2) * (b, thw/s**2, thw) -> (b, 0.5c, thw) y = torch.matmul(g_x, f_div_c) y = y.contiguous().view(batch_size, self.inter_channels, *x.size()[2:]) W_y = self.W(y) z = W_y + x return z def _concatenation_proper(self, x): batch_size = x.size(0) # g=>(b, c, t, h, w)->(b, 0.5c, thw/s**2) g_x = self.g(x).view(batch_size, self.inter_channels, -1) # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw) # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw/s**2) theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) # theta => (b, 0.5c, thw) -> (expand) (b, 0.5c, thw/s**2, thw) # phi => (b, 0.5c, thw/s**2) -> (expand) (b, 0.5c, thw/s**2, thw) # f=> RELU[(b, 0.5c, thw/s**2, thw) + (b, 0.5c, thw/s**2, thw)] = (b, 0.5c, thw/s**2, thw) f = theta_x.unsqueeze(dim=2).repeat(1,1,phi_x.size(2),1) + \ phi_x.unsqueeze(dim=3).repeat(1,1,1,theta_x.size(2)) f = F.relu(f, inplace=True) # psi -> W_psi^t * f -> (b, 1, thw/s**2, thw) -> (b, thw/s**2, thw) f = torch.squeeze(self.psi(f), dim=1) # Normalise the relations f_div_c = F.softmax(f, dim=1) # g(x_j) * f(x_j, x_i) # (b, 0.5c, thw/s**2) * (b, thw/s**2, thw) -> (b, 0.5c, thw) y = torch.matmul(g_x, f_div_c) y = y.contiguous().view(batch_size, self.inter_channels, *x.size()[2:]) W_y = self.W(y) z = W_y + x return z def _concatenation_proper_down(self, x): batch_size = x.size(0) # g=>(b, c, t, h, w)->(b, 0.5c, thw/s**2) g_x = self.g(x).view(batch_size, self.inter_channels, -1) # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw) # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw/s**2) theta_x = self.theta(x) downsampled_size = theta_x.size() theta_x = theta_x.view(batch_size, self.inter_channels, -1) phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) # theta => (b, 0.5c, thw) -> (expand) (b, 0.5c, thw/s**2, thw) # phi => (b, 0.5, thw/s**2) -> (expand) (b, 0.5c, thw/s**2, thw) # f=> RELU[(b, 0.5c, thw/s**2, thw) + (b, 0.5c, thw/s**2, thw)] = (b, 0.5c, thw/s**2, thw) f = theta_x.unsqueeze(dim=2).repeat(1,1,phi_x.size(2),1) + \ phi_x.unsqueeze(dim=3).repeat(1,1,1,theta_x.size(2)) f = F.relu(f, inplace=True) # psi -> W_psi^t * f -> (b, 0.5c, thw/s**2, thw) -> (b, 1, thw/s**2, thw) -> (b, thw/s**2, thw) f = torch.squeeze(self.psi(f), dim=1) # Normalise the relations f_div_c = F.softmax(f, dim=1) # g(x_j) * f(x_j, x_i) # (b, 0.5c, thw/s**2) * (b, thw/s**2, thw) -> (b, 0.5c, thw) y = torch.matmul(g_x, f_div_c) y = y.contiguous().view(batch_size, self.inter_channels, *downsampled_size[2:]) # upsample the final featuremaps # (b,0.5c,t/s1,h/s2,w/s3) y = F.upsample(y, size=x.size()[2:], mode='trilinear') # attention block output W_y = self.W(y) z = W_y + x return z class NONLocalBlock1D(_NonLocalBlockND): def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample_factor=2, bn_layer=True): super(NONLocalBlock1D, self).__init__(in_channels, inter_channels=inter_channels, dimension=1, mode=mode, sub_sample_factor=sub_sample_factor, bn_layer=bn_layer) class NONLocalBlock2D(_NonLocalBlockND): def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample_factor=2, bn_layer=True): super(NONLocalBlock2D, self).__init__(in_channels, inter_channels=inter_channels, dimension=2, mode=mode, sub_sample_factor=sub_sample_factor, bn_layer=bn_layer) class NONLocalBlock3D(_NonLocalBlockND): def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample_factor=2, bn_layer=True): super(NONLocalBlock3D, self).__init__(in_channels, inter_channels=inter_channels, dimension=3, mode=mode, sub_sample_factor=sub_sample_factor, bn_layer=bn_layer) if __name__ == '__main__': from torch.autograd import Variable mode_list = ['concatenation'] #mode_list = ['embedded_gaussian', 'gaussian', 'dot_product', ] for mode in mode_list: print(mode) img = Variable(torch.zeros(2, 4, 5)) net = NONLocalBlock1D(4, mode=mode, sub_sample_factor=2) out = net(img) print(out.size()) img = Variable(torch.zeros(2, 4, 5, 3)) net = NONLocalBlock2D(4, mode=mode, sub_sample_factor=1, bn_layer=False) out = net(img) print(out.size()) img = Variable(torch.zeros(2, 4, 5, 4, 5)) net = NONLocalBlock3D(4, mode=mode) out = net(img) print(out.size())
13,546
39.318452
127
py
Attention-Gated-Networks
Attention-Gated-Networks-master/models/layers/loss.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.loss import _Loss from torch.autograd import Function, Variable def cross_entropy_2D(input, target, weight=None, size_average=True): n, c, h, w = input.size() log_p = F.log_softmax(input, dim=1) log_p = log_p.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c) target = target.view(target.numel()) loss = F.nll_loss(log_p, target, weight=weight, size_average=False) if size_average: loss /= float(target.numel()) return loss def cross_entropy_3D(input, target, weight=None, size_average=True): n, c, h, w, s = input.size() log_p = F.log_softmax(input, dim=1) log_p = log_p.transpose(1, 2).transpose(2, 3).transpose(3, 4).contiguous().view(-1, c) target = target.view(target.numel()) loss = F.nll_loss(log_p, target, weight=weight, size_average=False) if size_average: loss /= float(target.numel()) return loss class SoftDiceLoss(nn.Module): def __init__(self, n_classes): super(SoftDiceLoss, self).__init__() self.one_hot_encoder = One_Hot(n_classes).forward self.n_classes = n_classes def forward(self, input, target): smooth = 0.01 batch_size = input.size(0) input = F.softmax(input, dim=1).view(batch_size, self.n_classes, -1) target = self.one_hot_encoder(target).contiguous().view(batch_size, self.n_classes, -1) inter = torch.sum(input * target, 2) + smooth union = torch.sum(input, 2) + torch.sum(target, 2) + smooth score = torch.sum(2.0 * inter / union) score = 1.0 - score / (float(batch_size) * float(self.n_classes)) return score class CustomSoftDiceLoss(nn.Module): def __init__(self, n_classes, class_ids): super(CustomSoftDiceLoss, self).__init__() self.one_hot_encoder = One_Hot(n_classes).forward self.n_classes = n_classes self.class_ids = class_ids def forward(self, input, target): smooth = 0.01 batch_size = input.size(0) input = F.softmax(input[:,self.class_ids], dim=1).view(batch_size, len(self.class_ids), -1) target = self.one_hot_encoder(target).contiguous().view(batch_size, self.n_classes, -1) target = target[:, self.class_ids, :] inter = torch.sum(input * target, 2) + smooth union = torch.sum(input, 2) + torch.sum(target, 2) + smooth score = torch.sum(2.0 * inter / union) score = 1.0 - score / (float(batch_size) * float(self.n_classes)) return score class One_Hot(nn.Module): def __init__(self, depth): super(One_Hot, self).__init__() self.depth = depth self.ones = torch.sparse.torch.eye(depth).cuda() def forward(self, X_in): n_dim = X_in.dim() output_size = X_in.size() + torch.Size([self.depth]) num_element = X_in.numel() X_in = X_in.data.long().view(num_element) out = Variable(self.ones.index_select(0, X_in)).view(output_size) return out.permute(0, -1, *range(1, n_dim)).squeeze(dim=2).float() def __repr__(self): return self.__class__.__name__ + "({})".format(self.depth) if __name__ == '__main__': from torch.autograd import Variable depth=3 batch_size=2 encoder = One_Hot(depth=depth).forward y = Variable(torch.LongTensor(batch_size, 1, 1, 2 ,2).random_() % depth).cuda() # 4 classes,1x3x3 img y_onehot = encoder(y) x = Variable(torch.randn(y_onehot.size()).float()).cuda() dicemetric = SoftDiceLoss(n_classes=depth) dicemetric(x,y)
3,621
34.509804
106
py
Attention-Gated-Networks
Attention-Gated-Networks-master/dataio/loader/test_dataset.py
import torch.utils.data as data import numpy as np import os from os import listdir from os.path import join from .utils import load_nifti_img, check_exceptions, is_image_file class TestDataset(data.Dataset): def __init__(self, root_dir, transform): super(TestDataset, self).__init__() image_dir = join(root_dir, 'image') self.image_filenames = sorted([join(image_dir, x) for x in listdir(image_dir) if is_image_file(x)]) # Add the corresponding ground-truth images if they exist self.label_filenames = [] label_dir = join(root_dir, 'label') if os.path.isdir(label_dir): self.label_filenames = sorted([join(label_dir, x) for x in listdir(label_dir) if is_image_file(x)]) assert len(self.label_filenames) == len(self.image_filenames) # data pre-processing self.transform = transform # report the number of images in the dataset print('Number of test images: {0} NIFTIs'.format(self.__len__())) def __getitem__(self, index): # load the NIFTI images input, input_meta = load_nifti_img(self.image_filenames[index], dtype=np.int16) # load the label image if it exists if self.label_filenames: label, _ = load_nifti_img(self.label_filenames[index], dtype=np.int16) check_exceptions(input, label) else: label = [] check_exceptions(input) # Pre-process the input 3D Nifti image input = self.transform(input) return input, input_meta, label def __len__(self): return len(self.image_filenames)
1,639
33.166667
111
py
Attention-Gated-Networks
Attention-Gated-Networks-master/dataio/loader/us_dataset.py
import torch import torch.utils.data as data import h5py import numpy as np import datetime from os import listdir from os.path import join #from .utils import check_exceptions class UltraSoundDataset(data.Dataset): def __init__(self, root_path, split, transform=None, preload_data=False): super(UltraSoundDataset, self).__init__() f = h5py.File(root_path) self.images = f['x_'+split] if preload_data: self.images = np.array(self.images[:]) self.labels = np.array(f['p_'+split][:], dtype=np.int64)#[:1000] self.label_names = [x.decode('utf-8') for x in f['label_names'][:].tolist()] #print(self.label_names) #print(np.unique(self.labels[:])) # construct weight for entry self.n_class = len(self.label_names) class_weight = np.zeros(self.n_class) for lab in range(self.n_class): class_weight[lab] = np.sum(self.labels[:] == lab) class_weight = 1 / class_weight self.weight = np.zeros(len(self.labels)) for i in range(len(self.labels)): self.weight[i] = class_weight[self.labels[i]] #print(class_weight) assert len(self.images) == len(self.labels) # data augmentation self.transform = transform # report the number of images in the dataset print('Number of {0} images: {1} NIFTIs'.format(split, self.__len__())) def __getitem__(self, index): # update the seed to avoid workers sample the same augmentation parameters np.random.seed(datetime.datetime.now().second + datetime.datetime.now().microsecond) # load the nifti images input = self.images[index][0] target = self.labels[index] #input = input.transpose((1,2,0)) # handle exceptions #check_exceptions(input, target) if self.transform: input = self.transform(input) #print(input.shape, torch.from_numpy(np.array([target]))) #print("target",np.int64(target)) return input, int(target) def __len__(self): return len(self.images) # if __name__ == '__main__': # dataset = UltraSoundDataset("/vol/bitbucket/js3611/data_ultrasound/preproc_combined_inp_224x288.hdf5",'test') # from torch.utils.data import DataLoader, sampler # ds = DataLoader(dataset=dataset, num_workers=1, batch_size=2)
2,405
30.657895
115
py
Attention-Gated-Networks
Attention-Gated-Networks-master/dataio/loader/cmr_3D_dataset.py
import torch.utils.data as data import numpy as np import datetime from os import listdir from os.path import join from .utils import load_nifti_img, check_exceptions, is_image_file class CMR3DDataset(data.Dataset): def __init__(self, root_dir, split, transform=None, preload_data=False): super(CMR3DDataset, self).__init__() image_dir = join(root_dir, split, 'image') target_dir = join(root_dir, split, 'label') self.image_filenames = sorted([join(image_dir, x) for x in listdir(image_dir) if is_image_file(x)]) self.target_filenames = sorted([join(target_dir, x) for x in listdir(target_dir) if is_image_file(x)]) assert len(self.image_filenames) == len(self.target_filenames) # report the number of images in the dataset print('Number of {0} images: {1} NIFTIs'.format(split, self.__len__())) # data augmentation self.transform = transform # data load into the ram memory self.preload_data = preload_data if self.preload_data: print('Preloading the {0} dataset ...'.format(split)) self.raw_images = [load_nifti_img(ii, dtype=np.int16)[0] for ii in self.image_filenames] self.raw_labels = [load_nifti_img(ii, dtype=np.uint8)[0] for ii in self.target_filenames] print('Loading is done\n') def __getitem__(self, index): # update the seed to avoid workers sample the same augmentation parameters np.random.seed(datetime.datetime.now().second + datetime.datetime.now().microsecond) # load the nifti images if not self.preload_data: input, _ = load_nifti_img(self.image_filenames[index], dtype=np.int16) target, _ = load_nifti_img(self.target_filenames[index], dtype=np.uint8) else: input = np.copy(self.raw_images[index]) target = np.copy(self.raw_labels[index]) # handle exceptions check_exceptions(input, target) if self.transform: input, target = self.transform(input, target) return input, target def __len__(self): return len(self.image_filenames)
2,167
39.148148
110
py
Attention-Gated-Networks
Attention-Gated-Networks-master/dataio/loader/ukbb_dataset.py
import torch.utils.data as data import numpy as np import datetime from os import listdir from os.path import join from .utils import load_nifti_img, check_exceptions, is_image_file class UKBBDataset(data.Dataset): def __init__(self, root_dir, split, transform=None, preload_data=False): super(UKBBDataset, self).__init__() image_dir = join(root_dir, split, 'image') target_dir = join(root_dir, split, 'label') self.image_filenames = sorted([join(image_dir, x) for x in listdir(image_dir) if is_image_file(x)]) self.target_filenames = sorted([join(target_dir, x) for x in listdir(target_dir) if is_image_file(x)]) assert len(self.image_filenames) == len(self.target_filenames) # report the number of images in the dataset print('Number of {0} images: {1} NIFTIs'.format(split, self.__len__())) # data augmentation self.transform = transform # data load into the ram memory self.preload_data = preload_data if self.preload_data: print('Preloading the {0} dataset ...'.format(split)) self.raw_images = [load_nifti_img(ii, dtype=np.int16)[0] for ii in self.image_filenames] self.raw_labels = [load_nifti_img(ii, dtype=np.uint8)[0] for ii in self.target_filenames] print('Loading is done\n') def __getitem__(self, index): # update the seed to avoid workers sample the same augmentation parameters np.random.seed(datetime.datetime.now().second + datetime.datetime.now().microsecond) # load the nifti images if not self.preload_data: input, _ = load_nifti_img(self.image_filenames[index], dtype=np.int16) target, _ = load_nifti_img(self.target_filenames[index], dtype=np.uint8) else: input = np.copy(self.raw_images[index]) target = np.copy(self.raw_labels[index]) # pass a random slice for the time being id_slice = np.random.randint(0,input.shape[2]) input = input[:,:,[id_slice]] target= target[:,:,[id_slice]] # handle exceptions check_exceptions(input, target) if self.transform: input, target = self.transform(input, target) return input, target def __len__(self): return len(self.image_filenames)
2,346
39.465517
110
py
Attention-Gated-Networks
Attention-Gated-Networks-master/dataio/transformation/myImageTransformations.py
import numpy as np import scipy import scipy.ndimage from scipy.ndimage.filters import gaussian_filter from scipy.ndimage.interpolation import map_coordinates import collections from PIL import Image import numbers def center_crop(x, center_crop_size): assert x.ndim == 3 centerw, centerh = x.shape[1] // 2, x.shape[2] // 2 halfw, halfh = center_crop_size[0] // 2, center_crop_size[1] // 2 return x[:, centerw - halfw:centerw + halfw, centerh - halfh:centerh + halfh] def to_tensor(x): import torch x = x.transpose((2, 0, 1)) print(x.shape) return torch.from_numpy(x).float() def random_num_generator(config, random_state=np.random): if config[0] == 'uniform': ret = random_state.uniform(config[1], config[2], 1)[0] elif config[0] == 'lognormal': ret = random_state.lognormal(config[1], config[2], 1)[0] else: print(config) raise Exception('unsupported format') return ret def poisson_downsampling(image, peak, random_state=np.random): if not isinstance(image, np.ndarray): imgArr = np.array(image, dtype='float32') else: imgArr = image.astype('float32') Q = imgArr.max(axis=(0, 1)) / peak if Q[0] == 0: return imgArr ima_lambda = imgArr / Q noisy_img = random_state.poisson(lam=ima_lambda) return noisy_img.astype('float32') def elastic_transform(image, alpha=1000, sigma=30, spline_order=1, mode='nearest', random_state=np.random): """Elastic deformation of image as described in [Simard2003]_. .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003. """ assert image.ndim == 3 shape = image.shape[:2] dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij') indices = [np.reshape(x + dx, (-1, 1)), np.reshape(y + dy, (-1, 1))] result = np.empty_like(image) for i in range(image.shape[2]): result[:, :, i] = map_coordinates( image[:, :, i], indices, order=spline_order, mode=mode).reshape(shape) return result class Merge(object): """Merge a group of images """ def __init__(self, axis=-1): self.axis = axis def __call__(self, images): if isinstance(images, collections.Sequence) or isinstance(images, np.ndarray): assert all([isinstance(i, np.ndarray) for i in images]), 'only numpy array is supported' shapes = [list(i.shape) for i in images] for s in shapes: s[self.axis] = None assert all([s == shapes[0] for s in shapes] ), 'shapes must be the same except the merge axis' return np.concatenate(images, axis=self.axis) else: raise Exception("obj is not a sequence (list, tuple, etc)") class Split(object): """Split images into individual arraies """ def __init__(self, *slices, **kwargs): assert isinstance(slices, collections.Sequence) slices_ = [] for s in slices: if isinstance(s, collections.Sequence): slices_.append(slice(*s)) else: slices_.append(s) assert all([isinstance(s, slice) for s in slices_] ), 'slices must be consist of slice instances' self.slices = slices_ self.axis = kwargs.get('axis', -1) def __call__(self, image): if isinstance(image, np.ndarray): ret = [] for s in self.slices: sl = [slice(None)] * image.ndim sl[self.axis] = s ret.append(image[sl]) return ret else: raise Exception("obj is not an numpy array") class ElasticTransform(object): """Apply elastic transformation on a numpy.ndarray (H x W x C) """ def __init__(self, alpha, sigma): self.alpha = alpha self.sigma = sigma def __call__(self, image): if isinstance(self.alpha, collections.Sequence): alpha = random_num_generator(self.alpha) else: alpha = self.alpha if isinstance(self.sigma, collections.Sequence): sigma = random_num_generator(self.sigma) else: sigma = self.sigma return elastic_transform(image, alpha=alpha, sigma=sigma) class PoissonSubsampling(object): """Poisson subsampling on a numpy.ndarray (H x W x C) """ def __init__(self, peak, random_state=np.random): self.peak = peak self.random_state = random_state def __call__(self, image): if isinstance(self.peak, collections.Sequence): peak = random_num_generator( self.peak, random_state=self.random_state) else: peak = self.peak return poisson_downsampling(image, peak, random_state=self.random_state) class AddGaussianNoise(object): """Add gaussian noise to a numpy.ndarray (H x W x C) """ def __init__(self, mean, sigma, random_state=np.random): self.sigma = sigma self.mean = mean self.random_state = random_state def __call__(self, image): if isinstance(self.sigma, collections.Sequence): sigma = random_num_generator(self.sigma, random_state=self.random_state) else: sigma = self.sigma if isinstance(self.mean, collections.Sequence): mean = random_num_generator(self.mean, random_state=self.random_state) else: mean = self.mean row, col, ch = image.shape gauss = self.random_state.normal(mean, sigma, (row, col, ch)) gauss = gauss.reshape(row, col, ch) image += gauss return image class AddSpeckleNoise(object): """Add speckle noise to a numpy.ndarray (H x W x C) """ def __init__(self, mean, sigma, random_state=np.random): self.sigma = sigma self.mean = mean self.random_state = random_state def __call__(self, image): if isinstance(self.sigma, collections.Sequence): sigma = random_num_generator( self.sigma, random_state=self.random_state) else: sigma = self.sigma if isinstance(self.mean, collections.Sequence): mean = random_num_generator( self.mean, random_state=self.random_state) else: mean = self.mean row, col, ch = image.shape gauss = self.random_state.normal(mean, sigma, (row, col, ch)) gauss = gauss.reshape(row, col, ch) image += image * gauss return image class GaussianBlurring(object): """Apply gaussian blur to a numpy.ndarray (H x W x C) """ def __init__(self, sigma, random_state=np.random): self.sigma = sigma self.random_state = random_state def __call__(self, image): if isinstance(self.sigma, collections.Sequence): sigma = random_num_generator( self.sigma, random_state=self.random_state) else: sigma = self.sigma image = gaussian_filter(image, sigma=(sigma, sigma, 0)) return image class AddGaussianPoissonNoise(object): """Add poisson noise with gaussian blurred image to a numpy.ndarray (H x W x C) """ def __init__(self, sigma, peak, random_state=np.random): self.sigma = sigma self.peak = peak self.random_state = random_state def __call__(self, image): if isinstance(self.sigma, collections.Sequence): sigma = random_num_generator( self.sigma, random_state=self.random_state) else: sigma = self.sigma if isinstance(self.peak, collections.Sequence): peak = random_num_generator( self.peak, random_state=self.random_state) else: peak = self.peak bg = gaussian_filter(image, sigma=(sigma, sigma, 0)) bg = poisson_downsampling( bg, peak=peak, random_state=self.random_state) return image + bg class MaxScaleNumpy(object): """scale with max and min of each channel of the numpy array i.e. channel = (channel - mean) / std """ def __init__(self, range_min=0.0, range_max=1.0): self.scale = (range_min, range_max) def __call__(self, image): mn = image.min(axis=(0, 1)) mx = image.max(axis=(0, 1)) return self.scale[0] + (image - mn) * (self.scale[1] - self.scale[0]) / (mx - mn) class MedianScaleNumpy(object): """Scale with median and mean of each channel of the numpy array i.e. channel = (channel - mean) / std """ def __init__(self, range_min=0.0, range_max=1.0): self.scale = (range_min, range_max) def __call__(self, image): mn = image.min(axis=(0, 1)) md = np.median(image, axis=(0, 1)) return self.scale[0] + (image - mn) * (self.scale[1] - self.scale[0]) / (md - mn) class NormalizeNumpy(object): """Normalize each channel of the numpy array i.e. channel = (channel - mean) / std """ def __call__(self, image): image -= image.mean(axis=(0, 1)) s = image.std(axis=(0, 1)) s[s == 0] = 1.0 image /= s return image class MutualExclude(object): """Remove elements from one channel """ def __init__(self, exclude_channel, from_channel): self.from_channel = from_channel self.exclude_channel = exclude_channel def __call__(self, image): mask = image[:, :, self.exclude_channel] > 0 image[:, :, self.from_channel][mask] = 0 return image class RandomCropNumpy(object): """Crops the given numpy array at a random location to have a region of the given size. size can be a tuple (target_height, target_width) or an integer, in which case the target will be of a square shape (size, size) """ def __init__(self, size, random_state=np.random): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size self.random_state = random_state def __call__(self, img): w, h = img.shape[:2] th, tw = self.size if w == tw and h == th: return img x1 = self.random_state.randint(0, w - tw) y1 = self.random_state.randint(0, h - th) return img[x1:x1 + tw, y1: y1 + th, :] class CenterCropNumpy(object): """Crops the given numpy array at the center to have a region of the given size. size can be a tuple (target_height, target_width) or an integer, in which case the target will be of a square shape (size, size) """ def __init__(self, size): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size def __call__(self, img): w, h = img.shape[:2] th, tw = self.size x1 = int(round((w - tw) / 2.)) y1 = int(round((h - th) / 2.)) return img[x1:x1 + tw, y1: y1 + th, :] class RandomRotate(object): """Rotate a PIL.Image or numpy.ndarray (H x W x C) randomly """ def __init__(self, angle_range=(0.0, 360.0), axes=(0, 1), mode='reflect', random_state=np.random): assert isinstance(angle_range, tuple) self.angle_range = angle_range self.random_state = random_state self.axes = axes self.mode = mode def __call__(self, image): angle = self.random_state.uniform( self.angle_range[0], self.angle_range[1]) if isinstance(image, np.ndarray): mi, ma = image.min(), image.max() image = scipy.ndimage.interpolation.rotate( image, angle, reshape=False, axes=self.axes, mode=self.mode) return np.clip(image, mi, ma) elif isinstance(image, Image.Image): return image.rotate(angle) else: raise Exception('unsupported type') class BilinearResize(object): """Resize a PIL.Image or numpy.ndarray (H x W x C) """ def __init__(self, zoom): self.zoom = [zoom, zoom, 1] def __call__(self, image): if isinstance(image, np.ndarray): return scipy.ndimage.interpolation.zoom(image, self.zoom) elif isinstance(image, Image.Image): return image.resize(self.size, Image.BILINEAR) else: raise Exception('unsupported type') class EnhancedCompose(object): """Composes several transforms together. Args: transforms (List[Transform]): list of transforms to compose. Example: >>> transforms.Compose([ >>> transforms.CenterCrop(10), >>> transforms.ToTensor(), >>> ]) """ def __init__(self, transforms): self.transforms = transforms def __call__(self, img): for t in self.transforms: if isinstance(t, collections.Sequence): assert isinstance(img, collections.Sequence) and len(img) == len( t), "size of image group and transform group does not fit" tmp_ = [] for i, im_ in enumerate(img): if callable(t[i]): tmp_.append(t[i](im_)) else: tmp_.append(im_) img = tmp_ elif callable(t): img = t(img) elif t is None: continue else: raise Exception('unexpected type') return img if __name__ == '__main__': from torchvision.transforms import Lambda input_channel = 3 target_channel = 3 # define a transform pipeline transform = EnhancedCompose([ Merge(), RandomCropNumpy(size=(512, 512)), RandomRotate(), Split([0, input_channel], [input_channel, input_channel + target_channel]), [CenterCropNumpy(size=(256, 256)), CenterCropNumpy(size=(256, 256))], [NormalizeNumpy(), MaxScaleNumpy(0, 1.0)], # for non-pytorch usage, remove to_tensor conversion [Lambda(to_tensor), Lambda(to_tensor)] ]) # read input dataio for test image_in = np.array(Image.open('input.jpg')) image_target = np.array(Image.open('target.jpg')) # apply the transform x, y = transform([image_in, image_target])
14,785
31.640177
107
py
Attention-Gated-Networks
Attention-Gated-Networks-master/dataio/transformation/transforms.py
import torchsample.transforms as ts from pprint import pprint class Transformations: def __init__(self, name): self.name = name # Input patch and scale size self.scale_size = (192, 192, 1) self.patch_size = (128, 128, 1) # self.patch_size = (208, 272, 1) # Affine and Intensity Transformations self.shift_val = (0.1, 0.1) self.rotate_val = 15.0 self.scale_val = (0.7, 1.3) self.inten_val = (1.0, 1.0) self.random_flip_prob = 0.0 # Divisibility factor for testing self.division_factor = (16, 16, 1) def get_transformation(self): return { 'ukbb_sax': self.cmr_3d_sax_transform, 'hms_sax': self.hms_sax_transform, 'test_sax': self.test_3d_sax_transform, 'acdc_sax': self.cmr_3d_sax_transform, 'us': self.ultrasound_transform, }[self.name]() def print(self): print('\n\n############# Augmentation Parameters #############') pprint(vars(self)) print('###################################################\n\n') def initialise(self, opts): t_opts = getattr(opts, self.name) # Affine and Intensity Transformations if hasattr(t_opts, 'scale_size'): self.scale_size = t_opts.scale_size if hasattr(t_opts, 'patch_size'): self.patch_size = t_opts.patch_size if hasattr(t_opts, 'shift_val'): self.shift_val = t_opts.shift if hasattr(t_opts, 'rotate_val'): self.rotate_val = t_opts.rotate if hasattr(t_opts, 'scale_val'): self.scale_val = t_opts.scale if hasattr(t_opts, 'inten_val'): self.inten_val = t_opts.intensity if hasattr(t_opts, 'random_flip_prob'): self.random_flip_prob = t_opts.random_flip_prob if hasattr(t_opts, 'division_factor'): self.division_factor = t_opts.division_factor def ukbb_sax_transform(self): train_transform = ts.Compose([ts.PadNumpy(size=self.scale_size), ts.ToTensor(), ts.ChannelsFirst(), ts.TypeCast(['float', 'float']), ts.RandomFlip(h=True, v=True, p=self.random_flip_prob), ts.RandomAffine(rotation_range=self.rotate_val, translation_range=self.shift_val, zoom_range=self.scale_val, interp=('bilinear', 'nearest')), ts.NormalizeMedicPercentile(norm_flag=(True, False)), ts.RandomCrop(size=self.patch_size), ts.TypeCast(['float', 'long']) ]) valid_transform = ts.Compose([ts.PadNumpy(size=self.scale_size), ts.ToTensor(), ts.ChannelsFirst(), ts.TypeCast(['float', 'float']), ts.NormalizeMedicPercentile(norm_flag=(True, False)), ts.SpecialCrop(size=self.patch_size, crop_type=0), ts.TypeCast(['float', 'long']) ]) return {'train': train_transform, 'valid': valid_transform} def cmr_3d_sax_transform(self): train_transform = ts.Compose([ts.PadNumpy(size=self.scale_size), ts.ToTensor(), ts.ChannelsFirst(), ts.TypeCast(['float', 'float']), ts.RandomFlip(h=True, v=True, p=self.random_flip_prob), ts.RandomAffine(rotation_range=self.rotate_val, translation_range=self.shift_val, zoom_range=self.scale_val, interp=('bilinear', 'nearest')), #ts.NormalizeMedicPercentile(norm_flag=(True, False)), ts.NormalizeMedic(norm_flag=(True, False)), ts.ChannelsLast(), ts.AddChannel(axis=0), ts.RandomCrop(size=self.patch_size), ts.TypeCast(['float', 'long']) ]) valid_transform = ts.Compose([ts.PadNumpy(size=self.scale_size), ts.ToTensor(), ts.ChannelsFirst(), ts.TypeCast(['float', 'float']), #ts.NormalizeMedicPercentile(norm_flag=(True, False)), ts.NormalizeMedic(norm_flag=(True, False)), ts.ChannelsLast(), ts.AddChannel(axis=0), ts.SpecialCrop(size=self.patch_size, crop_type=0), ts.TypeCast(['float', 'long']) ]) return {'train': train_transform, 'valid': valid_transform} def hms_sax_transform(self): # Training transformation # 2D Stack input - 3D High Resolution output segmentation train_transform = [] valid_transform = [] # First pad to a fixed size # Torch tensor # Channels first # Joint affine transformation # In-plane respiratory motion artefacts (translation and rotation) # Random Crop # Normalise the intensity range train_transform = ts.Compose([]) return {'train': train_transform, 'valid': valid_transform} def test_3d_sax_transform(self): test_transform = ts.Compose([ts.PadFactorNumpy(factor=self.division_factor), ts.ToTensor(), ts.ChannelsFirst(), ts.TypeCast(['float']), #ts.NormalizeMedicPercentile(norm_flag=True), ts.NormalizeMedic(norm_flag=True), ts.ChannelsLast(), ts.AddChannel(axis=0), ]) return {'test': test_transform} def ultrasound_transform(self): train_transform = ts.Compose([ts.ToTensor(), ts.TypeCast(['float']), ts.AddChannel(axis=0), ts.SpecialCrop(self.patch_size,0), ts.RandomFlip(h=True, v=False, p=self.random_flip_prob), ts.RandomAffine(rotation_range=self.rotate_val, translation_range=self.shift_val, zoom_range=self.scale_val, interp=('bilinear')), ts.StdNormalize(), ]) valid_transform = ts.Compose([ts.ToTensor(), ts.TypeCast(['float']), ts.AddChannel(axis=0), ts.SpecialCrop(self.patch_size,0), ts.StdNormalize(), ]) return {'train': train_transform, 'valid': valid_transform}
7,764
46.638037
119
py
Attention-Gated-Networks
Attention-Gated-Networks-master/utils/util.py
from __future__ import print_function import torch from PIL import Image import inspect, re import numpy as np import os import collections import json import csv from skimage.exposure import rescale_intensity # Converts a Tensor into a Numpy array # |imtype|: the desired type of the converted numpy array def tensor2im(image_tensor, imgtype='img', datatype=np.uint8): image_numpy = image_tensor[0].cpu().float().numpy() if image_numpy.ndim == 4:# image_numpy (C x W x H x S) mid_slice = image_numpy.shape[-1]//2 image_numpy = image_numpy[:,:,:,mid_slice] if image_numpy.shape[0] == 1: image_numpy = np.tile(image_numpy, (3, 1, 1)) image_numpy = np.transpose(image_numpy, (1, 2, 0)) if imgtype == 'img': image_numpy = (image_numpy + 8) / 16.0 * 255.0 if np.unique(image_numpy).size == int(1): return image_numpy.astype(datatype) return rescale_intensity(image_numpy.astype(datatype)) def diagnose_network(net, name='network'): mean = 0.0 count = 0 for param in net.parameters(): if param.grad is not None: mean += torch.mean(torch.abs(param.grad.data)) count += 1 if count > 0: mean = mean / count print(name) print(mean) def save_image(image_numpy, image_path): image_pil = Image.fromarray(image_numpy) image_pil.save(image_path) def info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [e for e in dir(object) if isinstance(getattr(object, e), collections.Callable)] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print( "\n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]) ) def varname(p): for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]: m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) if m: return m.group(1) def print_numpy(x, val=True, shp=False): x = x.astype(np.float64) if shp: print('shape,', x.shape) if val: x = x.flatten() print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % ( np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x))) def mkdirs(paths): if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths) def mkdir(path): if not os.path.exists(path): os.makedirs(path) def json_file_to_pyobj(filename): def _json_object_hook(d): return collections.namedtuple('X', d.keys())(*d.values()) def json2obj(data): return json.loads(data, object_hook=_json_object_hook) return json2obj(open(filename).read()) def determine_crop_size(inp_shape, div_factor): div_factor= np.array(div_factor, dtype=np.float32) new_shape = np.ceil(np.divide(inp_shape, div_factor)) * div_factor pre_pad = np.round((new_shape - inp_shape) / 2.0).astype(np.int16) post_pad = ((new_shape - inp_shape) - pre_pad).astype(np.int16) return pre_pad, post_pad def csv_write(out_filename, in_header_list, in_val_list): with open(out_filename, 'w') as f: writer = csv.writer(f) writer.writerow(in_header_list) writer.writerows(zip(*in_val_list))
3,464
32
97
py
Attention-Gated-Networks
Attention-Gated-Networks-master/utils/metrics.py
# Originally written by wkentaro # https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py import numpy as np import cv2 def _fast_hist(label_true, label_pred, n_class): mask = (label_true >= 0) & (label_true < n_class) hist = np.bincount( n_class * label_true[mask].astype(int) + label_pred[mask], minlength=n_class**2).reshape(n_class, n_class) return hist def segmentation_scores(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += _fast_hist(lt.flatten(), lp.flatten(), n_class) acc = np.diag(hist).sum() / hist.sum() acc_cls = np.diag(hist) / hist.sum(axis=1) acc_cls = np.nanmean(acc_cls) iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist)) mean_iu = np.nanmean(iu) freq = hist.sum(axis=1) / hist.sum() fwavacc = (freq[freq > 0] * iu[freq > 0]).sum() return {'overall_acc': acc, 'mean_acc': acc_cls, 'freq_w_acc': fwavacc, 'mean_iou': mean_iu} def dice_score_list(label_gt, label_pred, n_class): """ :param label_gt: [WxH] (2D images) :param label_pred: [WxH] (2D images) :param n_class: number of label classes :return: """ epsilon = 1.0e-6 assert len(label_gt) == len(label_pred) batchSize = len(label_gt) dice_scores = np.zeros((batchSize, n_class), dtype=np.float32) for batch_id, (l_gt, l_pred) in enumerate(zip(label_gt, label_pred)): for class_id in range(n_class): img_A = np.array(l_gt == class_id, dtype=np.float32).flatten() img_B = np.array(l_pred == class_id, dtype=np.float32).flatten() score = 2.0 * np.sum(img_A * img_B) / (np.sum(img_A) + np.sum(img_B) + epsilon) dice_scores[batch_id, class_id] = score return np.mean(dice_scores, axis=0) def dice_score(label_gt, label_pred, n_class): """ :param label_gt: :param label_pred: :param n_class: :return: """ epsilon = 1.0e-6 assert np.all(label_gt.shape == label_pred.shape) dice_scores = np.zeros(n_class, dtype=np.float32) for class_id in range(n_class): img_A = np.array(label_gt == class_id, dtype=np.float32).flatten() img_B = np.array(label_pred == class_id, dtype=np.float32).flatten() score = 2.0 * np.sum(img_A * img_B) / (np.sum(img_A) + np.sum(img_B) + epsilon) dice_scores[class_id] = score return dice_scores def precision_and_recall(label_gt, label_pred, n_class): from sklearn.metrics import precision_score, recall_score assert len(label_gt) == len(label_pred) precision = np.zeros(n_class, dtype=np.float32) recall = np.zeros(n_class, dtype=np.float32) img_A = np.array(label_gt, dtype=np.float32).flatten() img_B = np.array(label_pred, dtype=np.float32).flatten() precision[:] = precision_score(img_A, img_B, average=None, labels=range(n_class)) recall[:] = recall_score(img_A, img_B, average=None, labels=range(n_class)) return precision, recall def distance_metric(seg_A, seg_B, dx, k): """ Measure the distance errors between the contours of two segmentations. The manual contours are drawn on 2D slices. We calculate contour to contour distance for each slice. """ # Extract the label k from the segmentation maps to generate binary maps seg_A = (seg_A == k) seg_B = (seg_B == k) table_md = [] table_hd = [] X, Y, Z = seg_A.shape for z in range(Z): # Binary mask at this slice slice_A = seg_A[:, :, z].astype(np.uint8) slice_B = seg_B[:, :, z].astype(np.uint8) # The distance is defined only when both contours exist on this slice if np.sum(slice_A) > 0 and np.sum(slice_B) > 0: # Find contours and retrieve all the points _, contours, _ = cv2.findContours(cv2.inRange(slice_A, 1, 1), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) pts_A = contours[0] for i in range(1, len(contours)): pts_A = np.vstack((pts_A, contours[i])) _, contours, _ = cv2.findContours(cv2.inRange(slice_B, 1, 1), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) pts_B = contours[0] for i in range(1, len(contours)): pts_B = np.vstack((pts_B, contours[i])) # Distance matrix between point sets M = np.zeros((len(pts_A), len(pts_B))) for i in range(len(pts_A)): for j in range(len(pts_B)): M[i, j] = np.linalg.norm(pts_A[i, 0] - pts_B[j, 0]) # Mean distance and hausdorff distance md = 0.5 * (np.mean(np.min(M, axis=0)) + np.mean(np.min(M, axis=1))) * dx hd = np.max([np.max(np.min(M, axis=0)), np.max(np.min(M, axis=1))]) * dx table_md += [md] table_hd += [hd] # Return the mean distance and Hausdorff distance across 2D slices mean_md = np.mean(table_md) if table_md else None mean_hd = np.mean(table_hd) if table_hd else None return mean_md, mean_hd
5,458
36.390411
91
py
muLAn
muLAn-master/muLAn/plottypes/fitflux.py
# -*-coding:Utf-8 -* # ---------------------------------------------------------------------- # Routine to plot the result of the MCMC, in flux. # ---------------------------------------------------------------------- # External libraries # ---------------------------------------------------------------------- import sys import os # Full path of this file full_path_here = os.path.realpath(__file__) text = full_path_here.split('/') a = '' i = 0 while i < len(text) - 1: a = a + text[i] + '/' i = i + 1 full_path = a #filename = full_path + '../' + '.pythonexternallibpath' #file = open(filename, 'r') #for line in file: # path_lib_ext = line #file.close() #if path_lib_ext != 'None': # sys.path.insert(0, path_lib_ext[:-1]) # ---------------------------------------------------------------------- # Standard packages # ---------------------------------------------------------------------- import os import glob import sys import copy import cmath # import math import emcee # import pylab import pickle import pylab import zipfile import datetime from scipy import interpolate import subprocess import numpy as np from sklearn.mixture import GaussianMixture import pandas as pd import bokeh.layouts as blyt import bokeh.plotting as bplt from bokeh.models import HoverTool, TapTool, ColumnDataSource, OpenURL from bokeh.models.widgets import DateFormatter, NumberFormatter, DataTable, \ TableColumn import bokeh.io as io from scipy import stats import ConfigParser as cp from astropy.time import Time from PyAstronomy import pyasl import matplotlib as mpl import matplotlib.pyplot as plt from sklearn import linear_model from scipy.interpolate import interp1d from astropy.coordinates import SkyCoord from matplotlib.ticker import MultipleLocator, MaxNLocator from matplotlib.ticker import FixedLocator, FormatStrFormatter # ---------------------------------------------------------------------- # Non-standard packages # ---------------------------------------------------------------------- import muLAn.models.ephemeris as ephemeris # import models.esblparall as esblparall # import packages.plotconfig as plotconfig # import models.esblparallax as esblparallax # ---------------------------------------------------------------------- # CLASS # ---------------------------------------------------------------------- class printoption: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' reset = '\033[0m' bright = '\033[1m' dim = '\033[2m' underscore = '\033[4m' blink = '\033[5m' reverse = '\033[7m' hidden = '\033[8m' level0 = "\033[1m\033[31m" level1 = "\033[1m" good = "\033[32m" # ---------------------------------------------------------------------- # Functions # ---------------------------------------------------------------------- def communicate(cfg, verbose, text, opts=False, prefix=False, newline=False, tab=False): if cfg.getint('Modelling', 'Verbose') >= verbose: if prefix: text = "[muLAn] " + text if opts!=False: text2='' for a in opts: text2 = text2 + a text = text2 + text + printoption.reset if tab: text = " " + text if newline: text = "\n" + text print text else: if tab: text = " " + text if newline: text = "\n" + text print text # ---------------------------------------------------------------------- def help(): text = "Plot the light curve of a previously modelled event." return text # ---------------------------------------------------------------------- def bash_command(text): proc = subprocess.Popen(text, shell=True, executable="/bin/bash") proc.wait() # ---------------------------------------------------------------------- def unpack_options(cfgsetup, level0, level1, sep=','): options = [a.strip() for a in cfgsetup.get(level0, level1).split(sep)] del a, cfgsetup, level0, level1 return options # ---------------------------------------------------------------------- def fsfb(time_serie, cond, blending=True): #blending = True x = np.atleast_2d(time_serie['amp'][cond]).T y = np.atleast_2d(time_serie['flux'][cond]).T regr = linear_model.LinearRegression(fit_intercept=blending) regr.fit(x, y) fs = regr.coef_[0][0] # fb = regr.intercept_[0] if blending: fb = regr.intercept_[0] else: fb = 0.0 return fs, fb # ---------------------------------------------------------------------- def critic_roots(s, q, phi): """Sample of the critic curve. The convention is : - the heaviest body (mass m1) is the origin; - the lightest body (mass m2) is at (-s, 0). Arguments: s -- the binary separation; q -- the lens mass ratio q = m2/m1; phi -- the sample parameter in [0;2*pi]. Returns: result -- numpy array of the complex roots. """ coefs = [1, 2 * s, s ** 2 - np.exp(1j * phi), -2 * s * np.exp(1j * phi) / (1 + q), -(s ** 2 * np.exp(1j * phi) / (1 + q))] result = np.roots(coefs) del coefs return result # ---------------------------------------------------------------------- # Levi-Civita coefficient def epsilon(i, j, k): if (i == j or i == k or j == k): e = 0 else: if (i == 1 and j == 2 and k == 3): e = 1 if (i == 3 and j == 1 and k == 2): e = 1 if (i == 2 and j == 3 and k == 1): e = 1 if (i == 1 and j == 3 and k == 2): e = -1 if (i == 3 and j == 2 and k == 1): e = -1 if (i == 2 and j == 1 and k == 3): e = -1 return e # # Projection onto the sky def onSky(m_hat, n_hat, u): x = np.array( [epsilon(i + 1, j + 1, k + 1) * u[i] * n_hat[j] * m_hat[k] for i in xrange(3) for j in xrange(3) for k in xrange(3)]).sum() u_proj = (1.0 / np.sqrt(1 - ((n_hat * m_hat).sum()) ** 2)) \ * np.array([x, (n_hat * u).sum() - (n_hat * m_hat).sum() * ( u * m_hat).sum(), 0]) return u_proj # # Projection onto the sky def normalize(u): return u / np.sqrt((u * u).sum()) def angle_between(v1, v2): v1_u = normalize(v1) v2_u = normalize(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) # # def vectoriel(u, v): x = u[1] * v[2] - u[2] * v[1] y = u[2] * v[0] - u[0] * v[2] z = u[0] * v[1] - u[1] * v[0] return np.array([x, y, z]) def boussole(EarthSunFile=False, EarthSatelliteFile=False, cfg=False, \ t_D_xy=False): # Value of the origin of the developments t0par = cfg.getfloat('Modelling', 'tp') # Coordinates conversion of the event from the Equatorial frame to the Ecliptic frame c_icrs = SkyCoord(ra=cfg.get('EventDescription', 'RA'), dec=cfg.get('EventDescription', 'DEC'), frame='icrs') l = c_icrs.transform_to('barycentrictrueecliptic').lon.degree b = c_icrs.transform_to('barycentrictrueecliptic').lat.degree # Vector Earth --> Sun in Ecliptic frame (cartesian coordinates). # ------------------------------------------------------------------ format = {'names': ('dates', 'x', 'y', 'z', 'vx', 'vy', 'vz'), \ 'formats': ('f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8')} temp = np.loadtxt(EarthSunFile, usecols=(0, 5, 6, 7, 8, 9, 10), dtype=format, unpack=False) EarthSun = pd.DataFrame(temp) del temp # Time conversion: TDB->TCG->HJD temp = EarthSun['dates'] - 2400000.0 flag_clem = 0 if flag_clem: EarthSun['hjd'] = np.array( [pyasl.helio_jd(tc, c_icrs.ra.degree, c_icrs.dec.degree) for tc in Time(temp, format='mjd', scale='tdb').tcg.value]) - 50000.0 else: EarthSun['hjd'] = np.array([pyasl.helio_jd(tc, l, b) for tc in Time(temp, format='mjd', scale='tdb').tcg.value]) - 50000.0 del temp # Vector Earth --> Satellite in Ecliptic frame (cartesian coordinates). # ------------------------------------------------------------------ format = {'names': ('dates', 'x', 'y', 'z'), \ 'formats': ('f8', 'f8', 'f8', 'f8')} temp = np.loadtxt(EarthSatelliteFile, usecols=(0, 5, 6, 7), dtype=format, unpack=False) EarthSat = pd.DataFrame(temp) del temp # Time conversion: TDB->TCG->HJD temp = EarthSun['dates'] - 2400000.0 flag_clem = 0 if flag_clem: EarthSat['hjd'] = np.array( [pyasl.helio_jd(tc, c_icrs.ra.degree, c_icrs.dec.degree) for tc in Time(temp, format='mjd', scale='tdb').tcg.value]) - 50000.0 else: EarthSat['hjd'] = np.array([pyasl.helio_jd(tc, l, b) for tc in Time(temp, format='mjd', scale='tdb').tcg.value]) - 50000.0 del temp # Vector Earth --> Sun and velocity( Earth --> Sun ) at t0par sp = np.array( [interp1d(EarthSun['hjd'], EarthSun['x'], kind='linear')(t0par), \ interp1d(EarthSun['hjd'], EarthSun['y'], kind='linear')(t0par), \ interp1d(EarthSun['hjd'], EarthSun['z'], kind='linear')( t0par)]) vp = np.array([interp1d(EarthSun['hjd'], EarthSun['vx'], kind='linear')(t0par), interp1d(EarthSun['hjd'], EarthSun['vy'], kind='linear')(t0par), interp1d(EarthSun['hjd'], EarthSun['vz'], kind='linear')(t0par)]) # Ecliptic frame [gamma, y, nord], cartesian coordinates n_hat = np.array([0, 0, 1]) m_hat = np.array([np.cos(np.radians(b)) * np.cos(np.radians(l)), \ np.cos(np.radians(b)) * np.sin(np.radians(l)), \ np.sin(np.radians(b))]) # Sky ref. frame [East, North projected, microlens] # Cartesian coordinates # Parallax correction from Earth delta_pos = np.array([]) delta_pos_proj = np.array([]) pos_proj = np.array([]) for t in xrange(len(EarthSun)): pos = np.array( [EarthSun['x'][t], EarthSun['y'][t], EarthSun['z'][t]]) delta_pos_temp = pos - (EarthSun['hjd'][t] - t0par) * vp - sp delta_pos_proj = np.append(delta_pos_proj, onSky(m_hat, n_hat, delta_pos_temp)) pos_proj = np.append(pos_proj, onSky(m_hat, n_hat, pos)) delta_pos = np.append(delta_pos, delta_pos_temp) delta_pos = np.reshape(delta_pos, (delta_pos.shape[0] / 3, 3)) pos_proj = np.reshape(pos_proj, (pos_proj.shape[0] / 3, 3)) delta_pos_proj = np.reshape(delta_pos_proj, (delta_pos_proj.shape[0] / 3, 3)) EarthSun['xproj'] = pos_proj.T[0] EarthSun['yproj'] = pos_proj.T[1] EarthSun['zproj'] = pos_proj.T[2] EarthSun['deltaxproj'] = delta_pos_proj.T[0] EarthSun['deltayproj'] = delta_pos_proj.T[1] EarthSun['deltazproj'] = delta_pos_proj.T[2] EarthSun['deltax'] = delta_pos.T[0] EarthSun['deltay'] = delta_pos.T[1] EarthSun['deltaz'] = delta_pos.T[2] # Correction due to the Satellite + parallax delta_pos = np.array([]) delta_pos_proj = np.array([]) pos_proj = np.array([]) for t in xrange(len(EarthSat)): pos = np.array([EarthSun['x'][t] - EarthSat['x'][t], EarthSun['y'][t] - EarthSat['y'][t], EarthSun['z'][t] - EarthSat['z'][t]]) delta_pos_temp = pos - (EarthSat['hjd'][t] - t0par) * vp - sp delta_pos_proj = np.append(delta_pos_proj, onSky(m_hat, n_hat, delta_pos_temp)) pos_proj = np.append(pos_proj, onSky(m_hat, n_hat, pos)) delta_pos = np.append(delta_pos, delta_pos_temp) delta_pos = np.reshape(delta_pos, (delta_pos.shape[0] / 3, 3)) pos_proj = np.reshape(pos_proj, (pos_proj.shape[0] / 3, 3)) delta_pos_proj = np.reshape(delta_pos_proj, (delta_pos_proj.shape[0] / 3, 3)) EarthSat['xproj'] = pos_proj.T[0] EarthSat['yproj'] = pos_proj.T[1] EarthSat['zproj'] = pos_proj.T[2] EarthSat['deltaxproj'] = delta_pos_proj.T[0] EarthSat['deltayproj'] = delta_pos_proj.T[1] EarthSat['deltazproj'] = delta_pos_proj.T[2] EarthSat['deltax'] = delta_pos.T[0] EarthSat['deltay'] = delta_pos.T[1] EarthSat['deltaz'] = delta_pos.T[2] if t_D_xy != False: D_ecl = np.array([interp1d(EarthSat['hjd'], EarthSat['x'], kind='linear')(t_D_xy), \ interp1d(EarthSat['hjd'], EarthSat['y'], kind='linear')(t_D_xy), \ interp1d(EarthSat['hjd'], EarthSat['z'], kind='linear')(t_D_xy)]) D_enm = onSky(m_hat, n_hat, D_ecl) # print D_enm return EarthSun, EarthSat, D_enm # ---------------------------------------------------------------------- # Functions used to visualise DMCMC results # ---------------------------------------------------------------------- def plot(cfgsetup=False, models=False, model_param=False, time_serie=False, \ obs_properties=False, options=False, interpol_method=False): # Initialisation of parameters # ------------------------------------------------------------------ params = { 't0' : np.array([a.strip() for a in cfgsetup.get('Modelling', 't0').split(',')]),\ 'u0' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'u0').split(',')]),\ 'tE' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'tE').split(',')]),\ 'rho' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'rho').split(',')]),\ 'gamma' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'gamma').split(',')]),\ 'piEE' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'piEE').split(',')]),\ 'piEN' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'piEN').split(',')]),\ 's' : np.array([a.strip() for a in cfgsetup.get('Modelling', 's').split(',')]),\ 'q' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'q').split(',')]),\ 'alpha' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'alpha').split(',')]),\ 'dalpha': np.array([a.strip() for a in cfgsetup.get('Modelling', 'alpha').split(',')]),\ 'ds': np.array([a.strip() for a in cfgsetup.get('Modelling', 'alpha').split(',')])\ } flag_fix_gamma = 1 fitted_param = dict() result = np.array([]) if params['t0'][0] == "fit": fitted_param.update({'t0': params['t0'][3].astype(np.float64)}) result = np.append(result, fitted_param['t0']) if params['u0'][0] == "fit": fitted_param.update({'u0': params['u0'][3].astype(np.float64)}) result = np.append(result, fitted_param['u0']) if params['tE'][0] == "fit": fitted_param.update({'tE': params['tE'][3].astype(np.float64)}) result = np.append(result, fitted_param['tE']) if params['rho'][0] == "fit": fitted_param.update({'rho': params['rho'][3].astype(np.float64)}) result = np.append(result, fitted_param['rho']) if params['gamma'][0] == "fit": fitted_param.update({'gamma': params['gamma'][3].astype(np.float64)}) result = np.append(result, fitted_param['gamma']) flag_fix_gamma = 0 if params['piEE'][0] == "fit": fitted_param.update({'piEE': params['piEE'][3].astype(np.float64)}) result = np.append(result, fitted_param['piEE']) if params['piEN'][0] == "fit": fitted_param.update({'piEN': params['piEN'][3].astype(np.float64)}) result = np.append(result, fitted_param['piEN']) if params['s'][0] == "fit": fitted_param.update({'s': params['s'][3].astype(np.float64)}) result = np.append(result, fitted_param['s']) if params['q'][0] == "fit": fitted_param.update({'q': params['q'][3].astype(np.float64)}) result = np.append(result, fitted_param['q']) if params['alpha'][0] == "fit": fitted_param.update({'alpha': params['alpha'][3].astype(np.float64)}) result = np.append(result, fitted_param['alpha']) if params['dalpha'][0] == "fit": fitted_param.update({'dalpha': params['dalpha'][3].astype(np.float64)}) result = np.append(result, fitted_param['dalpha']) if params['ds'][0] == "fit": fitted_param.update({'ds': params['ds'][3].astype(np.float64)}) result = np.append(result, fitted_param['ds']) nb_param_fit = len(fitted_param) # Initialisation # ------------------------------------------------------------------ path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Chains') fnames_chains = glob.glob( path + cfgsetup.get('Controls', 'Archive') + "*-c*.txt") fnames_chains_exclude = glob.glob( path + cfgsetup.get('Controls', 'Archive') + "*g*.txt") temp = [] for a in fnames_chains: if (a in fnames_chains_exclude) == False: temp.append(a) fnames_chains = copy.deepcopy(temp) del temp, fnames_chains_exclude nb_chains = len(fnames_chains) samples_file = dict( {'chi2': [], 't0': [], 'u0': [], 'tE': [], 'rho': [], \ 'gamma': [], 'piEE': [], 'piEN': [], 's': [], 'q': [], \ 'alpha': [], 'dalpha': [], 'ds': [], 'chain': [], 'fullid': [], 'chi2': [], 'chi2/dof': [],\ 'date_save': [], 'time_save': [], 'id': [], 'accrate': []}) # filename_history = cfgsetup.get('FullPaths', 'Event') \ # + cfgsetup.get('RelativePaths', 'ModelsHistory') \ # + 'ModelsHistory.txt' filename_history = cfgsetup.get('FullPaths', 'Event') \ + cfgsetup.get('RelativePaths', 'ModelsHistory') \ + cfgsetup.get('Controls', 'Archive') \ + '-ModelsSummary.csv' flag_fix = 0 labels = ['t0', 'u0', 'tE', 'rho', 'gamma', 'piEN', 'piEE', 's', 'q', 'alpha', 'dalpha', 'ds'] for lab in labels: if unpack_options(cfgsetup, 'Modelling', lab)[0]!='fix': flag_fix = 1 if os.path.exists(filename_history) & flag_fix: file = open(filename_history, 'r') for line in file: params_model = line if params_model[0] == '#': continue samples_file['fullid'].append(int( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][0])) samples_file['t0'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][1])) samples_file['u0'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][2])) samples_file['tE'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][3])) samples_file['rho'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][4])) samples_file['gamma'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][5])) samples_file['piEN'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][6])) samples_file['piEE'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][7])) samples_file['s'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][8])) samples_file['q'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][9])) samples_file['alpha'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][10])) samples_file['dalpha'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][11])) samples_file['ds'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][12])) samples_file['chi2'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][13])) samples_file['chi2/dof'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][14])) samples_file['accrate'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][15])) samples_file['chain'].append(int( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][16])) file.close() elif flag_fix: # Read on the chains if nb_chains > 0: for i in xrange(nb_chains): file = open(fnames_chains[i], 'r') for line in file: params_model = line if params_model[0] == '#': continue samples_file['id'].append(int( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][0])) samples_file['t0'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][1])) samples_file['u0'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][2])) samples_file['tE'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][3])) samples_file['rho'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][4])) samples_file['gamma'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][5])) samples_file['piEN'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][6])) samples_file['piEE'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][7])) samples_file['s'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][8])) samples_file['q'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][9])) samples_file['alpha'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][10])) samples_file['dalpha'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][11])) samples_file['ds'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][12])) samples_file['chi2'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][13])) samples_file['accrate'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][14])) samples_file['date_save'].append(int( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][15])) samples_file['time_save'].append(int( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][16])) samples_file['chi2/dof'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][17])) samples_file['chain'].append(int(fnames_chains[i][-8:-4])) samples_file['fullid'].append(-1) file.close() # TO BE REMOVE: PB with negative rho. for ii in xrange(len(samples_file['rho'])): if samples_file['rho'][ii] < 0: samples_file['rho'][ii] = 0.000001 # ------------------------------------ # Best model # ------------------------------------------------------------------ rang_2plot = [0] if flag_fix: models2plot = unpack_options(cfgsetup, 'Plotting', 'Models') if len(models2plot)==1: models2plot = unpack_options(cfgsetup, 'Plotting', 'Models', sep='-') if len(models2plot) == 2: first = int(models2plot[0]) second = int(models2plot[1]) nb_local = second - first + 1 models2plot = np.linspace(first, second, nb_local, endpoint=True, dtype='i4') models2plot = ['{:d}'.format(a) for a in models2plot] rang_2plot = [] if (models2plot != ['']) & (os.path.exists(filename_history)): chi2_min = np.min(samples_file['chi2']) samples_file.update( {'dchi2': samples_file['chi2'] - chi2_min}) rang_best_model = np.where(samples_file['dchi2'] == 0)[0][0] for mod in models2plot: if mod != '': try: rang_2plot.append( np.where(np.array(samples_file['fullid']) == int(mod))[ 0][0]) except: sys.exit('Cannot find the models you ask me to plot.') else: chi2_min = np.min(samples_file['chi2']) samples_file.update( {'dchi2': samples_file['chi2'] - chi2_min}) rang_best_model = np.where(samples_file['dchi2'] == 0)[0][0] rang_2plot = [rang_best_model] else: rang_best_model = [0] # Plots for idmod in xrange(len(rang_2plot)): if flag_fix: best_model = dict({}) best_model.update({'t0': samples_file['t0'][rang_2plot[idmod]]}) best_model.update({'u0': samples_file['u0'][rang_2plot[idmod]]}) best_model.update({'tE': samples_file['tE'][rang_2plot[idmod]]}) best_model.update({'rho': samples_file['rho'][rang_2plot[idmod]]}) best_model.update({'gamma': samples_file['gamma'][rang_2plot[idmod]]}) best_model.update({'piEE': samples_file['piEE'][rang_2plot[idmod]]}) best_model.update({'piEN': samples_file['piEN'][rang_2plot[idmod]]}) # best_model.update({'piE': np.sqrt(np.power(samples_file['piEN'][rang_2plot[idmod]],2) + np.power(samples_file['piEN'][rang_2plot[idmod]],2))}) best_model.update({'s': samples_file['s'][rang_2plot[idmod]]}) best_model.update({'q': samples_file['q'][rang_2plot[idmod]]}) best_model.update({'alpha': samples_file['alpha'][rang_2plot[idmod]]}) best_model.update({'dalpha': samples_file['dalpha'][rang_2plot[idmod]]}) best_model.update({'ds': samples_file['ds'][rang_2plot[idmod]]}) best_model.update( {'chi2': samples_file['chi2'][rang_2plot[idmod]]}) best_model.update( {'chi2/dof': samples_file['chi2/dof'][rang_2plot[idmod]]}) # best_model.update({'id': samples_file['id'][rang_2plot[idmod]]}) best_model.update({'chain': samples_file['chain'][rang_2plot[idmod]]}) # best_model.update( # {'date_save': samples_file['date_save'][rang_2plot[idmod]]}) # best_model.update( # {'time_save': samples_file['time_save'][rang_2plot[idmod]]}) best_model.update( {'accrate': samples_file['accrate'][rang_2plot[idmod]]}) best_model.update( {'fullid': samples_file['fullid'][rang_2plot[idmod]]}) else: best_model = dict({}) labels = ['t0', 'u0', 'tE', 'rho', 'gamma', 'piEN', 'piEE', 's', 'q', 'alpha', 'dalpha', 'ds'] for lab in labels: best_model.update({lab: float(unpack_options(cfgsetup, 'Modelling', lab)[3])}) best_model.update({'chi2': 0}) best_model.update({'chi2/dof': 0}) best_model.update({'id': -1}) best_model.update({'chain': -1}) best_model.update({'date_save': -1}) best_model.update({'time_save': -1}) best_model.update({'accrate': 0}) best_model.update({'fullid': -1}) # ------------------------------------------------------------------- def lens_rotation(alpha0, s0, dalpha, ds, t, tb): ''' Compute the angle and the primary-secondary distance with a lens orbital motion. :alpha0: angle at tb :s0: separation at tb :dalpha: lens rotation velocity in rad.year^-1 :ds: separation velocity in year^-1 :t: numpy array of observation dates :tb: a reference date :return: numpy array of the value of the angle and separation for each date ''' Cte_yr_d = 365.25 # Julian year in days alpha = alpha0 - (t - tb) * dalpha / Cte_yr_d # (-1) because if the caustic rotates of dalpha, it is as if the source follows a trajectory with an angle of alpha(tb)-dalpha. s = s0 + (t - tb) * ds / Cte_yr_d return alpha, s # Parameters contraction s0 = best_model['s'] q = best_model['q'] u0 = best_model['u0'] alpha0 = best_model['alpha'] tE = best_model['tE'] t0 = best_model['t0'] piEN = best_model['piEN'] piEE = best_model['piEE'] gamma = best_model['gamma'] dalpha = best_model['dalpha'] ds = best_model['ds'] GL1 = s0 * q / (1 + q) GL2 = - s0 / (1 + q) tb = cfgsetup.getfloat('Modelling', 'tb') chi2_flux = 0 chi2dof_flux = 0 # Best model for data # ------------------------------------------------------------------ # Calculation of the amplification param_model = best_model observatories = np.unique(time_serie['obs']) models_lib = np.unique(time_serie['model']) if cfgsetup.getboolean('Plotting', 'Data'): time_serie.update({'x': np.empty(len(time_serie['dates']))}) time_serie.update({'y': np.empty(len(time_serie['dates']))}) for j in xrange(len(observatories)): cond2 = (time_serie['obs'] == observatories[j]) if flag_fix_gamma: param_model.update({'gamma': time_serie['gamma'][cond2][0]}) for i in xrange(models_lib.shape[0]): cond = (time_serie['model'] == models_lib[i]) &\ (time_serie['obs'] == observatories[j]) if cond.sum() > 0: time_serie_export = time_serie['dates'][cond] DsN_export = time_serie['DsN'][cond] DsE_export = time_serie['DsE'][cond] Ds_export = dict({'N': DsN_export, 'E': DsE_export}) try: kwargs_method = dict(cfgsetup.items(models_lib[i])) except: kwargs_method = dict() amp = models[models_lib[i]].magnifcalc(time_serie_export, param_model, Ds=Ds_export, tb=tb, **kwargs_method) time_serie['amp'][cond] = amp # print amp # print time_serie['amp'][cond] del amp # Calculation of fs and fb fs, fb = fsfb(time_serie, cond2, blending=True) # if (fb/fs < 0 and observatories[j]=="ogle-i"): # fs, fb = fsfb(time_serie, cond2, blending=False) time_serie['fs'][cond2] = fs time_serie['fb'][cond2] = fb # print fs, fb if (observatories[j] == cfgsetup.get('Observatories', 'Reference').lower()) \ | (j == 0): fs_ref = fs fb_ref = fb mag_baseline = 18.0 - 2.5 * np.log10(1.0 * fs_ref + fb_ref) # print fs, fb # Source postion if cond2.sum() > 0: DsN = time_serie['DsN'][cond2] DsE = time_serie['DsE'][cond2] t = time_serie['dates'][cond2] tau = (t - t0) / tE + piEN * DsN + piEE * DsE beta = u0 + piEN * DsE - piEE * DsN z = (tau + 1j * beta) * np.exp(1j * alpha0) time_serie['x'][cond2] = z.real time_serie['y'][cond2] = z.imag # Calculation of chi2 time_serie['flux_model'] = time_serie['amp'] * time_serie['fs'] + \ time_serie['fb'] # time_serie['chi2pp'] = np.power((time_serie['flux'] - time_serie[ # 'flux_model']) / time_serie['err_flux'], 2) time_serie['residus'] = time_serie['magnitude'] - (18.0 - 2.5 * np.log10(time_serie['flux_model'])) time_serie['residus_flux'] = time_serie['flux'] - time_serie['flux_model'] time_serie['chi2pp'] = np.power(time_serie['residus'] / time_serie['err_magn'], 2.0) time_serie['chi2pp_flux'] = np.power(time_serie['residus_flux'] / time_serie['err_flux'], 2.0) chi2 = np.sum(time_serie['chi2pp']) chi2_flux = np.sum(time_serie['chi2pp_flux']) # Calculation of the lightcurve model plot_min = float(options.split('/')[0].split('-')[0].strip()) plot_max = float(options.split('/')[0].split('-')[1].strip()) nb_pts = int(options.split('/')[1].strip()) locations = np.unique(obs_properties['loc']) print " Max magnification: {:.2f}".format(np.max(time_serie['amp'])) # print len(time_serie['amp']) # Fit summary text = "Fit summary" communicate(cfgsetup, 3, text, opts=[printoption.level0], prefix=True, newline=True, tab=False) observatories_com = np.unique(time_serie['obs']) if (cfgsetup.getint("Modelling", "Verbose") >= 3) & (rang_best_model == rang_2plot[idmod]): fn_output_terminal = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Outputs')\ + "Results.txt" # print fn_output_terminal file = open(fn_output_terminal, 'w') text = "\n\033[1m\033[7m {:25s} {:>9s} {:>9s} {:>9s} {:>9s} \033[0m".format( "Site", "chi^2", "chi^2/dof", "RF 1", "RF 2") print text text_precis = "\n {:25s} {:>18s} {:>18s} {:>18s} {:>18s} \n".format( "Site", "chi^2", "chi^2/dof", "RF 1", "RF 2") file.write(text_precis) params_raw = np.array(['t0', 'u0', 'tE', 'rho', 'gamma', 'piEN', 'piEE', 's', 'q', 'alpha', 'dalpha', 'ds']) n_param = nb_param_fit # n_param = int(len(time_serie['dates']) - chi2 / samples_file['chi2/dof'][rang_best_model]) nb_data_tot = 0 # observatories_com = np.unique(time_serie['obs']) text = "" text2 = "" text_precis = "" text2_precis = "" for i in xrange(len(observatories_com)): rf = [float(a.replace("(", "").replace(")", "").strip()) for a in unpack_options(cfgsetup, "Observatories", observatories_com[i])[:2]] cond = time_serie['obs']==observatories_com[i] chi2_com = np.sum(time_serie['chi2pp'][cond]) nb_data_tot = nb_data_tot + len(time_serie['chi2pp'][cond]) if len(time_serie['chi2pp'][cond]) > 0: chi2dof_com = chi2_com / (len(time_serie['chi2pp'][cond])-n_param) else: chi2dof_com = 0.0 text = text + " {:25s} {:9.3e} {:9.3e} {:9.3e} {:9.3e}\n".format(observatories_com[i].upper(), chi2_com, chi2dof_com, rf[0], rf[1]) text_precis = text_precis + " {:25s} {:18.12e} {:18.12e} {:18.12e} {:18.12e}\n".format(observatories_com[i].upper(), chi2_com, chi2dof_com, rf[0], rf[1]) try: g = time_serie["fb"][cond][0]/time_serie["fs"][cond][0] except: g = np.inf # Y = 18.0 - 2.5 * np.log10(time_serie['fb'][cond][0] + time_serie['fs'][cond][0]) Y = time_serie['fb'][cond][0] + time_serie['fs'][cond][0] # Yb = 18.0 - 2.5 * np.log10(time_serie['fb'][cond][0]) Yb = time_serie['fb'][cond][0] # Ys = 18.0 - 2.5 * np.log10(time_serie['fs'][cond][0]) Ys = time_serie['fs'][cond][0] text2 = text2 + " {:25s} {:8.3f} {:8.3f} {:8.3f} {:8.3f} {:5.3f}\n".format( observatories_com[i].upper(), Y, Yb, Ys, g, gamma) text2_precis = text2_precis + " {:25s} {:18.12e} {:18.12e} {:18.12e} {:18.12e} {:18.12e}\n".format( observatories_com[i].upper(), Y, Yb, Ys, g, gamma) if (observatories[i] == cfgsetup.get('Observatories', 'Reference').lower()) \ | (i == 0): Y = 18.0 - 2.5 * np.log10(time_serie['fb'][cond][0] + time_serie['fs'][cond][0]) Yb = 18.0 - 2.5 * np.log10(time_serie['fb'][cond][0]) Ys = 18.0 - 2.5 * np.log10(time_serie['fs'][cond][0]) text3 = "Reference for magnitudes:\n {:25s} {:8.3f} {:8.3f} {:8.3f}\n".format( observatories_com[i].upper(), Y, Yb, Ys) text3_precis = "Reference for magnitudes:\n {:25s} {:18.12e} {:18.12e} {:18.12e}\n".format( observatories_com[i].upper(), Y, Yb, Ys) print text file.write(text_precis) text = "{:25}={:2}{:9.3e}{:4}{:9.3e} (chi^2 on magn)".format("", "", chi2_flux, "", chi2/(nb_data_tot-n_param)) chi2dof_flux = chi2/(nb_data_tot-n_param) print text text = "{:25}={:2}{:18.12e}{:4}{:18.12e} (chi^2 on magn)".format("", "", chi2_flux, "", chi2/(nb_data_tot-n_param)) chi2dof_flux = chi2/(nb_data_tot-n_param) file.write(text) text = "\n\033[1m\033[7m {:78s}\033[0m".format("Best-fitting parameters") print text text = "\n {:78s}\n".format("Best-fitting parameters") file.write(text) piE = np.sqrt(np.power(samples_file['piEN'][rang_best_model], 2) + np.power(samples_file['piEE'][rang_best_model],2)) gamma = np.sqrt((samples_file['ds'][rang_best_model]/samples_file['s'][rang_best_model])**2 + samples_file['dalpha'][rang_best_model]**2) text = "{:>10} = {:.6f}\n".format("q", samples_file['q'][rang_best_model]) + "{:>10} = {:.6f}\n".format("s", samples_file['s'][rang_best_model]) + "{:>10} = {:.6f}\n".format("tE", samples_file['tE'][rang_best_model]) + "{:>10} = {:.6f}\n".format("rho", samples_file['rho'][rang_best_model]) + "{:>10} = {:.6f}\n".format("piEN", samples_file['piEN'][rang_best_model]) + "{:>10} = {:.6f}\n".format("piEE", samples_file['piEE'][rang_best_model]) + "{:>10} = {:.6f}\n".format("piE", piE) + "{:>10} = {:.6f}\n".format("t0", samples_file['t0'][rang_best_model]) + "{:>10} = {:.6f}\n".format("u0", samples_file['u0'][rang_best_model]) + "{:>10} = {:.6f}\n".format("alpha", samples_file['alpha'][rang_best_model]) + "{:>10} = {:.6f}\n".format("dalpha", samples_file['dalpha'][rang_best_model]) + "{:>10} = {:.6f}\n".format("ds", samples_file['ds'][rang_best_model]) + "{:>10} = {:.6f}\n".format("gammaL", gamma) + "{:>10} = {:.6f}\n".format("tp", cfgsetup.getfloat("Modelling", "tp")) + "{:>10} = {:.6f}\n".format("tb", cfgsetup.getfloat("Modelling", "tb")) print text text = "{:>10} = {:.12e}\n".format("q", samples_file['q'][rang_best_model]) + "{:>10} = {:.12e}\n".format("s", samples_file['s'][rang_best_model]) + "{:>10} = {:.12e}\n".format("tE", samples_file['tE'][rang_best_model]) + "{:>10} = {:.12e}\n".format("rho", samples_file['rho'][rang_best_model]) + "{:>10} = {:.12e}\n".format("piEN", samples_file['piEN'][rang_best_model]) + "{:>10} = {:.12e}\n".format("piEE", samples_file['piEE'][rang_best_model]) + "{:>10} = {:.12e}\n".format("piE", piE) + "{:>10} = {:.12e}\n".format("t0", samples_file['t0'][rang_best_model]) + "{:>10} = {:.12e}\n".format("u0", samples_file['u0'][rang_best_model]) + "{:>10} = {:.12e}\n".format("alpha", samples_file['alpha'][rang_best_model]) + "{:>10} = {:.12e}\n".format("dalpha", samples_file['dalpha'][rang_best_model]) + "{:>10} = {:.12e}\n".format("ds", samples_file['ds'][rang_best_model]) + "{:>10} = {:.12e}\n".format("gammaL", gamma) + "{:>10} = {:.12e}\n".format("tp", cfgsetup.getfloat("Modelling", "tp")) + "{:>10} = {:.12e}\n".format("tb", cfgsetup.getfloat("Modelling", "tb")) file.write(text) text = "\n\033[1m\033[7m {:25s} {:>8s} {:>8s} {:>8s} {:>6s} {:>5s}{:3s}\033[0m".format( "Site", "Baseline", "Blending", "Source", "Fb/Fs", "LLD", "") print text text = "\n {:25s} {:>18s} {:>18s} {:>18s} {:>18s} {:>18s}{:3s}\n".format( "Site", "Baseline", "Blending", "Source", "Fb/Fs", "LLD", "") file.write(text) print text2 file.write(text2_precis) print text3 file.write(text3_precis) file.close() # Best model theoretical light curve # ------------------------------------------------------------------ model2load = np.array([]) path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Data') if len(obs_properties['loc']) > 1: name1 = obs_properties['loc'][np.where(np.array( [obs == cfgsetup.get('Observatories', 'Reference').lower() for obs in observatories]) == True)[0][0]] name1 = glob.glob(path + name1 + '.*')[0] else: name1 = glob.glob(path + obs_properties['loc'][0] + '.*')[0] for i in xrange(len(locations)): name = 'Models_' + locations[i] models_temp = model_param[name] name = 'DateRanges_' + locations[i] dates_temp = model_param[name] # min = [] # max = [] # for j in xrange(len(models_temp)): # model2load = np.append(model2load, models_temp[j]) # tmin = float((dates_temp[j]).split('-')[0].strip()) # tmax = float((dates_temp[j]).split('-')[1].strip()) # # min = np.append(min, tmin) # max = np.append(min, tmax) # # min = np.min(min) # max = np.max(max) min = plot_min max = plot_max if i == 0: model_time_serie = np.array([dict({ 'dates': np.linspace(min, max, nb_pts), 'model': np.full(nb_pts, '0', dtype='S100'), 'amp': np.full(nb_pts, 0.1, dtype='f8'), })]) else: model_time_serie = np.append(model_time_serie, np.array([dict({ 'dates': np.linspace(min, max, nb_pts), 'model': np.full(nb_pts, '0', dtype='S100'), 'amp': np.full(nb_pts, 0.1, dtype='f8'), })])) for j in xrange(len(models_temp)): tmin = float((dates_temp[j]).split('-')[0].strip()) tmax = float((dates_temp[j]).split('-')[1].strip()) cond = (model_time_serie[i]['dates'] <= tmax) \ & (model_time_serie[i]['dates'] >= tmin) model_time_serie[i]['model'][cond] = models_temp[j] cond = model_time_serie[i]['model'] == '0' if cond.sum() > 0: model_time_serie[i]['model'][cond] = models_temp[0] # Ephemeris c_icrs = SkyCoord(ra=cfgsetup.get('EventDescription', 'RA'), \ dec=cfgsetup.get('EventDescription', 'DEC'), frame='icrs') # print c_icrs.transform_to('barycentrictrueecliptic') l = c_icrs.transform_to('barycentrictrueecliptic').lon.degree b = c_icrs.transform_to('barycentrictrueecliptic').lat.degree name2 = glob.glob(path + locations[i] + '.*')[0] sTe, sEe, sNe, DsTe, DsEe, DsNe, sTs, sEs, sNs, DsTs, DsEs, DsNs = \ ephemeris.Ds(name1, name2, l, b, cfgsetup.getfloat('Modelling', 'tp'), \ cfgsetup) if name1 != name2: DsN = DsNs DsE = DsEs else: DsN = DsNe DsE = DsEe model_time_serie[i].update({'DsN': np.array( [DsN(a) for a in model_time_serie[i]['dates']])}) model_time_serie[i].update({'DsE': np.array( [DsE(a) for a in model_time_serie[i]['dates']])}) # Amplification models_lib = np.unique(model_time_serie[i]['model']) for k in xrange(models_lib.shape[0]): cond = (model_time_serie[i]['model'] == models_lib[k]) if cond.sum() > 0: time_serie_export = model_time_serie[i]['dates'][cond] DsN_export = model_time_serie[i]['DsN'][cond] DsE_export = model_time_serie[i]['DsE'][cond] Ds_export = dict({'N': DsN_export, 'E': DsE_export}) try: kwargs_method = dict(cfgsetup.items(models_lib[k])) except: kwargs_method = dict() amp = models[models_lib[k]].magnifcalc(time_serie_export, param_model, Ds=Ds_export, tb=tb, **kwargs_method) model_time_serie[i]['amp'][cond] = amp if cfgsetup.getboolean('Plotting', 'Data'): model_time_serie[i].update({'magnitude': 18.0 - 2.5 * np.log10( fs_ref * model_time_serie[i]['amp'] + fb_ref)}) model_time_serie[i].update({'flux': fs_ref * model_time_serie[i]['amp'] + fb_ref}) # Source position in (x, y) DsN = model_time_serie[i]['DsN'] DsE = model_time_serie[i]['DsE'] t = model_time_serie[i]['dates'] tau = (t - t0) / tE + piEN * DsN + piEE * DsE beta = u0 + piEN * DsE - piEE * DsN z = (tau + 1j * beta) * np.exp(1j * alpha0) model_time_serie[i].update({'x': z.real}) model_time_serie[i].update({'y': z.imag}) del amp, DsN_export, DsE_export, Ds_export, cond, time_serie_export # print model_time_serie[1]['model'] # # Interpolation method # # ------------------------------------------------------------------------- # key_list = [key for key in interpol_method] # # interpol_func = dict() # if len(key_list) > 0: # for i in xrange(len(key_list)): # time_serie_export = interpol_method[key_list[i]][0] # # DsN_export = interpol_method[key_list[i]][1] # DsE_export = interpol_method[key_list[i]][2] # # Ds_export = dict({'N':DsN_export, 'E':DsE_export}) # # name = key_list[i].split('#')[1] # amp = models[name].magnifcalc(time_serie_export, param_model, Ds=Ds_export) # # interpol_method[key_list[i]][3] = amp # # interpol_func = interpolate.interp1d(time_serie_export, amp) # interpol_func.update({key_list[i]: interpolate.interp1d(time_serie_export, amp, kind='linear')}) # Reference frames # ------------------------------------------------------------------ # Orientations on the Sky path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Data') if len(model_time_serie) == 2: EarthSun, EarthSat, D_enm = boussole( EarthSunFile=path + "Earth.dat", EarthSatelliteFile=path + "Spitzer.dat", cfg=cfgsetup, t_D_xy=best_model['t0']) else: EarthSun, EarthSat, D_enm = boussole( EarthSunFile=path + "Earth.dat", EarthSatelliteFile=path + "Earth.dat", cfg=cfgsetup, t_D_xy=best_model['t0']) # Sigma clipping # ------------------------------------------------------------------ # Determine the best rescaling factors if (cfgsetup.getint("Modelling", "Verbose") > 4) & (nb_param_fit > 0): text = "\n\033[1m\033[7m{:>2s}{:<25s}{:1s}{:>10s}{:1s}{:>5s}{:1s}{:>10s}{:1s}{:>5s}{:1s}{:>10s}{:1s}{:>5s}{:2s}\033[0m".format( "", "Site", "", "RF1(loop3)", "", "Rej.", "", "RF1(loop5)", "", "Rej.", "", "RF1(loop7)", "", "Rej.", "") print text text = "" for j in xrange(len(observatories_com)): # Pre-defied rescaling factors f1 = float(unpack_options(cfgsetup, 'Observatories', observatories[0])[0].replace('(', '')) f2 = float(unpack_options(cfgsetup, 'Observatories', observatories[0])[1].replace(')', '')) if abs(f1-1.0) > 1e-10: text = "{:>2s}{:<25s}{:<30s}\n".format("", observatories_com[j].upper(), "RF 1 not equal to 1.0.") continue # Select the observatory condj = np.where(time_serie['obs'] == observatories[j]) time_serie_SC = copy.deepcopy(time_serie) [time_serie_SC.update({key: time_serie_SC[key][condj]}) for key in time_serie_SC] # Compute the degree of freedom ddl nb_data = len(time_serie_SC['dates']) if nb_data > nb_param_fit: ddl = nb_data - nb_param_fit else: ddl = nb_data # Compute the rescaling factor f1 from the value of f2 rejected_points_id = np.array([]) nb_reject_sc = 0 nb_loops = 7 text = text + "{:>2s}{:<25s}".format("", observatories_com[j].upper()) for i in xrange(nb_loops): mean = np.mean(time_serie_SC['err_magn']) sdt = np.std(time_serie_SC['err_magn']) toremove = np.where(np.abs(time_serie_SC['err_magn'] - mean) > 3.0 * sdt) nb_reject_sc = nb_reject_sc + len(toremove[0]) if len(toremove[0]) > 0: rejected_points_id = np.append(rejected_points_id, time_serie_SC['id'][toremove]) [time_serie_SC.update({key : np.delete(time_serie_SC[key], toremove)}) for key in time_serie_SC] if (i==2) | (i==4) | (i==6): f1_op = np.sqrt(np.sum(time_serie_SC['chi2pp']) * (1.0 / ddl - (f2 ** 2) * np.sum(np.power(time_serie_SC['residus'], -2.0)))) text = text + "{:>10.3f}{:1s}{:>5d}{:1s}".format( f1_op, "", nb_reject_sc, "") text = text + "\n" print text # --------------------------------------------------------------------- # Create an html webpage (amplification if no data, magnitude if so) # --------------------------------------------------------------------- if cfgsetup.getboolean('Plotting', 'Data'): filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if (best_model['fullid'] == -1) & flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-flux.html' title = cfgsetup.get('EventDescription', 'Name') + ': best model last MCMC' elif flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-flux-' \ + repr(best_model['fullid']) + '.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model # ' + repr( best_model['fullid']) else: filename = filename + cfgsetup.get('Controls', 'Archive') + '-flux-fix.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model fix' if os.path.exists(filename): os.remove(filename) bplt.output_file(filename) fig = np.array([]) # Preparation of the data time_serie.update({'colour': np.full(len(time_serie['dates']), 'black', dtype='S100')}) time_serie.update( {'mag_align': np.full(len(time_serie['dates']), 0, dtype='f8')}) time_serie.update({'flux_align': np.full(len(time_serie['dates']), 0, dtype='f8')}) time_serie.update({'sigflux_align': np.full(len(time_serie['dates']), 0, dtype='f8')}) time_serie.update({'resfluxalign': np.full(len(time_serie['dates']), 0, dtype='f8')}) palette = plt.get_cmap('Blues') observatories = np.unique(time_serie['obs']) for i in xrange(len(observatories)): cond = np.where(time_serie['obs'] == observatories[i]) cond2 = \ np.where(observatories[i] == np.array(obs_properties['key']))[0][0] color = '#' + obs_properties['colour'][cond2] time_serie['colour'][cond] = color # Align flux on reference # ----------------------- Y = ((time_serie['flux'][cond] - time_serie['fb'][cond])/time_serie['fs'][cond]) Y = fs_ref * Y + fb_ref time_serie['flux_align'][cond] = Y time_serie['sigflux_align'][cond] = fs_ref * time_serie['err_flux'][cond] / time_serie['fs'][cond] time_serie['resfluxalign'][cond] = fs_ref * time_serie['residus_flux'][cond] / time_serie['fs'][cond] # Create output files # --------------------------------------------------------------------- path_outputs = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Outputs') if not os.path.exists(path_outputs): os.makedirs(path_outputs) if nb_param_fit > 0: for j in xrange(len(observatories_com)): text = "#{0:>17s} {1:>6s} {2:>9s} {3:>12s} {4:>10s} {5:>9s} {6:>6s} {7:>9s}\n".format( "Date", "Magn", "Err_Magn", "Err_Magn_Res", "Resi", "Back", "Seeing", "Chi2") filename = path_outputs + observatories_com[j].upper() + ".dat" condj = np.where(time_serie['obs'] == observatories[j]) time_serie_SC = copy.deepcopy(time_serie) [time_serie_SC.update({key: time_serie_SC[key][condj]}) for key in time_serie_SC] for jj in xrange(len(time_serie_SC['dates'])): text = text +\ "{0:18.12f} {1:6.3f} {2:9.3e} {3:12.3e} {4:10.3e} {5:9.3f} {6:6.3f} {7:9.3e}".format( time_serie_SC['dates'][jj], time_serie_SC['mag_align'][jj], time_serie_SC['err_magn_orig'][jj], time_serie_SC['err_magn'][jj], time_serie_SC['residus'][jj], time_serie_SC['background'][jj], time_serie_SC['seeing'][jj], time_serie_SC['chi2pp'][jj]) text = text + "\n" file = open(filename, 'w') file.write(text) file.close() # -------------------------------------------------------------------- # Plot the flux and the model # -------------------------------------------------------------------- source = ColumnDataSource(time_serie) col_used = ['id', 'obs', 'dates', 'flux_align', 'x', 'y', 'colour', 'resfluxalign'] col_all = [key for key in time_serie] [col_all.remove(key) for key in col_used] [source.remove(key) for key in col_all] hover_plc = HoverTool(tooltips=[("ID", "@id{int}"), ("Obs", "@obs"), ("Date", "@dates{1.11}")]) tmin = float(options.split('/')[0].split('-')[0].strip()) tmax = float(options.split('/')[0].split('-')[1].strip()) ymin = np.min(time_serie['flux_align']) ymax = np.max(time_serie['flux_align']) tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap", hover_plc] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=1200, plot_height=600, x_range=(tmin, tmax), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[0] # Show the time interval of different algorithms # ---------------------------------------------- colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): name = 'Models_' + locations[i] models_temp = model_param[name] name = 'DateRanges_' + locations[i] dates_temp = model_param[name] for j in xrange(len(models_temp)): tmin = float((dates_temp[j]).split('-')[0].strip()) tmax = float((dates_temp[j]).split('-')[1].strip()) X = np.ones(2) * tmin Y = np.linspace(-1e6, 1e6, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) X = np.ones(2) * tmax Y = np.linspace(-1e6, 1e6, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 if cfgsetup.getboolean("Plotting", "Data"): # Plot the model # -------------- colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): X = model_time_serie[i]['dates'] Y = model_time_serie[i]['flux'] fig_curr.line(X, Y, line_width=2, color=colours[id_colour], alpha=1) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Plot the flux # ------------- fig_curr.circle('dates', 'flux_align', size=8, color='colour', alpha=0.4, source=source) # Write the legend # ---------------- for i in xrange(len(obs_properties['name'])): col = '#' + obs_properties['colour'][i] fig_curr.circle(-10000, -10000, size=8, color=col, alpha=0.4, legend=obs_properties['name'][i]) # Plot flux errors # ---------------- err_xs = [] err_ys = [] for x, y, yerr, colori in zip(time_serie['dates'], time_serie['flux_align'], time_serie['sigflux_align'], time_serie['colour']): err_xs.append((x, x)) err_ys.append((y - yerr, y + yerr)) fig_curr.multi_line(err_xs, err_ys, color=time_serie['colour']) # Layout # ------ fig_curr.xaxis.axis_label = u'HJD - 2,450,000' fig_curr.yaxis.axis_label = u'Flux' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None # -------------------------------------------------------------------- # Plot the residuals # -------------------------------------------------------------------- hover_prm = HoverTool(tooltips=[("ID", "@id{int}"), ("Obs", "@obs"), ("Date", "@dates{1.11}")]) tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap", hover_prm] fig = np.append(fig, bplt.figure(toolbar_location="above", plot_width=1200, plot_height=300, x_range=fig[0].x_range, y_range=(-0.25, 0.25), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[1] # Annotations # ----------- colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): name = 'Models_' + locations[i] models_temp = model_param[name] name = 'DateRanges_' + locations[i] dates_temp = model_param[name] for j in xrange(len(models_temp)): tmin = float((dates_temp[j]).split('-')[0].strip()) tmax = float((dates_temp[j]).split('-')[1].strip()) X = np.ones(2) * tmin Y = np.linspace(-100, 100, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) X = np.ones(2) * tmax Y = np.linspace(-100, 100, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Residuals (flux) # ---------------- fig_curr.circle('dates', 'resfluxalign', size=8, color='colour', alpha=0.4, source=source) # Errors on flux # -------------- err_xs = [] err_ys = [] for x, y, yerr, colori in zip(time_serie['dates'], time_serie['resfluxalign'], time_serie['sigflux_align'], time_serie['colour']): err_xs.append((x, x)) err_ys.append((y - yerr, y + yerr)) fig_curr.multi_line(err_xs, err_ys, color=time_serie['colour']) X = np.linspace(-100000, 100000, 2) Y = np.ones(2) * 0 fig_curr.line(X, Y, line_width=1, color='dimgray', alpha=1) X = np.linspace(-100000, 100000, 2) Y = np.ones(2) * 0.1 fig_curr.line(X, Y, line_width=0.5, color='dimgray', alpha=0.5) X = np.linspace(-100000, 100000, 2) Y = np.ones(2) * (-0.1) fig_curr.line(X, Y, line_width=0.5, color='dimgray', alpha=0.5) # Layout # ^^^^^^ fig_curr.xaxis.axis_label = u'HJD - 2,450,000' fig_curr.yaxis.axis_label = u'Residuals (flux)' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None # .................................................................. # Plot caustic 1 : pc1 # .................................................................. hover_pc1 = HoverTool( tooltips=[ ("ID", "@id{int}"), ("Obs", "@obs"), ("Date", "@dates{1.11}") ] ) xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap", hover_pc1] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=600, plot_height=560, x_range=(xmin, xmax), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[2] # Caustic # ^^^^^^^ # Case of lens orbital rotation try: time_caustic = options.split('/')[2].replace('[','').replace(']','').split('-') time_caustic = np.array([float(a.strip()) for a in time_caustic]) n_caustics = len(time_caustic) nb_pts_caus = 1000 alpha, s = lens_rotation(alpha0, s0, dalpha, ds, time_caustic, tb) color_caustics = np.array(['Orange', 'SeaGreen', 'LightSeaGreen', 'CornflowerBlue', 'DarkViolet']) except: nb_pts_caus = 1000 n_caustics = 0 if q > 1e-10: if n_caustics > 0: for i in xrange(n_caustics): # > Courbes critiques et caustiques delta = 2.0 * np.pi / (nb_pts_caus - 1.0) phi = np.arange(nb_pts_caus) * delta critic = np.array([]) for phi_temp in phi[:]: critic = np.append(critic, critic_roots(s[i], q, phi_temp)) caustic = critic - 1 / (1 + q) * (1 / critic.conjugate() + q / (critic.conjugate() + s[i])) caustic = caustic + GL1 # From Cassan (2008) to CM caustic = caustic * np.exp(1j*(alpha[i]-alpha0)) fig_curr.circle(caustic.real, caustic.imag, size=0.5, color=color_caustics[0], alpha=0.5) print color_caustics color_caustics = np.roll(color_caustics, -1) # > Courbes critiques et caustiques delta = 2.0 * np.pi / (nb_pts_caus - 1.0) phi = np.arange(nb_pts_caus) * delta critic = np.array([]) for phi_temp in phi[:]: critic = np.append(critic, critic_roots(s0, q, phi_temp)) caustic = critic - (1.0/(1 + q)) * (1/critic.conjugate() + q/(critic.conjugate() + s0)) caustic = caustic + GL1 # From Cassan (2008) to CM fig_curr.circle(caustic.real, caustic.imag, size=0.5, color='red', alpha=0.5) fig_curr.circle(GL1.real, GL1.imag, size=5, color='orange', alpha=1) fig_curr.circle(GL2.real, GL2.imag, size=5, color='orange', alpha=1) else: fig_curr.circle(0, 0, size=5, color='orange', alpha=1) # Trajectories # ^^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): temp = np.array([abs(a - best_model['t0']) for a in model_time_serie[i]['dates']]) rang_c = np.where(temp == np.min(temp))[0][0] X = model_time_serie[i]['x'] Y = model_time_serie[i]['y'] fig_curr.line(X, Y, line_width=2, color=colours[id_colour], alpha=1) # Arrows n = 0 z = (X[n] + 1j * Y[n]) - (X[n + 1] + 1j * Y[n + 1]) angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [X[n], X[n]] Y_arr = [Y[n], Y[n]] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) n = len(model_time_serie[i]['x']) - 2 z = (X[n] + 1j * Y[n]) - (X[n + 1] + 1j * Y[n + 1]) angle = [np.angle(z * np.exp(1j * np.pi / 5)), np.angle(z * np.exp(-1j * np.pi / 5))] X_arr = [X[n + 1], X[n + 1]] Y_arr = [Y[n + 1], Y[n + 1]] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) XX = np.array( X[rang_c] + 1j * Y[rang_c] + best_model['rho'] * np.exp( 1j * np.linspace(0, 2.0 * np.pi, 100))) # fig_curr.line(XX.real, XX.imag, line_width=0.5, color='black', alpha=0.5) fig_curr.patch(XX.real, XX.imag, color='black', alpha=0.3) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Trajectories (data) # ^^^^^^^^^^^^^^^^^^^ fig_curr.circle('x', 'y', size=8, color='colour', alpha=0.5, source=source) # Rotation for Earth + Spitzer # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ if len(model_time_serie) == 2: # Find the vector D in (x, y) at t0 source_t0_earth = np.array([ \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['x'], kind='linear')(best_model['t0']), \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['y'], kind='linear')(best_model['t0']) ]) source_t0_earth_pente = np.array([ \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['x'], kind='linear')(best_model['t0'] + 0.1), \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['y'], kind='linear')(best_model['t0'] + 0.1) ]) source_t0_earth_pente = ( source_t0_earth_pente - source_t0_earth) / 0.1 source_t0_spitzer = np.array([interp1d( model_time_serie[1]['dates'], model_time_serie[1]['x'], kind='linear')(best_model['t0']), \ interp1d( model_time_serie[1]['dates'], model_time_serie[1]['y'], kind='linear')( best_model['t0'])]) source_t0_spitzer_pente = np.array([ \ interp1d(model_time_serie[1]['dates'], model_time_serie[1]['x'], kind='linear')( best_model['t0'] + 0.1), \ interp1d(model_time_serie[1]['dates'], model_time_serie[1]['y'], kind='linear')( best_model['t0'] + 0.1) ]) source_t0_spitzer_pente = ( source_t0_spitzer_pente - source_t0_spitzer) / 0.1 D_t0_xy = source_t0_spitzer - source_t0_earth # Angle between D in (x,y) and (E,N) # Caution: we rotate (x,y) by pi/2, so y is towards left, x towards # top. Now we can compute the rotation angle beetween \Delta\zeta # and D in (E,N). This angle + pi/2 gives the rotation angle to draw # trajectories in (E,N). All this is necessary because (E,N,T) is # equivalent to (y, x, T) with T is the target. D_xy_c = (D_t0_xy[0] + 1j * D_t0_xy[1]) * np.exp(1j * np.pi / 2.0) D_c = D_enm[0] + 1j * D_enm[1] alpha1 = np.angle(D_xy_c, deg=False) alpha2 = np.angle(D_c, deg=False) # epsilon = (angle_between(D_t0_xy, np.array([D_enm[0], D_enm[1]]))) epsilon = (angle_between(np.array([D_xy_c.real, D_xy_c.imag]), np.array( [D_enm[0], D_enm[1]]))) + np.pi / 2.0 rotation = np.exp(1j * epsilon) # print alpha1*180.0/np.pi, alpha2*180.0/np.pi, epsilon*180.0/np.pi # Unit vectors in xy x_hat_xy = 1.0 y_hat_xy = 1j e_hat_xy = x_hat_xy * np.exp(1j * epsilon) n_hat_xy = y_hat_xy * np.exp(1j * epsilon) # Unit vectors in EN e_hat_en = 1.0 n_hat_en = 1j x_hat_en = e_hat_en * np.exp(-1j * epsilon) y_hat_en = n_hat_en * np.exp(-1j * epsilon) # D in (x,y) palette = plt.get_cmap('Paired') id_palette = 0.090909 # from 0 to 11 X = np.linspace(source_t0_earth[0], source_t0_spitzer[0], 2) Y = np.linspace(source_t0_earth[1], source_t0_spitzer[1], 2) n = 9 fig_curr.line(X, Y, line_width=2, line_dash='dashed', color='green', alpha=1) fig_curr.circle(X[0], Y[0], size=15, color='green', alpha=0.5) fig_curr.circle(X[1], Y[1], size=15, color='green', alpha=0.5) # ax_curr.plot(X, Y, dashes=(4, 2), lw=1, # color=palette(n * id_palette), alpha=1, zorder=20) # ax_curr.scatter(X[0], Y[0], 15, marker="o", linewidths=0.3, # facecolors=palette(n * id_palette), edgecolors='k', # alpha=0.8, zorder=20) # ax_curr.scatter(X[1], Y[1], 15, marker="o", linewidths=0.3, # facecolors=palette(n * id_palette), edgecolors='k', # alpha=0.8, zorder=20) # # Layout # ^^^^^^ fig_curr.xaxis.axis_label = u'\u03B8\u2081 (Einstein units)' fig_curr.yaxis.axis_label = u'\u03B8\u2082 (Einstein units)' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None # .................................................................. # Plot caustic 2 : pc2 # .................................................................. # if 0: if len(model_time_serie) == 2: # Caution: we draw in (East, North) with East towards the left hand side. # So, X must be Eastern component, Y must be Northern component. # Then, always plot -X, Y to get plots in (West, North) frame. # Finaly reverse x-axis to get back to the East towards left. # Preparation # ^^^^^^^^^^^ time_serie.update({'-x_complex': -( (time_serie['x'] + 1j * time_serie['y']) * rotation).real}) time_serie.update({'y_complex': ( (time_serie['x'] + 1j * time_serie['y']) * rotation).imag}) # Plot # ^^^^ source = ColumnDataSource(time_serie) hover_pc2 = HoverTool( tooltips=[ ("ID", "@id{int}"), ("Obs", "@obs"), ("Date", "@dates{1.11}") ] ) xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap", hover_pc2] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=560, plot_height=600, x_range=(xmax, xmin), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[3] # Caustic # ^^^^^^^ if q > 1e-10: caustic = caustic * rotation fig_curr.circle(-caustic.real, caustic.imag, size=0.5, color='red', alpha=0.5) X = (s0 * q / (1 + q)) * rotation fig_curr.circle(-X.real, X.imag, size=5, color='orange', alpha=1) X = (s0 * q / (1 + q) - s0) * rotation fig_curr.circle(-X.real, X.imag, size=5, color='orange', alpha=1) else: fig_curr.circle(0, 0, size=5, color='orange', alpha=1) # Trajectories # ^^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): X = (model_time_serie[i]['x'] + 1j * model_time_serie[i][ 'y']) * rotation fig_curr.line(-X.real, X.imag, line_width=2, color=colours[id_colour], alpha=1) # Arrows n = 0 z = X[n] - X[n + 1] angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [-X[n].real, -X[n].real] Y_arr = [X[n].imag, X[n].imag] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) n = len(model_time_serie[i]['x']) - 2 z = X[n] - X[n + 1] angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [-X[n + 1].real, -X[n + 1].real] Y_arr = [X[n + 1].imag, X[n + 1].imag] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Trajectories (data) # ^^^^^^^^^^^^^^^^^^^ fig_curr.circle('-x_complex', 'y_complex', size=8, color='colour', alpha=0.5, source=source) # Some specific positions # ^^^^^^^^^^^^^^^^^^^^^^^ # D in (e,n) at tO A = (source_t0_earth[0] + 1j * source_t0_earth[1]) * rotation B = (source_t0_spitzer[0] + 1j * source_t0_spitzer[1]) * rotation X = np.linspace(A.real, B.real, 2) Y = np.linspace(A.imag, B.imag, 2) n = 9 fig_curr.line(-X, Y, line_width=2, line_dash='dashed', color='green', alpha=1) fig_curr.circle(-X[0], Y[0], size=15, color='green', alpha=0.5) fig_curr.circle(-X[1], Y[1], size=15, color='green', alpha=0.5) # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'theta / theta_E (East)' fig_curr.yaxis.axis_label = 'theta / theta_E (North)' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None # ------------------------------------------------------------------ # Save the html page # ------------------------------------------------------------------ if len(model_time_serie) == 2: final = blyt.column(fig[0], fig[1], blyt.row(fig[2], fig[3])) bplt.save(final) if len(model_time_serie) != 2: final = blyt.column(fig[0], fig[1], fig[2]) # final = blyt.column(fig[0], fig[1]) bplt.save(final) # ------------------------------------------------------------------ # Modify the html page # ------------------------------------------------------------------ filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if cfgsetup.getboolean('Plotting', 'Data'): filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if (best_model['fullid'] == -1) & flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-flux.html' title = cfgsetup.get('EventDescription', 'Name') + ': best model last MCMC' elif flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-flux-' \ + repr(best_model['fullid']) + '.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model # ' + repr( best_model['fullid']) else: filename = filename + cfgsetup.get('Controls', 'Archive') + '-flux-fix.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model fix' file = open(filename, 'r') file_new = '' for line in file: # print line.strip()[:7] if line.strip()[:7] == '<title>': file_new = file_new \ + ' <style type="text/css">\n' \ + ' p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 43.0px; font: 36.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n'\ + ' p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 21.0px; font: 18.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n'\ + ' p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 15.0px; font: 12.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n'\ + ' p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 14.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000; min-height: 17.0px}\n'\ + ' p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}\n'\ + ' p.p6 {margin: 0.0px 0.0px 12.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}\n'\ + ' p.p7 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 14.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n'\ + ' span.s1 {font-kerning: none}\n'\ + ' span.s10 {font: 14.0px "Lucida Grande"; color: #585858}\n'\ + ' hr {\n'\ + ' display: block;\n'\ + ' margin-top: 0.5em;\n'\ + ' margin-bottom: 0.5em;\n'\ + ' margin-left: auto;\n'\ + ' margin-right: auto;\n'\ + ' border-style: inset;\n'\ + ' border-width: 1px;\n'\ + ' }\n'\ + ' </style>\n'\ + ' <title>' + 'muLAn ' + cfgsetup.get('EventDescription', 'Name')[4:] + '/' + cfgsetup.get('Controls', 'Archive') + '#' + repr(best_model['fullid']) + '</title>\n'\ + ' <meta name="Author" content="Clement Ranc">\n' elif line.strip()[:7] == '</head>': file_new = file_new\ + ' <script type="text/x-mathjax-config">\n'\ + " MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\\(','\\\)']]}});\n"\ + ' </script>\n'\ + ' <script type="text/javascript" async src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML"></script>\n'\ + ' </head>\n' elif line.strip()[:6] == '<body>': file_new = file_new \ + ' <body>\n\n' \ + '<p class="p1"><span class="s1"><b>' + title + '</b></span></p>\n' \ + '<p class="p2"><span class="s1"><br>\n' \ + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(t_0\) = ' + repr(best_model['t0']) + ' days</span></p>\n' \ + '<p class="p3"><span class="s1">\(u_0\) = ' + repr(best_model['u0']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(t_\mathrm{E}\) = ' + repr(best_model['tE']) + ' days</span></p>\n' \ + '<p class="p3"><span class="s1">\(\\rho\) = ' + repr(best_model['rho']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(\pi_\mathrm{EN}\) = ' + repr(best_model['piEN']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(\pi_\mathrm{EE}\) = ' + repr(best_model['piEE']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(s\) = ' + repr(best_model['s']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(q\) = ' + repr(best_model['q']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(\\alpha\) = ' + repr(best_model['alpha']) + ' radians</span></p>\n' \ + '<p class="p3"><span class="s1">\(\mathrm{d}\\alpha/\mathrm{d}t\)= ' + repr(best_model['dalpha']) + ' radians/years</span></p>\n' \ + '<p class="p3"><span class="s1">\(\mathrm{d}s/\mathrm{d}t\) = ' + repr(best_model['ds']) + ' years^-1</span></p>\n' \ + '<p class="p3"><span class="s1">\(\chi^2\) = ' + repr(chi2_flux) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(\chi^2/\mathrm{dof}\) = ' + repr(chi2dof_flux) + '</span></p>\n' \ + '<p class="p2"><span class="s1"><br>\n' \ + '</span></p>\n' elif line.strip()[:7] == '</body>': file_new = file_new \ + ' <BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n' \ + ' <BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n' \ + ' <hr>\n' \ + ' <BR>\n' \ + ' <footer>\n'\ + ' <p class="p7"><span class="s10">Modelling and page by muLAn (MicroLensing Analysis software).</span></p>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' </footer>\n' \ + ' </body>\n' else: file_new = file_new + line file.close() file = open(filename, 'w') file.write(file_new) file.close() if 0: # PLOT STATISTIC RESIDUAL IN MAG ================================== for j in xrange(len(observatories)): cond2 = (time_serie['obs'] == observatories[j]) # Configuration # ------------------------------------------------------------------ moteur = 'defaultSmall_pdf' # ------------------------------------------------------------------ # Conversions in2cm = 2.54 cm2in = 1.0 / in2cm in2pt = 72.27 pt2in = 1.0 / 72.27 cm2pt = cm2in * in2pt pt2cm = 1.0 / cm2pt # ------------------------------------------------------------------ # Configuration à compléter fig_width_cm = 6.5 fig_height_cm = 4.5 path = cfgsetup.get('FullPaths', 'Event')\ + cfgsetup.get('RelativePaths', 'Plots') filename = path + cfgsetup.get('Controls', 'Archive')\ + "-" + observatories[j]\ + '-Residuals_Statistics' # ------------------------------------------------------------------ # Calculs pour configuration fig_width_pt = fig_width_cm * cm2pt fig_height_pt = fig_height_cm * cm2pt # golden_mean = (math.sqrt(5)-1.0)/2.0 = 0.62 extension = moteur[-3:] filename_moteur = full_path + 'plotconfig/matplotlibrc_' + moteur pylab.rcParams.update( mpl.rc_params_from_file(filename_moteur, fail_on_error=True)) fig_size = np.array([fig_width_pt, fig_height_pt]) * pt2in # ------------------------------------------------------------------ fig1 = plt.figure('Figure', figsize=fig_size) # .................................................................. # Plot 1 # .................................................................. layout = [1.0, 0.8, 5, 3.1] # en cm kde = np.array(layout) * cm2in / np.array( [fig_size[0], fig_size[1], fig_size[0], fig_size[1]]) ax_curr = fig1.add_axes(kde) grandeur = time_serie['residus'][cond2] nb_bins = 2*int(np.sqrt(np.max([len(grandeur), 3]))) lim_stat = [np.min(grandeur), np.max(grandeur)] X = grandeur hist, bin_edges = np.histogram(X, bins=nb_bins, range=(lim_stat), density=1) hist_plot = np.append(hist, [hist[-1]]) / np.max(hist) ax_curr.step(bin_edges, hist_plot, 'k-', where="mid", zorder=2) # Model model = GaussianMixture(n_components=1).fit(np.atleast_2d(grandeur).T) X = np.atleast_2d(np.linspace(lim_stat[0], lim_stat[1], 1000)).T logprob = model.score_samples(X) pdf_individual = np.exp(logprob) pdf_individual = pdf_individual / np.max(pdf_individual) ax_curr.plot(X.T[0], pdf_individual, ls='-', color='b', zorder=1) mean = np.mean(X.T[0]) rms = np.std(X.T[0]) chat = "mean {:.4f}\nstd dev {:.4f}".format(mean, rms) position = [1, 1] ax_curr.annotate(chat, xy=position, xycoords='axes fraction', ha="right", va="center", color='k', fontsize=5, backgroundcolor='w', zorder=100) # Limits # ^^^^^^ # ax_curr.set_xlim(0, 3.5) ax_curr.set_ylim(0, 1.05) # ax_curr.set_ylim(ax_curr.get_ylim()[1], ax_curr.get_ylim()[0]) # ax_curr.set_xscale('log') # ax_curr.set_yscale('log') # Ticks # ^^^^^ # ax_curr.xaxis.set_major_locator(MultipleLocator(0.4)) ax_curr.xaxis.set_major_locator(MaxNLocator(5)) minor = 0.5 * (np.roll(ax_curr.get_xticks(), -1) - ax_curr.get_xticks())[0] minor_locator = MultipleLocator(minor) ax_curr.xaxis.set_minor_locator(minor_locator) ax_curr.yaxis.set_major_locator(MultipleLocator(0.2)) # ax_curr.yaxis.set_major_locator(MaxNLocator(4)) minor = 0.5 * (np.roll(ax_curr.get_yticks(), -1) - ax_curr.get_yticks())[0] minorLocator = MultipleLocator(minor) ax_curr.yaxis.set_minor_locator(minorLocator) # Legend # ^^^^^^ ax_curr.set_xlabel(ur"%s" % ("$\sigma$ (mag)"), labelpad=0) ax_curr.set_ylabel(ur"%s" % ("count"), labelpad=3) # # --> Options de fin # # for tick in ax_curr.get_yaxis().get_major_ticks(): # tick.set_pad(2) # tick.label1 = tick._get_text1() # for tick in ax_curr.get_xaxis().get_major_ticks(): # tick.set_pad(2) # tick.label1 = tick._get_text1() # .................................................................. # SAVE FIGURE # .................................................................. if 0: plt.show() fig1.savefig(filename + "." + extension, transparent=False, dpi=1400) plt.close() # ================================================================= else: filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if (best_model['fullid'] == -1) & flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification.html' title = cfgsetup.get('EventDescription', 'Name') + ': best model last MCMC' elif flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification-' \ + repr(best_model['fullid']) + '.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model # ' + repr( best_model['fullid']) else: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification-fix.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model fix' if os.path.exists(filename): os.remove(filename) bplt.output_file(filename) fig = np.array([]) plot_counter = 0 observatories = np.unique(time_serie['obs']) # .................................................................. # Plot light curve : amplification # .................................................................. tmin = float(options.split('/')[0].split('-')[0].strip()) tmax = float(options.split('/')[0].split('-')[1].strip()) ymin = 0.9 ymax = 0 for i in xrange(len(locations)): ymax_temp = np.max(model_time_serie[i]['amp']) ymax = np.max(np.array([ymax, ymax_temp])) tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap"] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=1200, plot_height=600, x_range=(tmin, tmax), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[plot_counter] # Annotations # ^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): name = 'Models_' + locations[i] models_temp = model_param[name] name = 'DateRanges_' + locations[i] dates_temp = model_param[name] for j in xrange(len(models_temp)): tmin = float((dates_temp[j]).split('-')[0].strip()) tmax = float((dates_temp[j]).split('-')[1].strip()) X = np.ones(2) * tmin Y = np.linspace(-100000, 100000, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) X = np.ones(2) * tmax Y = np.linspace(-100000, 100000, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) X = np.linspace(-100000, 100000, 2) Y = 1.0 * np.ones(2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Amplification models # ^^^^^^^^^^^^^^^^^^^^ colours = ['black', '#297CC4', 'green'] id_colour = 0 for i in xrange(len(locations)): X = model_time_serie[i]['dates'] Y = model_time_serie[i]['amp'] fig_curr.line(X, Y, line_width=2, color=colours[id_colour], alpha=1) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'HJD - 2,450,000' fig_curr.yaxis.axis_label = 'Amplification' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None plot_counter = plot_counter + 1 # .................................................................. # Plot caustic 1 : pc1 # .................................................................. # Plot # ^^^^ xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap"] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=600, plot_height=560, x_range=(xmin, xmax), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[plot_counter] # Caustic # ^^^^^^^ # Case of lens orbital rotation try: time_caustic = options.split('/')[2].replace('[','').replace(']','').split('-') time_caustic = np.array([float(a.strip()) for a in time_caustic]) n_caustics = len(time_caustic) nb_pts_caus = 1000 alpha, s = lens_rotation(alpha0, s0, dalpha, ds, time_caustic, tb) color_caustics = np.array(['Orange', 'SeaGreen', 'LightSeaGreen', 'CornflowerBlue', 'DarkViolet']) except: nb_pts_caus = 1000 n_caustics = 0 if q > 1e-10: if n_caustics > 0: for i in xrange(n_caustics): # > Courbes critiques et caustiques delta = 2.0 * np.pi / (nb_pts_caus - 1.0) phi = np.arange(nb_pts_caus) * delta critic = np.array([]) for phi_temp in phi[:]: critic = np.append(critic, critic_roots(s[i], q, phi_temp)) caustic = critic - 1 / (1 + q) * (1 / critic.conjugate() + q / (critic.conjugate() + s[i])) caustic = caustic + GL1 # From Cassan (2008) to CM caustic = caustic * np.exp(1j*(alpha[i]-alpha0)) fig_curr.circle(caustic.real, caustic.imag, size=0.5, color=color_caustics[0], alpha=0.5) color_caustics = np.roll(color_caustics, -1) # > Courbes critiques et caustiques delta = 2.0 * np.pi / (nb_pts_caus - 1.0) phi = np.arange(nb_pts_caus) * delta critic = np.array([]) for phi_temp in phi[:]: critic = np.append(critic, critic_roots(s0, q, phi_temp)) caustic = critic - 1 / (1 + q) * ( 1 / critic.conjugate() + q / (critic.conjugate() + s0)) caustic = caustic + GL1 # From Cassan (2008) to CM fig_curr.circle(caustic.real, caustic.imag, size=0.5, color='red', alpha=0.5) fig_curr.circle(GL1.real, GL1.imag, size=5, color='orange', alpha=1) fig_curr.circle(GL2.real, GL2.imag, size=5, color='orange', alpha=1) else: fig_curr.circle(0, 0, size=5, color='orange', alpha=1) # Trajectories # ^^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): temp = np.array([abs(a - best_model['t0']) for a in model_time_serie[i]['dates']]) rang_c = np.where(temp == np.min(temp))[0][0] X = model_time_serie[i]['x'] Y = model_time_serie[i]['y'] fig_curr.line(X, Y, line_width=2, color=colours[id_colour], alpha=1) # Arrows n = 0 z = (X[n] + 1j * Y[n]) - (X[n + 1] + 1j * Y[n + 1]) angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [X[n], X[n]] Y_arr = [Y[n], Y[n]] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) n = len(model_time_serie[i]['x']) - 2 z = (X[n] + 1j * Y[n]) - (X[n + 1] + 1j * Y[n + 1]) angle = [np.angle(z * np.exp(1j * np.pi / 5)), np.angle(z * np.exp(-1j * np.pi / 5))] X_arr = [X[n + 1], X[n + 1]] Y_arr = [Y[n + 1], Y[n + 1]] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) XX = np.array( X[rang_c] + 1j * Y[rang_c] + best_model['rho'] * np.exp( 1j * np.linspace(0, 2.0 * np.pi, 100))) # fig_curr.line(XX.real, XX.imag, line_width=0.5, color='black', alpha=0.5) fig_curr.patch(XX.real, XX.imag, color='black', alpha=0.3) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Rotation for Earth + Spitzer # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ if len(model_time_serie) == 2: # Find the vector D in (x, y) at t0 source_t0_earth = np.array([ \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['x'], kind='linear')(best_model['t0']), \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['y'], kind='linear')(best_model['t0']) ]) source_t0_earth_pente = np.array([ \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['x'], kind='linear')(best_model['t0'] + 0.1), \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['y'], kind='linear')(best_model['t0'] + 0.1) ]) source_t0_earth_pente = ( source_t0_earth_pente - source_t0_earth) / 0.1 source_t0_spitzer = np.array([interp1d( model_time_serie[1]['dates'], model_time_serie[1]['x'], kind='linear')(best_model['t0']), \ interp1d( model_time_serie[1]['dates'], model_time_serie[1]['y'], kind='linear')( best_model['t0'])]) source_t0_spitzer_pente = np.array([ \ interp1d(model_time_serie[1]['dates'], model_time_serie[1]['x'], kind='linear')( best_model['t0'] + 0.1), \ interp1d(model_time_serie[1]['dates'], model_time_serie[1]['y'], kind='linear')( best_model['t0'] + 0.1) ]) source_t0_spitzer_pente = ( source_t0_spitzer_pente - source_t0_spitzer) / 0.1 D_t0_xy = source_t0_spitzer - source_t0_earth # Angle between D in (x,y) and (E,N) # Caution: we rotate (x,y) by pi/2, so y is towards left, x towards # top. Now we can compute the rotation angle beetween \Delta\zeta # and D in (E,N). This angle + pi/2 gives the rotation angle to draw # trajectories in (E,N). All this is necessary because (E,N,T) is # equivalent to (y, x, T) with T is the target. D_xy_c = (D_t0_xy[0] + 1j * D_t0_xy[1]) * np.exp(1j * np.pi / 2.0) D_c = D_enm[0] + 1j * D_enm[1] alpha1 = np.angle(D_xy_c, deg=False) alpha2 = np.angle(D_c, deg=False) # epsilon = (angle_between(D_t0_xy, np.array([D_enm[0], D_enm[1]]))) epsilon = (angle_between(np.array([D_xy_c.real, D_xy_c.imag]), np.array( [D_enm[0], D_enm[1]]))) + np.pi / 2.0 rotation = np.exp(1j * epsilon) # print alpha1*180.0/np.pi, alpha2*180.0/np.pi, epsilon*180.0/np.pi # Unit vectors in xy x_hat_xy = 1.0 y_hat_xy = 1j e_hat_xy = x_hat_xy * np.exp(1j * epsilon) n_hat_xy = y_hat_xy * np.exp(1j * epsilon) # Unit vectors in EN e_hat_en = 1.0 n_hat_en = 1j x_hat_en = e_hat_en * np.exp(-1j * epsilon) y_hat_en = n_hat_en * np.exp(-1j * epsilon) # D in (x,y) palette = plt.get_cmap('Paired') id_palette = 0.090909 # from 0 to 11 X = np.linspace(source_t0_earth[0], source_t0_spitzer[0], 2) Y = np.linspace(source_t0_earth[1], source_t0_spitzer[1], 2) n = 9 fig_curr.line(X, Y, line_width=2, line_dash='dashed', color='green', alpha=1) fig_curr.circle(X[0], Y[0], size=15, color='green', alpha=0.5) fig_curr.circle(X[1], Y[1], size=15, color='green', alpha=0.5) # ax_curr.plot(X, Y, dashes=(4, 2), lw=1, # color=palette(n * id_palette), alpha=1, zorder=20) # ax_curr.scatter(X[0], Y[0], 15, marker="o", linewidths=0.3, # facecolors=palette(n * id_palette), edgecolors='k', # alpha=0.8, zorder=20) # ax_curr.scatter(X[1], Y[1], 15, marker="o", linewidths=0.3, # facecolors=palette(n * id_palette), edgecolors='k', # alpha=0.8, zorder=20) # # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'theta_x / theta_E' fig_curr.yaxis.axis_label = 'theta_y / theta_E' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None plot_counter = plot_counter + 1 # .................................................................. # Plot caustic 2 : pc2 # .................................................................. if len(model_time_serie) == 2: # Caution: we draw in (East, North) with East towards the left hand side. # So, X must be Eastern component, Y must be Northern component. # Then, always plot -X, Y to get plots in (West, North) frame. # Finaly reverse x-axis to get back to the East towards left. # Plot # ^^^^ xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap"] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=600, plot_height=560, x_range=(xmax, xmin), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[plot_counter] # Caustic # ^^^^^^^ if q > 1e-10: caustic = caustic * rotation fig_curr.circle(-caustic.real, caustic.imag, size=0.5, color='red', alpha=0.5) X = (s0 * q / (1 + q)) * rotation fig_curr.circle(-X.real, X.imag, size=5, color='orange', alpha=1) X = (s0 * q / (1 + q) - s) * rotation fig_curr.circle(-X.real, X.imag, size=5, color='orange', alpha=1) else: fig_curr.circle(0, 0, size=5, color='orange', alpha=1) # Trajectories # ^^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): X = (model_time_serie[i]['x'] + 1j * model_time_serie[i][ 'y']) * rotation fig_curr.line(-X.real, X.imag, line_width=2, color=colours[id_colour], alpha=1) # Arrows n = 0 z = X[n] - X[n + 1] angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [-X[n].real, -X[n].real] Y_arr = [X[n].imag, X[n].imag] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) n = len(model_time_serie[i]['x']) - 2 z = X[n] - X[n + 1] angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [-X[n + 1].real, -X[n + 1].real] Y_arr = [X[n + 1].imag, X[n + 1].imag] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Some specific positions # ^^^^^^^^^^^^^^^^^^^^^^^ # D in (e,n) at tO A = (source_t0_earth[0] + 1j * source_t0_earth[1]) * rotation B = (source_t0_spitzer[0] + 1j * source_t0_spitzer[1]) * rotation X = np.linspace(A.real, B.real, 2) Y = np.linspace(A.imag, B.imag, 2) n = 9 fig_curr.line(-X, Y, line_width=2, line_dash='dashed', color='green', alpha=1) fig_curr.circle(-X[0], Y[0], size=15, color='green', alpha=0.5) fig_curr.circle(-X[1], Y[1], size=15, color='green', alpha=0.5) # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'theta / theta_E (East)' fig_curr.yaxis.axis_label = 'theta / theta_E (North)' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None plot_counter = plot_counter + 1 # ------------------------------------------------------------------ # Save the html page # ------------------------------------------------------------------ if len(model_time_serie) == 2: final = blyt.column(fig[0], blyt.row(fig[1], fig[2])) bplt.save(final) if len(model_time_serie) != 2: final = blyt.column(fig[0], fig[1]) # final = bplt.vplot(fig[2]) bplt.save(final) # ------------------------------------------------------------------ # Modify the html page # ------------------------------------------------------------------ filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if (best_model['fullid'] == -1) & flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification.html' title = cfgsetup.get('EventDescription', 'Name') + ': best model last MCMC' elif flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification-' \ + repr(best_model['fullid']) + '.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model # ' + repr( best_model['fullid']) else: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification-fix.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model fix' file = open(filename, 'r') file_new = '' for line in file: # print line.strip()[:7] if line.strip()[:7] == '<title>': file_new = file_new \ + ' <style type="text/css">\n' \ + ' p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 43.0px; font: 36.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n' \ + ' p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 21.0px; font: 18.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n' \ + ' p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 15.0px; font: 12.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n' \ + ' p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 14.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000; min-height: 17.0px}\n' \ + ' p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}\n' \ + ' p.p6 {margin: 0.0px 0.0px 12.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}\n' \ + ' p.p7 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 14.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n' \ + ' span.s1 {font-kerning: none}\n' \ + ' span.s10 {font: 14.0px "Lucida Grande"; color: #585858}\n' \ + ' hr {\n' \ + ' display: block;\n' \ + ' margin-top: 0.5em;\n' \ + ' margin-bottom: 0.5em;\n' \ + ' margin-left: auto;\n' \ + ' margin-right: auto;\n' \ + ' border-style: inset;\n' \ + ' border-width: 1px;\n' \ + ' }\n' \ + ' </style>\n' \ + ' <title>' + 'muLAn ' + cfgsetup.get('EventDescription', 'Name')[4:] + '/' + cfgsetup.get('Controls', 'Archive') + '#'\ + repr(best_model['fullid']) + '</title>\n' \ + ' <meta name="Author" content="Clement Ranc">\n' elif line.strip()[:6] == '<body>': file_new = file_new \ + ' <body>\n\n' \ + '<p class="p1"><span class="s1"><b>' + title + '</b></span></p>\n' \ + '<p class="p2"><span class="s1"><br>\n' \ + '</span></p>\n' \ + '<p class="p3"><span class="s1">t0 = ' + repr( best_model['t0']) + ' days</span></p>\n' \ + '<p class="p3"><span class="s1">u0 = ' + repr( best_model['u0']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">tE = ' + repr( best_model['tE']) + ' days</span></p>\n' \ + '<p class="p3"><span class="s1">rho = ' + repr( best_model['rho']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">piEN = ' + repr( best_model['piEN']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">piEE = ' + repr( best_model['piEE']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">s = ' + repr( best_model['s']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">q = ' + repr( best_model['q']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">alpha = ' + repr( best_model['alpha']) + ' radians</span></p>\n' \ + '<p class="p3"><span class="s1">dalpha/dt= ' + repr( best_model['dalpha']) + ' radians/years</span></p>\n'\ + '<p class="p3"><span class="s1">ds/dt = ' + repr( best_model['ds']) + ' years^-1</span></p>\n' \ + '<p class="p3"><span class="s1">chi2 = ' + repr( best_model['chi2']) + ' radians</span></p>\n' \ + '<p class="p3"><span class="s1">chi2/dof = ' + repr( best_model['chi2/dof']) + ' radians</span></p>\n' \ + '<p class="p2"><span class="s1"><br>\n' \ + '</span></p>\n' elif line.strip()[:7] == '</body>': file_new = file_new \ + ' <BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n' \ + ' <hr>\n' \ + ' <BR>\n' \ + ' <footer>\n' \ + ' <p class="p7"><span class="s10">Modelling and page by muLAn (MicroLensing Analysis software).</span></p>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' </footer>\n' \ + ' </body>\n' else: file_new = file_new + line file.close() file = open(filename, 'w') file.write(file_new) file.close()
129,579
47.010374
1,076
py
muLAn
muLAn-master/muLAn/plottypes/fitmag.py
# -*-coding:Utf-8 -* # ---------------------------------------------------------------------- # Routine to plot the result of the MCMC, in magnitude. # ---------------------------------------------------------------------- # External libraries # ---------------------------------------------------------------------- import sys import os # Full path of this file full_path_here = os.path.realpath(__file__) text = full_path_here.split('/') a = '' i = 0 while i < len(text) - 1: a = a + text[i] + '/' i = i + 1 full_path = a # filename = full_path + '../' + '.pythonexternallibpath' # file = open(filename, 'r') # for line in file: # path_lib_ext = line # file.close() # if path_lib_ext != 'None': # sys.path.insert(0, path_lib_ext[:-1]) # ---------------------------------------------------------------------- # Standard packages # ---------------------------------------------------------------------- import os import glob import sys import copy import cmath # import math import emcee # import pylab import pickle import pylab import zipfile import datetime from scipy import interpolate import subprocess import numpy as np from sklearn.mixture import GaussianMixture from scipy.optimize import fsolve import pandas as pd import bokeh.layouts as blyt import bokeh.plotting as bplt from bokeh.models import HoverTool, TapTool, ColumnDataSource, OpenURL from bokeh.models.widgets import DateFormatter, NumberFormatter, DataTable, \ TableColumn import bokeh.io as io from scipy import stats import ConfigParser as cp from astropy.time import Time from PyAstronomy import pyasl import matplotlib as mpl import matplotlib.pyplot as plt from sklearn import linear_model from scipy.interpolate import interp1d from astropy.coordinates import SkyCoord from matplotlib.ticker import MultipleLocator, MaxNLocator from matplotlib.ticker import FixedLocator, FormatStrFormatter # ---------------------------------------------------------------------- # Non-standard packages # ---------------------------------------------------------------------- import muLAn.models.ephemeris as ephemeris import muLAn.packages.algebra as algebra # import models.esblparall as esblparall # import packages.plotconfig as plotconfig # import models.esblparallax as esblparallax # ---------------------------------------------------------------------- # CLASS # ---------------------------------------------------------------------- class printoption: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' reset = '\033[0m' bright = '\033[1m' dim = '\033[2m' underscore = '\033[4m' blink = '\033[5m' reverse = '\033[7m' hidden = '\033[8m' level0 = "\033[1m\033[31m" level1 = "\033[1m" good = "\033[32m" # ---------------------------------------------------------------------- # Functions # ---------------------------------------------------------------------- def communicate(cfg, verbose, text, opts=False, prefix=False, newline=False, tab=False): if cfg.getint('Modelling', 'Verbose') >= verbose: if prefix: text = "[muLAn] " + text if opts!=False: text2='' for a in opts: text2 = text2 + a text = text2 + text + printoption.reset if tab: text = " " + text if newline: text = "\n" + text print text else: if tab: text = " " + text if newline: text = "\n" + text print text # ---------------------------------------------------------------------- def help(): text = "Plot the light curve of a previously modelled event." return text # ---------------------------------------------------------------------- def bash_command(text): proc = subprocess.Popen(text, shell=True, executable="/bin/bash") proc.wait() # ---------------------------------------------------------------------- def unpack_options(cfgsetup, level0, level1, sep=','): options = [a.strip() for a in cfgsetup.get(level0, level1).split(sep)] del a, cfgsetup, level0, level1 return options # ---------------------------------------------------------------------- def critic_roots(s, q, phi): """Sample of the critic curve. The convention is : - the heaviest body (mass m1) is the origin; - the lightest body (mass m2) is at (-s, 0). Arguments: s -- the binary separation; q -- the lens mass ratio q = m2/m1; phi -- the sample parameter in [0;2*pi]. Returns: result -- numpy array of the complex roots. """ coefs = [1, 2 * s, s ** 2 - np.exp(1j * phi), -2 * s * np.exp(1j * phi) / (1 + q), -(s ** 2 * np.exp(1j * phi) / (1 + q))] result = np.roots(coefs) del coefs return result # ---------------------------------------------------------------------- # Levi-Civita coefficient def epsilon(i, j, k): if (i == j or i == k or j == k): e = 0 else: if (i == 1 and j == 2 and k == 3): e = 1 if (i == 3 and j == 1 and k == 2): e = 1 if (i == 2 and j == 3 and k == 1): e = 1 if (i == 1 and j == 3 and k == 2): e = -1 if (i == 3 and j == 2 and k == 1): e = -1 if (i == 2 and j == 1 and k == 3): e = -1 return e # # Projection onto the sky def onSky(m_hat, n_hat, u): x = np.array( [epsilon(i + 1, j + 1, k + 1) * u[i] * n_hat[j] * m_hat[k] for i in xrange(3) for j in xrange(3) for k in xrange(3)]).sum() u_proj = (1.0 / np.sqrt(1 - ((n_hat * m_hat).sum()) ** 2)) \ * np.array([x, (n_hat * u).sum() - (n_hat * m_hat).sum() * ( u * m_hat).sum(), 0]) return u_proj # # Projection onto the sky def normalize(u): return u / np.sqrt((u * u).sum()) def angle_between(v1, v2): v1_u = normalize(v1) v2_u = normalize(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) # # def vectoriel(u, v): x = u[1] * v[2] - u[2] * v[1] y = u[2] * v[0] - u[0] * v[2] z = u[0] * v[1] - u[1] * v[0] return np.array([x, y, z]) def boussole(EarthSunFile=False, EarthSatelliteFile=False, cfg=False, \ t_D_xy=False): # Value of the origin of the developments t0par = cfg.getfloat('Modelling', 'tp') # Coordinates conversion of the event from the Equatorial frame to the Ecliptic frame c_icrs = SkyCoord(ra=cfg.get('EventDescription', 'RA'), dec=cfg.get('EventDescription', 'DEC'), frame='icrs') l = c_icrs.transform_to('barycentrictrueecliptic').lon.degree b = c_icrs.transform_to('barycentrictrueecliptic').lat.degree # Vector Earth --> Sun in Ecliptic frame (cartesian coordinates). # ------------------------------------------------------------------ format = {'names': ('dates', 'x', 'y', 'z', 'vx', 'vy', 'vz'), \ 'formats': ('f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8')} temp = np.loadtxt(EarthSunFile, usecols=(0, 5, 6, 7, 8, 9, 10), dtype=format, unpack=False) EarthSun = pd.DataFrame(temp) del temp # Time conversion: TDB->TCG->HJD temp = EarthSun['dates'] - 2400000.0 flag_clem = 0 if flag_clem: EarthSun['hjd'] = np.array( [pyasl.helio_jd(tc, c_icrs.ra.degree, c_icrs.dec.degree) for tc in Time(temp, format='mjd', scale='tdb').tcg.value]) - 50000.0 else: EarthSun['hjd'] = np.array([pyasl.helio_jd(tc, l, b) for tc in Time(temp, format='mjd', scale='tdb').tcg.value]) - 50000.0 del temp # Vector Earth --> Satellite in Ecliptic frame (cartesian coordinates). # ------------------------------------------------------------------ format = {'names': ('dates', 'x', 'y', 'z'), \ 'formats': ('f8', 'f8', 'f8', 'f8')} temp = np.loadtxt(EarthSatelliteFile, usecols=(0, 5, 6, 7), dtype=format, unpack=False) EarthSat = pd.DataFrame(temp) del temp # Time conversion: TDB->TCG->HJD temp = EarthSun['dates'] - 2400000.0 flag_clem = 0 if flag_clem: EarthSat['hjd'] = np.array( [pyasl.helio_jd(tc, c_icrs.ra.degree, c_icrs.dec.degree) for tc in Time(temp, format='mjd', scale='tdb').tcg.value]) - 50000.0 else: EarthSat['hjd'] = np.array([pyasl.helio_jd(tc, l, b) for tc in Time(temp, format='mjd', scale='tdb').tcg.value]) - 50000.0 del temp # Vector Earth --> Sun and velocity( Earth --> Sun ) at t0par sp = np.array( [interp1d(EarthSun['hjd'], EarthSun['x'], kind='linear')(t0par), \ interp1d(EarthSun['hjd'], EarthSun['y'], kind='linear')(t0par), \ interp1d(EarthSun['hjd'], EarthSun['z'], kind='linear')( t0par)]) vp = np.array([interp1d(EarthSun['hjd'], EarthSun['vx'], kind='linear')(t0par), interp1d(EarthSun['hjd'], EarthSun['vy'], kind='linear')(t0par), interp1d(EarthSun['hjd'], EarthSun['vz'], kind='linear')(t0par)]) # Ecliptic frame [gamma, y, nord], cartesian coordinates n_hat = np.array([0, 0, 1]) m_hat = np.array([np.cos(np.radians(b)) * np.cos(np.radians(l)), \ np.cos(np.radians(b)) * np.sin(np.radians(l)), \ np.sin(np.radians(b))]) # Sky ref. frame [East, North projected, microlens] # Cartesian coordinates # Parallax correction from Earth delta_pos = np.array([]) delta_pos_proj = np.array([]) pos_proj = np.array([]) for t in xrange(len(EarthSun)): pos = np.array( [EarthSun['x'][t], EarthSun['y'][t], EarthSun['z'][t]]) delta_pos_temp = pos - (EarthSun['hjd'][t] - t0par) * vp - sp delta_pos_proj = np.append(delta_pos_proj, onSky(m_hat, n_hat, delta_pos_temp)) pos_proj = np.append(pos_proj, onSky(m_hat, n_hat, pos)) delta_pos = np.append(delta_pos, delta_pos_temp) delta_pos = np.reshape(delta_pos, (delta_pos.shape[0] / 3, 3)) pos_proj = np.reshape(pos_proj, (pos_proj.shape[0] / 3, 3)) delta_pos_proj = np.reshape(delta_pos_proj, (delta_pos_proj.shape[0] / 3, 3)) EarthSun['xproj'] = pos_proj.T[0] EarthSun['yproj'] = pos_proj.T[1] EarthSun['zproj'] = pos_proj.T[2] EarthSun['deltaxproj'] = delta_pos_proj.T[0] EarthSun['deltayproj'] = delta_pos_proj.T[1] EarthSun['deltazproj'] = delta_pos_proj.T[2] EarthSun['deltax'] = delta_pos.T[0] EarthSun['deltay'] = delta_pos.T[1] EarthSun['deltaz'] = delta_pos.T[2] # Correction due to the Satellite + parallax delta_pos = np.array([]) delta_pos_proj = np.array([]) pos_proj = np.array([]) for t in xrange(len(EarthSat)): pos = np.array([EarthSun['x'][t] - EarthSat['x'][t], EarthSun['y'][t] - EarthSat['y'][t], EarthSun['z'][t] - EarthSat['z'][t]]) delta_pos_temp = pos - (EarthSat['hjd'][t] - t0par) * vp - sp delta_pos_proj = np.append(delta_pos_proj, onSky(m_hat, n_hat, delta_pos_temp)) pos_proj = np.append(pos_proj, onSky(m_hat, n_hat, pos)) delta_pos = np.append(delta_pos, delta_pos_temp) delta_pos = np.reshape(delta_pos, (delta_pos.shape[0] / 3, 3)) pos_proj = np.reshape(pos_proj, (pos_proj.shape[0] / 3, 3)) delta_pos_proj = np.reshape(delta_pos_proj, (delta_pos_proj.shape[0] / 3, 3)) EarthSat['xproj'] = pos_proj.T[0] EarthSat['yproj'] = pos_proj.T[1] EarthSat['zproj'] = pos_proj.T[2] EarthSat['deltaxproj'] = delta_pos_proj.T[0] EarthSat['deltayproj'] = delta_pos_proj.T[1] EarthSat['deltazproj'] = delta_pos_proj.T[2] EarthSat['deltax'] = delta_pos.T[0] EarthSat['deltay'] = delta_pos.T[1] EarthSat['deltaz'] = delta_pos.T[2] if t_D_xy != False: D_ecl = np.array([interp1d(EarthSat['hjd'], EarthSat['x'], kind='linear')(t_D_xy), \ interp1d(EarthSat['hjd'], EarthSat['y'], kind='linear')(t_D_xy), \ interp1d(EarthSat['hjd'], EarthSat['z'], kind='linear')(t_D_xy)]) D_enm = onSky(m_hat, n_hat, D_ecl) # print D_enm return EarthSun, EarthSat, D_enm # ---------------------------------------------------------------------- # Functions used to visualise DMCMC results # ---------------------------------------------------------------------- def plot(cfgsetup=False, models=False, model_param=False, time_serie=False, \ obs_properties=False, options=False, interpol_method=False): # Initialisation of parameters # ------------------------------------------------------------------ params = { 't0' : np.array([a.strip() for a in cfgsetup.get('Modelling', 't0').split(',')]),\ 'u0' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'u0').split(',')]),\ 'tE' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'tE').split(',')]),\ 'rho' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'rho').split(',')]),\ 'gamma' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'gamma').split(',')]),\ 'piEE' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'piEE').split(',')]),\ 'piEN' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'piEN').split(',')]),\ 's' : np.array([a.strip() for a in cfgsetup.get('Modelling', 's').split(',')]),\ 'q' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'q').split(',')]),\ 'alpha' : np.array([a.strip() for a in cfgsetup.get('Modelling', 'alpha').split(',')]),\ 'dalpha': np.array([a.strip() for a in cfgsetup.get('Modelling', 'alpha').split(',')]),\ 'ds': np.array([a.strip() for a in cfgsetup.get('Modelling', 'alpha').split(',')])\ } flag_fix_gamma = 1 fitted_param = dict() result = np.array([]) if params['t0'][0] == "fit": fitted_param.update({'t0': params['t0'][3].astype(np.float64)}) result = np.append(result, fitted_param['t0']) if params['u0'][0] == "fit": fitted_param.update({'u0': params['u0'][3].astype(np.float64)}) result = np.append(result, fitted_param['u0']) if params['tE'][0] == "fit": fitted_param.update({'tE': params['tE'][3].astype(np.float64)}) result = np.append(result, fitted_param['tE']) if params['rho'][0] == "fit": fitted_param.update({'rho': params['rho'][3].astype(np.float64)}) result = np.append(result, fitted_param['rho']) if params['gamma'][0] == "fit": fitted_param.update({'gamma': params['gamma'][3].astype(np.float64)}) result = np.append(result, fitted_param['gamma']) flag_fix_gamma = 0 if params['piEE'][0] == "fit": fitted_param.update({'piEE': params['piEE'][3].astype(np.float64)}) result = np.append(result, fitted_param['piEE']) if params['piEN'][0] == "fit": fitted_param.update({'piEN': params['piEN'][3].astype(np.float64)}) result = np.append(result, fitted_param['piEN']) if params['s'][0] == "fit": fitted_param.update({'s': params['s'][3].astype(np.float64)}) result = np.append(result, fitted_param['s']) if params['q'][0] == "fit": fitted_param.update({'q': params['q'][3].astype(np.float64)}) result = np.append(result, fitted_param['q']) if params['alpha'][0] == "fit": fitted_param.update({'alpha': params['alpha'][3].astype(np.float64)}) result = np.append(result, fitted_param['alpha']) if params['dalpha'][0] == "fit": fitted_param.update({'dalpha': params['dalpha'][3].astype(np.float64)}) result = np.append(result, fitted_param['dalpha']) if params['ds'][0] == "fit": fitted_param.update({'ds': params['ds'][3].astype(np.float64)}) result = np.append(result, fitted_param['ds']) nb_param_fit = len(fitted_param) # Initialisation # ------------------------------------------------------------------ path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Chains') fnames_chains = glob.glob( path + cfgsetup.get('Controls', 'Archive') + "*-c*.txt") fnames_chains_exclude = glob.glob( path + cfgsetup.get('Controls', 'Archive') + "*g*.txt") temp = [] for a in fnames_chains: if (a in fnames_chains_exclude) == False: temp.append(a) fnames_chains = copy.deepcopy(temp) del temp, fnames_chains_exclude nb_chains = len(fnames_chains) samples_file = dict( {'chi2': [], 't0': [], 'u0': [], 'tE': [], 'rho': [], \ 'gamma': [], 'piEE': [], 'piEN': [], 's': [], 'q': [], \ 'alpha': [], 'dalpha': [], 'ds': [], 'chain': [], 'fullid': [], 'chi2': [], 'chi2/dof': [],\ 'date_save': [], 'time_save': [], 'id': [], 'accrate': []}) # filename_history = cfgsetup.get('FullPaths', 'Event') \ # + cfgsetup.get('RelativePaths', 'ModelsHistory') \ # + 'ModelsHistory.txt' filename_history = cfgsetup.get('FullPaths', 'Event') \ + cfgsetup.get('RelativePaths', 'ModelsHistory') \ + cfgsetup.get('Controls', 'Archive') \ + '-ModelsSummary.csv' flag_fix = 0 labels = ['t0', 'u0', 'tE', 'rho', 'gamma', 'piEN', 'piEE', 's', 'q', 'alpha', 'dalpha', 'ds'] for lab in labels: if unpack_options(cfgsetup, 'Modelling', lab)[0]!='fix': flag_fix = 1 if os.path.exists(filename_history) & flag_fix: file = open(filename_history, 'r') for line in file: params_model = line if params_model[0] == '#': continue samples_file['fullid'].append(int( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][0])) samples_file['t0'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][1])) samples_file['u0'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][2])) samples_file['tE'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][3])) samples_file['rho'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][4])) samples_file['gamma'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][5])) samples_file['piEN'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][6])) samples_file['piEE'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][7])) samples_file['s'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][8])) samples_file['q'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][9])) samples_file['alpha'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][10])) samples_file['dalpha'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][11])) samples_file['ds'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][12])) samples_file['chi2'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][13])) samples_file['chi2/dof'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][14])) samples_file['accrate'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][15])) samples_file['chain'].append(int( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][16])) file.close() elif flag_fix: # Read on the chains if nb_chains > 0: for i in xrange(nb_chains): file = open(fnames_chains[i], 'r') for line in file: params_model = line if params_model[0] == '#': continue samples_file['id'].append(int( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][0])) samples_file['t0'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][1])) samples_file['u0'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][2])) samples_file['tE'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][3])) samples_file['rho'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][4])) samples_file['gamma'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][5])) samples_file['piEN'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][6])) samples_file['piEE'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][7])) samples_file['s'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][8])) samples_file['q'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][9])) samples_file['alpha'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][10])) samples_file['dalpha'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][11])) samples_file['ds'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][12])) samples_file['chi2'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][13])) samples_file['accrate'].append(float( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][14])) samples_file['date_save'].append(int( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][15])) samples_file['time_save'].append(int( [a for a in (params_model.split('\n')[0].split(' ')) if (a != '')][16])) samples_file['chi2/dof'].append(float( [a for a in (params_model.split('\n')[0].split(',')) if (a != '')][17])) samples_file['chain'].append(int(fnames_chains[i][-8:-4])) samples_file['fullid'].append(-1) file.close() # TO BE REMOVE: PB with negative rho. for ii in xrange(len(samples_file['rho'])): if samples_file['rho'][ii] < 0: samples_file['rho'][ii] = 0.000001 # ------------------------------------ # Best model # ------------------------------------------------------------------ rang_2plot = [0] if flag_fix: models2plot = unpack_options(cfgsetup, 'Plotting', 'Models') if len(models2plot)==1: models2plot = unpack_options(cfgsetup, 'Plotting', 'Models', sep='-') if len(models2plot) == 2: first = int(models2plot[0]) second = int(models2plot[1]) nb_local = second - first + 1 models2plot = np.linspace(first, second, nb_local, endpoint=True, dtype='i4') models2plot = ['{:d}'.format(a) for a in models2plot] rang_2plot = [] if (models2plot != ['']) & (os.path.exists(filename_history)): chi2_min = np.min(samples_file['chi2']) samples_file.update( {'dchi2': samples_file['chi2'] - chi2_min}) rang_best_model = np.where(samples_file['dchi2'] == 0)[0][0] for mod in models2plot: if mod != '': try: rang_2plot.append( np.where(np.array(samples_file['fullid']) == int(mod))[ 0][0]) except: sys.exit('Cannot find the models you ask me to plot.') else: chi2_min = np.min(samples_file['chi2']) samples_file.update( {'dchi2': samples_file['chi2'] - chi2_min}) rang_best_model = np.where(samples_file['dchi2'] == 0)[0][0] rang_2plot = [rang_best_model] else: rang_best_model = 0 # Plots for idmod in xrange(len(rang_2plot)): if flag_fix: best_model = dict({}) best_model.update({'t0': samples_file['t0'][rang_2plot[idmod]]}) best_model.update({'u0': samples_file['u0'][rang_2plot[idmod]]}) best_model.update({'tE': samples_file['tE'][rang_2plot[idmod]]}) best_model.update({'rho': samples_file['rho'][rang_2plot[idmod]]}) best_model.update({'gamma': samples_file['gamma'][rang_2plot[idmod]]}) best_model.update({'piEE': samples_file['piEE'][rang_2plot[idmod]]}) best_model.update({'piEN': samples_file['piEN'][rang_2plot[idmod]]}) # best_model.update({'piE': np.sqrt(np.power(samples_file['piEN'][rang_2plot[idmod]],2) + np.power(samples_file['piEN'][rang_2plot[idmod]],2))}) best_model.update({'s': samples_file['s'][rang_2plot[idmod]]}) best_model.update({'q': samples_file['q'][rang_2plot[idmod]]}) best_model.update({'alpha': samples_file['alpha'][rang_2plot[idmod]]}) best_model.update({'dalpha': samples_file['dalpha'][rang_2plot[idmod]]}) best_model.update({'ds': samples_file['ds'][rang_2plot[idmod]]}) best_model.update( {'chi2': samples_file['chi2'][rang_2plot[idmod]]}) best_model.update( {'chi2/dof': samples_file['chi2/dof'][rang_2plot[idmod]]}) # best_model.update({'id': samples_file['id'][rang_2plot[idmod]]}) best_model.update({'chain': samples_file['chain'][rang_2plot[idmod]]}) # best_model.update( # {'date_save': samples_file['date_save'][rang_2plot[idmod]]}) # best_model.update( # {'time_save': samples_file['time_save'][rang_2plot[idmod]]}) best_model.update( {'accrate': samples_file['accrate'][rang_2plot[idmod]]}) best_model.update( {'fullid': samples_file['fullid'][rang_2plot[idmod]]}) else: best_model = dict({}) #samples_file = dict() labels = ['t0', 'u0', 'tE', 'rho', 'gamma', 'piEN', 'piEE', 's', 'q', 'alpha', 'dalpha', 'ds'] for lab in labels: best_model.update({lab: float(unpack_options(cfgsetup, 'Modelling', lab)[3])}) samples_file.update({lab: np.atleast_1d(float(unpack_options(cfgsetup, 'Modelling', lab)[3]))}) best_model.update({'chi2': 0}) best_model.update({'chi2/dof': 0}) best_model.update({'id': -1}) best_model.update({'chain': -1}) best_model.update({'date_save': -1}) best_model.update({'time_save': -1}) best_model.update({'accrate': 0}) best_model.update({'fullid': -1}) # ------------------------------------------------------------------- def lens_rotation(alpha0, s0, dalpha, ds, t, tb): ''' Compute the angle and the primary-secondary distance with a lens orbital motion. :alpha0: angle at tb :s0: separation at tb :dalpha: lens rotation velocity in rad.year^-1 :ds: separation velocity in year^-1 :t: numpy array of observation dates :tb: a reference date :return: numpy array of the value of the angle and separation for each date ''' Cte_yr_d = 365.25 # Julian year in days alpha = alpha0 - (t - tb) * dalpha / Cte_yr_d # (-1) because if the caustic rotates of dalpha, it is as if the source follows a trajectory with an angle of alpha(tb)-dalpha. s = s0 + (t - tb) * ds / Cte_yr_d return alpha, s # Parameters contraction s0 = best_model['s'] q = best_model['q'] u0 = best_model['u0'] alpha0 = best_model['alpha'] tE = best_model['tE'] t0 = best_model['t0'] piEN = best_model['piEN'] piEE = best_model['piEE'] gamma = best_model['gamma'] dalpha = best_model['dalpha'] ds = best_model['ds'] GL1 = s0 * q / (1 + q) GL2 = - s0 / (1 + q) tb = cfgsetup.getfloat('Modelling', 'tb') chi2_flux = 0 chi2dof_flux = 0 # Best model for data # ------------------------------------------------------------------ # Calculation of the amplification param_model = best_model observatories = np.unique(time_serie['obs']) models_lib = np.unique(time_serie['model']) if cfgsetup.getboolean('Plotting', 'Data'): time_serie.update({'x': np.empty(len(time_serie['dates']))}) time_serie.update({'y': np.empty(len(time_serie['dates']))}) for j in xrange(len(observatories)): cond2 = (time_serie['obs'] == observatories[j]) if flag_fix_gamma: param_model.update({'gamma': time_serie['gamma'][cond2][0]}) for i in xrange(models_lib.shape[0]): cond = (time_serie['model'] == models_lib[i]) &\ (time_serie['obs'] == observatories[j]) if cond.sum() > 0: time_serie_export = time_serie['dates'][cond] DsN_export = time_serie['DsN'][cond] DsE_export = time_serie['DsE'][cond] Ds_export = dict({'N': DsN_export, 'E': DsE_export}) try: kwargs_method = dict(cfgsetup.items(models_lib[i])) except: kwargs_method = dict() amp = models[models_lib[i]].magnifcalc(time_serie_export, param_model, Ds=Ds_export, tb=tb, **kwargs_method) time_serie['amp'][cond] = amp # print amp # print time_serie['amp'][cond] del amp # Calculation of fs and fb # fs, fb = fsfb(time_serie, cond2, blending=True) fs, fb = algebra.fsfbwsig(time_serie, cond2, blending=True) # if (fb/fs < 0 and observatories[j]=="ogle-i"): # fs, fb = fsfb(time_serie, cond2, blending=False) time_serie['fs'][cond2] = fs time_serie['fb'][cond2] = fb # print fs, fb if (observatories[j] == cfgsetup.get('Observatories', 'Reference').lower()) \ | (j == 0): fs_ref = fs fb_ref = fb mag_baseline = 18.0 - 2.5 * np.log10(1.0 * fs_ref + fb_ref) # print fs, fb # Source postion if cond2.sum() > 0: DsN = time_serie['DsN'][cond2] DsE = time_serie['DsE'][cond2] t = time_serie['dates'][cond2] tau = (t - t0) / tE + piEN * DsN + piEE * DsE beta = u0 + piEN * DsE - piEE * DsN z = (tau + 1j * beta) * np.exp(1j * alpha0) time_serie['x'][cond2] = z.real time_serie['y'][cond2] = z.imag # Calculation of chi2 time_serie['flux_model'] = time_serie['amp'] * time_serie['fs'] + \ time_serie['fb'] # time_serie['chi2pp'] = np.power((time_serie['flux'] - time_serie[ # 'flux_model']) / time_serie['err_flux'], 2) try: time_serie['residus'] = -(time_serie['magnitude'] - (18.0 - 2.5 * np.log10(time_serie['flux_model']))) except RuntimeWarning: time_serie['residus'] = 999.0 * np.ones(len(time_serie['magnitude'])) time_serie['residus_flux'] = -(time_serie['flux'] - time_serie['flux_model']) time_serie['mgf_data'] = (time_serie['flux'] - time_serie['fb']) / time_serie['fs'] time_serie['mgf_data_err'] = time_serie['err_flux'] / time_serie['fs'] time_serie['res_mgf'] = time_serie['mgf_data'] - time_serie['amp'] time_serie['chi2pp'] = np.power(time_serie['residus'] / time_serie['err_magn'], 2.0) time_serie['chi2pp_flux'] = np.power(time_serie['residus_flux'] / time_serie['err_flux'], 2.0) chi2 = np.sum(time_serie['chi2pp']) chi2_flux = np.sum(time_serie['chi2pp_flux']) # Calculation of the lightcurve model plot_min = float(options.split('/')[0].split('-')[0].strip()) plot_max = float(options.split('/')[0].split('-')[1].strip()) nb_pts = int(options.split('/')[1].strip()) locations = np.unique(obs_properties['loc']) print " Max magnification: {:.2f}".format(np.max(time_serie['amp'])) # print len(time_serie['amp']) # Fit summary text = "Fit summary" communicate(cfgsetup, 3, text, opts=[printoption.level0], prefix=True, newline=True, tab=False) observatories_com = np.unique(time_serie['obs']) if (cfgsetup.getint("Modelling", "Verbose") >= 3) & (rang_best_model == rang_2plot[idmod]): fn_output_terminal = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Outputs')\ + "Results.txt" path_outputs = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Outputs') if not os.path.exists(path_outputs): os.makedirs(path_outputs) # print fn_output_terminal file = open(fn_output_terminal, 'w') text = "\n\033[1m\033[7m {:25s} {:>9s} {:>9s} {:>9s} {:>9s} \033[0m".format( "Site", "chi^2", "chi^2/dof", "RF 1", "RF 2") print text text_precis = "\n {:25s} {:>18s} {:>18s} {:>18s} {:>18s} \n".format( "Site", "chi^2", "chi^2/dof", "RF 1", "RF 2") file.write(text_precis) params_raw = np.array(['t0', 'u0', 'tE', 'rho', 'gamma', 'piEN', 'piEE', 's', 'q', 'alpha', 'dalpha', 'ds']) n_param = nb_param_fit # n_param = int(len(time_serie['dates']) - chi2 / samples_file['chi2/dof'][rang_best_model]) nb_data_tot = 0 # observatories_com = np.unique(time_serie['obs']) text = "" text2 = "" text_precis = "" text2_precis = "" for i in xrange(len(observatories_com)): rf = [float(a.replace("(", "").replace(")", "").strip()) for a in unpack_options(cfgsetup, "Observatories", observatories_com[i])[:2]] cond = time_serie['obs']==observatories_com[i] chi2_com = np.sum(time_serie['chi2pp'][cond]) nb_data_tot = nb_data_tot + len(time_serie['chi2pp'][cond]) if len(time_serie['chi2pp'][cond]) > 0: chi2dof_com = chi2_com / (len(time_serie['chi2pp'][cond])-n_param) else: chi2dof_com = 0.0 text = text + " {:25s} {:9.3e} {:9.3e} {:9.3e} {:9.3e}\n".format(observatories_com[i].upper(), chi2_com, chi2dof_com, rf[0], rf[1]) text_precis = text_precis + " {:25s} {:18.12e} {:18.12e} {:18.12e} {:18.12e}\n".format(observatories_com[i].upper(), chi2_com, chi2dof_com, rf[0], rf[1]) try: g = time_serie["fb"][cond][0]/time_serie["fs"][cond][0] except: g = np.inf # Y = 18.0 - 2.5 * np.log10(time_serie['fb'][cond][0] + time_serie['fs'][cond][0]) Y = time_serie['fb'][cond][0] + time_serie['fs'][cond][0] # Yb = 18.0 - 2.5 * np.log10(time_serie['fb'][cond][0]) Yb = time_serie['fb'][cond][0] # Ys = 18.0 - 2.5 * np.log10(time_serie['fs'][cond][0]) Ys = time_serie['fs'][cond][0] text2 = text2 + " {:25s} {:8.3f} {:8.3f} {:8.3f} {:8.3f} {:5.3f}\n".format( observatories_com[i].upper(), Y, Yb, Ys, g, gamma) text2_precis = text2_precis + " {:25s} {:18.12e} {:18.12e} {:18.12e} {:18.12e} {:18.12e}\n".format( observatories_com[i].upper(), Y, Yb, Ys, g, gamma) if (observatories[i] == cfgsetup.get('Observatories', 'Reference').lower()) \ | (i == 0): Y = 18.0 - 2.5 * np.log10(time_serie['fb'][cond][0] + time_serie['fs'][cond][0]) if time_serie['fb'][cond][0] > 0: Yb = 18.0 - 2.5 * np.log10(time_serie['fb'][cond][0]) else: Yb = -1 Ys = 18.0 - 2.5 * np.log10(time_serie['fs'][cond][0]) text3 = "Reference for magnitudes:\n {:25s} {:8.3f} {:8.3f} {:8.3f}\n".format( observatories_com[i].upper(), Y, Yb, Ys) text3_precis = "Reference for magnitudes:\n {:25s} {:18.12e} {:18.12e} {:18.12e}\n".format( observatories_com[i].upper(), Y, Yb, Ys) print text file.write(text_precis) text = "{:25}={:2}{:9.3e}{:4}{:9.3e} (chi^2 on magn)".format("", "", chi2_flux, "", chi2/(nb_data_tot-n_param)) chi2dof_flux = chi2/(nb_data_tot-n_param) print text text = "{:25}={:2}{:18.12e}{:4}{:18.12e} (chi^2 on magn)".format("", "", chi2_flux, "", chi2/(nb_data_tot-n_param)) chi2dof_flux = chi2/(nb_data_tot-n_param) file.write(text) text = "\n\033[1m\033[7m {:78s}\033[0m".format("Best-fitting parameters") print text text = "\n {:78s}\n".format("Best-fitting parameters") file.write(text) #print samples_file piE = np.sqrt(np.power(samples_file['piEN'][rang_best_model], 2) + np.power(samples_file['piEE'][rang_best_model],2)) gamma = np.sqrt((samples_file['ds'][rang_best_model]/samples_file['s'][rang_best_model])**2 + samples_file['dalpha'][rang_best_model]**2) text = "{:>10} = {:.6f}\n".format("q", samples_file['q'][rang_best_model]) + "{:>10} = {:.6f}\n".format("s", samples_file['s'][rang_best_model]) + "{:>10} = {:.6f}\n".format("tE", samples_file['tE'][rang_best_model]) + "{:>10} = {:.6f}\n".format("rho", samples_file['rho'][rang_best_model]) + "{:>10} = {:.6f}\n".format("piEN", samples_file['piEN'][rang_best_model]) + "{:>10} = {:.6f}\n".format("piEE", samples_file['piEE'][rang_best_model]) + "{:>10} = {:.6f}\n".format("piE", piE) + "{:>10} = {:.6f}\n".format("t0", samples_file['t0'][rang_best_model]) + "{:>10} = {:.6f}\n".format("u0", samples_file['u0'][rang_best_model]) + "{:>10} = {:.6f}\n".format("alpha", samples_file['alpha'][rang_best_model]) + "{:>10} = {:.6f}\n".format("dalpha", samples_file['dalpha'][rang_best_model]) + "{:>10} = {:.6f}\n".format("ds", samples_file['ds'][rang_best_model]) + "{:>10} = {:.6f}\n".format("gammaL", gamma) + "{:>10} = {:.6f}\n".format("tp", cfgsetup.getfloat("Modelling", "tp")) + "{:>10} = {:.6f}\n".format("tb", cfgsetup.getfloat("Modelling", "tb")) print text text = "{:>10} = {:.12e}\n".format("q", samples_file['q'][rang_best_model]) + "{:>10} = {:.12e}\n".format("s", samples_file['s'][rang_best_model]) + "{:>10} = {:.12e}\n".format("tE", samples_file['tE'][rang_best_model]) + "{:>10} = {:.12e}\n".format("rho", samples_file['rho'][rang_best_model]) + "{:>10} = {:.12e}\n".format("piEN", samples_file['piEN'][rang_best_model]) + "{:>10} = {:.12e}\n".format("piEE", samples_file['piEE'][rang_best_model]) + "{:>10} = {:.12e}\n".format("piE", piE) + "{:>10} = {:.12e}\n".format("t0", samples_file['t0'][rang_best_model]) + "{:>10} = {:.12e}\n".format("u0", samples_file['u0'][rang_best_model]) + "{:>10} = {:.12e}\n".format("alpha", samples_file['alpha'][rang_best_model]) + "{:>10} = {:.12e}\n".format("dalpha", samples_file['dalpha'][rang_best_model]) + "{:>10} = {:.12e}\n".format("ds", samples_file['ds'][rang_best_model]) + "{:>10} = {:.12e}\n".format("gammaL", gamma) + "{:>10} = {:.12e}\n".format("tp", cfgsetup.getfloat("Modelling", "tp")) + "{:>10} = {:.12e}\n".format("tb", cfgsetup.getfloat("Modelling", "tb")) file.write(text) text = "\n\033[1m\033[7m {:25s} {:>8s} {:>8s} {:>8s} {:>6s} {:>5s}{:3s}\033[0m".format( "Site", "Baseline", "Blending", "Source", "Fb/Fs", "LLD", "") print text text = "\n {:25s} {:>18s} {:>18s} {:>18s} {:>18s} {:>18s}{:3s}\n".format( "Site", "Baseline", "Blending", "Source", "Fb/Fs", "LLD", "") file.write(text) print text2 file.write(text2_precis) print text3 file.write(text3_precis) file.close() # Best model theoretical light curve # ------------------------------------------------------------------ model2load = np.array([]) path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Data') if len(obs_properties['loc']) > 1: name1 = obs_properties['loc'][np.where(np.array( [obs == cfgsetup.get('Observatories', 'Reference').lower() for obs in observatories]) == True)[0][0]] name1 = glob.glob(path + name1 + '.*')[0] else: name1 = glob.glob(path + obs_properties['loc'][0] + '.*')[0] for i in xrange(len(locations)): name = 'Models_' + locations[i] models_temp = model_param[name] name = 'DateRanges_' + locations[i] dates_temp = model_param[name] # min = [] # max = [] # for j in xrange(len(models_temp)): # model2load = np.append(model2load, models_temp[j]) # tmin = float((dates_temp[j]).split('-')[0].strip()) # tmax = float((dates_temp[j]).split('-')[1].strip()) # # min = np.append(min, tmin) # max = np.append(min, tmax) # # min = np.min(min) # max = np.max(max) min = plot_min max = plot_max if i == 0: model_time_serie = np.array([dict({ 'dates': np.linspace(min, max, nb_pts), 'model': np.full(nb_pts, '0', dtype='S100'), 'amp': np.full(nb_pts, 0.1, dtype='f8'), })]) else: model_time_serie = np.append(model_time_serie, np.array([dict({ 'dates': np.linspace(min, max, nb_pts), 'model': np.full(nb_pts, '0', dtype='S100'), 'amp': np.full(nb_pts, 0.1, dtype='f8'), })])) for j in xrange(len(models_temp)): tmin = float((dates_temp[j]).split('-')[0].strip()) tmax = float((dates_temp[j]).split('-')[1].strip()) cond = (model_time_serie[i]['dates'] <= tmax) \ & (model_time_serie[i]['dates'] >= tmin) model_time_serie[i]['model'][cond] = models_temp[j] cond = model_time_serie[i]['model'] == '0' if cond.sum() > 0: model_time_serie[i]['model'][cond] = models_temp[0] # Ephemeris c_icrs = SkyCoord(ra=cfgsetup.get('EventDescription', 'RA'), \ dec=cfgsetup.get('EventDescription', 'DEC'), frame='icrs') # print c_icrs.transform_to('barycentrictrueecliptic') l = c_icrs.transform_to('barycentrictrueecliptic').lon.degree b = c_icrs.transform_to('barycentrictrueecliptic').lat.degree name2 = glob.glob(path + locations[i] + '.*')[0] sTe, sEe, sNe, DsTe, DsEe, DsNe, sTs, sEs, sNs, DsTs, DsEs, DsNs = \ ephemeris.Ds(name1, name2, l, b, cfgsetup.getfloat('Modelling', 'tp'), \ cfgsetup) if name1 != name2: DsN = DsNs DsE = DsEs else: DsN = DsNe DsE = DsEe model_time_serie[i].update({'DsN': np.array( [DsN(a) for a in model_time_serie[i]['dates']])}) model_time_serie[i].update({'DsE': np.array( [DsE(a) for a in model_time_serie[i]['dates']])}) # Amplification models_lib = np.unique(model_time_serie[i]['model']) for k in xrange(models_lib.shape[0]): cond = (model_time_serie[i]['model'] == models_lib[k]) if cond.sum() > 0: time_serie_export = model_time_serie[i]['dates'][cond] DsN_export = model_time_serie[i]['DsN'][cond] DsE_export = model_time_serie[i]['DsE'][cond] Ds_export = dict({'N': DsN_export, 'E': DsE_export}) try: kwargs_method = dict(cfgsetup.items(models_lib[k])) except: kwargs_method = dict() amp = models[models_lib[k]].magnifcalc(time_serie_export, param_model, Ds=Ds_export, tb=tb, **kwargs_method) model_time_serie[i]['amp'][cond] = amp if cfgsetup.getboolean('Plotting', 'Data'): model_time_serie[i].update({'magnitude': 18.0 - 2.5 * np.log10( fs_ref * model_time_serie[i]['amp'] + fb_ref)}) # Source position in (x, y) DsN = model_time_serie[i]['DsN'] DsE = model_time_serie[i]['DsE'] t = model_time_serie[i]['dates'] tau = (t - t0) / tE + piEN * DsN + piEE * DsE beta = u0 + piEN * DsE - piEE * DsN z = (tau + 1j * beta) * np.exp(1j * alpha0) model_time_serie[i].update({'x': z.real}) model_time_serie[i].update({'y': z.imag}) del amp, DsN_export, DsE_export, Ds_export, cond, time_serie_export # print model_time_serie[1]['model'] # # Interpolation method # # ------------------------------------------------------------------------- # key_list = [key for key in interpol_method] # # interpol_func = dict() # if len(key_list) > 0: # for i in xrange(len(key_list)): # time_serie_export = interpol_method[key_list[i]][0] # # DsN_export = interpol_method[key_list[i]][1] # DsE_export = interpol_method[key_list[i]][2] # # Ds_export = dict({'N':DsN_export, 'E':DsE_export}) # # name = key_list[i].split('#')[1] # amp = models[name].magnifcalc(time_serie_export, param_model, Ds=Ds_export) # # interpol_method[key_list[i]][3] = amp # # interpol_func = interpolate.interp1d(time_serie_export, amp) # interpol_func.update({key_list[i]: interpolate.interp1d(time_serie_export, amp, kind='linear')}) # Reference frames # ------------------------------------------------------------------ # Orientations on the Sky path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Data') if len(model_time_serie) == 2: EarthSun, EarthSat, D_enm = boussole( EarthSunFile=path + "Earth.dat", EarthSatelliteFile=path + "Spitzer.dat", cfg=cfgsetup, t_D_xy=best_model['t0']) else: EarthSun, EarthSat, D_enm = boussole( EarthSunFile=path + "Earth.dat", EarthSatelliteFile=path + "Earth.dat", cfg=cfgsetup, t_D_xy=best_model['t0']) # Sigma clipping # ------------------------------------------------------------------ # Determine the best rescaling factors if (cfgsetup.getint("Modelling", "Verbose") > 4) & (nb_param_fit > 0): text = "\n\033[1m\033[7m{:>2s}{:<25s}{:1s}{:>10s}{:1s}{:>5s}{:1s}{:>10s}{:1s}{:>5s}{:1s}{:>10s}{:1s}{:>5s}{:2s}\033[0m".format( "", "Site", "", "RF1(loop3)", "", "Rej.", "", "RF1(loop5)", "", "Rej.", "", "RF1(loop7)", "", "Rej.", "") print text def func(f1, table, f2, ddl): x = np.sum(np.power(table['residus'], 2)/(np.power(f1*table['err_magn'], 2) + f2**2)) x = x / ddl - 1.0 return x text = "" for j in xrange(len(observatories_com)): # Pre-defied rescaling factors f1 = float(unpack_options(cfgsetup, 'Observatories', observatories[0])[0].replace('(', '')) f2 = float(unpack_options(cfgsetup, 'Observatories', observatories[0])[1].replace(')', '')) if abs(f1-1.0) > 1e-10: text = "{:>2s}{:<25s}{:<30s}\n".format("", observatories_com[j].upper(), "RF 1 not equal to 1.0.") continue # Select the observatory condj = np.where(time_serie['obs'] == observatories[j]) time_serie_SC = copy.deepcopy(time_serie) [time_serie_SC.update({key: time_serie_SC[key][condj]}) for key in time_serie_SC] # Compute the degree of freedom ddl nb_data = len(time_serie_SC['dates']) if nb_data > nb_param_fit: ddl = nb_data - nb_param_fit else: ddl = nb_data # Compute the rescaling factor f1 from the value of f2 rejected_points_id = np.array([]) nb_reject_sc = 0 nb_loops = 7 text = text + "{:>2s}{:<25s}".format("", observatories_com[j].upper()) for i in xrange(nb_loops): mean = np.mean(time_serie_SC['err_magn']) sdt = np.std(time_serie_SC['err_magn']) toremove = np.where(np.abs(time_serie_SC['err_magn'] - mean) > 3.0 * sdt) nb_reject_sc = nb_reject_sc + len(toremove[0]) if len(toremove[0]) > 0: rejected_points_id = np.append(rejected_points_id, time_serie_SC['id'][toremove]) [time_serie_SC.update({key : np.delete(time_serie_SC[key], toremove)}) for key in time_serie_SC] if (i==2) | (i==4) | (i==6): try: f1_op = fsolve(func, 1.0, args=(time_serie_SC, f2, ddl)) except: f1_op = 0.0 text = text + "{:>10.3f}{:1s}{:>5d}{:1s}".format( f1_op[0], "", nb_reject_sc, "") text = text + "\n" print text # --------------------------------------------------------------------- # Create an html webpage (amplification if no data, magnitude if so) # --------------------------------------------------------------------- if cfgsetup.getboolean('Plotting', 'Data'): filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if (best_model['fullid'] == -1) & flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-summary.html' title = cfgsetup.get('EventDescription', 'Name') + ': best model last MCMC' elif flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-summary-' \ + repr(best_model['fullid']) + '.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model # ' + repr( best_model['fullid']) else: filename = filename + cfgsetup.get('Controls', 'Archive') + '-summary-fix.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model fix' if os.path.exists(filename): os.remove(filename) bplt.output_file(filename) fig = np.array([]) # Preparation of the data time_serie.update({'colour': np.full(len(time_serie['dates']), 'black', dtype='S100')}) time_serie.update( {'mag_align': np.full(len(time_serie['dates']), 0, dtype='f8')}) palette = plt.get_cmap('Blues') observatories = np.unique(time_serie['obs']) for i in xrange(len(observatories)): cond = np.where(time_serie['obs'] == observatories[i]) cond2 = \ np.where(observatories[i] == np.array(obs_properties['key']))[0][0] color = '#' + obs_properties['colour'][cond2] time_serie['colour'][cond] = color # Magnitude aligned Y = ((time_serie['flux'][cond] - time_serie['fb'][cond])/time_serie['fs'][cond]) ############# Y = 18.0 - 2.5 * np.log10(fs_ref * Y + fb_ref) # cond3 = cond & (Y>0) ################## # Y[cond3] = 18.0 - 2.5 * np.log10(fs_ref * Y[cond3] + fb_ref) ################## # cond3 = cond & (Y<=0) ################## # Y[cond3] = 1000 ################## time_serie['mag_align'][cond] = Y ################## # Create output files # --------------------------------------------------------------------- path_outputs = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Outputs') if not os.path.exists(path_outputs): os.makedirs(path_outputs) for j in xrange(len(observatories_com)): idx = [jj for jj in xrange(len(observatories_com)) if observatories_com[j]==obs_properties['key'][jj]][0] flag_fom = obs_properties['fluxoumag'][idx] if flag_fom.lower()=='magnitude': text = "#{11:>5s} {0:>18s} {1:>6s} {3:>12s} {4:>10s} {8:>8s} {9:>9s} {10:>9s} {5:>12s} {6:>12s} {13:>10s} {14:>10s} {7:>9s} {12:>20s} {2:>20s}\n".format( "Date", "Magn", "Err_Magn", "Err_Magn_Res", "Resi", "Back", "Seeing", "Chi2", "Mgf-dat", "Err_Mgf", "Resi-Mgf", "ID", "Input_Magn", "x", "y") elif flag_fom.lower()=='flux': text = "#{11:>5s} {0:>18s} {1:>6s} {3:>12s} {4:>10s} {8:>8s} {9:>9s} {10:>9s} {5:>12s} {6:>12s} {13:>10s} {14:>10s} {7:>9s} {12:>20s} {2:>20s}\n".format( "Date", "Magn", "Err_Flux", "Err_Magn_Res", "Resi", "Back", "Seeing", "Chi2", "Mgf-dat", "Err_Mgf", "Resi-Mgf", "ID", "Input_Flux") filename = path_outputs + observatories_com[j].upper() + ".dat" condj = np.where(time_serie['obs'] == observatories[j]) time_serie_SC = copy.deepcopy(time_serie) [time_serie_SC.update({key: time_serie_SC[key][condj]}) for key in time_serie_SC] if flag_fom.lower()=='magnitude': for jj in xrange(len(time_serie_SC['dates'])): text = text +\ "{11:6d} {0:18.12f} {1:6.3f} {3:12.3e} {4:10.3e} {8:8.3f} {9:9.3e} {10:9.2e} {5:12.5f} {6:12.5f} {13:10.6f} {14:10.6f} {7:9.3e} {12:20.12f} {2:20.12f}".format( time_serie_SC['dates'][jj], time_serie_SC['mag_align'][jj], time_serie_SC['err_magn_orig'][jj], time_serie_SC['err_magn'][jj], time_serie_SC['residus'][jj], time_serie_SC['background'][jj], time_serie_SC['seeing'][jj], time_serie_SC['chi2pp'][jj], time_serie_SC['mgf_data'][jj], time_serie_SC['mgf_data_err'][jj], time_serie_SC['res_mgf'][jj], time_serie_SC['id'][jj], time_serie_SC['magnitude'][jj], time_serie_SC['x'][jj], time_serie_SC['y'][jj] ) text = text + "\n" elif flag_fom.lower()=='flux': for jj in xrange(len(time_serie_SC['dates'])): text = text +\ "{11:6d} {0:18.12f} {1:6.3f} {3:12.3e} {4:10.3e} {8:8.3f} {9:9.3e} {10:9.2e} {5:12.5f} {6:12.5f} {13:10.6f} {14:10.6f} {7:9.3e} {12:20.12f} {2:20.12f}".format( time_serie_SC['dates'][jj], time_serie_SC['mag_align'][jj], time_serie_SC['err_flux_orig'][jj], time_serie_SC['err_magn'][jj], time_serie_SC['residus'][jj], time_serie_SC['background'][jj], time_serie_SC['seeing'][jj], time_serie_SC['chi2pp'][jj], time_serie_SC['mgf_data'][jj], time_serie_SC['mgf_data_err'][jj], time_serie_SC['res_mgf'][jj], time_serie_SC['id'][jj], time_serie_SC['flux'][jj], time_serie_SC['x'][jj], time_serie_SC['y'][jj] ) text = text + "\n" file = open(filename, 'w') file.write(text) file.close() # .................................................................. # Plot light curve : plc # .................................................................. cond = np.isnan(time_serie['mag_align']) time_serie['mag_align'][cond] = 0 source = ColumnDataSource(time_serie) col_used = ['id', 'obs', 'dates', 'mag_align', 'x', 'y', 'colour', 'residus'] col_all = [key for key in time_serie] [col_all.remove(key) for key in col_used] [source.remove(key) for key in col_all] hover_plc = HoverTool(tooltips=[("ID", "@id{int}"), ("Obs", "@obs"), ("Date", "@dates{1.11}")]) tmin = float(options.split('/')[0].split('-')[0].strip()) tmax = float(options.split('/')[0].split('-')[1].strip()) ymin = np.min(time_serie['mag_align']) ymax = np.max(time_serie['mag_align']) tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap", hover_plc] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=1200, plot_height=600, x_range=(tmin, tmax), y_range=(ymax, ymin), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[0] # Annotations # ^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): name = 'Models_' + locations[i] models_temp = model_param[name] name = 'DateRanges_' + locations[i] dates_temp = model_param[name] # print np.max(model_time_serie[i]['amp']) for j in xrange(len(models_temp)): tmin = float((dates_temp[j]).split('-')[0].strip()) tmax = float((dates_temp[j]).split('-')[1].strip()) X = np.ones(2) * tmin Y = np.linspace(0, 100000, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) X = np.ones(2) * tmax Y = np.linspace(0, 100000, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Amplification models # ^^^^^^^^^^^^^^^^^^^^ if cfgsetup.getboolean("Plotting", "Data"): colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): X = model_time_serie[i]['dates'] Y = model_time_serie[i]['magnitude'] fig_curr.line(X, Y, line_width=2, color=colours[id_colour], alpha=1) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Write output files for the models text = "#{0:>17s} {1:>9s} {2:>6s} {3:>7s} {4:>7s}\n".format("Date", "Mgf", "Magn", "x", "y") filename = path_outputs + locations[i].upper() + ".dat" time_serie_SC = copy.deepcopy(model_time_serie[i]) [time_serie_SC.update({key: time_serie_SC[key]}) for key in time_serie_SC] for jj in xrange(len(time_serie_SC['dates'])): text = text +\ "{0:18.12f} {1:9.3f} {2:6.3f} {3:7.3f} {4:7.3f}".format( time_serie_SC['dates'][jj], time_serie_SC['amp'][jj], time_serie_SC['magnitude'][jj], time_serie_SC['x'][jj], time_serie_SC['y'][jj] ) text = text + "\n" file = open(filename, 'w') file.write(text) file.close() # Magnitude fig_curr.circle('dates', 'mag_align', size=8, color='colour', alpha=0.4, source=source) # Legend for i in xrange(len(obs_properties['name'])): col = '#' + obs_properties['colour'][i] fig_curr.circle(-10000, -10000, size=8, color=col, alpha=0.4, legend=obs_properties['name'][i]) # Magnitude (errors) # ^^^^^^^^^^^^^^^^^^ err_xs = [] err_ys = [] for x, y, yerr, colori in zip(time_serie['dates'], time_serie['mag_align'], time_serie['err_magn'], time_serie['colour']): err_xs.append((x, x)) err_ys.append((y - yerr, y + yerr)) fig_curr.multi_line(err_xs, err_ys, color=time_serie['colour']) # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'HJD - 2,450,000' fig_curr.yaxis.axis_label = 'Magnitude' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None # .................................................................. # Plot residus in mag : prm # .................................................................. hover_prm = HoverTool( tooltips=[ ("ID", "@id{int}"), ("Obs", "@obs"), ("Date", "@dates{1.11}") ] ) tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap", hover_prm] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=1200, plot_height=300, x_range=fig[0].x_range, y_range=(-0.25, 0.25), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[1] # Annotations # ^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): name = 'Models_' + locations[i] models_temp = model_param[name] name = 'DateRanges_' + locations[i] dates_temp = model_param[name] for j in xrange(len(models_temp)): tmin = float((dates_temp[j]).split('-')[0].strip()) tmax = float((dates_temp[j]).split('-')[1].strip()) X = np.ones(2) * tmin Y = np.linspace(-100, 100, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) X = np.ones(2) * tmax Y = np.linspace(-100, 100, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Magnitude fig_curr.circle('dates', 'residus', size=8, color='colour', alpha=0.4, source=source) # Magnitude (errors) # ^^^^^^^^^^^^^^^^^^ err_xs = [] err_ys = [] for x, y, yerr, colori in zip(time_serie['dates'], time_serie['residus'], time_serie['err_magn'], time_serie['colour']): err_xs.append((x, x)) err_ys.append((y - yerr, y + yerr)) fig_curr.multi_line(err_xs, err_ys, color=time_serie['colour']) X = np.linspace(-100000, 100000, 2) Y = np.ones(2) * 0 fig_curr.line(X, Y, line_width=1, color='dimgray', alpha=1) X = np.linspace(-100000, 100000, 2) Y = np.ones(2) * 0.1 fig_curr.line(X, Y, line_width=0.5, color='dimgray', alpha=0.5) X = np.linspace(-100000, 100000, 2) Y = np.ones(2) * (-0.1) fig_curr.line(X, Y, line_width=0.5, color='dimgray', alpha=0.5) # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'HJD - 2,450,000' fig_curr.yaxis.axis_label = 'Residuals [mag]' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None # .................................................................. # Plot caustic 1 : pc1 # .................................................................. hover_pc1 = HoverTool( tooltips=[ ("ID", "@id{int}"), ("Obs", "@obs"), ("Date", "@dates{1.11}") ] ) xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap", hover_pc1] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=600, plot_height=560, x_range=(xmin, xmax), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[2] # Caustic # ^^^^^^^ # Case of lens orbital rotation try: time_caustic = options.split('/')[2].replace('[','').replace(']','').split('-') time_caustic = np.array([float(a.strip()) for a in time_caustic]) n_caustics = len(time_caustic) nb_pts_caus = 1000 alpha, s = lens_rotation(alpha0, s0, dalpha, ds, time_caustic, tb) color_caustics = np.array(['Orange', 'SeaGreen', 'LightSeaGreen', 'CornflowerBlue', 'DarkViolet']) except: nb_pts_caus = 1000 n_caustics = 0 if q > 1e-9: if n_caustics > 0: numerous_caustics = [] for i in xrange(n_caustics): # > Courbes critiques et caustiques delta = 2.0 * np.pi / (nb_pts_caus - 1.0) phi = np.arange(nb_pts_caus) * delta critic = np.array([]) for phi_temp in phi[:]: critic = np.append(critic, critic_roots(s[i], q, phi_temp)) caustic = critic - 1 / (1 + q) * (1 / critic.conjugate() + q / (critic.conjugate() + s[i])) caustic = caustic + GL1 # From Cassan (2008) to CM caustic = caustic * np.exp(1j*(alpha[i]-alpha0)) fig_curr.circle(caustic.real, caustic.imag, size=0.5, color=color_caustics[0], alpha=0.5) print color_caustics color_caustics = np.roll(color_caustics, -1) numerous_caustics.append(caustic) # > Courbes critiques et caustiques delta = 2.0 * np.pi / (nb_pts_caus - 1.0) phi = np.arange(nb_pts_caus) * delta critic = np.array([]) for phi_temp in phi[:]: critic = np.append(critic, critic_roots(s0, q, phi_temp)) caustic = critic - (1.0/(1 + q)) * (1/critic.conjugate() + q/(critic.conjugate() + s0)) caustic = caustic + GL1 # From Cassan (2008) to CM fig_curr.circle(caustic.real, caustic.imag, size=0.5, color='red', alpha=0.5) fig_curr.circle(GL1.real, GL1.imag, size=5, color='orange', alpha=1) fig_curr.circle(GL2.real, GL2.imag, size=5, color='orange', alpha=1) # Write output files text = "#{:>19s} {:>20s}".format("x", "y") if n_caustics > 0: for i in xrange(n_caustics): text = text +\ " x({0:17.6f}) y({0:17.6f})".format(time_caustic[i]) text = text + "\n" filename = path_outputs + "CAUSTIC.dat" for jj in xrange(len(caustic.real)): text = text +\ "{:20.12f} {:20.12f}".format( caustic.real[jj], caustic.imag[jj] ) if n_caustics > 0: for i in xrange(n_caustics): text = text +\ " {:20.12f} {:20.12f}".format( numerous_caustics[i].real[jj], numerous_caustics[i].imag[jj] ) text = text + "\n" file = open(filename, 'w') file.write(text) file.close() else: fig_curr.circle(0, 0, size=5, color='orange', alpha=1) # Trajectories # ^^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): temp = np.array([abs(a - best_model['t0']) for a in model_time_serie[i]['dates']]) rang_c = np.where(temp == np.min(temp))[0][0] X = model_time_serie[i]['x'] Y = model_time_serie[i]['y'] fig_curr.line(X, Y, line_width=2, color=colours[id_colour], alpha=1) # Arrows n = 0 z = (X[n] + 1j * Y[n]) - (X[n + 1] + 1j * Y[n + 1]) angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [X[n], X[n]] Y_arr = [Y[n], Y[n]] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) n = len(model_time_serie[i]['x']) - 2 z = (X[n] + 1j * Y[n]) - (X[n + 1] + 1j * Y[n + 1]) angle = [np.angle(z * np.exp(1j * np.pi / 5)), np.angle(z * np.exp(-1j * np.pi / 5))] X_arr = [X[n + 1], X[n + 1]] Y_arr = [Y[n + 1], Y[n + 1]] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) XX = np.array( X[rang_c] + 1j * Y[rang_c] + best_model['rho'] * np.exp( 1j * np.linspace(0, 2.0 * np.pi, 100))) # fig_curr.line(XX.real, XX.imag, line_width=0.5, color='black', alpha=0.5) fig_curr.patch(XX.real, XX.imag, color='black', alpha=0.3) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Trajectories (data) # ^^^^^^^^^^^^^^^^^^^ fig_curr.circle('x', 'y', size=8, color='colour', alpha=0.5, source=source) # Rotation for Earth + Spitzer # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ if len(model_time_serie) == 2: # Find the vector D in (x, y) at t0 source_t0_earth = np.array([ \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['x'], kind='linear')(best_model['t0']), \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['y'], kind='linear')(best_model['t0']) ]) source_t0_earth_pente = np.array([ \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['x'], kind='linear')(best_model['t0'] + 0.1), \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['y'], kind='linear')(best_model['t0'] + 0.1) ]) source_t0_earth_pente = ( source_t0_earth_pente - source_t0_earth) / 0.1 source_t0_spitzer = np.array([interp1d( model_time_serie[1]['dates'], model_time_serie[1]['x'], kind='linear')(best_model['t0']), \ interp1d( model_time_serie[1]['dates'], model_time_serie[1]['y'], kind='linear')( best_model['t0'])]) source_t0_spitzer_pente = np.array([ \ interp1d(model_time_serie[1]['dates'], model_time_serie[1]['x'], kind='linear')( best_model['t0'] + 0.1), \ interp1d(model_time_serie[1]['dates'], model_time_serie[1]['y'], kind='linear')( best_model['t0'] + 0.1) ]) source_t0_spitzer_pente = ( source_t0_spitzer_pente - source_t0_spitzer) / 0.1 D_t0_xy = source_t0_spitzer - source_t0_earth # Angle between D in (x,y) and (E,N) # Caution: we rotate (x,y) by pi/2, so y is towards left, x towards # top. Now we can compute the rotation angle beetween \Delta\zeta # and D in (E,N). This angle + pi/2 gives the rotation angle to draw # trajectories in (E,N). All this is necessary because (E,N,T) is # equivalent to (y, x, T) with T is the target. D_xy_c = (D_t0_xy[0] + 1j * D_t0_xy[1]) * np.exp(1j * np.pi / 2.0) D_c = D_enm[0] + 1j * D_enm[1] alpha1 = np.angle(D_xy_c, deg=False) alpha2 = np.angle(D_c, deg=False) # epsilon = (angle_between(D_t0_xy, np.array([D_enm[0], D_enm[1]]))) epsilon = (angle_between(np.array([D_xy_c.real, D_xy_c.imag]), np.array( [D_enm[0], D_enm[1]]))) + np.pi / 2.0 rotation = np.exp(1j * epsilon) # print alpha1*180.0/np.pi, alpha2*180.0/np.pi, epsilon*180.0/np.pi # Unit vectors in xy x_hat_xy = 1.0 y_hat_xy = 1j e_hat_xy = x_hat_xy * np.exp(1j * epsilon) n_hat_xy = y_hat_xy * np.exp(1j * epsilon) # Unit vectors in EN e_hat_en = 1.0 n_hat_en = 1j x_hat_en = e_hat_en * np.exp(-1j * epsilon) y_hat_en = n_hat_en * np.exp(-1j * epsilon) # D in (x,y) palette = plt.get_cmap('Paired') id_palette = 0.090909 # from 0 to 11 X = np.linspace(source_t0_earth[0], source_t0_spitzer[0], 2) Y = np.linspace(source_t0_earth[1], source_t0_spitzer[1], 2) n = 9 fig_curr.line(X, Y, line_width=2, line_dash='dashed', color='green', alpha=1) fig_curr.circle(X[0], Y[0], size=15, color='green', alpha=0.5) fig_curr.circle(X[1], Y[1], size=15, color='green', alpha=0.5) # ax_curr.plot(X, Y, dashes=(4, 2), lw=1, # color=palette(n * id_palette), alpha=1, zorder=20) # ax_curr.scatter(X[0], Y[0], 15, marker="o", linewidths=0.3, # facecolors=palette(n * id_palette), edgecolors='k', # alpha=0.8, zorder=20) # ax_curr.scatter(X[1], Y[1], 15, marker="o", linewidths=0.3, # facecolors=palette(n * id_palette), edgecolors='k', # alpha=0.8, zorder=20) # # Layout # ^^^^^^ fig_curr.xaxis.axis_label = u'\u03B8\u2081 (Einstein units)' fig_curr.yaxis.axis_label = u'\u03B8\u2082 (Einstein units)' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None # .................................................................. # Plot caustic 2 : pc2 # .................................................................. # if 0: if len(model_time_serie) == 2: # Caution: we draw in (East, North) with East towards the left hand side. # So, X must be Eastern component, Y must be Northern component. # Then, always plot -X, Y to get plots in (West, North) frame. # Finaly reverse x-axis to get back to the East towards left. # Preparation # ^^^^^^^^^^^ time_serie.update({'-x_complex': -( (time_serie['x'] + 1j * time_serie['y']) * rotation).real}) time_serie.update({'y_complex': ( (time_serie['x'] + 1j * time_serie['y']) * rotation).imag}) # Plot # ^^^^ source = ColumnDataSource(time_serie) hover_pc2 = HoverTool( tooltips=[ ("ID", "@id{int}"), ("Obs", "@obs"), ("Date", "@dates{1.11}") ] ) xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap", hover_pc2] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=560, plot_height=600, x_range=(xmax, xmin), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[3] # Caustic # ^^^^^^^ if q > 1e-9: caustic = caustic * rotation fig_curr.circle(-caustic.real, caustic.imag, size=0.5, color='red', alpha=0.5) X = (s0 * q / (1 + q)) * rotation fig_curr.circle(-X.real, X.imag, size=5, color='orange', alpha=1) X = (s0 * q / (1 + q) - s0) * rotation fig_curr.circle(-X.real, X.imag, size=5, color='orange', alpha=1) else: fig_curr.circle(0, 0, size=5, color='orange', alpha=1) # Trajectories # ^^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): X = (model_time_serie[i]['x'] + 1j * model_time_serie[i][ 'y']) * rotation fig_curr.line(-X.real, X.imag, line_width=2, color=colours[id_colour], alpha=1) # Arrows n = 0 z = X[n] - X[n + 1] angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [-X[n].real, -X[n].real] Y_arr = [X[n].imag, X[n].imag] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) n = len(model_time_serie[i]['x']) - 2 z = X[n] - X[n + 1] angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [-X[n + 1].real, -X[n + 1].real] Y_arr = [X[n + 1].imag, X[n + 1].imag] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Trajectories (data) # ^^^^^^^^^^^^^^^^^^^ fig_curr.circle('-x_complex', 'y_complex', size=8, color='colour', alpha=0.5, source=source) # Some specific positions # ^^^^^^^^^^^^^^^^^^^^^^^ # D in (e,n) at tO A = (source_t0_earth[0] + 1j * source_t0_earth[1]) * rotation B = (source_t0_spitzer[0] + 1j * source_t0_spitzer[1]) * rotation X = np.linspace(A.real, B.real, 2) Y = np.linspace(A.imag, B.imag, 2) n = 9 fig_curr.line(-X, Y, line_width=2, line_dash='dashed', color='green', alpha=1) fig_curr.circle(-X[0], Y[0], size=15, color='green', alpha=0.5) fig_curr.circle(-X[1], Y[1], size=15, color='green', alpha=0.5) # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'theta / theta_E (East)' fig_curr.yaxis.axis_label = 'theta / theta_E (North)' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None # ------------------------------------------------------------------ # Save the html page # ------------------------------------------------------------------ if len(model_time_serie) == 2: final = blyt.column(fig[0], fig[1], blyt.row(fig[2], fig[3])) bplt.save(final) if len(model_time_serie) != 2: final = blyt.column(fig[0], fig[1], fig[2]) # final = blyt.column(fig[0], fig[1]) bplt.save(final) # ------------------------------------------------------------------ # Modify the html page # ------------------------------------------------------------------ filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if cfgsetup.getboolean('Plotting', 'Data'): filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if (best_model['fullid'] == -1) & flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-summary.html' title = cfgsetup.get('EventDescription', 'Name') + ': best model last MCMC' elif flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-summary-' \ + repr(best_model['fullid']) + '.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model # ' + repr( best_model['fullid']) else: filename = filename + cfgsetup.get('Controls', 'Archive') + '-summary-fix.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model fix' file = open(filename, 'r') file_new = '' for line in file: # print line.strip()[:7] if line.strip()[:7] == '<title>': file_new = file_new \ + ' <style type="text/css">\n' \ + ' p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 43.0px; font: 36.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n'\ + ' p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 21.0px; font: 18.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n'\ + ' p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 15.0px; font: 12.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n'\ + ' p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 14.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000; min-height: 17.0px}\n'\ + ' p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}\n'\ + ' p.p6 {margin: 0.0px 0.0px 12.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}\n'\ + ' p.p7 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 14.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n'\ + ' span.s1 {font-kerning: none}\n'\ + ' span.s10 {font: 14.0px "Lucida Grande"; color: #585858}\n'\ + ' hr {\n'\ + ' display: block;\n'\ + ' margin-top: 0.5em;\n'\ + ' margin-bottom: 0.5em;\n'\ + ' margin-left: auto;\n'\ + ' margin-right: auto;\n'\ + ' border-style: inset;\n'\ + ' border-width: 1px;\n'\ + ' }\n'\ + ' </style>\n'\ + ' <title>' + 'muLAn ' + cfgsetup.get('EventDescription', 'Name')[4:] + '/' + cfgsetup.get('Controls', 'Archive') + '#' + repr(best_model['fullid']) + '</title>\n'\ + ' <meta name="Author" content="Clement Ranc">\n' elif line.strip()[:7] == '</head>': file_new = file_new\ + ' <script type="text/x-mathjax-config">\n'\ + " MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\\(','\\\)']]}});\n"\ + ' </script>\n'\ + ' <script type="text/javascript" async src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML"></script>\n'\ + ' </head>\n' elif line.strip()[:6] == '<body>': file_new = file_new \ + ' <body>\n\n' \ + '<p class="p1"><span class="s1"><b>' + title + '</b></span></p>\n' \ + '<p class="p2"><span class="s1"><br>\n' \ + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(t_0\) = ' + repr(best_model['t0']) + ' days</span></p>\n' \ + '<p class="p3"><span class="s1">\(u_0\) = ' + repr(best_model['u0']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(t_\mathrm{E}\) = ' + repr(best_model['tE']) + ' days</span></p>\n' \ + '<p class="p3"><span class="s1">\(\\rho\) = ' + repr(best_model['rho']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(\pi_\mathrm{EN}\) = ' + repr(best_model['piEN']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(\pi_\mathrm{EE}\) = ' + repr(best_model['piEE']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(s\) = ' + repr(best_model['s']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(q\) = ' + repr(best_model['q']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(\\alpha\) = ' + repr(best_model['alpha']) + ' radians</span></p>\n' \ + '<p class="p3"><span class="s1">\(\mathrm{d}\\alpha/\mathrm{d}t\)= ' + repr(best_model['dalpha']) + ' radians/years</span></p>\n' \ + '<p class="p3"><span class="s1">\(\mathrm{d}s/\mathrm{d}t\) = ' + repr(best_model['ds']) + ' years^-1</span></p>\n' \ + '<p class="p3"><span class="s1">\(\chi^2\) = ' + repr(chi2_flux) + '</span></p>\n' \ + '<p class="p3"><span class="s1">\(\chi^2/\mathrm{dof}\) = ' + repr(chi2dof_flux) + '</span></p>\n' \ + '<p class="p2"><span class="s1"><br>\n' \ + '</span></p>\n' elif line.strip()[:7] == '</body>': file_new = file_new \ + ' <BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n' \ + ' <BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n' \ + ' <hr>\n' \ + ' <BR>\n' \ + ' <footer>\n'\ + ' <p class="p7"><span class="s10">Modelling and page by muLAn (MicroLensing Analysis software).</span></p>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' </footer>\n' \ + ' </body>\n' else: file_new = file_new + line file.close() file = open(filename, 'w') file.write(file_new) file.close() if 0: # PLOT STATISTIC RESIDUAL IN MAG ================================== for j in xrange(len(observatories)): cond2 = (time_serie['obs'] == observatories[j]) # Configuration # ------------------------------------------------------------------ moteur = 'defaultSmall_pdf' # ------------------------------------------------------------------ # Conversions in2cm = 2.54 cm2in = 1.0 / in2cm in2pt = 72.27 pt2in = 1.0 / 72.27 cm2pt = cm2in * in2pt pt2cm = 1.0 / cm2pt # ------------------------------------------------------------------ # Configuration à compléter fig_width_cm = 6.5 fig_height_cm = 4.5 path = cfgsetup.get('FullPaths', 'Event')\ + cfgsetup.get('RelativePaths', 'Plots') filename = path + cfgsetup.get('Controls', 'Archive')\ + "-" + observatories[j]\ + '-Residuals_Statistics' # ------------------------------------------------------------------ # Calculs pour configuration fig_width_pt = fig_width_cm * cm2pt fig_height_pt = fig_height_cm * cm2pt # golden_mean = (math.sqrt(5)-1.0)/2.0 = 0.62 extension = moteur[-3:] filename_moteur = full_path + 'plotconfig/matplotlibrc_' + moteur pylab.rcParams.update( mpl.rc_params_from_file(filename_moteur, fail_on_error=True)) fig_size = np.array([fig_width_pt, fig_height_pt]) * pt2in # ------------------------------------------------------------------ fig1 = plt.figure('Figure', figsize=fig_size) # .................................................................. # Plot 1 # .................................................................. layout = [1.0, 0.8, 5, 3.1] # en cm kde = np.array(layout) * cm2in / np.array( [fig_size[0], fig_size[1], fig_size[0], fig_size[1]]) ax_curr = fig1.add_axes(kde) grandeur = time_serie['residus'][cond2] nb_bins = 2*int(np.sqrt(np.max([len(grandeur), 3]))) lim_stat = [np.min(grandeur), np.max(grandeur)] X = grandeur hist, bin_edges = np.histogram(X, bins=nb_bins, range=(lim_stat), density=1) hist_plot = np.append(hist, [hist[-1]]) / np.max(hist) ax_curr.step(bin_edges, hist_plot, 'k-', where="mid", zorder=2) # Model model = GaussianMixture(n_components=1).fit(np.atleast_2d(grandeur).T) X = np.atleast_2d(np.linspace(lim_stat[0], lim_stat[1], 1000)).T logprob = model.score_samples(X) pdf_individual = np.exp(logprob) pdf_individual = pdf_individual / np.max(pdf_individual) ax_curr.plot(X.T[0], pdf_individual, ls='-', color='b', zorder=1) mean = np.mean(X.T[0]) rms = np.std(X.T[0]) chat = "mean {:.4f}\nstd dev {:.4f}".format(mean, rms) position = [1, 1] ax_curr.annotate(chat, xy=position, xycoords='axes fraction', ha="right", va="center", color='k', fontsize=5, backgroundcolor='w', zorder=100) # Limits # ^^^^^^ # ax_curr.set_xlim(0, 3.5) ax_curr.set_ylim(0, 1.05) # ax_curr.set_ylim(ax_curr.get_ylim()[1], ax_curr.get_ylim()[0]) # ax_curr.set_xscale('log') # ax_curr.set_yscale('log') # Ticks # ^^^^^ # ax_curr.xaxis.set_major_locator(MultipleLocator(0.4)) ax_curr.xaxis.set_major_locator(MaxNLocator(5)) minor = 0.5 * (np.roll(ax_curr.get_xticks(), -1) - ax_curr.get_xticks())[0] minor_locator = MultipleLocator(minor) ax_curr.xaxis.set_minor_locator(minor_locator) ax_curr.yaxis.set_major_locator(MultipleLocator(0.2)) # ax_curr.yaxis.set_major_locator(MaxNLocator(4)) minor = 0.5 * (np.roll(ax_curr.get_yticks(), -1) - ax_curr.get_yticks())[0] minorLocator = MultipleLocator(minor) ax_curr.yaxis.set_minor_locator(minorLocator) # Legend # ^^^^^^ ax_curr.set_xlabel(ur"%s" % ("$\sigma$ (mag)"), labelpad=0) ax_curr.set_ylabel(ur"%s" % ("count"), labelpad=3) # # --> Options de fin # # for tick in ax_curr.get_yaxis().get_major_ticks(): # tick.set_pad(2) # tick.label1 = tick._get_text1() # for tick in ax_curr.get_xaxis().get_major_ticks(): # tick.set_pad(2) # tick.label1 = tick._get_text1() # .................................................................. # SAVE FIGURE # .................................................................. if 0: plt.show() fig1.savefig(filename + "." + extension, transparent=False, dpi=1400) plt.close() # ================================================================= else: filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if (best_model['fullid'] == -1) & flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification.html' title = cfgsetup.get('EventDescription', 'Name') + ': best model last MCMC' elif flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification-' \ + repr(best_model['fullid']) + '.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model # ' + repr( best_model['fullid']) else: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification-fix.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model fix' if os.path.exists(filename): os.remove(filename) bplt.output_file(filename) fig = np.array([]) plot_counter = 0 observatories = np.unique(time_serie['obs']) # .................................................................. # Plot light curve : amplification # .................................................................. tmin = float(options.split('/')[0].split('-')[0].strip()) tmax = float(options.split('/')[0].split('-')[1].strip()) ymin = 0.9 ymax = 0 for i in xrange(len(locations)): ymax_temp = np.max(model_time_serie[i]['amp']) ymax = np.max(np.array([ymax, ymax_temp])) tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap"] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=1200, plot_height=600, x_range=(tmin, tmax), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[plot_counter] # Annotations # ^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): name = 'Models_' + locations[i] models_temp = model_param[name] name = 'DateRanges_' + locations[i] dates_temp = model_param[name] for j in xrange(len(models_temp)): tmin = float((dates_temp[j]).split('-')[0].strip()) tmax = float((dates_temp[j]).split('-')[1].strip()) X = np.ones(2) * tmin Y = np.linspace(-100000, 100000, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) X = np.ones(2) * tmax Y = np.linspace(-100000, 100000, 2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) X = np.linspace(-100000, 100000, 2) Y = 1.0 * np.ones(2) fig_curr.line(X, Y, line_width=0.5, line_dash='dashed', color=colours[id_colour], alpha=0.4) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Amplification models # ^^^^^^^^^^^^^^^^^^^^ colours = ['black', '#297CC4', 'green'] id_colour = 0 for i in xrange(len(locations)): X = model_time_serie[i]['dates'] Y = model_time_serie[i]['amp'] fig_curr.line(X, Y, line_width=2, color=colours[id_colour], alpha=1) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'HJD - 2,450,000' fig_curr.yaxis.axis_label = 'Amplification' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None plot_counter = plot_counter + 1 # .................................................................. # Plot caustic 1 : pc1 # .................................................................. # Plot # ^^^^ xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap"] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=600, plot_height=560, x_range=(xmin, xmax), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[plot_counter] # Caustic # ^^^^^^^ # Case of lens orbital rotation try: time_caustic = options.split('/')[2].replace('[','').replace(']','').split('-') time_caustic = np.array([float(a.strip()) for a in time_caustic]) n_caustics = len(time_caustic) nb_pts_caus = 1000 alpha, s = lens_rotation(alpha0, s0, dalpha, ds, time_caustic, tb) color_caustics = np.array(['Orange', 'SeaGreen', 'LightSeaGreen', 'CornflowerBlue', 'DarkViolet']) except: nb_pts_caus = 1000 n_caustics = 0 if q > 1e-9: if n_caustics > 0: for i in xrange(n_caustics): # > Courbes critiques et caustiques delta = 2.0 * np.pi / (nb_pts_caus - 1.0) phi = np.arange(nb_pts_caus) * delta critic = np.array([]) for phi_temp in phi[:]: critic = np.append(critic, critic_roots(s[i], q, phi_temp)) caustic = critic - 1 / (1 + q) * (1 / critic.conjugate() + q / (critic.conjugate() + s[i])) caustic = caustic + GL1 # From Cassan (2008) to CM caustic = caustic * np.exp(1j*(alpha[i]-alpha0)) fig_curr.circle(caustic.real, caustic.imag, size=0.5, color=color_caustics[0], alpha=0.5) color_caustics = np.roll(color_caustics, -1) # > Courbes critiques et caustiques delta = 2.0 * np.pi / (nb_pts_caus - 1.0) phi = np.arange(nb_pts_caus) * delta critic = np.array([]) for phi_temp in phi[:]: critic = np.append(critic, critic_roots(s0, q, phi_temp)) caustic = critic - 1 / (1 + q) * ( 1 / critic.conjugate() + q / (critic.conjugate() + s0)) caustic = caustic + GL1 # From Cassan (2008) to CM fig_curr.circle(caustic.real, caustic.imag, size=0.5, color='red', alpha=0.5) fig_curr.circle(GL1.real, GL1.imag, size=5, color='orange', alpha=1) fig_curr.circle(GL2.real, GL2.imag, size=5, color='orange', alpha=1) else: fig_curr.circle(0, 0, size=5, color='orange', alpha=1) # Trajectories # ^^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): temp = np.array([abs(a - best_model['t0']) for a in model_time_serie[i]['dates']]) rang_c = np.where(temp == np.min(temp))[0][0] X = model_time_serie[i]['x'] Y = model_time_serie[i]['y'] fig_curr.line(X, Y, line_width=2, color=colours[id_colour], alpha=1) # Arrows n = 0 z = (X[n] + 1j * Y[n]) - (X[n + 1] + 1j * Y[n + 1]) angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [X[n], X[n]] Y_arr = [Y[n], Y[n]] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) n = len(model_time_serie[i]['x']) - 2 z = (X[n] + 1j * Y[n]) - (X[n + 1] + 1j * Y[n + 1]) angle = [np.angle(z * np.exp(1j * np.pi / 5)), np.angle(z * np.exp(-1j * np.pi / 5))] X_arr = [X[n + 1], X[n + 1]] Y_arr = [Y[n + 1], Y[n + 1]] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) XX = np.array( X[rang_c] + 1j * Y[rang_c] + best_model['rho'] * np.exp( 1j * np.linspace(0, 2.0 * np.pi, 100))) # fig_curr.line(XX.real, XX.imag, line_width=0.5, color='black', alpha=0.5) fig_curr.patch(XX.real, XX.imag, color='black', alpha=0.3) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Rotation for Earth + Spitzer # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ if len(model_time_serie) == 2: # Find the vector D in (x, y) at t0 source_t0_earth = np.array([ \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['x'], kind='linear')(best_model['t0']), \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['y'], kind='linear')(best_model['t0']) ]) source_t0_earth_pente = np.array([ \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['x'], kind='linear')(best_model['t0'] + 0.1), \ interp1d(model_time_serie[0]['dates'], model_time_serie[0]['y'], kind='linear')(best_model['t0'] + 0.1) ]) source_t0_earth_pente = ( source_t0_earth_pente - source_t0_earth) / 0.1 source_t0_spitzer = np.array([interp1d( model_time_serie[1]['dates'], model_time_serie[1]['x'], kind='linear')(best_model['t0']), \ interp1d( model_time_serie[1]['dates'], model_time_serie[1]['y'], kind='linear')( best_model['t0'])]) source_t0_spitzer_pente = np.array([ \ interp1d(model_time_serie[1]['dates'], model_time_serie[1]['x'], kind='linear')( best_model['t0'] + 0.1), \ interp1d(model_time_serie[1]['dates'], model_time_serie[1]['y'], kind='linear')( best_model['t0'] + 0.1) ]) source_t0_spitzer_pente = ( source_t0_spitzer_pente - source_t0_spitzer) / 0.1 D_t0_xy = source_t0_spitzer - source_t0_earth # Angle between D in (x,y) and (E,N) # Caution: we rotate (x,y) by pi/2, so y is towards left, x towards # top. Now we can compute the rotation angle beetween \Delta\zeta # and D in (E,N). This angle + pi/2 gives the rotation angle to draw # trajectories in (E,N). All this is necessary because (E,N,T) is # equivalent to (y, x, T) with T is the target. D_xy_c = (D_t0_xy[0] + 1j * D_t0_xy[1]) * np.exp(1j * np.pi / 2.0) D_c = D_enm[0] + 1j * D_enm[1] alpha1 = np.angle(D_xy_c, deg=False) alpha2 = np.angle(D_c, deg=False) # epsilon = (angle_between(D_t0_xy, np.array([D_enm[0], D_enm[1]]))) epsilon = (angle_between(np.array([D_xy_c.real, D_xy_c.imag]), np.array( [D_enm[0], D_enm[1]]))) + np.pi / 2.0 rotation = np.exp(1j * epsilon) # print alpha1*180.0/np.pi, alpha2*180.0/np.pi, epsilon*180.0/np.pi # Unit vectors in xy x_hat_xy = 1.0 y_hat_xy = 1j e_hat_xy = x_hat_xy * np.exp(1j * epsilon) n_hat_xy = y_hat_xy * np.exp(1j * epsilon) # Unit vectors in EN e_hat_en = 1.0 n_hat_en = 1j x_hat_en = e_hat_en * np.exp(-1j * epsilon) y_hat_en = n_hat_en * np.exp(-1j * epsilon) # D in (x,y) palette = plt.get_cmap('Paired') id_palette = 0.090909 # from 0 to 11 X = np.linspace(source_t0_earth[0], source_t0_spitzer[0], 2) Y = np.linspace(source_t0_earth[1], source_t0_spitzer[1], 2) n = 9 fig_curr.line(X, Y, line_width=2, line_dash='dashed', color='green', alpha=1) fig_curr.circle(X[0], Y[0], size=15, color='green', alpha=0.5) fig_curr.circle(X[1], Y[1], size=15, color='green', alpha=0.5) # ax_curr.plot(X, Y, dashes=(4, 2), lw=1, # color=palette(n * id_palette), alpha=1, zorder=20) # ax_curr.scatter(X[0], Y[0], 15, marker="o", linewidths=0.3, # facecolors=palette(n * id_palette), edgecolors='k', # alpha=0.8, zorder=20) # ax_curr.scatter(X[1], Y[1], 15, marker="o", linewidths=0.3, # facecolors=palette(n * id_palette), edgecolors='k', # alpha=0.8, zorder=20) # # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'theta_x / theta_E' fig_curr.yaxis.axis_label = 'theta_y / theta_E' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None plot_counter = plot_counter + 1 # .................................................................. # Plot caustic 2 : pc2 # .................................................................. if len(model_time_serie) == 2: # Caution: we draw in (East, North) with East towards the left hand side. # So, X must be Eastern component, Y must be Northern component. # Then, always plot -X, Y to get plots in (West, North) frame. # Finaly reverse x-axis to get back to the East towards left. # Plot # ^^^^ xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 tools = ["save", "pan", "box_zoom", "wheel_zoom", "reset", "tap"] fig = np.append(fig, \ bplt.figure(toolbar_location="above", plot_width=600, plot_height=560, x_range=(xmax, xmin), y_range=(ymin, ymax), \ title=None, min_border=10, min_border_left=50, tools=tools)) fig_curr = fig[plot_counter] # Caustic # ^^^^^^^ if q > 1e-9: caustic = caustic * rotation fig_curr.circle(-caustic.real, caustic.imag, size=0.5, color='red', alpha=0.5) X = (s0 * q / (1 + q)) * rotation fig_curr.circle(-X.real, X.imag, size=5, color='orange', alpha=1) X = (s0 * q / (1 + q) - s) * rotation fig_curr.circle(-X.real, X.imag, size=5, color='orange', alpha=1) else: fig_curr.circle(0, 0, size=5, color='orange', alpha=1) # Trajectories # ^^^^^^^^^^^^ colours = ['black', '#297CC4'] id_colour = 0 for i in xrange(len(locations)): X = (model_time_serie[i]['x'] + 1j * model_time_serie[i][ 'y']) * rotation fig_curr.line(-X.real, X.imag, line_width=2, color=colours[id_colour], alpha=1) # Arrows n = 0 z = X[n] - X[n + 1] angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [-X[n].real, -X[n].real] Y_arr = [X[n].imag, X[n].imag] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) n = len(model_time_serie[i]['x']) - 2 z = X[n] - X[n + 1] angle = [np.angle(z * np.exp(1j * np.pi / 5.0)), np.angle(z * np.exp(-1j * np.pi / 5.0))] X_arr = [-X[n + 1].real, -X[n + 1].real] Y_arr = [X[n + 1].imag, X[n + 1].imag] fig_curr.ray(X_arr, Y_arr, length=0.05, angle=angle, color=colours[id_colour], line_width=1, alpha=0.5) if id_colour < len(colours) - 1: id_colour = id_colour + 1 else: id_colour = 0 # Some specific positions # ^^^^^^^^^^^^^^^^^^^^^^^ # D in (e,n) at tO A = (source_t0_earth[0] + 1j * source_t0_earth[1]) * rotation B = (source_t0_spitzer[0] + 1j * source_t0_spitzer[1]) * rotation X = np.linspace(A.real, B.real, 2) Y = np.linspace(A.imag, B.imag, 2) n = 9 fig_curr.line(-X, Y, line_width=2, line_dash='dashed', color='green', alpha=1) fig_curr.circle(-X[0], Y[0], size=15, color='green', alpha=0.5) fig_curr.circle(-X[1], Y[1], size=15, color='green', alpha=0.5) # Layout # ^^^^^^ fig_curr.xaxis.axis_label = 'theta / theta_E (East)' fig_curr.yaxis.axis_label = 'theta / theta_E (North)' fig_curr.xaxis.axis_label_text_font = 'helvetica' fig_curr.yaxis.axis_label_text_font = 'helvetica' fig_curr.xaxis.axis_label_text_font_size = '10pt' fig_curr.yaxis.axis_label_text_font_size = '10pt' fig_curr.min_border_top = 10 fig_curr.min_border_bottom = 0 fig_curr.min_border_left = 0 fig_curr.xgrid.grid_line_color = None fig_curr.ygrid.grid_line_color = None plot_counter = plot_counter + 1 # ------------------------------------------------------------------ # Save the html page # ------------------------------------------------------------------ if len(model_time_serie) == 2: final = blyt.column(fig[0], blyt.row(fig[1], fig[2])) bplt.save(final) if len(model_time_serie) != 2: final = blyt.column(fig[0], fig[1]) # final = bplt.vplot(fig[2]) bplt.save(final) # ------------------------------------------------------------------ # Modify the html page # ------------------------------------------------------------------ filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get( 'RelativePaths', 'Plots') if (best_model['fullid'] == -1) & flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification.html' title = cfgsetup.get('EventDescription', 'Name') + ': best model last MCMC' elif flag_fix: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification-' \ + repr(best_model['fullid']) + '.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model # ' + repr( best_model['fullid']) else: filename = filename + cfgsetup.get('Controls', 'Archive') + '-amplification-fix.html' title = cfgsetup.get('EventDescription', 'Name') + ' - Model fix' file = open(filename, 'r') file_new = '' for line in file: # print line.strip()[:7] if line.strip()[:7] == '<title>': file_new = file_new \ + ' <style type="text/css">\n' \ + ' p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 43.0px; font: 36.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n' \ + ' p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 21.0px; font: 18.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n' \ + ' p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 15.0px; font: 12.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n' \ + ' p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 14.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000; min-height: 17.0px}\n' \ + ' p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}\n' \ + ' p.p6 {margin: 0.0px 0.0px 12.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}\n' \ + ' p.p7 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 14.0px "Lucida Grande"; color: #000000; -webkit-text-stroke: #000000}\n' \ + ' span.s1 {font-kerning: none}\n' \ + ' span.s10 {font: 14.0px "Lucida Grande"; color: #585858}\n' \ + ' hr {\n' \ + ' display: block;\n' \ + ' margin-top: 0.5em;\n' \ + ' margin-bottom: 0.5em;\n' \ + ' margin-left: auto;\n' \ + ' margin-right: auto;\n' \ + ' border-style: inset;\n' \ + ' border-width: 1px;\n' \ + ' }\n' \ + ' </style>\n' \ + ' <title>' + 'muLAn ' + cfgsetup.get('EventDescription', 'Name')[4:] + '/' + cfgsetup.get('Controls', 'Archive') + '#'\ + repr(best_model['fullid']) + '</title>\n' \ + ' <meta name="Author" content="Clement Ranc">\n' elif line.strip()[:6] == '<body>': file_new = file_new \ + ' <body>\n\n' \ + '<p class="p1"><span class="s1"><b>' + title + '</b></span></p>\n' \ + '<p class="p2"><span class="s1"><br>\n' \ + '</span></p>\n' \ + '<p class="p3"><span class="s1">t0 = ' + repr( best_model['t0']) + ' days</span></p>\n' \ + '<p class="p3"><span class="s1">u0 = ' + repr( best_model['u0']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">tE = ' + repr( best_model['tE']) + ' days</span></p>\n' \ + '<p class="p3"><span class="s1">rho = ' + repr( best_model['rho']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">piEN = ' + repr( best_model['piEN']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">piEE = ' + repr( best_model['piEE']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">s = ' + repr( best_model['s']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">q = ' + repr( best_model['q']) + '</span></p>\n' \ + '<p class="p3"><span class="s1">alpha = ' + repr( best_model['alpha']) + ' radians</span></p>\n' \ + '<p class="p3"><span class="s1">dalpha/dt= ' + repr( best_model['dalpha']) + ' radians/years</span></p>\n'\ + '<p class="p3"><span class="s1">ds/dt = ' + repr( best_model['ds']) + ' years^-1</span></p>\n' \ + '<p class="p3"><span class="s1">chi2 = ' + repr( best_model['chi2']) + ' radians</span></p>\n' \ + '<p class="p3"><span class="s1">chi2/dof = ' + repr( best_model['chi2/dof']) + ' radians</span></p>\n' \ + '<p class="p2"><span class="s1"><br>\n' \ + '</span></p>\n' elif line.strip()[:7] == '</body>': file_new = file_new \ + ' <BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n<BR>\n' \ + ' <hr>\n' \ + ' <BR>\n' \ + ' <footer>\n' \ + ' <p class="p7"><span class="s10">Modelling and page by muLAn (MicroLensing Analysis software).</span></p>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' <BR>\n' \ + ' </footer>\n' \ + ' </body>\n' else: file_new = file_new + line file.close() file = open(filename, 'w') file.write(file_new) file.close()
135,360
47.068537
1,076
py
CDGS
CDGS-main/losses.py
"""All functions related to loss computation and optimization.""" import torch import torch.optim as optim import numpy as np from models import utils as mutils from sde_lib import VPSDE def get_optimizer(config, params): """Return a flax optimizer object based on `config`.""" if config.optim.optimizer == 'Adam': optimizer = optim.Adam(params, lr=config.optim.lr, betas=(config.optim.beta1, 0.999), eps=config.optim.eps, weight_decay=config.optim.weight_decay) else: raise NotImplementedError( f'Optimizer {config.optim.optimizer} not supported yet!' ) return optimizer def optimization_manager(config): """Return an optimize_fn based on `config`.""" def optimize_fn(optimizer, params, step, lr=config.optim.lr, warmup=config.optim.warmup, grad_clip=config.optim.grad_clip): """Optimize with warmup and gradient clipping (disabled if negative).""" if warmup > 0: for g in optimizer.param_groups: g['lr'] = lr * np.minimum(step / warmup, 1.0) if grad_clip >= 0: torch.nn.utils.clip_grad_norm_(params, max_norm=grad_clip) optimizer.step() return optimize_fn def get_multi_sde_loss_fn(atom_sde, bond_sde, train, reduce_mean=True, continuous=True, eps=1e-5): """ Create a loss function for training with arbitrary node SDE and edge SDE. Args: atom_sde, bond_sde: An `sde_lib.SDE` object that represents the forward SDE. train: `True` for training loss and `False` for evaluation loss. reduce_mean: If `True`, average the loss across data dimensions. Otherwise, sum the loss across data dimensions. continuous: `True` indicates that the model is defined to take continuous time steps. Otherwise, it requires ad-hoc interpolation to take continuous time steps. eps: A `float` number. The smallest time step to sample from. Returns: A loss function. """ def loss_fn(model, batch): """Compute the loss function. Args: model: A score model. batch: A mini-batch of training data, including node_features, adjacency matrices, node mask and adj mask. Returns: loss: A scalar that represents the average loss value across the mini-batch. """ atom_feat, atom_mask, bond_feat, bond_mask = batch score_fn = mutils.get_multi_score_fn(atom_sde, bond_sde, model, train=train, continuous=continuous) t = torch.rand(atom_feat.shape[0], device=atom_feat.device) * (atom_sde.T - eps) + eps # perturbing atom z_atom = torch.randn_like(atom_feat) # [B, N, C] mean_atom, std_atom = atom_sde.marginal_prob(atom_feat, t) perturbed_atom = (mean_atom + std_atom[:, None, None] * z_atom) * atom_mask[:, :, None] # perturbing bond z_bond = torch.randn_like(bond_feat) # [B, C, N, N] z_bond = torch.tril(z_bond, -1) z_bond = z_bond + z_bond.transpose(-1, -2) mean_bond, std_bond = bond_sde.marginal_prob(bond_feat, t) perturbed_bond = (mean_bond + std_bond[:, None, None, None] * z_bond) * bond_mask atom_score, bond_score = score_fn((perturbed_atom, perturbed_bond), t, atom_mask=atom_mask, bond_mask=bond_mask) # atom loss atom_mask = atom_mask[:, :, None].repeat(1, 1, atom_feat.shape[-1]) atom_mask = atom_mask.reshape(atom_mask.shape[0], -1) losses_atom = torch.square(atom_score * std_atom[:, None, None] + z_atom) losses_atom = losses_atom.reshape(losses_atom.shape[0], -1) if reduce_mean: losses_atom = torch.sum(losses_atom * atom_mask, dim=-1) / torch.sum(atom_mask, dim=-1) else: losses_atom = 0.5 * torch.sum(losses_atom * atom_mask, dim=-1) loss_atom = losses_atom.mean() # bond loss bond_mask = bond_mask.repeat(1, bond_feat.shape[1], 1, 1) bond_mask = bond_mask.reshape(bond_mask.shape[0], -1) losses_bond = torch.square(bond_score * std_bond[:, None, None, None] + z_bond) losses_bond = losses_bond.reshape(losses_bond.shape[0], -1) if reduce_mean: losses_bond = torch.sum(losses_bond * bond_mask, dim=-1) / (torch.sum(bond_mask, dim=-1) + 1e-8) else: losses_bond = 0.5 * torch.sum(losses_bond * bond_mask, dim=-1) loss_bond = losses_bond.mean() return loss_atom + loss_bond return loss_fn def get_step_fn(sde, train, optimize_fn=None, reduce_mean=False, continuous=True, likelihood_weighting=False): """Create a one-step training/evaluation function. Args: sde: An `sde_lib.SDE` object that represents the forward SDE. Tuple (`sde_lib.SDE`, `sde_lib.SDE`) that represents the forward node SDE and edge SDE. optimize_fn: An optimization function. reduce_mean: If `True`, average the loss across data dimensions. Otherwise, sum the loss across data dimensions. continuous: `True` indicates that the model is defined to take continuous time steps. likelihood_weighting: If `True`, weight the mixture of score matching losses according to https://arxiv.org/abs/2101.09258; otherwise, use the weighting recommended by score-sde. Returns: A one-step function for training or evaluation. """ if continuous: if isinstance(sde, tuple): loss_fn = get_multi_sde_loss_fn(sde[0], sde[1], train, reduce_mean=reduce_mean, continuous=True) else: loss_fn = get_sde_loss_fn(sde, train, reduce_mean=reduce_mean, continuous=True, likelihood_weighting=likelihood_weighting) else: assert not likelihood_weighting, "Likelihood weighting is not supported for original SMLD/DDPM training." if isinstance(sde, VPSDE): loss_fn = get_ddpm_loss_fn(sde, train, reduce_mean=reduce_mean) elif isinstance(sde, tuple): raise ValueError("Discrete training for multi sde is not recommended.") else: raise ValueError(f"Discrete training for {sde.__class__.__name__} is not recommended.") def step_fn(state, batch): """Running one step of training or evaluation. For jax version: This function will undergo `jax.lax.scan` so that multiple steps can be pmapped and jit-compiled together for faster execution. Args: state: A dictionary of training information, containing the score model, optimizer, EMA status, and number of optimization steps. batch: A mini-batch of training/evaluation data, including min-batch adjacency matrices and mask. Returns: loss: The average loss value of this state. """ model = state['model'] if train: optimizer = state['optimizer'] optimizer.zero_grad() loss = loss_fn(model, batch) loss.backward() optimize_fn(optimizer, model.parameters(), step=state['step']) state['step'] += 1 state['ema'].update(model.parameters()) else: with torch.no_grad(): ema = state['ema'] ema.store(model.parameters()) ema.copy_to(model.parameters()) loss = loss_fn(model, batch) ema.restore(model.parameters()) return loss return step_fn
7,611
42.00565
124
py
CDGS
CDGS-main/dpm_solvers.py
# DPM solvers: stiff semi-linear ODE # Note: hyperparams of Atom_SDE and Bond_SDE should keep the same for DPM-Solver-1, DPM-Solver-2 and DPM-Solver-3 !!! import torch import numpy as np import functools from models.utils import get_multi_theta_fn, get_multi_score_fn, get_theta_fn def sample_nodes(n_nodes_pmf, atom_shape, device): n_nodes = torch.multinomial(n_nodes_pmf, atom_shape[0], replacement=True) atom_mask = torch.zeros((atom_shape[0], atom_shape[1]), device=device) for i in range(atom_shape[0]): atom_mask[i][:n_nodes[i]] = 1. bond_mask = (atom_mask[:, None, :] * atom_mask[:, :, None]).unsqueeze(1) bond_mask = torch.tril(bond_mask, -1) bond_mask = bond_mask + bond_mask.transpose(-1, -2) return n_nodes, atom_mask, bond_mask def expand_dim(x, n_dim): if n_dim == 3: x = x[:, None, None] elif n_dim == 4: x = x[:, None, None, None] return x def dpm1_update(x_last, t_last, t_i, sde, theta): # dpm_solver 1 order update function expand_fn = functools.partial(expand_dim, n_dim=len(x_last.shape)) lambda_i, alpha_i, std_i = sde.log_snr(t_i) lambda_last, alpha_last, _ = sde.log_snr(t_last) h_i = lambda_i - lambda_last x_i = expand_fn(alpha_i / alpha_last) * x_last - expand_fn(std_i * torch.expm1(h_i)) * theta return x_i def dpm_mol_solver_1(atom_sde, bond_sde, theta_fn, x_atom_last, x_bond_last, t_last, t_i, atom_mask, bond_mask): # run solver func once vec_t_last = torch.ones(x_atom_last.shape[0], device=x_atom_last.device) * t_last vec_t_i = torch.ones(x_atom_last.shape[0], device=x_atom_last.device) * t_i atom_fn = functools.partial(expand_dim, n_dim=len(x_atom_last.shape)) bond_fn = functools.partial(expand_dim, n_dim=len(x_bond_last.shape)) lambda_i, alpha_i, std_i = atom_sde.log_snr(vec_t_i) lambda_last, alpha_last, _ = atom_sde.log_snr(vec_t_last) h_i = lambda_i - lambda_last atom_theta, bond_theta = theta_fn((x_atom_last, x_bond_last), vec_t_last, atom_mask=atom_mask, bond_mask=bond_mask) tmp_linear = alpha_i / alpha_last tmp_nonlinear = std_i * torch.expm1(h_i) x_atom_i = atom_fn(tmp_linear) * x_atom_last - atom_fn(tmp_nonlinear) * atom_theta x_bond_i = bond_fn(tmp_linear) * x_bond_last - bond_fn(tmp_nonlinear) * bond_theta return x_atom_i, x_bond_i def dpm_mol_solver_2(atom_sde, bond_sde, theta_fn, x_atom_last, x_bond_last, t_last, t_i, atom_mask, bond_mask, r1=0.5): vec_t_last = torch.ones(x_atom_last.shape[0], device=x_atom_last.device) * t_last vec_t_i = torch.ones(x_atom_last.shape[0], device=x_atom_last.device) * t_i atom_fn = functools.partial(expand_dim, n_dim=len(x_atom_last.shape)) bond_fn = functools.partial(expand_dim, n_dim=len(x_bond_last.shape)) lambda_i, alpha_i, std_i = atom_sde.log_snr(vec_t_i) lambda_last, alpha_last, _ = atom_sde.log_snr(vec_t_last) h_i = lambda_i - lambda_last s_i = atom_sde.lambda2t(lambda_last + r1 * h_i) _, alpha_si, std_si = atom_sde.log_snr(s_i) atom_theta_0, bond_theta_0 = theta_fn((x_atom_last, x_bond_last), vec_t_last, atom_mask=atom_mask, bond_mask=bond_mask) tmp_lin = alpha_si / alpha_last tmp_nonlin = std_si * torch.expm1(r1 * h_i) u_atom_i = atom_fn(tmp_lin) * x_atom_last - atom_fn(tmp_nonlin) * atom_theta_0 u_bond_i = bond_fn(tmp_lin) * x_bond_last - bond_fn(tmp_nonlin) * bond_theta_0 atom_theta_si, bond_theta_si = theta_fn((u_atom_i, u_bond_i), s_i, atom_mask=atom_mask, bond_mask=bond_mask) tmp_lin = alpha_i / alpha_last tmp_nonlin1 = std_i * torch.expm1(h_i) tmp_nonlin2 = (std_i / (2. * r1)) * torch.expm1(h_i) x_atom_i = atom_fn(tmp_lin) * x_atom_last - atom_fn(tmp_nonlin1) * atom_theta_0 - \ atom_fn(tmp_nonlin2) * (atom_theta_si - atom_theta_0) x_bond_i = bond_fn(tmp_lin) * x_bond_last - bond_fn(tmp_nonlin1) * bond_theta_0 - \ bond_fn(tmp_nonlin2) * (bond_theta_si - bond_theta_0) return x_atom_i, x_bond_i def dpm_mol_solver_3(atom_sde, bond_sde, theta_fn, x_atom_last, x_bond_last, t_last, t_i, atom_mask, bond_mask, r1=1./3., r2=2./3.): vec_t_last = torch.ones(x_atom_last.shape[0], device=x_atom_last.device) * t_last vec_t_i = torch.ones(x_atom_last.shape[0], device=x_atom_last.device) * t_i atom_fn = functools.partial(expand_dim, n_dim=len(x_atom_last.shape)) bond_fn = functools.partial(expand_dim, n_dim=len(x_bond_last.shape)) lambda_i, alpha_i, std_i = atom_sde.log_snr(vec_t_i) lambda_last, alpha_last, _ = atom_sde.log_snr(vec_t_last) h_i = lambda_i - lambda_last s1 = atom_sde.lambda2t(lambda_last + r1 * h_i) s2 = atom_sde.lambda2t(lambda_last + r2 * h_i) _, alpha_s1, std_s1 = atom_sde.log_snr(s1) _, alpha_s2, std_s2 = atom_sde.log_snr(s2) atom_theta_0, bond_theta_0 = theta_fn((x_atom_last, x_bond_last), vec_t_last, atom_mask=atom_mask, bond_mask=bond_mask) tmp_lin = alpha_s1 / alpha_last tmp_nonlin = std_s1 * torch.expm1(r1 * h_i) u_atom_1 = atom_fn(tmp_lin) * x_atom_last - atom_fn(tmp_nonlin) * atom_theta_0 u_bond_1 = bond_fn(tmp_lin) * x_bond_last - bond_fn(tmp_nonlin) * bond_theta_0 atom_theta_s1, bond_theta_s1 = theta_fn((u_atom_1, u_bond_1), s1, atom_mask=atom_mask, bond_mask=bond_mask) D_atom_1 = atom_theta_s1 - atom_theta_0 D_bond_1 = bond_theta_s1 - bond_theta_0 tmp_lin = alpha_s2 / alpha_last tmp_nonlin1 = std_s2 * torch.expm1(r2 * h_i) tmp_nonlin2 = (std_s2 * r2 / r1) * (torch.expm1(r2 * h_i) / (r2 * h_i) - 1) u_atom_2 = atom_fn(tmp_lin) * x_atom_last - atom_fn(tmp_nonlin1) * atom_theta_0 - atom_fn(tmp_nonlin2) * D_atom_1 u_bond_2 = bond_fn(tmp_lin) * x_bond_last - bond_fn(tmp_nonlin1) * bond_theta_0 - bond_fn(tmp_nonlin2) * D_bond_1 atom_theta_s2, bond_theta_s2 = theta_fn((u_atom_2, u_bond_2), s2, atom_mask=atom_mask, bond_mask=bond_mask) D_atom_2 = atom_theta_s2 - atom_theta_0 D_bond_2 = bond_theta_s2 - bond_theta_0 tmp_lin = alpha_i / alpha_last tmp_nonlin1 = std_i * torch.expm1(h_i) tmp_nonlin2 = (std_i / r2) * (torch.expm1(h_i) / h_i - 1) x_atom_i = atom_fn(tmp_lin) * x_atom_last - atom_fn(tmp_nonlin1) * atom_theta_0 - atom_fn(tmp_nonlin2) * D_atom_2 x_bond_i = bond_fn(tmp_lin) * x_bond_last - bond_fn(tmp_nonlin1) * bond_theta_0 - bond_fn(tmp_nonlin2) * D_bond_2 return x_atom_i, x_bond_i def dpm_solver_3(sde, theta_fn, x_last, t_last, t_i, mask, r1=1./3., r2=2./3.): vec_t_last = torch.ones(x_last.shape[0], device=x_last.device) * t_last vec_t_i = torch.ones(x_last.shape[0], device=x_last.device) * t_i expand_fn = functools.partial(expand_dim, n_dim=len(x_last.shape)) lambda_i, alpha_i, std_i = sde.log_snr(vec_t_i) lambda_last, alpha_last, _ = sde.log_snr(vec_t_last) h_i = lambda_i - lambda_last s1 = sde.lambda2t(lambda_last + r1 * h_i) s2 = sde.lambda2t(lambda_last + r2 * h_i) _, alpha_s1, std_s1 = sde.log_snr(s1) _, alpha_s2, std_s2 = sde.log_snr(s2) theta_0 = theta_fn(x_last, vec_t_last, mask=mask) tmp_lin = alpha_s1 / alpha_last tmp_nonlin = std_s1 * torch.expm1(r1 * h_i) u_1 = expand_fn(tmp_lin) * x_last - expand_fn(tmp_nonlin) * theta_0 theta_s1 = theta_fn(u_1, s1, mask=mask) D_1 = theta_s1 - theta_0 tmp_lin = alpha_s2 / alpha_last tmp_nonlin1 = std_s2 * torch.expm1(r2 * h_i) tmp_nonlin2 = (std_s2 * r2 / r1) * (torch.expm1(r2 * h_i) / (r2 * h_i) - 1) u_2 = expand_fn(tmp_lin) * x_last - expand_fn(tmp_nonlin1) * theta_0 - expand_fn(tmp_nonlin2) * D_1 theta_s2 = theta_fn(u_2, s2, mask=mask) D_2 = theta_s2 - theta_0 tmp_lin = alpha_i / alpha_last tmp_nonlin1 = std_i * torch.expm1(h_i) tmp_nonlin2 = (std_i / r2) * (torch.expm1(h_i) / h_i - 1) x_i = expand_fn(tmp_lin) * x_last - expand_fn(tmp_nonlin1) * theta_0 - expand_fn(tmp_nonlin2) * D_2 return x_i def get_mol_sampler_dpm1(atom_sde, bond_sde, atom_shape, bond_shape, inverse_scaler, time_step, eps=1e-3, denoise=False, device='cuda'): # arrange time schedule start_lambda = atom_sde.log_snr_np(atom_sde.T) stop_lambda = atom_sde.log_snr_np(eps) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=int(time_step + 1)) time_steps = [atom_sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] # time_steps = np.linspace(start=atom_sde.T, stop=eps, num=int(time_step + 1)) def sampler(model, n_nodes_pmf, z=None): with torch.no_grad(): # set up dpm theta func theta_fn = get_multi_theta_fn(atom_sde, bond_sde, model, train=False, continuous=True) # initial sample assert z is None # If not represent, sample the latent code from the prior distribution of the SDE. x_atom = atom_sde.prior_sampling(atom_shape).to(device) x_bond = bond_sde.prior_sampling(bond_shape).to(device) # Sample the number of nodes, if z is None n_nodes, atom_mask, bond_mask = sample_nodes(n_nodes_pmf, atom_shape, device) x_atom = x_atom * atom_mask.unsqueeze(-1) x_bond = x_bond * bond_mask # run solver func according to time schedule t_last = time_steps[0] for t_i in time_steps[1:]: x_atom, x_bond = dpm_mol_solver_1(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) t_last = t_i if denoise: pass x_atom = inverse_scaler(x_atom, atom=True) * atom_mask.unsqueeze(-1) x_bond = inverse_scaler(x_bond, atom=False) * bond_mask return x_atom, x_bond, len(time_steps) - 1, n_nodes return sampler def get_mol_sampler_dpm2(atom_sde, bond_sde, atom_shape, bond_shape, inverse_scaler, time_step, eps=1e-3, denoise=False, device='cuda'): # arrange time schedule num_step = int(time_step // 2) start_lambda = atom_sde.log_snr_np(atom_sde.T) stop_lambda = atom_sde.log_snr_np(eps) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step+1) time_steps = [atom_sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] # time_steps = np.linspace(start=atom_sde.T, stop=eps, num=num_step + 1) def sampler(model, n_nodes_pmf, z=None): with torch.no_grad(): # set up dpm theta func theta_fn = get_multi_theta_fn(atom_sde, bond_sde, model, train=False, continuous=True) # initial sample assert z is None # If not represent, sample the latent code from the prior distribution of the SDE. x_atom = atom_sde.prior_sampling(atom_shape).to(device) x_bond = bond_sde.prior_sampling(bond_shape).to(device) # Sample the number of nodes, if z is None n_nodes, atom_mask, bond_mask = sample_nodes(n_nodes_pmf, atom_shape, device) x_atom = x_atom * atom_mask.unsqueeze(-1) x_bond = x_bond * bond_mask # run solver func according to time schedule t_last = time_steps[0] for t_i in time_steps[1:]: x_atom, x_bond = dpm_mol_solver_2(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) t_last = t_i if denoise: pass x_atom = inverse_scaler(x_atom, atom=True) * atom_mask.unsqueeze(-1) x_bond = inverse_scaler(x_bond, atom=False) * bond_mask return x_atom, x_bond, num_step * 2, n_nodes return sampler def get_mol_sampler_dpm3(atom_sde, bond_sde, atom_shape, bond_shape, inverse_scaler, time_step, eps=1e-3, denoise=False, device='cuda'): # arrange time schedule num_step = int(time_step // 3) def sampler(model, n_nodes_pmf=None, time_point=None, z=None, atom_mask=None, bond_mask=None, theta_fn=None): if time_point is None: start_lambda = atom_sde.log_snr_np(atom_sde.T) stop_lambda = atom_sde.log_snr_np(eps) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step + 1) time_steps = [atom_sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] else: start_time, stop_time = time_point start_lambda = atom_sde.log_snr_np(start_time) stop_lambda = atom_sde.log_snr_np(stop_time) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step + 1) time_steps = [atom_sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] with torch.no_grad(): # set up dpm theta func if theta_fn is None: theta_fn = get_multi_theta_fn(atom_sde, bond_sde, model, train=False, continuous=True) else: theta_fn = theta_fn # initial sample if z is None: # If not represent, sample the latent code from the prior distribution of the SDE. x_atom = atom_sde.prior_sampling(atom_shape).to(device) x_bond = bond_sde.prior_sampling(bond_shape).to(device) # Sample the number of nodes, if z is None n_nodes, atom_mask, bond_mask = sample_nodes(n_nodes_pmf, atom_shape, device) x_atom = x_atom * atom_mask.unsqueeze(-1) x_bond = x_bond * bond_mask else: # just use the concurrent prior z and node_mask, bond_mask x_atom, x_bond = z n_nodes = atom_mask.sum(-1).long() # run solver func according to time schedule t_last = time_steps[0] for t_i in time_steps[1:]: x_atom, x_bond = dpm_mol_solver_3(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) t_last = t_i if denoise: pass x_atom = inverse_scaler(x_atom, atom=True) * atom_mask.unsqueeze(-1) x_bond = inverse_scaler(x_bond, atom=False) * bond_mask return x_atom, x_bond, num_step * 3, n_nodes return sampler def get_mol_encoder_dpm3(atom_sde, bond_sde, time_step, eps=1e-3, device='cuda'): # arrange time schedule num_step = int(time_step // 3) def sampler(model, batch, time_point=None): if time_point is None: start_lambda = atom_sde.log_snr_np(atom_sde.T) stop_lambda = atom_sde.log_snr_np(eps) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step + 1) time_steps = [atom_sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] time_steps.reverse() else: start_time, stop_time = time_point start_lambda = atom_sde.log_snr_np(start_time) stop_lambda = atom_sde.log_snr_np(stop_time) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step + 1) time_steps = [atom_sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] with torch.no_grad(): # set up dpm theta func theta_fn = get_multi_theta_fn(atom_sde, bond_sde, model, train=False, continuous=True) # run forward deterministic diffusion process x_atom, atom_mask, x_bond, bond_mask = batch # run solver func according to time schedule t_last = time_steps[0] for t_i in time_steps[1:]: x_atom, x_bond = dpm_mol_solver_3(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) # pdb.set_trace() t_last = t_i return x_atom, x_bond, num_step * 3 return sampler def get_mol_sampler_dpm_mix(atom_sde, bond_sde, atom_shape, bond_shape, inverse_scaler, time_step, eps=1e-3, denoise=False, device='cuda'): # arrange time schedule num_step = int(time_step // 3) start_lambda = atom_sde.log_snr_np(atom_sde.T) stop_lambda = atom_sde.log_snr_np(eps) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step+1) time_steps = [atom_sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] R = int(time_step) % 3 # time_steps = np.linspace(start=atom_sde.T, stop=eps, num=num_step + 1) def sampler(model, n_nodes_pmf, z=None): with torch.no_grad(): # set up dpm theta func theta_fn = get_multi_theta_fn(atom_sde, bond_sde, model, train=False, continuous=True) # initial sample assert z is None # If not represent, sample the latent code from the prior distribution of the SDE. x_atom = atom_sde.prior_sampling(atom_shape).to(device) x_bond = bond_sde.prior_sampling(bond_shape).to(device) # Sample the number of nodes, if z is None n_nodes, atom_mask, bond_mask = sample_nodes(n_nodes_pmf, atom_shape, device) x_atom = x_atom * atom_mask.unsqueeze(-1) x_bond = x_bond * bond_mask # run solver func according to time schedule t_last = time_steps[0] if R == 0: for t_i in time_steps[1:-2]: x_atom, x_bond = dpm_mol_solver_3(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) t_last = t_i t_i = time_steps[-2] x_atom, x_bond = dpm_mol_solver_2(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) t_last = t_i t_i = time_steps[-1] x_atom, x_bond = dpm_mol_solver_1(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) else: for t_i in time_steps[1:-1]: x_atom, x_bond = dpm_mol_solver_3(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) t_last = t_i t_i = time_steps[-1] if R == 1: x_atom, x_bond = dpm_mol_solver_1(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) elif R == 2: x_atom, x_bond = dpm_mol_solver_2(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) else: raise ValueError('Step Error in mix DPM-solver.') if denoise: pass x_atom = inverse_scaler(x_atom, atom=True) * atom_mask.unsqueeze(-1) x_bond = inverse_scaler(x_bond, atom=False) * bond_mask return x_atom, x_bond, time_step, n_nodes return sampler def get_sampler_dpm3(sde, shape, inverse_scaler, time_step, eps=1e-3, denoise=False, device='cuda'): # arrange time schedule num_step = int(time_step // 3) def sampler(model, n_nodes_pmf=None, time_point=None, z=None, mask=None, theta_fn=None): if time_point is None: start_lambda = sde.log_snr_np(sde.T) stop_lambda = sde.log_snr_np(eps) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step + 1) time_steps = [sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] else: start_time, stop_time = time_point start_lambda = sde.log_snr_np(start_time) stop_lambda = sde.log_snr_np(stop_time) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step + 1) time_steps = [sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] with torch.no_grad(): # set up dpm theta func if theta_fn is None: theta_fn = get_theta_fn(sde, model, train=False, continuous=True) else: theta_fn = theta_fn # initial sample if z is None: # If not represent, sample the latent code from the prior distribution of the SDE. x = sde.prior_sampling(shape).to(device) # Sample the number of nodes, if z is None n_nodes = torch.multinomial(n_nodes_pmf, shape[0], replacement=True) mask = torch.zeros((shape[0], shape[-1]), device=device) for i in range(shape[0]): mask[i][:n_nodes[i]] = 1. mask = (mask[:, None, :] * mask[:, :, None]).unsqueeze(1) else: x = z batch_size, _, max_num_nodes, _ = mask.shape node_mask = mask[:, 0, 0, :].clone() # without checking correctness node_mask[:, 0] = 1 n_nodes = node_mask.sum(-1).long() # run solver func according to time schedule t_last = time_steps[0] for t_i in time_steps[1:]: x = dpm_solver_3(sde, theta_fn, x, t_last, t_i, mask) t_last = t_i if denoise: pass x = inverse_scaler(x) * mask return x, num_step * 3, n_nodes return sampler def get_mol_dpm3_twostage(atom_sde, bond_sde, atom_shape, bond_shape, inverse_scaler, time_step, eps=1e-3, denoise=False, device='cuda'): # arrange time schedule num_step = int(time_step // 3) def sampler(model, n_nodes_pmf, time_point, guided_theta_fn): start_lambda = atom_sde.log_snr_np(atom_sde.T) stop_lambda = atom_sde.log_snr_np(eps) lambda_sched = np.linspace(start=start_lambda, stop=stop_lambda, num=num_step + 1) time_steps = [atom_sde.lambda2t_np(lambda_ori) for lambda_ori in lambda_sched] with torch.no_grad(): # set up dpm theta func theta_fn = get_multi_theta_fn(atom_sde, bond_sde, model, train=False, continuous=True) # initial sample x_atom = atom_sde.prior_sampling(atom_shape).to(device) x_bond = bond_sde.prior_sampling(bond_shape).to(device) # Sample the number of nodes, if z is None n_nodes, atom_mask, bond_mask = sample_nodes(n_nodes_pmf, atom_shape, device) x_atom = x_atom * atom_mask.unsqueeze(-1) x_bond = x_bond * bond_mask # run solver func according to time schedule t_last = time_steps[0] for t_i in time_steps[1:]: if t_last > time_point: x_atom, x_bond = dpm_mol_solver_3(atom_sde, bond_sde, theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) else: x_atom, x_bond = dpm_mol_solver_3(atom_sde, bond_sde, guided_theta_fn, x_atom, x_bond, t_last, t_i, atom_mask, bond_mask) t_last = t_i if denoise: pass x_atom = inverse_scaler(x_atom, atom=True) * atom_mask.unsqueeze(-1) x_bond = inverse_scaler(x_bond, atom=False) * bond_mask return x_atom, x_bond, num_step * 3, n_nodes return sampler
23,918
43.376623
119
py
CDGS
CDGS-main/run_lib.py
import os import torch import numpy as np import random import logging import time from absl import flags from torch.utils import tensorboard from torch_geometric.loader import DataLoader, DenseDataLoader import pickle from rdkit import RDLogger, Chem from models import cdgs import losses import sampling from models import utils as mutils from models.ema import ExponentialMovingAverage import datasets from evaluation import get_FCDMetric, get_nspdk_eval import sde_lib import visualize from utils import * from moses.metrics.metrics import get_all_metrics FLAGS = flags.FLAGS def set_random_seed(config): seed = config.seed os.environ['PYTHONHASHSEED'] = str(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def mol_sde_train(config, workdir): """Runs the training pipeline of molecule generation. Args: config: Configuration to use. workdir: Working directory for checkpoints and TF summaries. If this contains checkpoint training will be resumed from the latest checkpoint. """ ### Ignore info output by RDKit RDLogger.DisableLog('rdApp.error') RDLogger.DisableLog('rdApp.warning') # Create directories for experimental logs sample_dir = os.path.join(workdir, "samples") if not os.path.exists(sample_dir): os.makedirs(sample_dir) tb_dir = os.path.join(workdir, "tensorboard") if not os.path.exists(tb_dir): os.makedirs(tb_dir) writer = tensorboard.SummaryWriter(tb_dir) # Initialize model. score_model = mutils.create_model(config) ema = ExponentialMovingAverage(score_model.parameters(), decay=config.model.ema_rate) optimizer = losses.get_optimizer(config, score_model.parameters()) state = dict(optimizer=optimizer, model=score_model, ema=ema, step=0) # Create checkpoints directly checkpoint_dir = os.path.join(workdir, "checkpoints") # Intermediate checkpoints to resume training checkpoint_meta_dir = os.path.join(workdir, "checkpoints-meta", "checkpoint.pth") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) if not os.path.exists(os.path.dirname(checkpoint_meta_dir)): os.makedirs(os.path.dirname(checkpoint_meta_dir)) # Resume training when intermediate checkpoints are detected state = restore_checkpoint(checkpoint_meta_dir, state, config.device) initial_step = int(state['step']) # Build dataloader and iterators train_ds, eval_ds, test_ds, n_node_pmf = datasets.get_dataset(config) train_loader = DenseDataLoader(train_ds, batch_size=config.training.batch_size, shuffle=True) eval_loader = DenseDataLoader(eval_ds, batch_size=config.training.eval_batch_size, shuffle=False) test_loader = DenseDataLoader(test_ds, batch_size=config.training.eval_batch_size, shuffle=False) n_node_pmf = torch.from_numpy(n_node_pmf).to(config.device) train_iter = iter(train_loader) # create data normalizer and its inverse scaler = datasets.get_data_scaler(config) inverse_scaler = datasets.get_data_inverse_scaler(config) # Setup SDEs if config.training.sde.lower() == 'vpsde': atom_sde = sde_lib.VPSDE(beta_min=config.model.node_beta_min, beta_max=config.model.node_beta_max, N=config.model.num_scales) bond_sde = sde_lib.VPSDE(beta_min=config.model.edge_beta_min, beta_max=config.model.edge_beta_max, N=config.model.num_scales) sampling_eps = 1e-3 else: raise NotImplementedError(f"SDE {config.training.sde} unknown.") # Build one-step training and evaluation functions optimize_fn = losses.optimization_manager(config) continuous = config.training.continuous reduce_mean = config.training.reduce_mean likelihood_weighting = config.training.likelihood_weighting train_step_fn = losses.get_step_fn((atom_sde, bond_sde), train=True, optimize_fn=optimize_fn, reduce_mean=reduce_mean, continuous=continuous, likelihood_weighting=likelihood_weighting) eval_step_fn = losses.get_step_fn((atom_sde, bond_sde), train=False, optimize_fn=optimize_fn, reduce_mean=reduce_mean, continuous=continuous, likelihood_weighting=likelihood_weighting) test_FCDMetric = get_FCDMetric(test_ds.sub_smiles, device=config.device) eval_FCDMetric = get_FCDMetric(eval_ds.sub_smiles, device=config.device) # Build sampling functions if config.training.snapshot_sampling: sampling_atom_shape = (config.training.eval_batch_size, config.data.max_node, config.data.atom_channels) sampling_bond_shape = (config.training.eval_batch_size, config.data.bond_channels, config.data.max_node, config.data.max_node) sampling_fn = sampling.get_mol_sampling_fn(config, atom_sde, bond_sde, sampling_atom_shape, sampling_bond_shape, inverse_scaler, sampling_eps) num_train_steps = config.training.n_iters logging.info("Starting training loop at step %d." % (initial_step,)) for step in range(initial_step, num_train_steps + 1): try: graphs = next(train_iter) except StopIteration: train_iter = train_loader.__iter__() graphs = next(train_iter) batch = dense_mol(graphs, scaler, config.data.dequantization) # Execute one training step loss = train_step_fn(state, batch) if step % config.training.log_freq == 0: logging.info("step: %d, training_loss: %.5e" % (step, loss.item())) writer.add_scalar("training_loss", loss, step) # Save a temporary checkpoint to resume training after pre-emption periodically if step != 0 and step % config.training.snapshot_freq_for_preemption == 0: save_checkpoint(checkpoint_meta_dir, state) # Report the loss on evaluation dataset periodically if step % config.training.eval_freq == 0: for eval_graphs in eval_loader: eval_batch = dense_mol(eval_graphs, scaler) eval_loss = eval_step_fn(state, eval_batch) logging.info("step: %d, eval_loss: %.5e" % (step, eval_loss.item())) writer.add_scalar("eval_loss", eval_loss.item(), step) break for test_graphs in test_loader: test_batch = dense_mol(test_graphs, scaler) test_loss = eval_step_fn(state, test_batch) logging.info("step: %d, test_loss: %.5e" % (step, test_loss.item())) writer.add_scalar("test_loss", test_loss.item(), step) break # Save a checkpoint periodically and generate samples if step != 0 and step % config.training.snapshot_freq == 0 or step == num_train_steps: # Save the checkpoint. save_step = step // config.training.snapshot_freq save_checkpoint(os.path.join(checkpoint_dir, f'checkpoint_{save_step}.pth'), state) # Generate and save samples if config.training.snapshot_sampling: ema.store(score_model.parameters()) ema.copy_to(score_model.parameters()) atom_sample, bond_sample, sample_steps, sample_nodes = sampling_fn(score_model, n_node_pmf) sample_list, valid_wd = tensor2mol(atom_sample, bond_sample, sample_nodes, config.data.atom_list, correct_validity=True, largest_connected_comp=True) ## fcd value smile_list = [Chem.MolToSmiles(mol) for mol in sample_list] fcd_test = test_FCDMetric(smile_list) fcd_eval = eval_FCDMetric(smile_list) ## log info valid_wd_rate = np.sum(valid_wd) / len(valid_wd) logging.info("step: %d, n_mol: %d, validity rate wd check: %.4f, fcd_val: %.4f, fcd_test: %.4f" % (step, len(sample_list), valid_wd_rate, fcd_eval, fcd_test)) ema.restore(score_model.parameters()) this_sample_dir = os.path.join(sample_dir, "iter_{}".format(step)) if not os.path.exists(this_sample_dir): os.makedirs(this_sample_dir) # graph visualization and save figs visualize.visualize_mols(sample_list[:16], this_sample_dir, config) def mol_sde_evaluate(config, workdir, eval_folder="eval"): """Evaluate trained models. Args: config: Configuration to use. workdir: Working directory for checkpoints. eval_folder: The subfolder for storing evaluation results. Default to "eval". """ ### Ignore info output by RDKit RDLogger.DisableLog('rdApp.error') RDLogger.DisableLog('rdApp.warning') # Create directory to eval_folder eval_dir = os.path.join(workdir, eval_folder) if not os.path.exists(eval_dir): os.makedirs(eval_dir) # Build data pipeline train_ds, _, test_ds, n_node_pmf = datasets.get_dataset(config) n_node_pmf = torch.from_numpy(n_node_pmf).to(config.device) # test_FCDMetric = get_FCDMetric(test_ds.sub_smiles, device=config.device) # Creat data normalizer and its inverse scaler = datasets.get_data_scaler(config) inverse_scaler = datasets.get_data_inverse_scaler(config) # Initialize model score_model = mutils.create_model(config) optimizer = losses.get_optimizer(config, score_model.parameters()) ema = ExponentialMovingAverage(score_model.parameters(), decay=config.model.ema_rate) state = dict(optimizer=optimizer, model=score_model, ema=ema, step=0) checkpoint_dir = os.path.join(workdir, "checkpoints") # Setup SDEs if config.training.sde.lower() == 'vpsde': atom_sde = sde_lib.VPSDE(beta_min=config.model.node_beta_min, beta_max=config.model.node_beta_max, N=config.model.num_scales) bond_sde = sde_lib.VPSDE(beta_min=config.model.edge_beta_min, beta_max=config.model.edge_beta_max, N=config.model.num_scales) sampling_eps = 1e-3 elif config.training.sde.lower() == 'subvpsde': atom_sde = sde_lib.subVPSDE(beta_min=config.model.node_beta_min, beta_max=config.model.node_beta_max, N=config.model.num_scales) bond_sde = sde_lib.subVPSDE(beta_min=config.model.edge_beta_min, beta_max=config.model.edge_beta_nax, N=config.model.num_scales) sampling_eps = 1e-3 else: raise NotImplementedError(f"SDE {config.training.sde} unknown.") if config.eval.enable_sampling: sampling_atom_shape = (config.eval.batch_size, config.data.max_node, config.data.atom_channels) sampling_bond_shape = (config.eval.batch_size, config.data.bond_channels, config.data.max_node, config.data.max_node) sampling_fn = sampling.get_mol_sampling_fn(config, atom_sde, bond_sde, sampling_atom_shape, sampling_bond_shape, inverse_scaler, sampling_eps) # Begin evaluation begin_ckpt = config.eval.begin_ckpt logging.info("begin checkpoint: %d" % (begin_ckpt,)) for ckpt in range(begin_ckpt, config.eval.end_ckpt + 1): # Wait if the target checkpoint doesn't exist yet waiting_message_printed = False ckpt_filename = os.path.join(checkpoint_dir, "checkpoint_{}.pth".format(ckpt)) while not os.path.exists(ckpt_filename): if not waiting_message_printed: logging.warning("Waiting for the arrival of checkpoint_%d" % (ckpt,)) waiting_message_printed = True time.sleep(60) # Wait for 2 additional mins in case the file exists but is not ready for reading ckpt_path = os.path.join(checkpoint_dir, f'checkpoint_{ckpt}.pth') try: state = restore_checkpoint(ckpt_path, state, device=config.device) except: time.sleep(60) try: state = restore_checkpoint(ckpt_path, state, device=config.device) except: time.sleep(120) state = restore_checkpoint(ckpt_path, state, device=config.device) ema.copy_to(score_model.parameters()) # Generate samples and compute MMD stats if config.eval.enable_sampling: num_sampling_rounds = int(np.ceil(config.eval.num_samples / config.eval.batch_size)) all_samples = [] all_valid_wd = [] for r in range(num_sampling_rounds): logging.info("sampling -- ckpt: %d, round: %d" % (ckpt, r)) atom_sample, bond_sample, sample_steps, sample_nodes = sampling_fn(score_model, n_node_pmf) logging.info("sample steps: %d" % sample_steps) sample_list, valid_wd = tensor2mol(atom_sample, bond_sample, sample_nodes, config.data.atom_list, correct_validity=True, largest_connected_comp=True) all_samples += sample_list all_valid_wd += valid_wd all_samples = all_samples[:config.eval.num_samples] all_valid_wd = all_valid_wd[:config.eval.num_samples] smile_list = [] for mol in all_samples: if mol is not None: smile_list.append(Chem.MolToSmiles(mol)) # save the graphs sampler_name = config.sampling.method if config.eval.save_graph: # save the smile strings instead of rdkit mol object graph_file = os.path.join(eval_dir, sampler_name + "_ckpt_{}.pkl".format(ckpt)) with open(graph_file, "wb") as f: pickle.dump(smile_list, f) # evaluate logging.info('Number of molecules: %d' % len(all_samples)) ## valid, novelty, unique rate logging.info('sampling -- ckpt: {}, validity w/o correction: {:.6f}'. format(ckpt, np.sum(all_valid_wd) / len(all_valid_wd))) ## moses metric scores = get_all_metrics(gen=smile_list, k=len(smile_list), device=config.device, n_jobs=8, test=test_ds.sub_smiles, train=train_ds.sub_smiles) for metric in ['valid', f'unique@{len(smile_list)}', 'FCD/Test', 'Novelty']: logging.info(f'sampling -- ckpt: {ckpt}, {metric}: {scores[metric]}') ## NSPDK evaluation if config.eval.nspdk: nspdk_eval = get_nspdk_eval(config) test_smiles = test_ds.sub_smiles test_mols = [] for smile in test_smiles: mol = Chem.MolFromSmiles(smile) # Chem.Kekulize(mol) test_mols.append(mol) test_nx_graphs = mols_to_nx(test_mols) gen_nx_graphs = mols_to_nx(all_samples) nspdk_res = nspdk_eval(test_nx_graphs, gen_nx_graphs) logging.info('sampling -- ckpt: {}, NSPDK: {}'.format(ckpt, nspdk_res)) run_train_dict = { 'mol_sde': mol_sde_train } run_eval_dict = { 'mol_sde': mol_sde_evaluate, } def train(config, workdir): run_train_dict[config.model_type](config, workdir) def evaluate(config, workdir, eval_folder='eval'): run_eval_dict[config.model_type](config, workdir, eval_folder)
15,886
43.00831
120
py
CDGS
CDGS-main/utils.py
import torch import os import logging import re import copy import numpy as np import torch.nn.functional as F import networkx as nx from rdkit import Chem, DataStructs from rdkit.Chem import AllChem, rdMolDescriptors from rdkit.Chem.Descriptors import MolLogP, qed from sascorer import calculateScore ATOM_VALENCY = {6: 4, 7: 3, 8: 2, 9: 1, 15: 3, 16: 2, 17: 1, 35: 1, 53: 1} bond_decoder_m = {1: Chem.rdchem.BondType.SINGLE, 2: Chem.rdchem.BondType.DOUBLE, 3: Chem.rdchem.BondType.TRIPLE} def restore_checkpoint(ckpt_dir, state, device): if not os.path.exists(ckpt_dir): if not os.path.exists(os.path.dirname(ckpt_dir)): os.makedirs(os.path.dirname(ckpt_dir)) logging.warning(f"No checkpoint found at {ckpt_dir}. " f"Returned the same state as input") return state else: loaded_state = torch.load(ckpt_dir, map_location=device) state['optimizer'].load_state_dict(loaded_state['optimizer']) state['model'].load_state_dict(loaded_state['model'], strict=False) state['ema'].load_state_dict(loaded_state['ema']) state['step'] = loaded_state['step'] return state def save_checkpoint(ckpt_dir, state): saved_state = { 'optimizer': state['optimizer'].state_dict(), 'model': state['model'].state_dict(), 'ema': state['ema'].state_dict(), 'step': state['step'] } torch.save(saved_state, ckpt_dir) @torch.no_grad() def dense_mol(graph_data, scaler=None, dequantization=False): """Extract features and masks from PyG Dense DataBatch. Args: graph_data: DataBatch object. y: [B, 1] graph property values. num_atom: [B, 1] number of atoms in graphs. smile: [B] smile sequences. x: [B, max_node, channel1] atom type features. adj: [B, channel2, max_node, max_node] bond type features. atom_mask: [B, max_node] Returns: atom_feat: [B, max_node, channel1] atom_mask: [B, max_node] bond_feat: [B, channel2, max_node, max_node] bond_mask: [B, 1, max_node, max_node] """ atom_feat = graph_data.x bond_feat = graph_data.adj atom_mask = graph_data.atom_mask if len(atom_mask.shape) == 1: atom_mask = atom_mask.unsqueeze(0) bond_mask = (atom_mask[:, None, :] * atom_mask[:, :, None]).unsqueeze(1) bond_mask = torch.tril(bond_mask, -1) bond_mask = bond_mask + bond_mask.transpose(-1, -2) if dequantization: atom_noise = torch.rand_like(atom_feat) atom_feat = (atom_feat + atom_noise) / 2. * atom_mask[:, :, None] bond_noise = torch.rand_like(bond_feat) bond_noise = torch.tril(bond_noise, -1) bond_noise = bond_noise + bond_noise.transpose(1, 2) bond_feat = (bond_feat + bond_noise) / 2. * bond_mask atom_feat = scaler(atom_feat, atom=True) bond_feat = scaler(bond_feat, atom=False) return atom_feat * atom_mask.unsqueeze(-1), atom_mask, bond_feat * bond_mask, bond_mask def adj2graph(adj, sample_nodes): """Covert the PyTorch tensor adjacency matrices to numpy array. Args: adj: [Batch_size, channel, Max_node, Max_node], assume channel=1 sample_nodes: [Batch_size] """ adj_list = [] # discretization adj[adj >= 0.5] = 1. adj[adj < 0.5] = 0. for i in range(adj.shape[0]): adj_tmp = adj[i, 0] # symmetric adj_tmp = torch.tril(adj_tmp, -1) adj_tmp = adj_tmp + adj_tmp.transpose(0, 1) # truncate adj_tmp = adj_tmp.cpu().numpy()[:sample_nodes[i], :sample_nodes[i]] adj_list.append(adj_tmp) return adj_list def quantize_mol(adjs): # Quantize generated molecules [B, 1, N, N] adjs = adjs.squeeze(1) if type(adjs).__name__ == 'Tensor': adjs = adjs.detach().cpu() else: adjs = torch.tensor(adjs) adjs = adjs * 3 adjs[adjs >= 2.5] = 3 adjs[torch.bitwise_and(adjs >= 1.5, adjs < 2.5)] = 2 adjs[torch.bitwise_and(adjs >= 0.5, adjs < 1.5)] = 1 adjs[adjs < 0.5] = 0 return np.array(adjs.to(torch.int64)) def quantize_mol_2(adjs): # Quantize generated molecules [B, 2, N, N] # The 2nd channel: 0 -> edge type; 1 -> edge existence if type(adjs).__name__ == 'Tensor': adjs = adjs.detach().cpu() else: adjs = torch.tensor(adjs) adj_0 = adjs[:, 0, :, :] adj_1 = adjs[:, 1, :, :] adj_0 = adj_0 * 3 adj_0[adj_0 >= 2.5] = 3 adj_0[torch.bitwise_and(adj_0 >= 1.5, adj_0 < 2.5)] = 2 adj_0[torch.bitwise_and(adj_0 >= 0.5, adj_0 < 1.5)] = 1 adj_0[adj_0 < 0.5] = 0 adj_1[adj_1 < 0.5] = 0 adj_1[adj_1 >= 0.5] = 1 adjs = adj_0 * adj_1 return np.array(adjs.to(torch.int64)) def construct_mol(x, A, num_node, atomic_num_list): mol = Chem.RWMol() atoms = np.argmax(x, axis=1) atoms = atoms[:num_node] for atom in atoms: mol.AddAtom(Chem.Atom(int(atomic_num_list[atom]))) if len(A.shape) == 2: adj = A[:num_node, :num_node] elif A.shape[0] == 4: # A (edge_type, max_num_node, max_num_node) adj = np.argmax(A, axis=0) adj = np.array(adj) adj = adj[:num_node, :num_node] # Note. 3 means no existing edge (when constructing adj matrices) adj[adj == 3] = -1 adj += 1 adj = adj - np.eye(num_node) else: raise ValueError('Wrong Adj shape.') for start, end in zip(*np.nonzero(adj)): if start > end: mol.AddBond(int(start), int(end), bond_decoder_m[adj[start, end]]) # remove formal charge for fair comparison with GraphAF, GraphDF, GraphCNF # add formal charge to atom: e.g. [O+], [N+], [S+], not support [O-], [N-], [NH+] etc. flag, atomid_valence = check_valency(mol) if flag: continue else: assert len(atomid_valence) == 2 idx = atomid_valence[0] v = atomid_valence[1] an = mol.GetAtomWithIdx(idx).GetAtomicNum() if an in (7, 8, 16) and (v - ATOM_VALENCY[an]) == 1: mol.GetAtomWithIdx(idx).SetFormalCharge(1) return mol def check_valency(mol): """ Checks that no atoms in the mol have exceeded their possible valency Return: True if no valency issues, False otherwise """ try: Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_PROPERTIES) return True, None except ValueError as e: e = str(e) p = e.find('#') e_sub = e[p:] atomid_valence = list(map(int, re.findall(r'\d+', e_sub))) return False, atomid_valence def correct_mol(mol): no_correct = False flag, _ = check_valency(mol) if flag: no_correct = True while True: flag, atomid_valence = check_valency(mol) if flag: break else: assert len(atomid_valence) == 2 idx = atomid_valence[0] queue = [] for b in mol.GetAtomWithIdx(idx).GetBonds(): queue.append( (b.GetIdx(), int(b.GetBondType()), b.GetBeginAtomIdx(), b.GetEndAtomIdx()) ) queue.sort(key=lambda tup: tup[1], reverse=True) if len(queue) > 0: start = queue[0][2] end = queue[0][3] t = queue[0][1] - 1 mol.RemoveBond(start, end) if t >= 1: mol.AddBond(start, end, bond_decoder_m[t]) return mol, no_correct def valid_mol_can_with_seg(x, largest_connected_comp=True): if x is None: return None sm = Chem.MolToSmiles(x, isomericSmiles=True) mol = Chem.MolFromSmiles(sm) if largest_connected_comp and '.' in sm: vsm = [(s, len(s)) for s in sm.split('.')] # 'C.CC.CCc1ccc(N)cc1CCC=O'.split('.') vsm.sort(key=lambda tup: tup[1], reverse=True) mol = Chem.MolFromSmiles(vsm[0][0]) return mol def check_chemical_validity(mol): """ Check the chemical validity of the mol object. Existing mol object is not modified. Args: mol: Rdkit mol object Return: True if chemically valid, False otherwise """ s = Chem.MolToSmiles(mol, isomericSmiles=True) m = Chem.MolFromSmiles(s) # implicitly performs sanitization if m: return True else: return False def tensor2mol(x_atom, x_bond, num_atoms, atomic_num_list, correct_validity=True, largest_connected_comp=True): """Construct molecules from the atom and bond tensors. Args: x_atom: The node tensor [`number of samples`, `maximum number of atoms`, `number of possible atom types`]. x_bond: The adjacency tensor [`number of samples`, `number of possible bond type`, `maximum number of atoms`, `maximum number of atoms`] num_atoms: The number of nodes for every sample [`number of samples`] atomic_num_list: A list to specify what each atom channel corresponds to. correct_validity: Whether to use the validity correction introduced by `MoFlow`. largest_connected_comp: Whether to use the largest connected component as the final molecule in the validity correction. Return: The list of Rdkit mol object. The check_chemical_validity rate without check. """ if x_bond.shape[1] == 1: x_bond = quantize_mol(x_bond) elif x_bond.shape[1] == 2: x_bond = quantize_mol_2(x_bond) else: x_bond = x_bond.cpu().detach().numpy() x_atom = x_atom.cpu().detach().numpy() num_nodes = num_atoms.cpu().detach().numpy() gen_mols = [] valid_cum = [] for atom_elem, bond_elem, num_node in zip(x_atom, x_bond, num_nodes): mol = construct_mol(atom_elem, bond_elem, num_node, atomic_num_list) if correct_validity: # correct the invalid molecule cmol, no_correct = correct_mol(mol) if no_correct: valid_cum.append(1) else: valid_cum.append(0) vcmol = valid_mol_can_with_seg(cmol, largest_connected_comp=largest_connected_comp) gen_mols.append(vcmol) else: gen_mols.append(mol) return gen_mols, valid_cum def penalized_logp(mol): """ Calculate the reward that consists of log p penalized by SA and # long cycles, as described in (Kusner et al. 2017). Scores are normalized based on the statistics of 250k_rndm_zinc_drugs_clean.smi dataset. Args: mol: Rdkit mol object Returns: :class:`float` """ # normalization constants, statistics from 250k_rndm_zinc_drugs_clean.smi logP_mean = 2.4570953396190123 logP_std = 1.434324401111988 SA_mean = -3.0525811293166134 SA_std = 0.8335207024513095 cycle_mean = -0.0485696876403053 cycle_std = 0.2860212110245455 log_p = MolLogP(mol) SA = -calculateScore(mol) # cycle score cycle_list = nx.cycle_basis(nx.Graph( Chem.rdmolops.GetAdjacencyMatrix(mol))) if len(cycle_list) == 0: cycle_length = 0 else: cycle_length = max([len(j) for j in cycle_list]) if cycle_length <= 6: cycle_length = 0 else: cycle_length = cycle_length - 6 cycle_score = -cycle_length normalized_log_p = (log_p - logP_mean) / logP_std normalized_SA = (SA - SA_mean) / SA_std normalized_cycle = (cycle_score - cycle_mean) / cycle_std return normalized_log_p + normalized_SA + normalized_cycle def get_mol_qed(mol): return qed(mol) def calculate_min_plogp(mol): """ Calculate the reward that consists of log p penalized by SA and # long cycles, as described in (Kusner et al. 2017). Scores are normalized based on the statistics of 250k_rndm_zinc_drugs_clean.smi dataset. Args: mol: Rdkit mol object :rtype: :class:`float` """ p1 = penalized_logp(mol) s1 = Chem.MolToSmiles(mol, isomericSmiles=True) s2 = Chem.MolToSmiles(mol, isomericSmiles=False) mol1 = Chem.MolFromSmiles(s1) mol2 = Chem.MolFromSmiles(s2) p2 = penalized_logp(mol1) p3 = penalized_logp(mol2) final_p = min(p1, p2) final_p = min(final_p, p3) return final_p def reward_target_molecule_similarity(mol, target, radius=2, nBits=2048, useChirality=True): """ Calculate the similarity, based on tanimoto similarity between the ECFP fingerprints of the x molecule and target molecule. Args: mol: Rdkit mol object target: Rdkit mol object Returns: :class:`float`, [0.0, 1.0] """ x = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=radius, nBits=nBits, useChirality=useChirality) target = rdMolDescriptors.GetMorganFingerprintAsBitVect(target, radius=radius, nBits=nBits, useChirality=useChirality) return DataStructs.TanimotoSimilarity(x, target) def convert_radical_electrons_to_hydrogens(mol): """ Convert radical electrons in a molecule into bonds to hydrogens. Only use this if molecule is valid. Return a new mol object. Args: mol: Rdkit mol object :rtype: Rdkit mol object """ m = copy.deepcopy(mol) if Chem.Descriptors.NumRadicalElectrons(m) == 0: # not a radical return m else: # a radical print('converting radical electrons to H') for a in m.GetAtoms(): num_radical_e = a.GetNumRadicalElectrons() if num_radical_e > 0: a.SetNumRadicalElectrons(0) a.SetNumExplicitHs(num_radical_e) return m def get_final_smiles(mol): """ Returns a SMILES of the final molecule. Converts any radical electrons into hydrogens. Works only if molecule is valid :return: SMILES """ m = convert_radical_electrons_to_hydrogens(mol) return Chem.MolToSmiles(m, isomericSmiles=True) def mols_to_nx(mols): nx_graphs = [] for mol in mols: G = nx.Graph() for atom in mol.GetAtoms(): G.add_node(atom.GetIdx(), label=atom.GetSymbol()) # atomic_num=atom.GetAtomicNum(), # formal_charge=atom.GetFormalCharge(), # chiral_tag=atom.GetChiralTag(), # hybridization=atom.GetHybridization(), # num_explicit_hs=atom.GetNumExplicitHs(), # is_aromatic=atom.GetIsAromatic()) for bond in mol.GetBonds(): G.add_edge(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx(), label=int(bond.GetBondTypeAsDouble())) # bond_type=bond.GetBondType()) nx_graphs.append(G) return nx_graphs
14,882
30.801282
117
py
CDGS
CDGS-main/sampling.py
"""Various sampling methods.""" import functools import torch import numpy as np import abc from models.utils import get_multi_score_fn from scipy import integrate # from torchdiffeq import odeint import sde_lib from models import utils as mutils from dpm_solvers import get_mol_sampler_dpm1, get_mol_sampler_dpm2, get_mol_sampler_dpm3, \ get_mol_sampler_dpm_mix, get_sampler_dpm3 import time _CORRECTORS = {} _PREDICTORS = {} def register_predictor(cls=None, *, name=None): """A decorator for registering predictor classes.""" def _register(cls): if name is None: local_name = cls.__name__ else: local_name = name if local_name in _PREDICTORS: raise ValueError(f'Already registered predictor with name: {local_name}') _PREDICTORS[local_name] = cls return cls if cls is None: return _register else: return _register(cls) def register_corrector(cls=None, *, name=None): """A decorator for registering corrector classes.""" def _register(cls): if name is None: local_name = cls.__name__ else: local_name = name if local_name in _CORRECTORS: raise ValueError(f'Already registered corrector with name: {local_name}') _CORRECTORS[local_name] = cls return cls if cls is None: return _register else: return _register(cls) def get_predictor(name): return _PREDICTORS[name] def get_corrector(name): return _CORRECTORS[name] def get_mol_sampling_fn(config, atom_sde, bond_sde, atom_shape, bond_shape, inverse_scaler, eps): """Create a sampling function for molecule. Args: config: A `ml_collections.ConfigDict` object that contains all configuration information. atom_sde, bond_sde: A `sde_lib.SDE` object that represents the forward SDE. atom_shape, bond_shape: A sequence of integers representing the expected shape of a single sample. inverse_scaler: The inverse data normalizer function. eps: A `float` number. The reverse-time SDE is only integrated to `eps` for numerical stability. Returns: A function that takes random states and a replicated training state and outputs samples with the trailing dimensions matching `shape`. """ sampler_name = config.sampling.method if sampler_name.lower() == 'dpm1': sampling_fn = get_mol_sampler_dpm1(atom_sde=atom_sde, bond_sde=bond_sde, atom_shape=atom_shape, bond_shape=bond_shape, inverse_scaler=inverse_scaler, time_step=config.sampling.ode_step, eps=eps, denoise=config.sampling.noise_removal, device=config.device) elif sampler_name.lower() == 'dpm2': sampling_fn = get_mol_sampler_dpm2(atom_sde=atom_sde, bond_sde=bond_sde, atom_shape=atom_shape, bond_shape=bond_shape, inverse_scaler=inverse_scaler, time_step=config.sampling.ode_step, eps=eps, denoise=config.sampling.noise_removal, device=config.device) elif sampler_name.lower() == 'dpm3': sampling_fn = get_mol_sampler_dpm3(atom_sde=atom_sde, bond_sde=bond_sde, atom_shape=atom_shape, bond_shape=bond_shape, inverse_scaler=inverse_scaler, time_step=config.sampling.ode_step, eps=eps, denoise=config.sampling.noise_removal, device=config.device) elif sampler_name.lower() == 'dpm_mix': sampling_fn = get_mol_sampler_dpm_mix(atom_sde=atom_sde, bond_sde=bond_sde, atom_shape=atom_shape, bond_shape=bond_shape, inverse_scaler=inverse_scaler, time_step=config.sampling.ode_step, eps=eps, denoise=config.sampling.noise_removal, device=config.device) # Predictor-Corrector sampling. Predictor-only and Corrector-only samplers are special cases. elif sampler_name.lower() == 'pc': predictor = get_predictor(config.sampling.predictor.lower()) corrector = get_corrector(config.sampling.corrector.lower()) sampling_fn = get_mol_pc_sampler(atom_sde=atom_sde, bond_sde=bond_sde, atom_shape=atom_shape, bond_shape=bond_shape, predictor=predictor, corrector=corrector, inverse_scaler=inverse_scaler, snr=(config.sampling.atom_snr, config.sampling.bond_snr), n_steps=config.sampling.n_steps_each, probability_flow=config.sampling.probability_flow, continuous=config.training.continuous, denoise=config.sampling.noise_removal, eps=eps, device=config.device) else: raise ValueError(f"Sampler name {sampler_name} unknown.") return sampling_fn class Predictor(abc.ABC): """The abstract class for a predictor algorithm.""" def __init__(self, sde, score_fn, probability_flow=False): super().__init__() self.sde = sde # Compute the reverse SDE/ODE if isinstance(sde, tuple): self.rsde = (sde[0].reverse(score_fn, probability_flow), sde[1].reverse(score_fn, probability_flow)) else: self.rsde = sde.reverse(score_fn, probability_flow) self.score_fn = score_fn @abc.abstractmethod def update_fn(self, x, t, *args, **kwargs): """One update of the predictor. Args: x: A PyTorch tensor representing the current state. t: A PyTorch tensor representing the current time step. Returns: x: A PyTorch tensor of the next state. x_mean: A PyTorch tensor. The next state without random noise. Useful for denoising. """ pass @abc.abstractmethod def update_mol_fn(self, x, t, *args, **kwargs): """One update of the predictor for molecule graphs. Args: x: A tuple of PyTorch tensor (x_atom, x_bond) representing the current state. t: A PyTorch tensor representing the current time step. Returns: x: A tuple of PyTorch tensor (x_atom, x_bond) of the next state. x_mean: A tuple of PyTorch tensor. The next state without random noise. Useful for denoising. """ pass class Corrector(abc.ABC): """The abstract class for a corrector algorithm.""" def __init__(self, sde, score_fn, snr, n_steps): super().__init__() self.sde = sde self.score_fn = score_fn self.snr = snr self.n_steps = n_steps @abc.abstractmethod def update_fn(self, x, t, *args, **kwargs): """One update of the corrector. Args: x: A PyTorch tensor representing the current state. t: A PyTorch tensor representing the current time step. Returns: x: A PyTorch tensor of the next state. x_mean: A PyTorch tensor. The next state without random noise. Useful for denoising. """ pass @abc.abstractmethod def update_mol_fn(self, x, t, *args, **kwargs): """One update of the corrector for molecule graphs. Args: x: A tuple of PyTorch tensor (x_atom, x_bond) representing the current state. t: A PyTorch tensor representing the current time step. Returns: x: A tuple of PyTorch tensor (x_atom, x_bond) of the next state. x_mean: A tuple of PyTorch tensor. The next state without random noise. Useful for denoising. """ pass @register_predictor(name='euler_maruyama') class EulerMaruyamaPredictor(Predictor): def __init__(self, sde, score_fn, probability_flow=False): super().__init__(sde, score_fn, probability_flow) def update_fn(self, x, t, *args, **kwargs): dt = -1. / self.rsde.N z = torch.randn_like(x) z = torch.tril(z, -1) z = z + z.transpose(-1, -2) drift, diffusion = self.rsde.sde(x, t, *args, **kwargs) drift = torch.tril(drift, -1) drift = drift + drift.transpose(-1, -2) x_mean = x + drift * dt x = x_mean + diffusion[:, None, None, None] * np.sqrt(-dt) * z return x, x_mean def update_mol_fn(self, x, t, *args, **kwargs): atom_score, bond_score = self.score_fn(x, t, *args, **kwargs) # print('predictor atom norm: ', torch.norm(atom_score.reshape(atom_score.shape[0], -1), dim=-1).mean(), t[0]) x_atom, x_bond = x dt = -1. / self.rsde[0].N # atom update z_atom = torch.randn_like(x_atom) drift_atom, diffusion_atom = self.rsde[0].sde_score(x_atom, t, atom_score) x_atom_mean = x_atom + drift_atom * dt x_atom = x_atom_mean + diffusion_atom[:, None, None] * np.sqrt(-dt) * z_atom # bond update z_bond = torch.randn_like(x_bond) z_bond = torch.tril(z_bond, -1) z_bond = z_bond + z_bond.transpose(-1, -2) drift_bond, diffusion_bond = self.rsde[1].sde_score(x_bond, t, bond_score) x_bond_mean = x_bond + drift_bond * dt x_bond = x_bond_mean + diffusion_bond[:, None, None, None] * np.sqrt(-dt) * z_bond return (x_atom, x_bond), (x_atom_mean, x_bond_mean) @register_corrector(name='langevin') class LangevinCorrector(Corrector): def __init__(self, sde, score_fn, snr, n_steps): super().__init__(sde, score_fn, snr, n_steps) def update_fn(self, x, t, *args, **kwargs): sde = self.sde score_fn = self.score_fn n_steps = self.n_steps target_snr = self.snr if isinstance(sde, sde_lib.VPSDE) or isinstance(sde, sde_lib.subVPSDE): timestep = (t * (sde.N - 1) / sde.T).long() # Note: it seems that subVPSDE doesn't set alphas alpha = sde.alphas.to(t.device)[timestep] else: alpha = torch.ones_like(t) for i in range(n_steps): grad = score_fn(x, t, *args, **kwargs) noise = torch.randn_like(x) noise = torch.tril(noise, -1) noise = noise + noise.transpose(-1, -2) mask = kwargs['mask'] # mask invalid elements and calculate norm mask_tmp = mask.reshape(mask.shape[0], -1) grad_norm = torch.norm(mask_tmp * grad.reshape(grad.shape[0], -1), dim=-1).mean() noise_norm = torch.norm(mask_tmp * noise.reshape(noise.shape[0], -1), dim=-1).mean() step_size = (target_snr * noise_norm / grad_norm) ** 2 * 2 * alpha x_mean = x + step_size[:, None, None, None] * grad x = x_mean + torch.sqrt(step_size * 2)[:, None, None, None] * noise return x, x_mean def update_mol_fn(self, x, t, *args, **kwargs): x_atom, x_bond = x atom_sde, bond_sde = self.sde score_fn = self.score_fn n_steps = self.n_steps atom_snr, bond_snr = self.snr if isinstance(atom_sde, sde_lib.VPSDE) or isinstance(atom_sde, sde_lib.subVPSDE): timestep = (t * (atom_sde.N - 1) / atom_sde.T).long() # Note: it seems that subVPSDE doesn't set alphas alpha_atom = atom_sde.alphas.to(t.device)[timestep] alpha_bond = bond_sde.alphas.to(t.device)[timestep] else: alpha_atom = alpha_bond = torch.ones_like(t) for i in range(n_steps): grad_atom, grad_bond = score_fn(x, t, *args, **kwargs) # update atom noise_atom = torch.randn_like(x_atom) noise_atom = noise_atom * kwargs['atom_mask'].unsqueeze(-1) ## mask invalid elements and calculate norm # atom_mask = kwargs['atom_mask'].unsqueeze(-1) # atom_mask = atom_mask.repeat(1, 1, grad_atom.shape[-1]).reshape(grad_atom.shape[0], -1) # grad_norm_a = torch.norm(atom_mask * grad_atom.reshape(grad_atom.shape[0], -1), dim=-1).mean() # noise_norm_a = torch.norm(atom_mask * noise_atom.reshape(noise_atom.shape[0], -1), dim=-1).mean() grad_norm_a = torch.norm(grad_atom.reshape(grad_atom.shape[0], -1), dim=-1).mean() noise_norm_a = torch.norm(noise_atom.reshape(noise_atom.shape[0], -1), dim=-1).mean() # print('Corrector atom score norm:', grad_norm_a, t[0]) step_size_a = (atom_snr * noise_norm_a / grad_norm_a) ** 2 * 2 * alpha_atom x_atom_mean = x_atom + step_size_a[:, None, None] * grad_norm_a x_atom = x_atom_mean + torch.sqrt(step_size_a * 2)[:, None, None] * noise_atom # update bond noise_bond = torch.randn_like(x_bond) noise_bond = torch.tril(noise_bond, -1) noise_bond = noise_bond + noise_bond.transpose(-1, -2) noise_bond = noise_bond * kwargs['bond_mask'] # bond_mask = kwargs['bond_mask'].repeat(1, grad_bond.shape[1], 1, 1).reshape(grad_bond.shape[0], -1) # grad_norm_b = torch.norm(bond_mask * grad_bond.reshape(grad_bond.shape[0], -1), dim=-1).mean() # noise_norm_b = torch.norm(bond_mask * noise_bond.reshape(noise_bond.shape[0], -1), dim=-1).mean() grad_norm_b = torch.norm(grad_bond.reshape(grad_bond.shape[0], -1), dim=-1).mean() noise_norm_b = torch.norm(noise_bond.reshape(noise_bond.shape[0], -1), dim=-1).mean() step_size_b = (bond_snr * noise_norm_b / grad_norm_b) ** 2 * 2 * alpha_bond x_bond_mean = x_bond + step_size_b[:, None, None, None] * grad_norm_b x_bond = x_bond_mean + torch.sqrt(step_size_b * 2)[:, None, None, None] * noise_bond return (x_atom, x_bond), (x_atom_mean, x_bond_mean) @register_predictor(name='none') class NonePredictor(Predictor): """An empty predictor that does nothing.""" def __init__(self, sde, score_fn, probability_flow=False): pass def update_fn(self, x, t, *args, **kwargs): return x, x def update_mol_fn(self, x, t, *args, **kwargs): return x, x @register_corrector(name='none') class NoneCorrector(Corrector): """An empty corrector that does nothing.""" def __init__(self, sde, score_fn, snr, n_steps): pass def update_fn(self, x, t, *args, **kwargs): return x, x def update_atom_fn(self, x, t, *args, **kwargs): return x, x def update_bond_fn(self, x, t, *args, **kwargs): return x, x def update_mol_fn(self, x, t, *args, **kwargs): return x, x def shared_predictor_update_fn(x, t, sde, model, predictor, probability_flow, continuous, *args, **kwargs): """A wrapper that configures and returns the update function of predictors.""" if isinstance(sde, tuple): score_fn = mutils.get_multi_score_fn(sde[0], sde[1], model, train=False, continuous=continuous) else: # score_fn = mutils.get_score_fn(sde, model, train=False, continuous=continuous) raise ValueError('Score function error.') if predictor is None: # Corrector-only sampler predictor_obj = NonePredictor(sde, score_fn, probability_flow) else: predictor_obj = predictor(sde, score_fn, probability_flow) if isinstance(sde, tuple): return predictor_obj.update_mol_fn(x, t, *args, **kwargs) return predictor_obj.update_fn(x, t, *args, **kwargs) def shared_corrector_update_fn(x, t, sde, model, corrector, continuous, snr, n_steps, *args, **kwargs): """A wrapper that configures and returns the update function of correctors.""" if isinstance(sde, tuple): score_fn = mutils.get_multi_score_fn(sde[0], sde[1], model, train=False, continuous=continuous) else: # score_fn = mutils.get_score_fn(sde, model, train=False, continuous=continuous) raise ValueError('Score function error.') if corrector is None: # Predictor-only sampler corrector_obj = NoneCorrector(sde, score_fn, snr, n_steps) else: corrector_obj = corrector(sde, score_fn, snr, n_steps) if isinstance(sde, tuple): return corrector_obj.update_mol_fn(x, t, *args, **kwargs) return corrector_obj.update_fn(x, t, *args, **kwargs) def get_mol_pc_sampler(atom_sde, bond_sde, atom_shape, bond_shape, predictor, corrector, inverse_scaler, snr, n_steps=1, probability_flow=False, continuous=False, denoise=True, eps=1e-3, device='cuda'): """Create a Predictor-Corrector (PC) sampler for molecule graph generation. Args: atom_sde, bond_sde: An `sde_lib.SDE` object representing the forward SDE. atom_shape, bond_shape: A sequence of integers. The expected shape of a single sample. predictor: A subclass of `sampling.Predictor` representing the predictor algorithm. corrector: A subclass of `sampling.Corrector` representing the corrector algorithm. inverse_scaler: The inverse data normalizer. snr: A `float` number. The signal-to-noise ratio for configuring correctors. n_steps: An integer. The number of corrector steps per predictor update. probability_flow: If `True`, solve the reverse-time probability flow ODE when running the predictor. continuous: `True` indicates that the score model was continuously trained. denoise: If `True`, add one-step denoising to the final samples. eps: A `float` number. The reverse-time SDE and ODE are integrated to `epsilon` to avoid numerical issues. device: PyTorch device. Returns: A sampling function that returns samples and the number of function evaluations during sampling. """ # Create predictor & corrector update functions predictor_update_fn = functools.partial(shared_predictor_update_fn, sde=(atom_sde, bond_sde), predictor=predictor, probability_flow=probability_flow, continuous=continuous) corrector_update_fn = functools.partial(shared_corrector_update_fn, sde=(atom_sde, bond_sde), corrector=corrector, continuous=continuous, snr=snr, n_steps=n_steps) def mol_pc_sampler(model, n_nodes_pmf): """The PC sampler function. Args: model: A score model. n_nodes_pmf: Probability mass function of graph nodes. Returns: Samples, number of function evaluations. """ with torch.no_grad(): # Initial sample x_atom = atom_sde.prior_sampling(atom_shape).to(device) x_bond = bond_sde.prior_sampling(bond_shape).to(device) timesteps = torch.linspace(atom_sde.T, eps, atom_sde.N, device=device) # Sample the number of nodes n_nodes = torch.multinomial(n_nodes_pmf, atom_shape[0], replacement=True) atom_mask = torch.zeros((atom_shape[0], atom_shape[1]), device=device) for i in range(atom_shape[0]): atom_mask[i][:n_nodes[i]] = 1. bond_mask = (atom_mask[:, None, :] * atom_mask[:, :, None]).unsqueeze(1) bond_mask = torch.tril(bond_mask, -1) bond_mask = bond_mask + bond_mask.transpose(-1, -2) x_atom = x_atom * atom_mask.unsqueeze(-1) x_bond = x_bond * bond_mask for i in range(atom_sde.N): t = timesteps[i] vec_t = torch.ones(atom_shape[0], device=t.device) * t (x_atom, x_bond), (x_atom_mean, x_bond_mean) = corrector_update_fn((x_atom, x_bond), vec_t, model=model, atom_mask=atom_mask, bond_mask=bond_mask) x_atom = x_atom * atom_mask.unsqueeze(-1) x_bond = x_bond * bond_mask (x_atom, x_bond), (x_atom_mean, x_bond_mean) = predictor_update_fn((x_atom, x_bond), vec_t, model=model, atom_mask=atom_mask, bond_mask=bond_mask) x_atom = x_atom * atom_mask.unsqueeze(-1) x_bond = x_bond * bond_mask return inverse_scaler(x_atom_mean if denoise else x_atom, atom=True) * atom_mask.unsqueeze(-1),\ inverse_scaler(x_bond_mean if denoise else x_bond, atom=False) * bond_mask,\ atom_sde.N * (n_steps + 1), n_nodes return mol_pc_sampler
22,407
41.845124
120
py
CDGS
CDGS-main/datasets.py
import ast import torch import json import os import numpy as np import os.path as osp import pandas as pd import pickle as pk from itertools import repeat from rdkit import Chem import torch_geometric.transforms as T from torch_geometric.data import Data, InMemoryDataset, download_url from torch_geometric.utils import from_networkx, degree, to_networkx bond_type_to_int = {Chem.BondType.SINGLE: 0, Chem.BondType.DOUBLE: 1, Chem.BondType.TRIPLE: 2} def get_data_scaler(config): """Data normalizer. Assume data are always in [0, 1].""" centered = config.data.centered if hasattr(config.data, "shift"): shift = config.data.shift else: shift = 0. if hasattr(config.data, 'norm'): atom_norm, bond_norm = config.data.norm assert shift == 0. def scale_fn(x, atom=False): if centered: x = x * 2. - 1. else: x = x if atom: x = x * atom_norm else: x = x * bond_norm return x return scale_fn else: if centered: # Rescale to [-1, 1] return lambda x: x * 2. - 1. + shift else: assert shift == 0. return lambda x: x def get_data_inverse_scaler(config): """Inverse data normalizer.""" centered = config.data.centered if hasattr(config.data, "shift"): shift = config.data.shift else: shift = 0. if hasattr(config.data, 'norm'): atom_norm, bond_norm = config.data.norm assert shift == 0. def inverse_scale_fn(x, atom=False): if atom: x = x / atom_norm else: x = x / bond_norm if centered: x = (x + 1.) / 2. else: x = x return x return inverse_scale_fn else: if centered: # Rescale [-1, 1] to [0, 1] return lambda x: (x + 1. - shift) / 2. else: assert shift == 0. return lambda x: x def networkx_graphs(dataset): return [to_networkx(dataset[i], to_undirected=True, remove_self_loops=True) for i in range(len(dataset))] class StructureDataset(InMemoryDataset): def __init__(self, root, dataset_name, transform=None, pre_transform=None, pre_filter=None): self.dataset_name = dataset_name super(StructureDataset, self).__init__(root, transform, pre_transform, pre_filter) if not os.path.exists(self.raw_paths[0]): raise ValueError("Without raw files.") if os.path.exists(self.processed_paths[0]): self.data, self.slices = torch.load(self.processed_paths[0]) else: self.process() @property def raw_file_names(self): return [self.dataset_name + '.pkl'] @property def processed_file_names(self): return [self.dataset_name + '.pt'] @property def num_node_features(self): if self.data.x is None: return 0 return self.data.x.size(1) def __repr__(self) -> str: arg_repr = str(len(self)) if len(self) > 1 else '' return f'{self.dataset_name}({arg_repr})' def process(self): # Read data into 'Data' list input_path = self.raw_paths[0] with open(input_path, 'rb') as f: graphs_nx = pk.load(f) data_list = [from_networkx(G) for G in graphs_nx] if self.pre_filter is not None: data_list = [data for data in data_list if self.pre_filter(data)] if self.pre_transform is not None: data_list = [self.pre_transform(data) for data in data_list] self.data, self.slices = self.collate(data_list) torch.save((self.data, self.slices), self.processed_paths[0]) @torch.no_grad() def max_degree(self): data_list = [self.get(i) for i in range(len(self))] def graph_max_degree(g_data): return max(degree(g_data.edge_index[1], num_nodes=g_data.num_nodes)) degree_list = [graph_max_degree(data) for data in data_list] return int(max(degree_list).item()) def n_node_pmf(self): node_list = [self.get(i).num_nodes for i in range(len(self))] n_node_pmf = np.bincount(node_list) n_node_pmf = n_node_pmf / n_node_pmf.sum() return n_node_pmf class MolDataset(InMemoryDataset): # from DIG: Dive into Graphs """ A Pytorch Geometric data interface for datasets used in molecule generation. .. note:: Some datasets may not come with any node labels, like :obj:`moses`. Since they don't have any properties in the original data file. The process of the dataset can only save the current input property and will load the same property label when the processed dataset is used. You can change the augment :obj:`processed_filename` to re-process the dataset with intended property. Args: root (string, optional): Root directory where the dataset should be saved. name (string, optional): The name of the dataset. Available dataset names are as follows: :obj:`zinc250k`, :obj:`zinc_800_graphaf`, :obj:`zinc_800_jt`, :obj:`zinc250k_property`, :obj:`qm9_property`, :obj:`qm9`, :obj:`moses`. bond_ch (int): The channels for bond matrices. {1, 2, 4} prop_name (string, optional): The molecular property desired and used as the optimization target. (eg. "obj:`penalized_logp`) conf_dict (dictionary, optional): dictionary that stores all the configuration for the corresponding dataset transform (callable, optional): A function/transform that takes in an :obj:`torch_geometric.data.Data` object and returns a transformed version. The data object will be transformed before every access. pre_transform (callable, optional): A function/transform that takes in an :obj:`torch_geometric.data.Data` object and returns a transformed version.The data object will be transformed before being saved to disk. pre_filter (callable, optional): A function that takes in an :obj:`torch_geometric.data.Data` object and returns a boolean value, indicating whether the data object should be included in the final dataset. """ def __init__(self, root, name, bond_ch, prop_name='penalized_logp', conf_dict=None, transform=None, pre_transform=None, pre_filter=None, processed_filename='data.pt'): self.processed_filename = processed_filename self.root = root self.name = name self.prop_name = prop_name self.bond_ch = bond_ch if conf_dict is None: config_file = pd.read_csv(os.path.join(os.path.dirname(__file__), 'mol_config.csv'), index_col=0) if self.name not in config_file: error_mssg = 'Invalid dataset name {}.\n'.format(self.name) error_mssg += 'Available datasets are as follows:\n' error_mssg += '\n'.join(config_file.keys()) raise ValueError(error_mssg) config = config_file[self.name] else: config = conf_dict self.url = config['url'] self.available_prop = str(prop_name) in ast.literal_eval(config['prop_list']) self.smile_col = config['smile'] self.num_max_node = int(config['num_max_node']) self.atom_list = ast.literal_eval(config['atom_list']) super(MolDataset, self).__init__(root, transform, pre_transform, pre_filter) if not osp.exists(self.raw_paths[0]): self.download() if osp.exists(self.processed_paths[0]): self.data, self.slices, self.all_smiles = torch.load(self.processed_paths[0]) else: self.process() @property def raw_dir(self): name = 'raw' return osp.join(self.root, name) @property def processed_dir(self): name = 'processed' return osp.join(self.root, self.name, name) @property def raw_file_names(self): name = self.name + '.csv' return name @property def processed_file_names(self): return self.processed_filename def download(self): print('making raw files:', self.raw_dir) if not osp.exists(self.raw_dir): os.makedirs(self.raw_dir) url = self.url path = download_url(url, self.raw_dir) def process(self): """Process the dataset from raw data file to the :obj:`self.processed_dir` folder.""" print('Processing...') self.data, self.slices = self.pre_process() if self.pre_filter is not None: data_list = [self.get(idx) for idx in range(len(self))] data_list = [data for data in data_list if self.pre_filter(data)] self.data, self.slices = self.collate(data_list) if self.pre_transform is not None: data_list = [self.get(idx) for idx in range(len(self))] data_list = [self.pre_transform(data) for data in data_list] self.data, self.slices = self.collate(data_list) print('making processed files:', self.processed_dir) if not osp.exists(self.processed_dir): os.makedirs(self.processed_dir) torch.save((self.data, self.slices, self.all_smiles), self.processed_paths[0]) print('Done!') def __repr__(self): return '{}({})'.format(self.name, len(self)) def get(self, idx): """Get the data object at index idx. """ data = self.data.__class__() if hasattr(self.data, '__num_nodes__'): data.num_nodes = self.data.__num_nodes__[idx] for key in self.data.keys: item, slices = self.data[key], self.slices[key] if torch.is_tensor(item): s = list(repeat(slice(None), item.dim())) s[self.data.__cat_dim__(key, item)] = slice(slices[idx], slices[idx + 1]) else: s = slice(slices[idx], slices[idx + 1]) data[key] = item[s] data['smile'] = self.all_smiles[idx] if self.bond_ch == 1: with torch.no_grad(): adj = data.adj ch = adj.shape[0] adj = torch.argmax(adj, dim=0) adj[adj == 3] = -1 adj = (adj + 1).float() data['adj'] = adj.unsqueeze(0) / (ch - 1) elif self.bond_ch == 2: with torch.no_grad(): adj = data.adj ch = adj.shape[0] adj = torch.argmax(adj, dim=0) adj[adj == 3] = -1 adj_1 = ((adj + 1) != 0).float() adj = (adj + 1).float() adj = torch.stack([adj / (ch - 1), adj_1]) data['adj'] = adj return data def pre_process(self): input_path = self.raw_paths[0] input_df = pd.read_csv(input_path, sep=',', dtype='str') smile_list = list(input_df[self.smile_col]) if self.available_prop: prop_list = list(input_df[self.prop_name]) self.all_smiles = smile_list data_list = [] for i in range(len(smile_list)): smile = smile_list[i] mol = Chem.MolFromSmiles(smile) Chem.Kekulize(mol) num_atom = mol.GetNumAtoms() if num_atom > self.num_max_node: continue else: # atoms atom_array = np.zeros((self.num_max_node, len(self.atom_list)), dtype=np.float32) atom_mask = np.zeros(self.num_max_node, dtype=np.float32) atom_mask[:num_atom] = 1. atom_idx = 0 for atom in mol.GetAtoms(): atom_feature = atom.GetAtomicNum() atom_array[atom_idx, self.atom_list.index(atom_feature)] = 1 atom_idx += 1 x = torch.tensor(atom_array) # bonds adj_array = np.zeros([4, self.num_max_node, self.num_max_node], dtype=np.float32) for bond in mol.GetBonds(): bond_type = bond.GetBondType() ch = bond_type_to_int[bond_type] i = bond.GetBeginAtomIdx() j = bond.GetEndAtomIdx() adj_array[ch, i, j] = 1. adj_array[ch, j, i] = 1. adj_array[-1, :, :] = 1 - np.sum(adj_array, axis=0) # adj_array += np.eye(self.num_max_node) data = Data(x=x) data.adj = torch.tensor(adj_array) data.num_atom = num_atom data.atom_mask = torch.tensor(atom_mask) if self.available_prop: data.y = torch.tensor([float(prop_list[i])]) data_list.append(data) data, slices = self.collate(data_list) return data, slices def get_split_idx(self): """ Gets the train-valid set split indices of the dataset. Return: A dictionary for training-validation split with key `train_idx` and `valid_idx`. """ if self.name.find('zinc250k') != -1: path = os.path.join(self.root, 'raw/valid_idx_zinc250k.json') with open(path) as f: valid_idx = json.load(f) elif self.name.find('qm9') != -1: path = os.path.join(self.root, 'raw/valid_idx_qm9.json') with open(path) as f: valid_idx = json.load(f)['valid_idxs'] valid_idx = list(map(int, valid_idx)) else: print('No available split file for this dataset, please check.') return None train_idx = list(set(np.arange(self.__len__())).difference(set(valid_idx))) return {'train_idx': torch.tensor(train_idx, dtype=torch.long), 'valid_idx': torch.tensor(valid_idx, dtype=torch.long)} def n_node_pmf(self): # if 'qm9' in self.name: # n_node_pmf = [0. for _ in range(10)] # n_node_pmf[-1] = 1. # return np.array(n_node_pmf) node_list = [self.get(i).num_atom.item() for i in range(len(self))] n_node_pmf = np.bincount(node_list) n_node_pmf = n_node_pmf / n_node_pmf.sum() return n_node_pmf class QM9(MolDataset): def __init__(self, root='./', bond_ch=4, prop_name='penalized_logp', conf_dict=None, transform=None, pre_transform=None, pre_filter=None, processed_filename='data.pt'): name = 'qm9_property' super(QM9, self).__init__(root, name, bond_ch, prop_name, conf_dict, transform, pre_transform, pre_filter, processed_filename) class ZINC250k(MolDataset): """ The attributes of the output data: x: the node features. y: the property labels for the graph. adj: the edge features in the form of dense adjacent matrices. batch: the assignment vector which maps each node to its respective graph identifier and can help reconstruct single graphs. num_atom: number of atoms for each graph. smile: original SMILE sequences for the graphs. """ def __init__(self, root='./', bond_ch=4, prop_name='penalized_logp', conf_dict=None, transform=None, pre_transform=None, pre_filter=None, processed_filename='data.pt'): name = 'zinc250k_property' super(ZINC250k, self).__init__(root, name, bond_ch, prop_name, conf_dict, transform, pre_transform, pre_filter, processed_filename) class MOSES(MolDataset): def __init__(self, root='./', bond_ch=4, prop_name=None, conf_dict=None, transform=None, pre_transform=None, pre_filter=None, processed_filename='data.pt'): name = 'moses' super(MOSES, self).__init__(root, name, bond_ch, prop_name, conf_dict, transform, pre_transform, pre_filter, processed_filename) class ZINC800(MolDataset): """ ZINC800 contains 800 selected molecules with lowest penalized logP scores. While method `jt` selects from the test set and `graphaf` selects from the train set. """ def __init__(self, root='./', method='jt', bond_ch=4, prop_name='penalized_logp', conf_dict=None, transform=None, pre_transform=None, pre_filter=None, processed_filename='data.pt'): name = 'zinc_800' name = name + '_' + method super(ZINC800, self).__init__(root, name, bond_ch, prop_name, conf_dict, transform, pre_transform, pre_filter, processed_filename) def get_opt_dataset(config): """Create data loaders for similarity constrained molecule optimization. Args: config: A ml_collection.ConfigDict parsed from config files. Returns: dataset """ transform = T.Compose([ T.ToDevice(config.device) ]) assert 'zinc_800' in config.data.name if 'jt' in config.data.name: dataset = ZINC800(config.data.root, 'jt', bond_ch=config.data.bond_channels, transform=transform) elif 'graphaf' in config.data.name: dataset = ZINC800(config.data.root, 'graphaf', bond_ch=config.data.bond_channels, transform=transform) else: error_mssg = 'Invalid method type {}.\n'.format(config.data.name) error_mssg += 'Available datasets are as follows:\n' error_mssg += '\n'.join(['jt', 'graphaf']) raise ValueError(error_mssg) return dataset def get_dataset(config): """Create data loaders for training and evaluation. Args: config: A ml_collection.ConfigDict parsed from config files. Returns: train_ds, eval_ds, test_ds, n_node_pmf """ # define data transforms transform = T.Compose([ # T.ToDense(config.data.max_node), T.ToDevice(config.device) ]) # Build up data iterators if config.model_type == 'mol_sde' or config.model_type == 'sep_mol_sde': if config.data.name == 'QM9': dataset = QM9(config.data.root, bond_ch=config.data.bond_channels, transform=transform) elif config.data.name == 'ZINC250K': if hasattr(config.data, 'property'): property = config.data.property else: property = 'penalized_logp' if property == 'qed': dataset = ZINC250k(config.data.root, prop_name=property, bond_ch=config.data.bond_channels, transform=transform, processed_filename='qed_data.pt') else: dataset = ZINC250k(config.data.root, prop_name=property, bond_ch=config.data.bond_channels, transform=transform) elif config.data.name == 'MOSES': dataset = MOSES(config.data.root, bond_ch=config.data.bond_channels, transform=transform) else: raise ValueError('Undefined dataset name.') all_smiles = dataset.all_smiles splits = dataset.get_split_idx() train_idx = splits['train_idx'] test_idx = splits['valid_idx'] train_dataset = dataset[train_idx] train_dataset.sub_smiles = [all_smiles[idx] for idx in train_idx] test_dataset = dataset[test_idx] test_dataset.sub_smiles = [all_smiles[idx] for idx in test_idx] eval_idx = train_idx[torch.randperm(len(train_idx))[:len(test_idx)]] eval_dataset = dataset[eval_idx] eval_dataset.sub_smiles = [all_smiles[idx] for idx in eval_idx] else: dataset = StructureDataset(config.data.root, config.data.name, transform=transform) num_train = int(len(dataset) * config.data.split_ratio) num_test = len(dataset) - num_train train_dataset = dataset[:num_train] eval_dataset = dataset[:num_test] test_dataset = dataset[num_train:] n_node_pmf = train_dataset.n_node_pmf() return train_dataset, eval_dataset, test_dataset, n_node_pmf
20,430
36.147273
129
py
CDGS
CDGS-main/sde_lib.py
"""Abstract SDE classes, Reverse SDE, and VE/VP SDEs.""" import abc import torch import numpy as np class SDE(abc.ABC): """SDE abstract class. Functions are designed for a mini-batch of inputs.""" def __init__(self, N): """Construct an SDE. Args: N: number of discretization time steps. """ super().__init__() self.N = N @property @abc.abstractmethod def T(self): """End time of the SDE.""" pass @abc.abstractmethod def sde(self, x, t): pass @abc.abstractmethod def marginal_prob(self, x, t): """Parameters to determine the marginal distribution of the SDE, $p_t(x)$""" pass @abc.abstractmethod def prior_sampling(self, shape): """Generate one sample from the prior distribution, $p_T(x)$.""" pass @abc.abstractmethod def prior_logp(self, z, mask): """Compute log-density of the prior distribution. Useful for computing the log-likelihood via probability flow ODE. Args: z: latent code Returns: log probability density """ pass def discretize(self, x, t): """Discretize the SDE in the form: x_{i+1} = x_i + f_i(x_i) + G_i z_i. Useful for reverse diffusion sampling and probability flow sampling. Defaults to Euler-Maruyama discretization. Args: x: a torch tensor t: a torch float representing the time step (from 0 to `self.T`) Returns: f, G """ dt = 1 / self.N drift, diffusion = self.sde(x, t) f = drift * dt G = diffusion * torch.sqrt(torch.tensor(dt, device=t.device)) return f, G def reverse(self, score_fn, probability_flow=False): """Create the reverse-time SDE/ODE. Args: score_fn: A time-dependent score-based model that takes x and t and returns the score. probability_flow: If `True`, create the reverse-time ODE used for probability flow sampling. """ N = self.N T = self.T sde_fn = self.sde discretize_fn = self.discretize # Build the class for reverse-time SDE. class RSDE(self.__class__): def __init__(self): self.N = N self.probability_flow = probability_flow @property def T(self): return T def sde(self, x, t, *args, **kwargs): """Create the drift and diffusion functions for the reverse SDE/ODE.""" drift, diffusion = sde_fn(x, t) score = score_fn(x, t, *args, **kwargs) drift = drift - diffusion[:, None, None, None] ** 2 * score * (0.5 if self.probability_flow else 1.) # Set the diffusion function to zero for ODEs. diffusion = 0. if self.probability_flow else diffusion return drift, diffusion def sde_score(self, x, t, score): """Create the drift and diffusion functions for the reverse SDE/ODE, given score values.""" drift, diffusion = sde_fn(x, t) if len(score.shape) == 4: drift = drift - diffusion[:, None, None, None] ** 2 * score * (0.5 if self.probability_flow else 1.) elif len(score.shape) == 3: drift = drift - diffusion[:, None, None] ** 2 * score * (0.5 if self.probability_flow else 1.) else: raise ValueError diffusion = 0. if self.probability_flow else diffusion return drift, diffusion def discretize(self, x, t, *args, **kwargs): """Create discretized iteration rules for the reverse diffusion sampler.""" f, G = discretize_fn(x, t) rev_f = f - G[:, None, None, None] ** 2 * score_fn(x, t, *args, **kwargs) * \ (0.5 if self.probability_flow else 1.) rev_G = torch.zeros_like(G) if self.probability_flow else G return rev_f, rev_G def discretize_score(self, x, t, score): """Create discretized iteration rules for the reverse diffusion sampler, given score values.""" f, G = discretize_fn(x, t) if len(score.shape) == 4: rev_f = f - G[:, None, None, None] ** 2 * score * \ (0.5 if self.probability_flow else 1.) elif len(score.shape) == 3: rev_f = f - G[:, None, None] ** 2 * score * (0.5 if self.probability_flow else 1.) else: raise ValueError rev_G = torch.zeros_like(G) if self.probability_flow else G return rev_f, rev_G return RSDE() class VPSDE(SDE): def __init__(self, beta_min=0.1, beta_max=20, N=1000): """Construct a Variance Preserving SDE. Args: beta_min: value of beta(0) beta_max: value of beta(1) N: number of discretization steps """ super().__init__(N) self.beta_0 = beta_min self.beta_1 = beta_max self.N = N self.discrete_betas = torch.linspace(beta_min / N, beta_max / N, N) self.alphas = 1. - self.discrete_betas self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) self.sqrt_alphas_cumprod = torch.sqrt(self.alphas_cumprod) self.sqrt_1m_alphas_cumprod = torch.sqrt(1. - self.alphas_cumprod) @property def T(self): return 1 def sde(self, x, t): beta_t = self.beta_0 + t * (self.beta_1 - self.beta_0) if len(x.shape) == 4: drift = -0.5 * beta_t[:, None, None, None] * x elif len(x.shape) == 3: drift = -0.5 * beta_t[:, None, None] * x else: raise NotImplementedError diffusion = torch.sqrt(beta_t) return drift, diffusion def marginal_prob(self, x, t): log_mean_coeff = -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0 if len(x.shape) == 4: mean = torch.exp(log_mean_coeff[:, None, None, None]) * x elif len(x.shape) == 3: mean = torch.exp(log_mean_coeff[:, None, None]) * x else: raise ValueError("The shape of x in marginal_prob is not correct.") std = torch.sqrt(1. - torch.exp(2. * log_mean_coeff)) return mean, std def log_snr(self, t): log_mean_coeff = -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0 mean = torch.exp(log_mean_coeff) std = torch.sqrt(1. - torch.exp(2. * log_mean_coeff)) log_snr = torch.log(mean / std) return log_snr, mean, std def log_snr_np(self, t): log_mean_coeff = -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0 mean = np.exp(log_mean_coeff) std = np.sqrt(1. - np.exp(2. * log_mean_coeff)) log_snr = np.log(mean / std) return log_snr def lambda2t(self, lambda_ori): log_val = torch.log(torch.exp(-2. * lambda_ori) + 1.) t = 2. * log_val / (torch.sqrt(self.beta_0 ** 2 + 2. * (self.beta_1 - self.beta_0) * log_val) + self.beta_0) return t def lambda2t_np(self, lambda_ori): log_val = np.log(np.exp(-2. * lambda_ori) + 1.) t = 2. * log_val / (np.sqrt(self.beta_0 ** 2 + 2. * (self.beta_1 - self.beta_0) * log_val) + self.beta_0) return t def prior_sampling(self, shape): sample = torch.randn(*shape) if len(shape) == 4: sample = torch.tril(sample, -1) sample = sample + sample.transpose(-1, -2) return sample def prior_logp(self, z, mask): N = torch.sum(mask, dim=tuple(range(1, len(mask.shape)))) logps = -N / 2. * np.log(2 * np.pi) - torch.sum((z * mask) ** 2, dim=(1, 2, 3)) / 2. return logps def discretize(self, x, t): """DDPM discretization.""" timestep = (t * (self.N - 1) / self.T).long() beta = self.discrete_betas.to(x.device)[timestep] alpha = self.alphas.to(x.device)[timestep] sqrt_beta = torch.sqrt(beta) if len(x.shape) == 4: f = torch.sqrt(alpha)[:, None, None, None] * x - x elif len(x.shape) == 3: f = torch.sqrt(alpha)[:, None, None] * x - x else: NotImplementedError G = sqrt_beta return f, G
8,565
35.14346
120
py
CDGS
CDGS-main/evaluation/mol_metrics.py
from fcd_torch import FCD def compute_intermediate_FCD(smiles, n_jobs=1, device='cpu', batch_size=512): """ Precomputes statistics such as mean and variance for FCD. """ kwargs_fcd = {'n_jobs': n_jobs, 'device': device, 'batch_size': batch_size} stats = FCD(**kwargs_fcd).precalc(smiles) return stats def get_FCDMetric(ref_smiles, n_jobs=1, device='cpu', batch_size=512): pref = compute_intermediate_FCD(ref_smiles, n_jobs, device, batch_size) def FCDMetric(gen_smiles): kwargs_fcd = {'n_jobs': n_jobs, 'device': device, 'batch_size': batch_size} return FCD(**kwargs_fcd)(gen=gen_smiles, pref=pref) return FCDMetric
674
31.142857
83
py
CDGS
CDGS-main/models/cdgs.py
import torch.nn as nn import torch import functools from torch_geometric.utils import dense_to_sparse from . import utils, layers from .hmpb import HybridMPBlock get_act = layers.get_act conv1x1 = layers.conv1x1 @utils.register_model(name='CDGS') class CDGS(nn.Module): """ Graph Noise Prediction Model. """ def __init__(self, config): super().__init__() self.config = config self.act = act = get_act(config) # get input channels(data.num_channels), hidden channels(model.nf), number of blocks(model.num_res_blocks) self.nf = nf = config.model.nf self.num_gnn_layers = num_gnn_layers = config.model.num_gnn_layers dropout = config.model.dropout self.embedding_type = embedding_type = config.model.embedding_type.lower() self.conditional = conditional = config.model.conditional self.edge_th = config.model.edge_th self.rw_depth = rw_depth = config.model.rw_depth modules = [] # timestep/noise_level embedding; only for continuous training if embedding_type == 'positional': embed_dim = nf else: raise ValueError(f'embedding type {embedding_type} unknown.') if conditional: modules.append(nn.Linear(embed_dim, nf * 2)) modules.append(nn.Linear(nf * 2, nf)) atom_ch = config.data.atom_channels bond_ch = config.data.bond_channels temb_dim = nf # project bond features assert bond_ch == 2 bond_se_ch = int(nf * 0.4) bond_type_ch = int(0.5 * (nf - bond_se_ch)) modules.append(conv1x1(1, bond_type_ch)) modules.append(conv1x1(1, bond_type_ch)) modules.append(conv1x1(rw_depth + 1, bond_se_ch)) modules.append(nn.Linear(bond_se_ch + 2 * bond_type_ch, nf)) # project atom features atom_se_ch = int(nf * 0.2) atom_type_ch = nf - 2 * atom_se_ch modules.append(nn.Linear(bond_ch, atom_se_ch)) modules.append(nn.Linear(atom_ch, atom_type_ch)) modules.append(nn.Linear(rw_depth, atom_se_ch)) modules.append(nn.Linear(atom_type_ch + 2 * atom_se_ch, nf)) self.x_ch = nf # gnn network cat_dim = (nf * 2) // num_gnn_layers for _ in range(num_gnn_layers): modules.append(HybridMPBlock(nf, config.model.graph_layer, "FullTrans_1", config.model.heads, temb_dim=temb_dim, act=act, dropout=dropout, attn_dropout=dropout)) modules.append(nn.Linear(nf, cat_dim)) modules.append(nn.Linear(nf, cat_dim)) # atom output modules.append(nn.Linear(cat_dim * num_gnn_layers + atom_type_ch, nf)) modules.append(nn.Linear(nf, nf // 2)) modules.append(nn.Linear(nf // 2, atom_ch)) # bond output modules.append(conv1x1(cat_dim * num_gnn_layers + bond_type_ch, nf)) modules.append(conv1x1(nf, nf // 2)) modules.append(conv1x1(nf // 2, 1)) # structure output modules.append(conv1x1(cat_dim * num_gnn_layers + bond_type_ch, nf)) modules.append(conv1x1(nf, nf // 2)) modules.append(conv1x1(nf // 2, 1)) self.all_modules = nn.ModuleList(modules) def forward(self, x, time_cond, *args, **kwargs): atom_feat, bond_feat = x atom_mask = kwargs['atom_mask'] bond_mask = kwargs['bond_mask'] edge_exist = bond_feat[:, 1:, :, :] edge_cate = bond_feat[:, 0:1, :, :] # timestep/noise_level embedding; only for continuous training modules = self.all_modules m_idx = 0 if self.embedding_type == 'positional': # Sinusoidal positional embeddings. timesteps = time_cond temb = layers.get_timestep_embedding(timesteps, self.nf) else: raise ValueError(f'embedding type {self.embedding_type} unknown.') if self.conditional: temb = modules[m_idx](temb) m_idx += 1 temb = modules[m_idx](self.act(temb)) m_idx += 1 else: temb = None if not self.config.data.centered: # rescale the input data to [-1, 1] atom_feat = atom_feat * 2. - 1. bond_feat = bond_feat * 2. - 1. # discretize dense adj with torch.no_grad(): adj = edge_exist.squeeze(1).clone() # [B, N, N] adj[adj >= 0.] = 1. adj[adj < 0.] = 0. adj = adj * bond_mask.squeeze(1) # extract RWSE and Shortest-Path Distance rw_landing, spd_onehot = utils.get_rw_feat(self.rw_depth, adj) # construct edge feature [B, N, N, F] adj_mask = bond_mask.permute(0, 2, 3, 1) dense_cate = modules[m_idx](edge_cate).permute(0, 2, 3, 1) * adj_mask m_idx += 1 dense_exist = modules[m_idx](edge_exist).permute(0, 2, 3, 1) * adj_mask m_idx += 1 dense_spd = modules[m_idx](spd_onehot).permute(0, 2, 3, 1) * adj_mask m_idx += 1 dense_edge = modules[m_idx](torch.cat([dense_cate, dense_exist, dense_spd], dim=-1)) * adj_mask m_idx += 1 # Use Degree as atom feature atom_degree = torch.sum(bond_feat, dim=-1).permute(0, 2, 1) # [B, N, C] atom_degree = modules[m_idx](atom_degree) # [B, N, nf] m_idx += 1 atom_cate = modules[m_idx](atom_feat) m_idx += 1 x_rwl = modules[m_idx](rw_landing) m_idx += 1 x_atom = modules[m_idx](torch.cat([atom_degree, atom_cate, x_rwl], dim=-1)) m_idx += 1 h_atom = x_atom.reshape(-1, self.x_ch) # Dense to sparse node [BxN, -1] dense_index = adj.nonzero(as_tuple=True) edge_index, _ = dense_to_sparse(adj) h_dense_edge = dense_edge # Run GNN layers atom_hids = [] bond_hids = [] for _ in range(self.num_gnn_layers): h_atom, h_dense_edge = modules[m_idx](h_atom, edge_index, h_dense_edge, dense_index, atom_mask, adj_mask, temb) m_idx += 1 atom_hids.append(modules[m_idx](h_atom.reshape(x_atom.shape))) m_idx += 1 bond_hids.append(modules[m_idx](h_dense_edge)) m_idx += 1 atom_hids = torch.cat(atom_hids, dim=-1) bond_hids = torch.cat(bond_hids, dim=-1) # Output atom_score = self.act(modules[m_idx](torch.cat([atom_cate, atom_hids], dim=-1))) \ * atom_mask.unsqueeze(-1) m_idx += 1 atom_score = self.act(modules[m_idx](atom_score)) m_idx += 1 atom_score = modules[m_idx](atom_score) m_idx += 1 bond_score = self.act(modules[m_idx](torch.cat([dense_cate, bond_hids], dim=-1).permute(0, 3, 1, 2))) \ * bond_mask m_idx += 1 bond_score = self.act(modules[m_idx](bond_score)) m_idx += 1 bond_score = modules[m_idx](bond_score) m_idx += 1 exist_score = self.act(modules[m_idx](torch.cat([dense_exist, bond_hids], dim=-1).permute(0, 3, 1, 2))) \ * bond_mask m_idx += 1 exist_score = self.act(modules[m_idx](exist_score)) m_idx += 1 exist_score = modules[m_idx](exist_score) m_idx += 1 # make score symmetric bond_score = torch.cat([bond_score, exist_score], dim=1) bond_score = (bond_score + bond_score.transpose(2, 3)) / 2. assert m_idx == len(modules) atom_score = atom_score * atom_mask.unsqueeze(-1) bond_score = bond_score * bond_mask return atom_score, bond_score
7,728
35.116822
114
py
CDGS
CDGS-main/models/utils.py
"""All functions and modules related to model definition. """ import torch import sde_lib import numpy as np from torch_scatter import scatter_min, scatter_max, scatter_mean, scatter_std _MODELS = {} def register_model(cls=None, *, name=None): """A decorator for registering model classes.""" def _register(cls): if name is None: local_name = cls.__name__ else: local_name = name if local_name in _MODELS: raise ValueError(f'Already registered model with name: {local_name}') _MODELS[local_name] = cls return cls if cls is None: return _register else: return _register(cls) def get_model(name): return _MODELS[name] def create_model(config): """Create the score model.""" model_name = config.model.name score_model = get_model(model_name)(config) score_model = score_model.to(config.device) score_model = torch.nn.DataParallel(score_model) return score_model def get_model_fn(model, train=False): """Create a function to give the output of the score-based model. Args: model: The score model. train: `True` for training and `False` for evaluation. Returns: A model function. """ def model_fn(x, labels, *args, **kwargs): """Compute the output of the score-based model. Args: x: A mini-batch of input data (Adjacency matrices). labels: A mini-batch of conditioning variables for time steps. Should be interpreted differently for different models. mask: Mask for adjacency matrices. Returns: A tuple of (model output, new mutable states) """ if not train: model.eval() return model(x, labels, *args, **kwargs) else: model.train() return model(x, labels, *args, **kwargs) return model_fn def get_multi_score_fn(atom_sde, bond_sde, model, train=False, continuous=False): """Wraps `score_fn` so that the model output corresponds to a real time-dependent score function. Args: atom_sde: An `sde_lib.SDE` object that represents the forward SDE. bond_sde: An `sde_lib.SDE` object that represents the forward SDE. model: A score model. train: `True` for training and `False` for evaluation. continuous: If `True`, the score-based model is expected to directly take continuous time steps. Returns: A score function. """ model_fn = get_model_fn(model, train=train) if isinstance(atom_sde, sde_lib.VPSDE) or isinstance(atom_sde, sde_lib.subVPSDE): def score_fn(x, t, *args, **kwargs): # Scale neural network output by standard deviation and flip sign if continuous or isinstance(sde, sde_lib.subVPSDE): # For VP-trained models, t=0 corresponds to the lowest noise level # The maximum value of time embedding is assumed to 999 for continuously-trained models. labels = t * 999 atom_score, bond_score = model_fn(x, labels, *args, **kwargs) atom_std = atom_sde.marginal_prob(torch.zeros_like(x[0]), t)[1] bond_std = bond_sde.marginal_prob(torch.zeros_like(x[1]), t)[1] else: # For VP-trained models, t=0 corresponds to the lowest noise level labels = t * (sde.N - 1) atom_score, bond_score = model_fn(x, labels, *args, **kwargs) atom_std = atom_sde.sqrt_1m_alpha_cumprod.to(labels.device)[labels.long()] bond_std = bond_sde.sqrt_1m_alpha_cumprod.to(labels.device)[labels.long()] atom_score = -atom_score / atom_std[:, None, None] bond_score = -bond_score / bond_std[:, None, None, None] return atom_score, bond_score else: raise NotImplementedError(f"SDE class {sde.__class__.__name__} not yet supported.") return score_fn def get_multi_theta_fn(atom_sde, bond_sde, model, train=False, continuous=False): """Wraps `theta_fn` so that the model output corresponds to a real time-dependent score function. Args: atom_sde: An `sde_lib.SDE` object that represents the forward SDE. bond_sde: An `sde_lib.SDE` object that represents the forward SDE. model: A score model. train: `True` for training and `False` for evaluation. continuous: If `True`, the score-based model is expected to directly take continuous time steps. Returns: A theta function. """ model_fn = get_model_fn(model, train=train) if isinstance(atom_sde, sde_lib.VPSDE) or isinstance(atom_sde, sde_lib.subVPSDE): def theta_fn(x, t, *args, **kwargs): # Scale neural network output by standard deviation and flip sign if continuous or isinstance(sde, sde_lib.subVPSDE): # For VP-trained models, t=0 corresponds to the lowest noise level # The maximum value of time embedding is assumed to 999 for continuously-trained models. labels = t * 999 atom_theta, bond_theta = model_fn(x, labels, *args, **kwargs) else: raise NotImplementedError() return atom_theta, bond_theta else: raise NotImplementedError(f"SDE class {sde.__class__.__name__} not yet supported.") return theta_fn def get_mol_regressor_grad_fn(atom_sde, bond_sde, regressor_fn, norm=False): """Get the noise graph regressor gradient fn.""" N = atom_sde.N - 1 def mol_regressor_grad_fn(x, t, only_grad=False, std=False, *args, **kwargs): label = t * N atom_std = atom_sde.marginal_prob(torch.zeros_like(x[0]), t)[1] bond_std = bond_sde.marginal_prob(torch.zeros_like(x[1]), t)[1] with torch.enable_grad(): atom_in, bond_in = x atom_in = atom_in.detach().requires_grad_(True) bond_in = bond_in.detach().requires_grad_(True) pred = regressor_fn((atom_in, bond_in), label, *args, **kwargs) try: atom_grad, bond_grad = torch.autograd.grad(pred.sum(), [atom_in, bond_in]) except: print('WARNING: grad error!') atom_grad = torch.zeros_like(atom_in) bond_grad = torch.zeros_like(bond_in) # multiply mask, std atom_grad = atom_grad * kwargs['atom_mask'].unsqueeze(-1) bond_grad = bond_grad * kwargs['bond_mask'] if only_grad: if std: return atom_grad, bond_grad, atom_std, bond_std return atom_grad, bond_grad atom_norm = torch.norm(atom_grad.reshape(atom_grad.shape[0], -1), dim=-1) bond_norm = torch.norm(bond_grad.reshape(bond_grad.shape[0], -1), dim=-1) if norm: atom_grad = atom_grad / (atom_norm + 1e-8)[:, None, None] bond_grad = bond_grad / (bond_norm + 1e-8)[:, None, None, None] atom_grad = - atom_std[:, None, None] * atom_grad bond_grad = - bond_std[:, None, None, None] * bond_grad return atom_grad, bond_grad return mol_regressor_grad_fn def get_guided_theta_fn(theta_fn, regressor_grad_fn, guidance_scale=1.0): """theta function with gradient guidance.""" def guided_theta_fn(x, t, *args, **kwargs): atom_theta, bond_theta = theta_fn(x, t, *args, **kwargs) atom_grad, bond_grad = regressor_grad_fn(x, t, *args, **kwargs) # atom_grad, bond_grad, atom_norm, bond_norm, atom_std, bond_std = regressor_grad_fn(x, t, True, *args, **kwargs) # atom_score = - atom_theta / atom_std[:, None, None] # atom_score_norm = torch.norm(atom_score.reshape(atom_score.shape[0], -1), dim=-1) # bond_score = - bond_theta / bond_std[:, None, None, None] # bond_score_norm = torch.norm(bond_score.reshape(bond_score.shape[0], -1), dim=-1) # atom_grad = - atom_std[:, None, None] * atom_grad * atom_score_norm[:, None, None] / (atom_norm + 1e-8)[:, None, None] # bond_grad = - bond_std[:, None, None, None] * bond_grad * bond_score_norm[:, None, None, None] / (bond_norm + 1e-8)[:, None, None, None] return atom_theta + atom_grad * guidance_scale, bond_theta + bond_grad * guidance_scale return guided_theta_fn def get_theta_fn(sde, model, train=False, continuous=False): model_fn = get_model_fn(model, train=train) if isinstance(sde, sde_lib.VPSDE) or isinstance(sde, sde_lib.subVPSDE): def theta_fn(x, t, *args, **kwargs): # Scale neural network output by standard deviation and flip sign if continuous or isinstance(sde, sde_lib.subVPSDE): # For VP-trained models, t=0 corresponds to the lowest noise level # The maximum value of time embedding is assumed to 999 for continuously-trained models. labels = t * 999 theta = model_fn(x, labels, *args, **kwargs) else: raise NotImplementedError() return theta else: raise NotImplementedError(f"SDE class {sde.__class__.__name__} not yet supported.") return theta_fn @torch.no_grad() def get_rw_feat(k_step, dense_adj): """Compute k_step Random Walk for given dense adjacency matrix.""" rw_list = [] deg = dense_adj.sum(-1, keepdims=True) AD = dense_adj / (deg + 1e-8) rw_list.append(AD) for _ in range(k_step): rw = torch.bmm(rw_list[-1], AD) rw_list.append(rw) rw_map = torch.stack(rw_list[1:], dim=1) # [B, k_step, N, N] rw_landing = torch.diagonal(rw_map, offset=0, dim1=2, dim2=3) # [B, k_step, N] rw_landing = rw_landing.permute(0, 2, 1) # [B, N, rw_depth] # get the shortest path distance indices tmp_rw = rw_map.sort(dim=1)[0] spd_ind = (tmp_rw <= 0).sum(dim=1) # [B, N, N] spd_onehot = torch.nn.functional.one_hot(spd_ind, num_classes=k_step+1).to(torch.float) spd_onehot = spd_onehot.permute(0, 3, 1, 2) # [B, kstep, N, N] return rw_landing, spd_onehot
10,204
38.099617
146
py
CDGS
CDGS-main/models/transformer_layers.py
import math from typing import Union, Tuple, Optional from torch_geometric.typing import PairTensor, Adj, OptTensor import torch import torch.nn as nn from torch import Tensor import torch.nn.functional as F from torch.nn import Linear from torch_scatter import scatter from torch_geometric.nn.conv import MessagePassing from torch_geometric.utils import softmax class EdgeGateTransLayer(MessagePassing): """The version of edge feature gating.""" _alpha: OptTensor def __init__(self, x_channels: int, out_channels: int, heads: int = 1, dropout: float = 0., edge_dim: Optional[int] = None, bias: bool = True, **kwargs): kwargs.setdefault('aggr', 'add') super(EdgeGateTransLayer, self).__init__(node_dim=0, **kwargs) self.x_channels = x_channels self.in_channels = in_channels = x_channels self.out_channels = out_channels self.heads = heads self.dropout = dropout self.edge_dim = edge_dim self.lin_key = Linear(in_channels, heads * out_channels, bias=bias) self.lin_query = Linear(in_channels, heads * out_channels, bias=bias) self.lin_value = Linear(in_channels, heads * out_channels, bias=bias) self.lin_edge0 = Linear(edge_dim, heads * out_channels, bias=False) self.lin_edge1 = Linear(edge_dim, heads * out_channels, bias=False) self.reset_parameters() def reset_parameters(self): self.lin_key.reset_parameters() self.lin_query.reset_parameters() self.lin_value.reset_parameters() self.lin_edge0.reset_parameters() self.lin_edge1.reset_parameters() def forward(self, x: OptTensor, edge_index: Adj, edge_attr: OptTensor = None ) -> Tensor: """""" H, C = self.heads, self.out_channels x_feat = x query = self.lin_query(x_feat).view(-1, H, C) key = self.lin_key(x_feat).view(-1, H, C) value = self.lin_value(x_feat).view(-1, H, C) # propagate_type: (x: PairTensor, edge_attr: OptTensor) out_x = self.propagate(edge_index, query=query, key=key, value=value, edge_attr=edge_attr, size=None) out_x = out_x.view(-1, self.heads * self.out_channels) return out_x def message(self, query_i: Tensor, key_j: Tensor, value_j: Tensor, edge_attr: OptTensor, index: Tensor, ptr: OptTensor, size_i: Optional[int]) -> Tuple[Tensor, Tensor]: edge_attn = self.lin_edge0(edge_attr).view(-1, self.heads, self.out_channels) edge_attn = torch.tanh(edge_attn) alpha = (query_i * key_j * edge_attn).sum(dim=-1) / math.sqrt(self.out_channels) alpha = softmax(alpha, index, ptr, size_i) alpha = F.dropout(alpha, p=self.dropout, training=self.training) # node feature message msg = value_j msg = msg * torch.tanh(self.lin_edge1(edge_attr).view(-1, self.heads, self.out_channels)) msg = msg * alpha.view(-1, self.heads, 1) return msg def __repr__(self): return '{}({}, {}, heads={})'.format(self.__class__.__name__, self.in_channels, self.out_channels, self.heads)
3,328
35.184783
109
py
CDGS
CDGS-main/models/layers.py
"""Common layers for defining score networks.""" import torch.nn as nn import torch import torch.nn.functional as F import numpy as np import math import torch_geometric.nn as graph_nn def get_act(config): """Get actiuvation functions from the config file.""" if config.model.nonlinearity.lower() == 'elu': return nn.ELU() elif config.model.nonlinearity.lower() == 'relu': return nn.ReLU() elif config.model.nonlinearity.lower() == 'lrelu': return nn.LeakyReLU(negative_slope=0.2) elif config.model.nonlinearity.lower() == 'swish': return nn.SiLU() elif config.model.nonlinearity.lower() == 'tanh': return nn.Tanh() else: raise NotImplementedError('activation function does not exist!') def conv1x1(in_planes, out_planes, stride=1, bias=True, dilation=1, padding=0): conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=bias, dilation=dilation, padding=padding) return conv # from DDPM def get_timestep_embedding(timesteps, embedding_dim, max_positions=10000): assert len(timesteps.shape) == 1 half_dim = embedding_dim // 2 # magic number 10000 is from transformers emb = math.log(max_positions) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.float32, device=timesteps.device) * -emb) emb = timesteps.float()[:, None] * emb[None, :] emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) if embedding_dim % 2 == 1: # zero pad emb = F.pad(emb, (0, 1), mode='constant') assert emb.shape == (timesteps.shape[0], embedding_dim) return emb
1,641
33.93617
103
py
CDGS
CDGS-main/models/ema.py
import torch class ExponentialMovingAverage: """ Maintains (exponential) moving average of a set of parameters. """ def __init__(self, parameters, decay, use_num_updates=True): """ Args: parameters: Iterable of `torch.nn.Parameter`; usually the result of `model.parameters()`. decay: The exponential decay. use_num_updates: Whether to use number of updates when computing averages. """ if decay < 0.0 or decay > 1.0: raise ValueError('Decay must be between 0 and 1') self.decay = decay self.num_updates = 0 if use_num_updates else None self.shadow_params = [p.clone().detach() for p in parameters if p.requires_grad] self.collected_params = [] def update(self, parameters): """ Update currently maintained parameters. Call this every time the parameters are updated, such as the result of the `optimizer.step()` call. Args: parameters: Iterable of `torch.nn.Parameter`; usually the same set of parameters used to initialize this object. """ decay = self.decay if self.num_updates is not None: self.num_updates += 1 decay = min(decay, (1 + self.num_updates) / (10 + self.num_updates)) one_minus_decay = 1.0 - decay with torch.no_grad(): parameters = [p for p in parameters if p.requires_grad] for s_param, param in zip(self.shadow_params, parameters): s_param.sub_(one_minus_decay * (s_param - param)) def copy_to(self, parameters): """ Copy current parameters into given collection of parameters. Args: parameters: Iterable of `torch.nn.Parameter`; the parameters to be updated with the stored moving averages. """ parameters = [p for p in parameters if p.requires_grad] for s_param, param in zip(self.shadow_params, parameters): if param.requires_grad: param.data.copy_(s_param.data) def store(self, parameters): """ Save the current parameters for restoring later. Args: parameters: Iterable of `torch.nn.Parameter`; the parameters to be temporarily stored. """ self.collected_params = [param.clone() for param in parameters] def restore(self, parameters): """ Restore the parameters stored with the `store` method. Useful to validate the model with EMA parameters without affecting the original optimization process. Store the parameters before the `copy_to` method. After validation (or model saving), use this to restore the former parameters. Args: parameters: Iterable of `torch.nn.Parameter`; the parameters to be updated with the stored parameters. """ for c_param, param in zip(self.collected_params, parameters): param.data.copy_(c_param.data) def state_dict(self): return dict(decay=self.decay, num_updates=self.num_updates, shadow_params=self.shadow_params) def load_state_dict(self, state_dict): self.decay = state_dict['decay'] self.num_updates = state_dict['num_updates'] self.shadow_params = state_dict['shadow_params']
3,373
38.232558
114
py
CDGS
CDGS-main/models/hmpb.py
import numpy as np import torch import math import torch.nn as nn import torch.nn.functional as F import torch_geometric.nn as pygnn from torch_geometric.nn import Linear as Linear_pyg from torch_geometric.utils import dense_to_sparse from .transformer_layers import EdgeGateTransLayer class HybridMPBlock(nn.Module): """Local MPNN + fully-connected attention-based message passing layer. Inspired by GPSLayer.""" def __init__(self, dim_h, local_gnn_type, global_model_type, num_heads, temb_dim=None, act=None, dropout=0.0, attn_dropout=0.0): super().__init__() self.dim_h = dim_h self.num_heads = num_heads self.attn_dropout = attn_dropout self.local_gnn_type = local_gnn_type self.global_model_type = global_model_type if act is None: self.act = nn.ReLU() else: self.act = act # time embedding if temb_dim is not None: self.t_node = nn.Linear(temb_dim, dim_h) self.t_edge = nn.Linear(temb_dim, dim_h) # local message-passing model if local_gnn_type == 'None': self.local_model = None elif local_gnn_type == 'GINE': gin_nn = nn.Sequential(Linear_pyg(dim_h, dim_h), nn.ReLU(), Linear_pyg(dim_h, dim_h)) self.local_model = pygnn.GINEConv(gin_nn) elif local_gnn_type == 'GAT': self.local_model = pygnn.GATConv(in_channels=dim_h, out_channels=dim_h // num_heads, heads=num_heads, edge_dim=dim_h) elif local_gnn_type == 'LocalTrans_1': self.local_model = EdgeGateTransLayer(dim_h, dim_h // num_heads, num_heads, edge_dim=dim_h) else: raise ValueError(f"Unsupported local GNN model: {local_gnn_type}") # Global attention transformer-style model. if global_model_type == 'None': self.self_attn = None elif global_model_type == 'FullTrans_1': self.self_attn = EdgeGateTransLayer(dim_h, dim_h // num_heads, num_heads, edge_dim=dim_h) else: raise ValueError(f"Unsupported global x-former model: " f"{global_model_type}") # Normalization for MPNN and Self-Attention representations. self.norm1_local = nn.GroupNorm(num_groups=min(dim_h // 4, 32), num_channels=dim_h, eps=1e-6) self.norm1_attn = nn.GroupNorm(num_groups=min(dim_h // 4, 32), num_channels=dim_h, eps=1e-6) self.dropout = nn.Dropout(dropout) # Feed Forward block -> node. self.ff_linear1 = nn.Linear(dim_h, dim_h * 2) self.ff_linear2 = nn.Linear(dim_h * 2, dim_h) self.norm2_node = nn.GroupNorm(num_groups=min(dim_h // 4, 32), num_channels=dim_h, eps=1e-6) # Feed Forward block -> edge. self.ff_linear3 = nn.Linear(dim_h, dim_h * 2) self.ff_linear4 = nn.Linear(dim_h * 2, dim_h) self.norm2_edge = nn.GroupNorm(num_groups=min(dim_h // 4, 32), num_channels=dim_h, eps=1e-6) def _ff_block_node(self, x): """Feed Forward block. """ x = self.dropout(self.act(self.ff_linear1(x))) return self.dropout(self.ff_linear2(x)) def _ff_block_edge(self, x): """Feed Forward block. """ x = self.dropout(self.act(self.ff_linear3(x))) return self.dropout(self.ff_linear4(x)) def forward(self, x, edge_index, dense_edge, dense_index, node_mask, adj_mask, temb=None): """ Args: x: node feature [B*N, dim_h] edge_index: [2, edge_length] dense_edge: edge features in dense form [B, N, N, dim_h] dense_index: indices for valid edges [B, N, N, 1] node_mask: [B, N] adj_mask: [B, N, N, 1] temb: time conditional embedding [B, temb_dim] Returns: h edge """ B, N, _, _ = dense_edge.shape h_in1 = x h_in2 = dense_edge if temb is not None: h_edge = (dense_edge + self.t_edge(self.act(temb))[:, None, None, :]) * adj_mask temb = temb.unsqueeze(1).repeat(1, N, 1) temb = temb.reshape(-1, temb.size(-1)) h = (x + self.t_node(self.act(temb))) * node_mask.reshape(-1, 1) h_out_list = [] # Local MPNN with edge attributes if self.local_model is not None: edge_attr = h_edge[dense_index] h_local = self.local_model(h, edge_index, edge_attr) * node_mask.reshape(-1, 1) h_local = h_in1 + self.dropout(h_local) h_local = self.norm1_local(h_local) h_out_list.append(h_local) # Multi-head attention if self.self_attn is not None: if 'FullTrans' in self.global_model_type: # extract full connect edge_index and edge_attr dense_index_full = adj_mask.squeeze(-1).nonzero(as_tuple=True) edge_index_full, _ = dense_to_sparse(adj_mask.squeeze(-1)) edge_attr_full = h_edge[dense_index_full] h_attn = self.self_attn(h, edge_index_full, edge_attr_full) else: raise ValueError(f"Unsupported global transformer layer") h_attn = h_in1 + self.dropout(h_attn) h_attn = self.norm1_attn(h_attn) h_out_list.append(h_attn) # Combine local and global outputs assert len(h_out_list) > 0 h = sum(h_out_list) * node_mask.reshape(-1, 1) h_dense = h.reshape(B, N, -1) h_edge = h_dense.unsqueeze(1) + h_dense.unsqueeze(2) # Feed Forward block h = h + self._ff_block_node(h) h = self.norm2_node(h) * node_mask.reshape(-1, 1) h_edge = h_in2 + self._ff_block_edge(h_edge) h_edge = self.norm2_edge(h_edge.permute(0, 3, 1, 2)).permute(0, 2, 3, 1) * adj_mask return h, h_edge
6,040
38.743421
103
py
CDGS
CDGS-main/configs/vp_zinc_cdgs.py
"""Training GNN on ZINC250k with continuous VPSDE.""" import ml_collections import torch def get_config(): config = ml_collections.ConfigDict() config.model_type = 'mol_sde' # training config.training = training = ml_collections.ConfigDict() training.sde = 'vpsde' training.continuous = True training.reduce_mean = False training.batch_size = 64 training.eval_batch_size = 64 training.n_iters = 2000000 training.snapshot_freq = 5000 # SET Larger values to save less checkpoints training.log_freq = 200 training.eval_freq = 5000 ## store additional checkpoints for preemption training.snapshot_freq_for_preemption = 2000 ## produce samples at each snapshot. training.snapshot_sampling = True training.likelihood_weighting = False # sampling config.sampling = sampling = ml_collections.ConfigDict() sampling.method = 'pc' sampling.predictor = 'euler_maruyama' sampling.corrector = 'none' sampling.rtol = 1e-5 sampling.atol = 1e-5 sampling.ode_method = 'rk4' sampling.ode_step = 0.01 sampling.n_steps_each = 1 sampling.noise_removal = True sampling.probability_flow = False sampling.atom_snr = 0.16 sampling.bond_snr = 0.16 sampling.vis_row = 4 sampling.vis_col = 4 # evaluation config.eval = evaluate = ml_collections.ConfigDict() evaluate.begin_ckpt = 15 evaluate.end_ckpt = 40 evaluate.batch_size = 2000 # 1024 evaluate.enable_sampling = True evaluate.num_samples = 10000 evaluate.mmd_distance = 'RBF' evaluate.max_subgraph = False evaluate.save_graph = False evaluate.nn_eval = False evaluate.nspdk = False # data config.data = data = ml_collections.ConfigDict() data.centered = True data.dequantization = False data.root = 'data' data.name = 'ZINC250K' data.split_ratio = 0.8 data.max_node = 38 data.atom_channels = 9 data.bond_channels = 2 data.atom_list = [6, 7, 8, 9, 15, 16, 17, 35, 53] data.norm = (0.5, 1.0) # model config.model = model = ml_collections.ConfigDict() model.name = 'CDGS' model.ema_rate = 0.9999 model.normalization = 'GroupNorm' model.nonlinearity = 'swish' model.nf = 256 model.num_gnn_layers = 10 model.conditional = True model.embedding_type = 'positional' model.rw_depth = 20 model.graph_layer = 'GINE' model.edge_th = -1. model.heads = 8 model.dropout = 0.1 model.num_scales = 1000 # SDE total steps (N) model.sigma_min = 0.01 model.sigma_max = 50 model.node_beta_min = 0.1 model.node_beta_max = 20. model.edge_beta_min = 0.1 model.edge_beta_max = 20. # optimization config.optim = optim = ml_collections.ConfigDict() optim.weight_decay = 0 optim.optimizer = 'Adam' optim.lr = 1e-4 optim.beta1 = 0.9 optim.eps = 1e-8 optim.warmup = 1000 optim.grad_clip = 1. # SET Larger values to converge faster, e.g., 10. config.seed = 42 config.device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu') return config
3,149
26.876106
96
py
CDGS
CDGS-main/configs/vp_qm9_cdgs.py
"""Training GNN on QM9 with continuous VPSDE.""" import ml_collections import torch def get_config(): config = ml_collections.ConfigDict() config.model_type = 'mol_sde' # training config.training = training = ml_collections.ConfigDict() training.sde = 'vpsde' training.continuous = True training.reduce_mean = False training.batch_size = 128 training.eval_batch_size = 512 training.n_iters = 1000000 training.snapshot_freq = 5000 # SET Larger values to save less checkpoints training.log_freq = 200 training.eval_freq = 5000 ## store additional checkpoints for preemption training.snapshot_freq_for_preemption = 2000 ## produce samples at each snapshot. training.snapshot_sampling = True training.likelihood_weighting = False # sampling config.sampling = sampling = ml_collections.ConfigDict() sampling.method = 'pc' sampling.predictor = 'euler_maruyama' sampling.corrector = 'none' sampling.rtol = 1e-5 sampling.atol = 1e-5 sampling.ode_method = 'rk4' sampling.ode_step = 0.01 sampling.n_steps_each = 1 sampling.noise_removal = True sampling.probability_flow = False sampling.atom_snr = 0.16 sampling.bond_snr = 0.16 sampling.vis_row = 4 sampling.vis_col = 4 # evaluation config.eval = evaluate = ml_collections.ConfigDict() evaluate.begin_ckpt = 15 evaluate.end_ckpt = 40 evaluate.batch_size = 10000 # 1024 evaluate.enable_sampling = True evaluate.num_samples = 10000 evaluate.mmd_distance = 'RBF' evaluate.max_subgraph = False evaluate.save_graph = False evaluate.nn_eval = False evaluate.nspdk = False # data config.data = data = ml_collections.ConfigDict() data.centered = True data.dequantization = False data.root = 'data' data.name = 'QM9' data.split_ratio = 0.8 data.max_node = 9 data.atom_channels = 4 data.bond_channels = 2 data.atom_list = [6, 7, 8, 9] data.norm = (0.5, 1.0) # model config.model = model = ml_collections.ConfigDict() model.name = 'CDGS' model.ema_rate = 0.9999 model.normalization = 'GroupNorm' model.nonlinearity = 'swish' model.nf = 64 model.num_gnn_layers = 6 model.conditional = True model.embedding_type = 'positional' model.rw_depth = 8 model.graph_layer = 'GINE' model.edge_th = -1. model.heads = 8 model.dropout = 0.1 model.num_scales = 1000 # SDE total steps (N) model.sigma_min = 0.01 model.sigma_max = 50 model.node_beta_min = 0.1 model.node_beta_max = 20. model.edge_beta_min = 0.1 model.edge_beta_max = 20. # optimization config.optim = optim = ml_collections.ConfigDict() optim.weight_decay = 0 optim.optimizer = 'Adam' optim.lr = 1e-4 optim.beta1 = 0.9 optim.eps = 1e-8 optim.warmup = 1000 optim.grad_clip = 1. # SET Larger values to converge faster, e.g., 10. config.seed = 42 config.device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu') return config
3,118
26.60177
96
py
pubmed_parser
pubmed_parser-master/docs/conf.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) import sys import os import sphinx import pubmed_parser import sphinx_gallery # -- Project information ----------------------------------------------------- project = 'Pubmed Parser' copyright = '2020, Titipat Achakulvisut' author = 'Titipat Achakulvisut' version = pubmed_parser.__version__ release = pubmed_parser.__version__ # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx.ext.autosummary', 'sphinx.ext.doctest' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = []
2,161
32.261538
79
py
crpn
crpn-master/tools/compress_net.py
#!/usr/bin/env python # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Compress a Fast R-CNN network using truncated SVD.""" import _init_paths import caffe import argparse import numpy as np import os, sys def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Compress a Fast R-CNN network') parser.add_argument('--def', dest='prototxt', help='prototxt file defining the uncompressed network', default=None, type=str) parser.add_argument('--def-svd', dest='prototxt_svd', help='prototxt file defining the SVD compressed network', default=None, type=str) parser.add_argument('--net', dest='caffemodel', help='model to compress', default=None, type=str) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args def compress_weights(W, l): """Compress the weight matrix W of an inner product (fully connected) layer using truncated SVD. Parameters: W: N x M weights matrix l: number of singular values to retain Returns: Ul, L: matrices such that W \approx Ul*L """ # numpy doesn't seem to have a fast truncated SVD algorithm... # this could be faster U, s, V = np.linalg.svd(W, full_matrices=False) Ul = U[:, :l] sl = s[:l] Vl = V[:l, :] L = np.dot(np.diag(sl), Vl) return Ul, L def main(): args = parse_args() # prototxt = 'models/VGG16/test.prototxt' # caffemodel = 'snapshots/vgg16_fast_rcnn_iter_40000.caffemodel' net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST) # prototxt_svd = 'models/VGG16/svd/test_fc6_fc7.prototxt' # caffemodel = 'snapshots/vgg16_fast_rcnn_iter_40000.caffemodel' net_svd = caffe.Net(args.prototxt_svd, args.caffemodel, caffe.TEST) print('Uncompressed network {} : {}'.format(args.prototxt, args.caffemodel)) print('Compressed network prototxt {}'.format(args.prototxt_svd)) out = os.path.splitext(os.path.basename(args.caffemodel))[0] + '_svd' out_dir = os.path.dirname(args.caffemodel) # Compress fc6 if net_svd.params.has_key('fc6_L'): l_fc6 = net_svd.params['fc6_L'][0].data.shape[0] print(' fc6_L bottleneck size: {}'.format(l_fc6)) # uncompressed weights and biases W_fc6 = net.params['fc6'][0].data B_fc6 = net.params['fc6'][1].data print(' compressing fc6...') Ul_fc6, L_fc6 = compress_weights(W_fc6, l_fc6) assert(len(net_svd.params['fc6_L']) == 1) # install compressed matrix factors (and original biases) net_svd.params['fc6_L'][0].data[...] = L_fc6 net_svd.params['fc6_U'][0].data[...] = Ul_fc6 net_svd.params['fc6_U'][1].data[...] = B_fc6 out += '_fc6_{}'.format(l_fc6) # Compress fc7 if net_svd.params.has_key('fc7_L'): l_fc7 = net_svd.params['fc7_L'][0].data.shape[0] print ' fc7_L bottleneck size: {}'.format(l_fc7) W_fc7 = net.params['fc7'][0].data B_fc7 = net.params['fc7'][1].data print(' compressing fc7...') Ul_fc7, L_fc7 = compress_weights(W_fc7, l_fc7) assert(len(net_svd.params['fc7_L']) == 1) net_svd.params['fc7_L'][0].data[...] = L_fc7 net_svd.params['fc7_U'][0].data[...] = Ul_fc7 net_svd.params['fc7_U'][1].data[...] = B_fc7 out += '_fc7_{}'.format(l_fc7) filename = '{}/{}.caffemodel'.format(out_dir, out) net_svd.save(filename) print 'Wrote svd model to: {:s}'.format(filename) if __name__ == '__main__': main()
3,918
30.103175
81
py
crpn
crpn-master/tools/train_faster_rcnn_alt_opt.py
#!/usr/bin/env python # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Train a Faster R-CNN network using alternating optimization. This tool implements the alternating optimization algorithm described in our NIPS 2015 paper ("Faster R-CNN: Towards Real-time Object Detection with Region Proposal Networks." Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun.) """ import _init_paths from fast_rcnn.train import get_training_roidb, train_net from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list, get_output_dir from datasets.factory import get_imdb from rpn.generate import imdb_proposals import argparse import pprint import numpy as np import sys, os import multiprocessing as mp import cPickle import shutil def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a Faster R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--net_name', dest='net_name', help='network name (e.g., "ZF")', default=None, type=str) parser.add_argument('--weights', dest='pretrained_model', help='initialize with pretrained model weights', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to train on', default='voc_2007_trainval', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args def get_roidb(imdb_name, rpn_file=None): imdb = get_imdb(imdb_name) print 'Loaded dataset `{:s}` for training'.format(imdb.name) imdb.set_proposal_method(cfg.TRAIN.PROPOSAL_METHOD) print 'Set proposal method: {:s}'.format(cfg.TRAIN.PROPOSAL_METHOD) if rpn_file is not None: imdb.config['rpn_file'] = rpn_file roidb = get_training_roidb(imdb) return roidb, imdb def get_solvers(net_name): # Faster R-CNN Alternating Optimization n = 'faster_rcnn_alt_opt' # Solver for each training stage solvers = [[net_name, n, 'stage1_rpn_solver60k80k.pt'], [net_name, n, 'stage1_fast_rcnn_solver30k40k.pt'], [net_name, n, 'stage2_rpn_solver60k80k.pt'], [net_name, n, 'stage2_fast_rcnn_solver30k40k.pt']] solvers = [os.path.join(cfg.MODELS_DIR, *s) for s in solvers] # Iterations for each training stage max_iters = [80000, 40000, 80000, 40000] # max_iters = [100, 100, 100, 100] # Test prototxt for the RPN rpn_test_prototxt = os.path.join( cfg.MODELS_DIR, net_name, n, 'rpn_test.pt') return solvers, max_iters, rpn_test_prototxt # ------------------------------------------------------------------------------ # Pycaffe doesn't reliably free GPU memory when instantiated nets are discarded # (e.g. "del net" in Python code). To work around this issue, each training # stage is executed in a separate process using multiprocessing.Process. # ------------------------------------------------------------------------------ def _init_caffe(cfg): """Initialize pycaffe in a training process. """ import caffe # fix the random seeds (numpy and caffe) for reproducibility np.random.seed(cfg.RNG_SEED) caffe.set_random_seed(cfg.RNG_SEED) # set up caffe caffe.set_mode_gpu() caffe.set_device(cfg.GPU_ID) def train_rpn(queue=None, imdb_name=None, init_model=None, solver=None, max_iters=None, cfg=None): """Train a Region Proposal Network in a separate training process. """ # Not using any proposals, just ground-truth boxes cfg.TRAIN.HAS_RPN = True cfg.TRAIN.BBOX_REG = False # applies only to Fast R-CNN bbox regression cfg.TRAIN.PROPOSAL_METHOD = 'gt' cfg.TRAIN.IMS_PER_BATCH = 1 print 'Init model: {}'.format(init_model) print('Using config:') pprint.pprint(cfg) import caffe _init_caffe(cfg) roidb, imdb = get_roidb(imdb_name) print 'roidb len: {}'.format(len(roidb)) output_dir = get_output_dir(imdb) print 'Output will be saved to `{:s}`'.format(output_dir) model_paths = train_net(solver, roidb, output_dir, pretrained_model=init_model, max_iters=max_iters) # Cleanup all but the final model for i in model_paths[:-1]: os.remove(i) rpn_model_path = model_paths[-1] # Send final model path through the multiprocessing queue queue.put({'model_path': rpn_model_path}) def rpn_generate(queue=None, imdb_name=None, rpn_model_path=None, cfg=None, rpn_test_prototxt=None): """Use a trained RPN to generate proposals. """ cfg.TEST.RPN_PRE_NMS_TOP_N = -1 # no pre NMS filtering cfg.TEST.RPN_POST_NMS_TOP_N = 2000 # limit top boxes after NMS print 'RPN model: {}'.format(rpn_model_path) print('Using config:') pprint.pprint(cfg) import caffe _init_caffe(cfg) # NOTE: the matlab implementation computes proposals on flipped images, too. # We compute them on the image once and then flip the already computed # proposals. This might cause a minor loss in mAP (less proposal jittering). imdb = get_imdb(imdb_name) print 'Loaded dataset `{:s}` for proposal generation'.format(imdb.name) # Load RPN and configure output directory rpn_net = caffe.Net(rpn_test_prototxt, rpn_model_path, caffe.TEST) output_dir = get_output_dir(imdb) print 'Output will be saved to `{:s}`'.format(output_dir) # Generate proposals on the imdb rpn_proposals = imdb_proposals(rpn_net, imdb) # Write proposals to disk and send the proposal file path through the # multiprocessing queue rpn_net_name = os.path.splitext(os.path.basename(rpn_model_path))[0] rpn_proposals_path = os.path.join( output_dir, rpn_net_name + '_proposals.pkl') with open(rpn_proposals_path, 'wb') as f: cPickle.dump(rpn_proposals, f, cPickle.HIGHEST_PROTOCOL) print 'Wrote RPN proposals to {}'.format(rpn_proposals_path) queue.put({'proposal_path': rpn_proposals_path}) def train_fast_rcnn(queue=None, imdb_name=None, init_model=None, solver=None, max_iters=None, cfg=None, rpn_file=None): """Train a Fast R-CNN using proposals generated by an RPN. """ cfg.TRAIN.HAS_RPN = False # not generating prosals on-the-fly cfg.TRAIN.PROPOSAL_METHOD = 'rpn' # use pre-computed RPN proposals instead cfg.TRAIN.IMS_PER_BATCH = 2 print 'Init model: {}'.format(init_model) print 'RPN proposals: {}'.format(rpn_file) print('Using config:') pprint.pprint(cfg) import caffe _init_caffe(cfg) roidb, imdb = get_roidb(imdb_name, rpn_file=rpn_file) output_dir = get_output_dir(imdb) print 'Output will be saved to `{:s}`'.format(output_dir) # Train Fast R-CNN model_paths = train_net(solver, roidb, output_dir, pretrained_model=init_model, max_iters=max_iters) # Cleanup all but the final model for i in model_paths[:-1]: os.remove(i) fast_rcnn_model_path = model_paths[-1] # Send Fast R-CNN model path over the multiprocessing queue queue.put({'model_path': fast_rcnn_model_path}) if __name__ == '__main__': args = parse_args() print('Called with args:') print(args) if args.cfg_file is not None: cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) cfg.GPU_ID = args.gpu_id # -------------------------------------------------------------------------- # Pycaffe doesn't reliably free GPU memory when instantiated nets are # discarded (e.g. "del net" in Python code). To work around this issue, each # training stage is executed in a separate process using # multiprocessing.Process. # -------------------------------------------------------------------------- # queue for communicated results between processes mp_queue = mp.Queue() # solves, iters, etc. for each training stage solvers, max_iters, rpn_test_prototxt = get_solvers(args.net_name) print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Stage 1 RPN, init from ImageNet model' print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' cfg.TRAIN.SNAPSHOT_INFIX = 'stage1' mp_kwargs = dict( queue=mp_queue, imdb_name=args.imdb_name, init_model=args.pretrained_model, solver=solvers[0], max_iters=max_iters[0], cfg=cfg) p = mp.Process(target=train_rpn, kwargs=mp_kwargs) p.start() rpn_stage1_out = mp_queue.get() p.join() print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Stage 1 RPN, generate proposals' print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' mp_kwargs = dict( queue=mp_queue, imdb_name=args.imdb_name, rpn_model_path=str(rpn_stage1_out['model_path']), cfg=cfg, rpn_test_prototxt=rpn_test_prototxt) p = mp.Process(target=rpn_generate, kwargs=mp_kwargs) p.start() rpn_stage1_out['proposal_path'] = mp_queue.get()['proposal_path'] p.join() print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Stage 1 Fast R-CNN using RPN proposals, init from ImageNet model' print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' cfg.TRAIN.SNAPSHOT_INFIX = 'stage1' mp_kwargs = dict( queue=mp_queue, imdb_name=args.imdb_name, init_model=args.pretrained_model, solver=solvers[1], max_iters=max_iters[1], cfg=cfg, rpn_file=rpn_stage1_out['proposal_path']) p = mp.Process(target=train_fast_rcnn, kwargs=mp_kwargs) p.start() fast_rcnn_stage1_out = mp_queue.get() p.join() print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Stage 2 RPN, init from stage 1 Fast R-CNN model' print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' cfg.TRAIN.SNAPSHOT_INFIX = 'stage2' mp_kwargs = dict( queue=mp_queue, imdb_name=args.imdb_name, init_model=str(fast_rcnn_stage1_out['model_path']), solver=solvers[2], max_iters=max_iters[2], cfg=cfg) p = mp.Process(target=train_rpn, kwargs=mp_kwargs) p.start() rpn_stage2_out = mp_queue.get() p.join() print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Stage 2 RPN, generate proposals' print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' mp_kwargs = dict( queue=mp_queue, imdb_name=args.imdb_name, rpn_model_path=str(rpn_stage2_out['model_path']), cfg=cfg, rpn_test_prototxt=rpn_test_prototxt) p = mp.Process(target=rpn_generate, kwargs=mp_kwargs) p.start() rpn_stage2_out['proposal_path'] = mp_queue.get()['proposal_path'] p.join() print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Stage 2 Fast R-CNN, init from stage 2 RPN R-CNN model' print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' cfg.TRAIN.SNAPSHOT_INFIX = 'stage2' mp_kwargs = dict( queue=mp_queue, imdb_name=args.imdb_name, init_model=str(rpn_stage2_out['model_path']), solver=solvers[3], max_iters=max_iters[3], cfg=cfg, rpn_file=rpn_stage2_out['proposal_path']) p = mp.Process(target=train_fast_rcnn, kwargs=mp_kwargs) p.start() fast_rcnn_stage2_out = mp_queue.get() p.join() # Create final model (just a copy of the last stage) final_path = os.path.join( os.path.dirname(fast_rcnn_stage2_out['model_path']), args.net_name + '_faster_rcnn_final.caffemodel') print 'cp {} -> {}'.format( fast_rcnn_stage2_out['model_path'], final_path) shutil.copy(fast_rcnn_stage2_out['model_path'], final_path) print 'Final model: {}'.format(final_path)
12,871
37.423881
80
py
crpn
crpn-master/tools/test_net.py
#!/usr/bin/env python # -------------------------------------------------------- # 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 image database.""" import _init_paths from fast_rcnn.test import test_net from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list from datasets.factory import get_imdb import caffe import argparse import pprint import time, os, sys def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use', default=0, type=int) parser.add_argument('--def', dest='prototxt', help='prototxt file defining the network', default=None, type=str) parser.add_argument('--net', dest='caffemodel', help='model to test', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--wait', dest='wait', help='wait until net file exists', default=True, type=bool) parser.add_argument('--imdb', dest='imdb_name', help='dataset to test', default='voc_2007_test', type=str) parser.add_argument('--comp', dest='comp_mode', help='competition mode', action='store_true') parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) parser.add_argument('--vis', dest='vis', help='visualize detections', action='store_true') parser.add_argument('--num_dets', dest='max_per_image', help='max number of detections per image', default=100, type=int) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() print('Called with args:') print(args) if args.cfg_file is not None: cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) cfg.GPU_ID = args.gpu_id print('Using config:') pprint.pprint(cfg) while not os.path.exists(args.caffemodel) and args.wait: print('Waiting for {} to exist...'.format(args.caffemodel)) time.sleep(10) caffe.set_mode_gpu() caffe.set_device(args.gpu_id) net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST) net.name = os.path.splitext(os.path.basename(args.caffemodel))[0] imdb = get_imdb(args.imdb_name) imdb.competition_mode(args.comp_mode) if not cfg.TEST.HAS_RPN: imdb.set_proposal_method(cfg.TEST.PROPOSAL_METHOD) test_net(net, imdb, max_per_image=args.max_per_image, vis=args.vis)
3,165
33.791209
77
py
crpn
crpn-master/tools/_init_paths.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Set up paths for Fast R-CNN.""" import os.path as osp import sys def add_path(path): if path not in sys.path: sys.path.insert(0, path) this_dir = osp.dirname(__file__) # Add caffe to PYTHONPATH caffe_path = osp.join(this_dir, '..', 'caffe-fast-rcnn', 'python') add_path(caffe_path) # Add lib to PYTHONPATH lib_path = osp.join(this_dir, '..', 'lib') add_path(lib_path)
637
23.538462
66
py
crpn
crpn-master/tools/model_libs.py
import os import _init_paths import caffe from caffe import layers as L from caffe import params as P from caffe.proto import caffe_pb2 def check_if_exist(path): return os.path.exists(path) def make_if_not_exist(path): if not os.path.exists(path): os.makedirs(path) def UnpackVariable(var, num): assert len > 0 if type(var) is list and len(var) == num: return var else: ret = [] if type(var) is list: assert len(var) == 1 for i in xrange(0, num): ret.append(var[0]) else: for i in xrange(0, num): ret.append(var) return ret def ConvBNLayer(net, from_layer, out_layer, use_bn, use_relu, num_output, kernel_size, pad, stride, dilation=1, use_scale=True, lr_mult=1, conv_prefix='', conv_postfix='', bn_prefix='', bn_postfix='_bn', scale_prefix='', scale_postfix='_scale', bias_prefix='', bias_postfix='_bias', **bn_params): if use_bn: # parameters for convolution layer with batchnorm. kwargs = { 'param': [dict(lr_mult=lr_mult, decay_mult=1)], 'weight_filler': dict(type='gaussian', std=0.01), 'bias_term': False, } eps = bn_params.get('eps', 0.001) moving_average_fraction = bn_params.get('moving_average_fraction', 0.999) use_global_stats = bn_params.get('use_global_stats', False) # parameters for batchnorm layer. bn_kwargs = { 'param': [ dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0)], 'eps': eps, 'moving_average_fraction': moving_average_fraction, } bn_lr_mult = lr_mult if use_global_stats: # only specify if use_global_stats is explicitly provided; # otherwise, use_global_stats_ = this->phase_ == TEST; bn_kwargs = { 'param': [ dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0)], 'eps': eps, 'use_global_stats': use_global_stats, } # not updating scale/bias parameters bn_lr_mult = 0 # parameters for scale bias layer after batchnorm. if use_scale: sb_kwargs = { 'bias_term': True, 'param': [ dict(lr_mult=bn_lr_mult, decay_mult=0), dict(lr_mult=bn_lr_mult, decay_mult=0)], 'filler': dict(type='constant', value=1.0), 'bias_filler': dict(type='constant', value=0.0), } else: bias_kwargs = { 'param': [dict(lr_mult=bn_lr_mult, decay_mult=0)], 'filler': dict(type='constant', value=0.0), } else: kwargs = { 'param': [ dict(lr_mult=lr_mult, decay_mult=1), dict(lr_mult=2 * lr_mult, decay_mult=0)], 'weight_filler': dict(type='xavier'), 'bias_filler': dict(type='constant', value=0) } conv_name = '{}{}{}'.format(conv_prefix, out_layer, conv_postfix) [kernel_h, kernel_w] = UnpackVariable(kernel_size, 2) [pad_h, pad_w] = UnpackVariable(pad, 2) [stride_h, stride_w] = UnpackVariable(stride, 2) if kernel_h == kernel_w: net[conv_name] = L.Convolution(net[from_layer], num_output=num_output, kernel_size=kernel_h, pad=pad_h, stride=stride_h, **kwargs) else: net[conv_name] = L.Convolution(net[from_layer], num_output=num_output, kernel_h=kernel_h, kernel_w=kernel_w, pad_h=pad_h, pad_w=pad_w, stride_h=stride_h, stride_w=stride_w, **kwargs) if dilation > 1: net.update(conv_name, {'dilation': dilation}) if use_bn: bn_name = '{}{}{}'.format(bn_prefix, out_layer, bn_postfix) net[bn_name] = L.BatchNorm(net[conv_name], in_place=True, **bn_kwargs) if use_scale: sb_name = '{}{}{}'.format(scale_prefix, out_layer, scale_postfix) net[sb_name] = L.Scale(net[bn_name], in_place=True, **sb_kwargs) else: bias_name = '{}{}{}'.format(bias_prefix, out_layer, bias_postfix) net[bias_name] = L.Bias(net[bn_name], in_place=True, **bias_kwargs) if use_relu: relu_name = '{}_relu'.format(conv_name) net[relu_name] = L.ReLU(net[conv_name], in_place=True) def ResBody(net, from_layer, block_name, out2a, out2b, out2c, stride, use_branch1, dilation=1, **bn_param): # ResBody(net, 'pool1', '2a', 64, 64, 256, 1, True) conv_prefix = 'res{}_'.format(block_name) conv_postfix = '' bn_prefix = 'bn{}_'.format(block_name) bn_postfix = '' scale_prefix = 'scale{}_'.format(block_name) scale_postfix = '' use_scale = True if use_branch1: branch_name = 'branch1' ConvBNLayer(net, from_layer, branch_name, use_bn=True, use_relu=False, num_output=out2c, kernel_size=1, pad=0, stride=stride, use_scale=use_scale, conv_prefix=conv_prefix, conv_postfix=conv_postfix, bn_prefix=bn_prefix, bn_postfix=bn_postfix, scale_prefix=scale_prefix, scale_postfix=scale_postfix, **bn_param) branch1 = '{}{}'.format(conv_prefix, branch_name) else: branch1 = from_layer branch_name = 'branch2a' ConvBNLayer(net, from_layer, branch_name, use_bn=True, use_relu=True, num_output=out2a, kernel_size=1, pad=0, stride=stride, use_scale=use_scale, conv_prefix=conv_prefix, conv_postfix=conv_postfix, bn_prefix=bn_prefix, bn_postfix=bn_postfix, scale_prefix=scale_prefix, scale_postfix=scale_postfix, **bn_param) out_name = '{}{}'.format(conv_prefix, branch_name) branch_name = 'branch2b' if dilation == 1: ConvBNLayer(net, out_name, branch_name, use_bn=True, use_relu=True, num_output=out2b, kernel_size=3, pad=1, stride=1, use_scale=use_scale, conv_prefix=conv_prefix, conv_postfix=conv_postfix, bn_prefix=bn_prefix, bn_postfix=bn_postfix, scale_prefix=scale_prefix, scale_postfix=scale_postfix, **bn_param) else: pad = int((3 + (dilation - 1) * 2) - 1) / 2 ConvBNLayer(net, out_name, branch_name, use_bn=True, use_relu=True, num_output=out2b, kernel_size=3, pad=pad, stride=1, use_scale=use_scale, dilation=dilation, conv_prefix=conv_prefix, conv_postfix=conv_postfix, bn_prefix=bn_prefix, bn_postfix=bn_postfix, scale_prefix=scale_prefix, scale_postfix=scale_postfix, **bn_param) out_name = '{}{}'.format(conv_prefix, branch_name) branch_name = 'branch2c' ConvBNLayer(net, out_name, branch_name, use_bn=True, use_relu=False, num_output=out2c, kernel_size=1, pad=0, stride=1, use_scale=use_scale, conv_prefix=conv_prefix, conv_postfix=conv_postfix, bn_prefix=bn_prefix, bn_postfix=bn_postfix, scale_prefix=scale_prefix, scale_postfix=scale_postfix, **bn_param) branch2 = '{}{}'.format(conv_prefix, branch_name) res_name = 'res{}'.format(block_name) net[res_name] = L.Eltwise(net[branch1], net[branch2]) relu_name = '{}_relu'.format(res_name) net[relu_name] = L.ReLU(net[res_name], in_place=True) def InceptionTower(net, from_layer, tower_name, layer_params, **bn_param): use_scale = False for param in layer_params: tower_layer = '{}/{}'.format(tower_name, param['name']) del param['name'] if 'pool' in tower_layer: net[tower_layer] = L.Pooling(net[from_layer], **param) else: param.update(bn_param) ConvBNLayer(net, from_layer, tower_layer, use_bn=True, use_relu=True, use_scale=use_scale, **param) from_layer = tower_layer return net[from_layer] def CreateAnnotatedDataLayer(source, batch_size=32, backend=P.Data.LMDB, output_label=True, train=True, label_map_file='', anno_type=None, transform_param={}, batch_sampler=[{}]): if train: kwargs = { 'include': dict(phase=caffe_pb2.Phase.Value('TRAIN')), 'transform_param': transform_param, } else: kwargs = { 'include': dict(phase=caffe_pb2.Phase.Value('TEST')), 'transform_param': transform_param, } ntop = 1 if output_label: ntop = 2 annotated_data_param = { 'label_map_file': label_map_file, 'batch_sampler': batch_sampler, } if anno_type is not None: annotated_data_param.update({'anno_type': anno_type}) return L.AnnotatedData(name="data", annotated_data_param=annotated_data_param, data_param=dict(batch_size=batch_size, backend=backend, source=source), ntop=ntop, **kwargs) def ZFNetBody(net, from_layer, need_fc=True, fully_conv=False, reduced=False, dilated=False, dropout=True, need_fc8=False, freeze_layers=[]): kwargs = { 'param': [dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], 'weight_filler': dict(type='xavier'), 'bias_filler': dict(type='constant', value=0)} assert from_layer in net.keys() net.conv1 = L.Convolution(net[from_layer], num_output=96, pad=3, kernel_size=7, stride=2, **kwargs) net.relu1 = L.ReLU(net.conv1, in_place=True) net.norm1 = L.LRN(net.relu1, local_size=3, alpha=0.00005, beta=0.75, norm_region=P.LRN.WITHIN_CHANNEL, engine=P.LRN.CAFFE) net.pool1 = L.Pooling(net.norm1, pool=P.Pooling.MAX, pad=1, kernel_size=3, stride=2) net.conv2 = L.Convolution(net.pool1, num_output=256, pad=2, kernel_size=5, stride=2, **kwargs) net.relu2 = L.ReLU(net.conv2, in_place=True) net.norm2 = L.LRN(net.relu2, local_size=3, alpha=0.00005, beta=0.75, norm_region=P.LRN.WITHIN_CHANNEL, engine=P.LRN.CAFFE) net.pool2 = L.Pooling(net.norm2, pool=P.Pooling.MAX, pad=1, kernel_size=3, stride=2) net.conv3 = L.Convolution(net.pool2, num_output=384, pad=1, kernel_size=3, **kwargs) net.relu3 = L.ReLU(net.conv3, in_place=True) net.conv4 = L.Convolution(net.relu3, num_output=384, pad=1, kernel_size=3, **kwargs) net.relu4 = L.ReLU(net.conv4, in_place=True) net.conv5 = L.Convolution(net.relu4, num_output=256, pad=1, kernel_size=3, **kwargs) net.relu5 = L.ReLU(net.conv5, in_place=True) if need_fc: if dilated: name = 'pool5' net[name] = L.Pooling(net.relu5, pool=P.Pooling.MAX, pad=1, kernel_size=3, stride=1) else: name = 'pool5' net[name] = L.Pooling(net.relu5, pool=P.Pooling.MAX, pad=1, kernel_size=3, stride=2) if fully_conv: if dilated: if reduced: net.fc6 = L.Convolution(net[name], num_output=1024, pad=5, kernel_size=3, dilation=5, **kwargs) else: net.fc6 = L.Convolution(net[name], num_output=4096, pad=5, kernel_size=6, dilation=2, **kwargs) else: if reduced: net.fc6 = L.Convolution(net[name], num_output=1024, pad=2, kernel_size=3, dilation=2, **kwargs) else: net.fc6 = L.Convolution(net[name], num_output=4096, pad=2, kernel_size=6, **kwargs) net.relu6 = L.ReLU(net.fc6, in_place=True) if dropout: net.drop6 = L.Dropout(net.relu6, dropout_ratio=0.5, in_place=True) if reduced: net.fc7 = L.Convolution(net.relu6, num_output=1024, kernel_size=1, **kwargs) else: net.fc7 = L.Convolution(net.relu6, num_output=4096, kernel_size=1, **kwargs) net.relu7 = L.ReLU(net.fc7, in_place=True) if dropout: net.drop7 = L.Dropout(net.relu7, dropout_ratio=0.5, in_place=True) else: net.fc6 = L.InnerProduct(net.pool5, num_output=4096) net.relu6 = L.ReLU(net.fc6, in_place=True) if dropout: net.drop6 = L.Dropout(net.relu6, dropout_ratio=0.5, in_place=True) net.fc7 = L.InnerProduct(net.relu6, num_output=4096) net.relu7 = L.ReLU(net.fc7, in_place=True) if dropout: net.drop7 = L.Dropout(net.relu7, dropout_ratio=0.5, in_place=True) if need_fc8: from_layer = net.keys()[-1] if fully_conv: net.fc8 = L.Convolution(net[from_layer], num_output=1000, kernel_size=1, **kwargs) else: net.fc8 = L.InnerProduct(net[from_layer], num_output=1000) net.prob = L.Softmax(net.fc8) # Update freeze layers. kwargs['param'] = [dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0)] layers = net.keys() for freeze_layer in freeze_layers: if freeze_layer in layers: net.update(freeze_layer, kwargs) return net def VGGNetBody(net, from_layer, need_fc=True, fully_conv=False, reduced=False, dilated=False, nopool=False, dropout=True, freeze_layers=[], dilate_pool4=False): kwargs = { 'param': [dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], 'weight_filler': dict(type='xavier'), 'bias_filler': dict(type='constant', value=0)} assert from_layer in net.keys() net.conv1_1 = L.Convolution(net[from_layer], num_output=64, pad=1, kernel_size=3, **kwargs) net.relu1_1 = L.ReLU(net.conv1_1, in_place=True) net.conv1_2 = L.Convolution(net.relu1_1, num_output=64, pad=1, kernel_size=3, **kwargs) net.relu1_2 = L.ReLU(net.conv1_2, in_place=True) if nopool: name = 'conv1_3' net[name] = L.Convolution(net.relu1_2, num_output=64, pad=1, kernel_size=3, stride=2, **kwargs) else: name = 'pool1' net.pool1 = L.Pooling(net.relu1_2, pool=P.Pooling.MAX, kernel_size=2, stride=2) net.conv2_1 = L.Convolution(net[name], num_output=128, pad=1, kernel_size=3, **kwargs) net.relu2_1 = L.ReLU(net.conv2_1, in_place=True) net.conv2_2 = L.Convolution(net.relu2_1, num_output=128, pad=1, kernel_size=3, **kwargs) net.relu2_2 = L.ReLU(net.conv2_2, in_place=True) if nopool: name = 'conv2_3' net[name] = L.Convolution(net.relu2_2, num_output=128, pad=1, kernel_size=3, stride=2, **kwargs) else: name = 'pool2' net[name] = L.Pooling(net.relu2_2, pool=P.Pooling.MAX, kernel_size=2, stride=2) net.conv3_1 = L.Convolution(net[name], num_output=256, pad=1, kernel_size=3, **kwargs) net.relu3_1 = L.ReLU(net.conv3_1, in_place=True) net.conv3_2 = L.Convolution(net.relu3_1, num_output=256, pad=1, kernel_size=3, **kwargs) net.relu3_2 = L.ReLU(net.conv3_2, in_place=True) net.conv3_3 = L.Convolution(net.relu3_2, num_output=256, pad=1, kernel_size=3, **kwargs) net.relu3_3 = L.ReLU(net.conv3_3, in_place=True) if nopool: name = 'conv3_4' net[name] = L.Convolution(net.relu3_3, num_output=256, pad=1, kernel_size=3, stride=2, **kwargs) else: name = 'pool3' net[name] = L.Pooling(net.relu3_3, pool=P.Pooling.MAX, kernel_size=2, stride=2) net.conv4_1 = L.Convolution(net[name], num_output=512, pad=1, kernel_size=3, **kwargs) net.relu4_1 = L.ReLU(net.conv4_1, in_place=True) net.conv4_2 = L.Convolution(net.relu4_1, num_output=512, pad=1, kernel_size=3, **kwargs) net.relu4_2 = L.ReLU(net.conv4_2, in_place=True) net.conv4_3 = L.Convolution(net.relu4_2, num_output=512, pad=1, kernel_size=3, **kwargs) net.relu4_3 = L.ReLU(net.conv4_3, in_place=True) if nopool: name = 'conv4_4' net[name] = L.Convolution(net.relu4_3, num_output=512, pad=1, kernel_size=3, stride=2, **kwargs) else: name = 'pool4' if dilate_pool4: net[name] = L.Pooling(net.relu4_3, pool=P.Pooling.MAX, kernel_size=3, stride=1, pad=1) dilation = 2 else: net[name] = L.Pooling(net.relu4_3, pool=P.Pooling.MAX, kernel_size=2, stride=2) dilation = 1 kernel_size = 3 pad = int((kernel_size + (dilation - 1) * (kernel_size - 1)) - 1) / 2 net.conv5_1 = L.Convolution(net[name], num_output=512, pad=pad, kernel_size=kernel_size, dilation=dilation, **kwargs) net.relu5_1 = L.ReLU(net.conv5_1, in_place=True) net.conv5_2 = L.Convolution(net.relu5_1, num_output=512, pad=pad, kernel_size=kernel_size, dilation=dilation, **kwargs) net.relu5_2 = L.ReLU(net.conv5_2, in_place=True) net.conv5_3 = L.Convolution(net.relu5_2, num_output=512, pad=pad, kernel_size=kernel_size, dilation=dilation, **kwargs) net.relu5_3 = L.ReLU(net.conv5_3, in_place=True) if need_fc: if dilated: if nopool: name = 'conv5_4' net[name] = L.Convolution(net.relu5_3, num_output=512, pad=1, kernel_size=3, stride=1, **kwargs) else: name = 'pool5' net[name] = L.Pooling(net.relu5_3, pool=P.Pooling.MAX, pad=1, kernel_size=3, stride=1) else: if nopool: name = 'conv5_4' net[name] = L.Convolution(net.relu5_3, num_output=512, pad=1, kernel_size=3, stride=2, **kwargs) else: name = 'pool5' net[name] = L.Pooling(net.relu5_3, pool=P.Pooling.MAX, kernel_size=2, stride=2) if fully_conv: if dilated: if reduced: dilation = dilation * 6 kernel_size = 3 num_output = 1024 else: dilation = dilation * 2 kernel_size = 7 num_output = 4096 else: if reduced: dilation = dilation * 3 kernel_size = 3 num_output = 1024 else: kernel_size = 7 num_output = 4096 pad = int((kernel_size + (dilation - 1) * (kernel_size - 1)) - 1) / 2 net.fc6 = L.Convolution(net[name], num_output=num_output, pad=pad, kernel_size=kernel_size, dilation=dilation, **kwargs) net.relu6 = L.ReLU(net.fc6, in_place=True) if dropout: net.drop6 = L.Dropout(net.relu6, dropout_ratio=0.5, in_place=True) if reduced: net.fc7 = L.Convolution(net.relu6, num_output=1024, kernel_size=1, **kwargs) else: net.fc7 = L.Convolution(net.relu6, num_output=4096, kernel_size=1, **kwargs) net.relu7 = L.ReLU(net.fc7, in_place=True) if dropout: net.drop7 = L.Dropout(net.relu7, dropout_ratio=0.5, in_place=True) else: net.fc6 = L.InnerProduct(net.pool5, num_output=4096) net.relu6 = L.ReLU(net.fc6, in_place=True) if dropout: net.drop6 = L.Dropout(net.relu6, dropout_ratio=0.5, in_place=True) net.fc7 = L.InnerProduct(net.relu6, num_output=4096) net.relu7 = L.ReLU(net.fc7, in_place=True) if dropout: net.drop7 = L.Dropout(net.relu7, dropout_ratio=0.5, in_place=True) # Update freeze layers. kwargs['param'] = [dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0)] layers = net.keys() for freeze_layer in freeze_layers: if freeze_layer in layers: net.update(freeze_layer, kwargs) return net def ResNet101Body(net, from_layer, use_pool5=True, use_dilation_conv5=False, **bn_param): conv_prefix = '' conv_postfix = '' bn_prefix = 'bn_' bn_postfix = '' scale_prefix = 'scale_' scale_postfix = '' ConvBNLayer(net, from_layer, 'conv1', use_bn=True, use_relu=True, num_output=64, kernel_size=7, pad=3, stride=2, conv_prefix=conv_prefix, conv_postfix=conv_postfix, bn_prefix=bn_prefix, bn_postfix=bn_postfix, scale_prefix=scale_prefix, scale_postfix=scale_postfix, **bn_param) net.pool1 = L.Pooling(net.conv1, pool=P.Pooling.MAX, kernel_size=3, stride=2) ResBody(net, 'pool1', '2a', out2a=64, out2b=64, out2c=256, stride=1, use_branch1=True, **bn_param) ResBody(net, 'res2a', '2b', out2a=64, out2b=64, out2c=256, stride=1, use_branch1=False, **bn_param) ResBody(net, 'res2b', '2c', out2a=64, out2b=64, out2c=256, stride=1, use_branch1=False, **bn_param) ResBody(net, 'res2c', '3a', out2a=128, out2b=128, out2c=512, stride=2, use_branch1=True, **bn_param) from_layer = 'res3a' for i in xrange(1, 4): block_name = '3b{}'.format(i) ResBody(net, from_layer, block_name, out2a=128, out2b=128, out2c=512, stride=1, use_branch1=False, **bn_param) from_layer = 'res{}'.format(block_name) ResBody(net, from_layer, '4a', out2a=256, out2b=256, out2c=1024, stride=2, use_branch1=True, **bn_param) from_layer = 'res4a' for i in xrange(1, 23): block_name = '4b{}'.format(i) ResBody(net, from_layer, block_name, out2a=256, out2b=256, out2c=1024, stride=1, use_branch1=False, **bn_param) from_layer = 'res{}'.format(block_name) stride = 2 dilation = 1 if use_dilation_conv5: stride = 1 dilation = 2 ResBody(net, from_layer, '5a', out2a=512, out2b=512, out2c=2048, stride=stride, use_branch1=True, dilation=dilation, **bn_param) ResBody(net, 'res5a', '5b', out2a=512, out2b=512, out2c=2048, stride=1, use_branch1=False, dilation=dilation, **bn_param) ResBody(net, 'res5b', '5c', out2a=512, out2b=512, out2c=2048, stride=1, use_branch1=False, dilation=dilation, **bn_param) if use_pool5: net.pool5 = L.Pooling(net.res5c, pool=P.Pooling.AVE, global_pooling=True) return net def ResNet152Body(net, from_layer, use_pool5=True, use_dilation_conv5=False, **bn_param): conv_prefix = '' conv_postfix = '' bn_prefix = 'bn_' bn_postfix = '' scale_prefix = 'scale_' scale_postfix = '' ConvBNLayer(net, from_layer, 'conv1', use_bn=True, use_relu=True, num_output=64, kernel_size=7, pad=3, stride=2, conv_prefix=conv_prefix, conv_postfix=conv_postfix, bn_prefix=bn_prefix, bn_postfix=bn_postfix, scale_prefix=scale_prefix, scale_postfix=scale_postfix, **bn_param) net.pool1 = L.Pooling(net.conv1, pool=P.Pooling.MAX, kernel_size=3, stride=2) ResBody(net, 'pool1', '2a', out2a=64, out2b=64, out2c=256, stride=1, use_branch1=True, **bn_param) ResBody(net, 'res2a', '2b', out2a=64, out2b=64, out2c=256, stride=1, use_branch1=False, **bn_param) ResBody(net, 'res2b', '2c', out2a=64, out2b=64, out2c=256, stride=1, use_branch1=False, **bn_param) ResBody(net, 'res2c', '3a', out2a=128, out2b=128, out2c=512, stride=2, use_branch1=True, **bn_param) from_layer = 'res3a' for i in xrange(1, 8): block_name = '3b{}'.format(i) ResBody(net, from_layer, block_name, out2a=128, out2b=128, out2c=512, stride=1, use_branch1=False, **bn_param) from_layer = 'res{}'.format(block_name) ResBody(net, from_layer, '4a', out2a=256, out2b=256, out2c=1024, stride=2, use_branch1=True, **bn_param) from_layer = 'res4a' for i in xrange(1, 36): block_name = '4b{}'.format(i) ResBody(net, from_layer, block_name, out2a=256, out2b=256, out2c=1024, stride=1, use_branch1=False, **bn_param) from_layer = 'res{}'.format(block_name) stride = 2 dilation = 1 if use_dilation_conv5: stride = 1 dilation = 2 ResBody(net, from_layer, '5a', out2a=512, out2b=512, out2c=2048, stride=stride, use_branch1=True, dilation=dilation, **bn_param) ResBody(net, 'res5a', '5b', out2a=512, out2b=512, out2c=2048, stride=1, use_branch1=False, dilation=dilation, **bn_param) ResBody(net, 'res5b', '5c', out2a=512, out2b=512, out2c=2048, stride=1, use_branch1=False, dilation=dilation, **bn_param) if use_pool5: net.pool5 = L.Pooling(net.res5c, pool=P.Pooling.AVE, global_pooling=True) return net def InceptionV3Body(net, from_layer, output_pred=False, **bn_param): # scale is fixed to 1, thus we ignore it. use_scale = False out_layer = 'conv' ConvBNLayer(net, from_layer, out_layer, use_bn=True, use_relu=True, num_output=32, kernel_size=3, pad=0, stride=2, use_scale=use_scale, **bn_param) from_layer = out_layer out_layer = 'conv_1' ConvBNLayer(net, from_layer, out_layer, use_bn=True, use_relu=True, num_output=32, kernel_size=3, pad=0, stride=1, use_scale=use_scale, **bn_param) from_layer = out_layer out_layer = 'conv_2' ConvBNLayer(net, from_layer, out_layer, use_bn=True, use_relu=True, num_output=64, kernel_size=3, pad=1, stride=1, use_scale=use_scale, **bn_param) from_layer = out_layer out_layer = 'pool' net[out_layer] = L.Pooling(net[from_layer], pool=P.Pooling.MAX, kernel_size=3, stride=2, pad=0) from_layer = out_layer out_layer = 'conv_3' ConvBNLayer(net, from_layer, out_layer, use_bn=True, use_relu=True, num_output=80, kernel_size=1, pad=0, stride=1, use_scale=use_scale, **bn_param) from_layer = out_layer out_layer = 'conv_4' ConvBNLayer(net, from_layer, out_layer, use_bn=True, use_relu=True, num_output=192, kernel_size=3, pad=0, stride=1, use_scale=use_scale, **bn_param) from_layer = out_layer out_layer = 'pool_1' net[out_layer] = L.Pooling(net[from_layer], pool=P.Pooling.MAX, kernel_size=3, stride=2, pad=0) from_layer = out_layer # inceptions with 1x1, 3x3, 5x5 convolutions for inception_id in xrange(0, 3): if inception_id == 0: out_layer = 'mixed' tower_2_conv_num_output = 32 else: out_layer = 'mixed_{}'.format(inception_id) tower_2_conv_num_output = 64 towers = [] tower_name = '{}'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=64, kernel_size=1, pad=0, stride=1), ], **bn_param) towers.append(tower) tower_name = '{}/tower'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=48, kernel_size=1, pad=0, stride=1), dict(name='conv_1', num_output=64, kernel_size=5, pad=2, stride=1), ], **bn_param) towers.append(tower) tower_name = '{}/tower_1'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=64, kernel_size=1, pad=0, stride=1), dict(name='conv_1', num_output=96, kernel_size=3, pad=1, stride=1), dict(name='conv_2', num_output=96, kernel_size=3, pad=1, stride=1), ], **bn_param) towers.append(tower) tower_name = '{}/tower_2'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='pool', pool=P.Pooling.AVE, kernel_size=3, pad=1, stride=1), dict(name='conv', num_output=tower_2_conv_num_output, kernel_size=1, pad=0, stride=1), ], **bn_param) towers.append(tower) out_layer = '{}/join'.format(out_layer) net[out_layer] = L.Concat(*towers, axis=1) from_layer = out_layer # inceptions with 1x1, 3x3(in sequence) convolutions out_layer = 'mixed_3' towers = [] tower_name = '{}'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=384, kernel_size=3, pad=0, stride=2), ], **bn_param) towers.append(tower) tower_name = '{}/tower'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=64, kernel_size=1, pad=0, stride=1), dict(name='conv_1', num_output=96, kernel_size=3, pad=1, stride=1), dict(name='conv_2', num_output=96, kernel_size=3, pad=0, stride=2), ], **bn_param) towers.append(tower) tower_name = '{}'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='pool', pool=P.Pooling.MAX, kernel_size=3, pad=0, stride=2), ], **bn_param) towers.append(tower) out_layer = '{}/join'.format(out_layer) net[out_layer] = L.Concat(*towers, axis=1) from_layer = out_layer # inceptions with 1x1, 7x1, 1x7 convolutions for inception_id in xrange(4, 8): if inception_id == 4: num_output = 128 elif inception_id == 5 or inception_id == 6: num_output = 160 elif inception_id == 7: num_output = 192 out_layer = 'mixed_{}'.format(inception_id) towers = [] tower_name = '{}'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=192, kernel_size=1, pad=0, stride=1), ], **bn_param) towers.append(tower) tower_name = '{}/tower'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=num_output, kernel_size=1, pad=0, stride=1), dict(name='conv_1', num_output=num_output, kernel_size=[1, 7], pad=[0, 3], stride=[1, 1]), dict(name='conv_2', num_output=192, kernel_size=[7, 1], pad=[3, 0], stride=[1, 1]), ], **bn_param) towers.append(tower) tower_name = '{}/tower_1'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=num_output, kernel_size=1, pad=0, stride=1), dict(name='conv_1', num_output=num_output, kernel_size=[7, 1], pad=[3, 0], stride=[1, 1]), dict(name='conv_2', num_output=num_output, kernel_size=[1, 7], pad=[0, 3], stride=[1, 1]), dict(name='conv_3', num_output=num_output, kernel_size=[7, 1], pad=[3, 0], stride=[1, 1]), dict(name='conv_4', num_output=192, kernel_size=[1, 7], pad=[0, 3], stride=[1, 1]), ], **bn_param) towers.append(tower) tower_name = '{}/tower_2'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='pool', pool=P.Pooling.AVE, kernel_size=3, pad=1, stride=1), dict(name='conv', num_output=192, kernel_size=1, pad=0, stride=1), ], **bn_param) towers.append(tower) out_layer = '{}/join'.format(out_layer) net[out_layer] = L.Concat(*towers, axis=1) from_layer = out_layer # inceptions with 1x1, 3x3, 1x7, 7x1 filters out_layer = 'mixed_8' towers = [] tower_name = '{}/tower'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=192, kernel_size=1, pad=0, stride=1), dict(name='conv_1', num_output=320, kernel_size=3, pad=0, stride=2), ], **bn_param) towers.append(tower) tower_name = '{}/tower_1'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=192, kernel_size=1, pad=0, stride=1), dict(name='conv_1', num_output=192, kernel_size=[1, 7], pad=[0, 3], stride=[1, 1]), dict(name='conv_2', num_output=192, kernel_size=[7, 1], pad=[3, 0], stride=[1, 1]), dict(name='conv_3', num_output=192, kernel_size=3, pad=0, stride=2), ], **bn_param) towers.append(tower) tower_name = '{}'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='pool', pool=P.Pooling.MAX, kernel_size=3, pad=0, stride=2), ], **bn_param) towers.append(tower) out_layer = '{}/join'.format(out_layer) net[out_layer] = L.Concat(*towers, axis=1) from_layer = out_layer for inception_id in xrange(9, 11): num_output = 384 num_output2 = 448 if inception_id == 9: pool = P.Pooling.AVE else: pool = P.Pooling.MAX out_layer = 'mixed_{}'.format(inception_id) towers = [] tower_name = '{}'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=320, kernel_size=1, pad=0, stride=1), ], **bn_param) towers.append(tower) tower_name = '{}/tower'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=num_output, kernel_size=1, pad=0, stride=1), ], **bn_param) subtowers = [] subtower_name = '{}/mixed'.format(tower_name) subtower = InceptionTower(net, '{}/conv'.format(tower_name), subtower_name, [ dict(name='conv', num_output=num_output, kernel_size=[1, 3], pad=[0, 1], stride=[1, 1]), ], **bn_param) subtowers.append(subtower) subtower = InceptionTower(net, '{}/conv'.format(tower_name), subtower_name, [ dict(name='conv_1', num_output=num_output, kernel_size=[3, 1], pad=[1, 0], stride=[1, 1]), ], **bn_param) subtowers.append(subtower) net[subtower_name] = L.Concat(*subtowers, axis=1) towers.append(net[subtower_name]) tower_name = '{}/tower_1'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='conv', num_output=num_output2, kernel_size=1, pad=0, stride=1), dict(name='conv_1', num_output=num_output, kernel_size=3, pad=1, stride=1), ], **bn_param) subtowers = [] subtower_name = '{}/mixed'.format(tower_name) subtower = InceptionTower(net, '{}/conv_1'.format(tower_name), subtower_name, [ dict(name='conv', num_output=num_output, kernel_size=[1, 3], pad=[0, 1], stride=[1, 1]), ], **bn_param) subtowers.append(subtower) subtower = InceptionTower(net, '{}/conv_1'.format(tower_name), subtower_name, [ dict(name='conv_1', num_output=num_output, kernel_size=[3, 1], pad=[1, 0], stride=[1, 1]), ], **bn_param) subtowers.append(subtower) net[subtower_name] = L.Concat(*subtowers, axis=1) towers.append(net[subtower_name]) tower_name = '{}/tower_2'.format(out_layer) tower = InceptionTower(net, from_layer, tower_name, [ dict(name='pool', pool=pool, kernel_size=3, pad=1, stride=1), dict(name='conv', num_output=192, kernel_size=1, pad=0, stride=1), ], **bn_param) towers.append(tower) out_layer = '{}/join'.format(out_layer) net[out_layer] = L.Concat(*towers, axis=1) from_layer = out_layer if output_pred: net.pool_3 = L.Pooling(net[from_layer], pool=P.Pooling.AVE, kernel_size=8, pad=0, stride=1) net.softmax = L.InnerProduct(net.pool_3, num_output=1008) net.softmax_prob = L.Softmax(net.softmax) return net def CreateMultiBoxHead(net, data_layer="data", num_classes=[], from_layers=[], use_objectness=False, normalizations=[], use_batchnorm=True, lr_mult=1, use_scale=True, min_sizes=[], max_sizes=[], prior_variance = [0.1], aspect_ratios=[], steps=[], img_height=0, img_width=0, share_location=True, flip=True, clip=True, offset=0.5, inter_layer_depth=[], kernel_size=1, pad=0, conf_postfix='', loc_postfix='', **bn_param): assert num_classes, "must provide num_classes" assert num_classes > 0, "num_classes must be positive number" if normalizations: assert len(from_layers) == len(normalizations), "from_layers and normalizations should have same length" assert len(from_layers) == len(min_sizes), "from_layers and min_sizes should have same length" if max_sizes: assert len(from_layers) == len(max_sizes), "from_layers and max_sizes should have same length" if aspect_ratios: assert len(from_layers) == len(aspect_ratios), "from_layers and aspect_ratios should have same length" if steps: assert len(from_layers) == len(steps), "from_layers and steps should have same length" net_layers = net.keys() assert data_layer in net_layers, "data_layer is not in net's layers" if inter_layer_depth: assert len(from_layers) == len(inter_layer_depth), "from_layers and inter_layer_depth should have same length" num = len(from_layers) priorbox_layers = [] loc_layers = [] conf_layers = [] objectness_layers = [] for i in range(0, num): from_layer = from_layers[i] # Get the normalize value. if normalizations: if normalizations[i] != -1: norm_name = "{}_norm".format(from_layer) net[norm_name] = L.Normalize(net[from_layer], scale_filler=dict(type="constant", value=normalizations[i]), across_spatial=False, channel_shared=False) from_layer = norm_name # Add intermediate layers. if inter_layer_depth: if inter_layer_depth[i] > 0: inter_name = "{}_inter".format(from_layer) ConvBNLayer(net, from_layer, inter_name, use_bn=use_batchnorm, use_relu=True, lr_mult=lr_mult, num_output=inter_layer_depth[i], kernel_size=3, pad=1, stride=1, **bn_param) from_layer = inter_name # Estimate number of priors per location given provided parameters. min_size = min_sizes[i] if type(min_size) is not list: min_size = [min_size] aspect_ratio = [] if len(aspect_ratios) > i: aspect_ratio = aspect_ratios[i] if type(aspect_ratio) is not list: aspect_ratio = [aspect_ratio] max_size = [] if len(max_sizes) > i: max_size = max_sizes[i] if type(max_size) is not list: max_size = [max_size] if max_size: assert len(max_size) == len(min_size), "max_size and min_size should have same length." if max_size: num_priors_per_location = (2 + len(aspect_ratio)) * len(min_size) else: num_priors_per_location = (1 + len(aspect_ratio)) * len(min_size) if flip: num_priors_per_location += len(aspect_ratio) * len(min_size) step = [] if len(steps) > i: step = steps[i] # Create location prediction layer. name = "{}_mbox_loc{}".format(from_layer, loc_postfix) num_loc_output = num_priors_per_location * 4; if not share_location: num_loc_output *= num_classes ConvBNLayer(net, from_layer, name, use_bn=use_batchnorm, use_relu=False, lr_mult=lr_mult, num_output=num_loc_output, kernel_size=kernel_size, pad=pad, stride=1, **bn_param) permute_name = "{}_perm".format(name) net[permute_name] = L.Permute(net[name], order=[0, 2, 3, 1]) flatten_name = "{}_flat".format(name) net[flatten_name] = L.Flatten(net[permute_name], axis=1) loc_layers.append(net[flatten_name]) # Create confidence prediction layer. name = "{}_mbox_conf{}".format(from_layer, conf_postfix) num_conf_output = num_priors_per_location * num_classes; ConvBNLayer(net, from_layer, name, use_bn=use_batchnorm, use_relu=False, lr_mult=lr_mult, num_output=num_conf_output, kernel_size=kernel_size, pad=pad, stride=1, **bn_param) permute_name = "{}_perm".format(name) net[permute_name] = L.Permute(net[name], order=[0, 2, 3, 1]) flatten_name = "{}_flat".format(name) net[flatten_name] = L.Flatten(net[permute_name], axis=1) conf_layers.append(net[flatten_name]) # Create prior generation layer. name = "{}_mbox_priorbox".format(from_layer) net[name] = L.PriorBox(net[from_layer], net[data_layer], min_size=min_size, clip=clip, variance=prior_variance, offset=offset) if max_size: net.update(name, {'max_size': max_size}) if aspect_ratio: net.update(name, {'aspect_ratio': aspect_ratio, 'flip': flip}) if step: net.update(name, {'step': step}) if img_height != 0 and img_width != 0: if img_height == img_width: net.update(name, {'img_size': img_height}) else: net.update(name, {'img_h': img_height, 'img_w': img_width}) priorbox_layers.append(net[name]) # Create objectness prediction layer. if use_objectness: name = "{}_mbox_objectness".format(from_layer) num_obj_output = num_priors_per_location * 2; ConvBNLayer(net, from_layer, name, use_bn=use_batchnorm, use_relu=False, lr_mult=lr_mult, num_output=num_obj_output, kernel_size=kernel_size, pad=pad, stride=1, **bn_param) permute_name = "{}_perm".format(name) net[permute_name] = L.Permute(net[name], order=[0, 2, 3, 1]) flatten_name = "{}_flat".format(name) net[flatten_name] = L.Flatten(net[permute_name], axis=1) objectness_layers.append(net[flatten_name]) # Concatenate priorbox, loc, and conf layers. mbox_layers = [] name = "mbox_loc" net[name] = L.Concat(*loc_layers, axis=1) mbox_layers.append(net[name]) name = "mbox_conf" net[name] = L.Concat(*conf_layers, axis=1) mbox_layers.append(net[name]) name = "mbox_priorbox" net[name] = L.Concat(*priorbox_layers, axis=2) mbox_layers.append(net[name]) if use_objectness: name = "mbox_objectness" net[name] = L.Concat(*objectness_layers, axis=1) mbox_layers.append(net[name]) return mbox_layers
40,548
42.367914
132
py
crpn
crpn-master/tools/demo.py
#!/usr/bin/env python # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """ Demo script showing detections in sample images. See README.md for installation instructions before running. """ import _init_paths from fast_rcnn.config import cfg, cfg_from_file from fast_rcnn.test import im_detect from fast_rcnn.nms_wrapper import nms from utils.timer import Timer import matplotlib.pyplot as plt import numpy as np import scipy.io as sio import caffe, os, sys, cv2 import argparse from quad.sort_points import sort_points CLASSES = ('__background__', 'text') NETS = {'vgg16': ('VGG16', 'VGG16_faster_rcnn_final.caffemodel'), 'zf': ('ZF', 'ZF_faster_rcnn_final.caffemodel')} def vis_detections(im, class_name, dets, thresh=0.5): """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return 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 vis_quads(im, class_name, dets): """Visual debugging of detections.""" import matplotlib.pyplot as plt quads = dets[:, :8] for pts in quads: # im = cv2.polylines(im, pts, True, (0, 255, 0), 3) cv2.line(im, (pts[0], pts[1]), (pts[2], pts[3]), (0, 255, 0), 3) cv2.line(im, (pts[2], pts[3]), (pts[4], pts[5]), (0, 255, 0), 3) cv2.line(im, (pts[4], pts[5]), (pts[6], pts[7]), (0, 255, 0), 3) cv2.line(im, (pts[6], pts[7]), (pts[0], pts[1]), (0, 255, 0), 3) im = im[:, :, (2, 1, 0)] plt.cla() plt.imshow(im) plt.show() def demo(net, image_name): """Detect object classes in an image using pre-computed object proposals.""" # Load the demo image im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name) im = cv2.imread(im_file) # Detect all object classes and regress object bounds timer = Timer() timer.tic() scores, boxes = im_detect(net, im) timer.toc() # Visualize detections for each class if boxes.shape[1] == 5: print ('Detection took {:.3f}s for ' '{:d} object proposals').format(timer.total_time, boxes.shape[0]) CONF_THRESH = 0.8 NMS_THRESH = 0.3 for cls_ind, cls in enumerate(CLASSES[1:]): cls_ind += 1 # because we skipped background cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)] cls_scores = scores[:, cls_ind] dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])).astype(np.float32) keep = nms(dets, NMS_THRESH) dets = dets[keep, :] vis_detections(im, cls, dets, thresh=CONF_THRESH) else: CONF_THRESH = 0.5 for cls_ind, cls in enumerate(CLASSES[1:]): cls_ind += 1 # because we skipped background inds = np.where(scores[:, cls_ind] >= CONF_THRESH)[0] cls_scores = scores[inds, cls_ind] cls_boxes = boxes[inds, cls_ind * 8:(cls_ind + 1) * 8] cls_boxes = sort_points(cls_boxes) cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])).astype(np.float32, copy=False) keep = nms(cls_dets, cfg.TEST.NMS) cls_dets = cls_dets[keep, :] print ('Detection took {:.3f}s for ' '{:d} text regions').format(timer.total_time, len(keep)) vis_quads(im, cls, cls_dets) def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Faster R-CNN demo') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--cpu', dest='cpu_mode', help='Use CPU mode (overrides --gpu)', action='store_true') # parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]', choices=NETS.keys(), default=None) parser.add_argument('--model', dest='model', help='*.caffemodel file', default=None) args = parser.parse_args() return args if __name__ == '__main__': cfg.TEST.HAS_RPN = True # Use RPN for proposals args = parse_args() # if args.demo_net is None: prototxt = os.path.join(cfg.MODELS_DIR, NETS[args.demo_net][0], 'faster_rcnn_end2end', 'test.prototxt') cfg_file = None else: prototxt = os.path.join('./models', args.demo_net, 'test.pt') cfg_file = os.path.join('./models', args.demo_net, 'config.yml') if cfg_file is not None: cfg_from_file(cfg_file) if args.model is None: caffemodel = os.path.join(cfg.DATA_DIR, 'faster_rcnn_models', NETS[args.demo_net][1]) else: caffemodel = args.model if not os.path.isfile(caffemodel): raise IOError(('{:s} not found.\nDid you run ./data/script/' 'fetch_faster_rcnn_models.sh?').format(caffemodel)) if args.cpu_mode: caffe.set_mode_cpu() else: caffe.set_mode_gpu() caffe.set_device(args.gpu_id) cfg.GPU_ID = args.gpu_id net = caffe.Net(prototxt, caffemodel, caffe.TEST) print '\n\nLoaded network {:s}'.format(caffemodel) # Warmup on a dummy image # im = 128 * np.ones((300, 500, 3), dtype=np.uint8) # for i in xrange(2): # _, _= im_detect(net, im) im_names = ['img_10.jpg', 'img_14.jpg', 'img_45.jpg'] for im_name in im_names: print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Demo for data/demo/{}'.format(im_name) demo(net, im_name) plt.show()
6,624
32.974359
111
py
crpn
crpn-master/tools/train_svms.py
#!/usr/bin/env python # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """ Train post-hoc SVMs using the algorithm and hyper-parameters from traditional R-CNN. """ import _init_paths from fast_rcnn.config import cfg, cfg_from_file from datasets.factory import get_imdb from fast_rcnn.test import im_detect from utils.timer import Timer import caffe import argparse import pprint import numpy as np import numpy.random as npr import cv2 from sklearn import svm import os, sys class SVMTrainer(object): """ Trains post-hoc detection SVMs for all classes using the algorithm and hyper-parameters of traditional R-CNN. """ def __init__(self, net, imdb): self.imdb = imdb self.net = net self.layer = 'fc7' self.hard_thresh = -1.0001 self.neg_iou_thresh = 0.3 dim = net.params['cls_score'][0].data.shape[1] scale = self._get_feature_scale() print('Feature dim: {}'.format(dim)) print('Feature scale: {:.3f}'.format(scale)) self.trainers = [SVMClassTrainer(cls, dim, feature_scale=scale) for cls in imdb.classes] def _get_feature_scale(self, num_images=100): TARGET_NORM = 20.0 # Magic value from traditional R-CNN _t = Timer() roidb = self.imdb.roidb total_norm = 0.0 count = 0.0 inds = npr.choice(xrange(self.imdb.num_images), size=num_images, replace=False) for i_, i in enumerate(inds): im = cv2.imread(self.imdb.image_path_at(i)) if roidb[i]['flipped']: im = im[:, ::-1, :] _t.tic() scores, boxes = im_detect(self.net, im, roidb[i]['boxes']) _t.toc() feat = self.net.blobs[self.layer].data total_norm += np.sqrt((feat ** 2).sum(axis=1)).sum() count += feat.shape[0] print('{}/{}: avg feature norm: {:.3f}'.format(i_ + 1, num_images, total_norm / count)) return TARGET_NORM * 1.0 / (total_norm / count) def _get_pos_counts(self): counts = np.zeros((len(self.imdb.classes)), dtype=np.int) roidb = self.imdb.roidb for i in xrange(len(roidb)): for j in xrange(1, self.imdb.num_classes): I = np.where(roidb[i]['gt_classes'] == j)[0] counts[j] += len(I) for j in xrange(1, self.imdb.num_classes): print('class {:s} has {:d} positives'. format(self.imdb.classes[j], counts[j])) return counts def get_pos_examples(self): counts = self._get_pos_counts() for i in xrange(len(counts)): self.trainers[i].alloc_pos(counts[i]) _t = Timer() roidb = self.imdb.roidb num_images = len(roidb) # num_images = 100 for i in xrange(num_images): im = cv2.imread(self.imdb.image_path_at(i)) if roidb[i]['flipped']: im = im[:, ::-1, :] gt_inds = np.where(roidb[i]['gt_classes'] > 0)[0] gt_boxes = roidb[i]['boxes'][gt_inds] _t.tic() scores, boxes = im_detect(self.net, im, gt_boxes) _t.toc() feat = self.net.blobs[self.layer].data for j in xrange(1, self.imdb.num_classes): cls_inds = np.where(roidb[i]['gt_classes'][gt_inds] == j)[0] if len(cls_inds) > 0: cls_feat = feat[cls_inds, :] self.trainers[j].append_pos(cls_feat) print 'get_pos_examples: {:d}/{:d} {:.3f}s' \ .format(i + 1, len(roidb), _t.average_time) def initialize_net(self): # Start all SVM parameters at zero self.net.params['cls_score'][0].data[...] = 0 self.net.params['cls_score'][1].data[...] = 0 # Initialize SVMs in a smart way. Not doing this because its such # a good initialization that we might not learn something close to # the SVM solution. # # subtract background weights and biases for the foreground classes # w_bg = self.net.params['cls_score'][0].data[0, :] # b_bg = self.net.params['cls_score'][1].data[0] # self.net.params['cls_score'][0].data[1:, :] -= w_bg # self.net.params['cls_score'][1].data[1:] -= b_bg # # set the background weights and biases to 0 (where they shall remain) # self.net.params['cls_score'][0].data[0, :] = 0 # self.net.params['cls_score'][1].data[0] = 0 def update_net(self, cls_ind, w, b): self.net.params['cls_score'][0].data[cls_ind, :] = w self.net.params['cls_score'][1].data[cls_ind] = b def train_with_hard_negatives(self): _t = Timer() roidb = self.imdb.roidb num_images = len(roidb) # num_images = 100 for i in xrange(num_images): im = cv2.imread(self.imdb.image_path_at(i)) if roidb[i]['flipped']: im = im[:, ::-1, :] _t.tic() scores, boxes = im_detect(self.net, im, roidb[i]['boxes']) _t.toc() feat = self.net.blobs[self.layer].data for j in xrange(1, self.imdb.num_classes): hard_inds = \ np.where((scores[:, j] > self.hard_thresh) & (roidb[i]['gt_overlaps'][:, j].toarray().ravel() < self.neg_iou_thresh))[0] if len(hard_inds) > 0: hard_feat = feat[hard_inds, :].copy() new_w_b = \ self.trainers[j].append_neg_and_retrain(feat=hard_feat) if new_w_b is not None: self.update_net(j, new_w_b[0], new_w_b[1]) print(('train_with_hard_negatives: ' '{:d}/{:d} {:.3f}s').format(i + 1, len(roidb), _t.average_time)) def train(self): # Initialize SVMs using # a. w_i = fc8_w_i - fc8_w_0 # b. b_i = fc8_b_i - fc8_b_0 # c. Install SVMs into net self.initialize_net() # Pass over roidb to count num positives for each class # a. Pre-allocate arrays for positive feature vectors # Pass over roidb, computing features for positives only self.get_pos_examples() # Pass over roidb # a. Compute cls_score with forward pass # b. For each class # i. Select hard negatives # ii. Add them to cache # c. For each class # i. If SVM retrain criteria met, update SVM # ii. Install new SVM into net self.train_with_hard_negatives() # One final SVM retraining for each class # Install SVMs into net for j in xrange(1, self.imdb.num_classes): new_w_b = self.trainers[j].append_neg_and_retrain(force=True) self.update_net(j, new_w_b[0], new_w_b[1]) class SVMClassTrainer(object): """Manages post-hoc SVM training for a single object class.""" def __init__(self, cls, dim, feature_scale=1.0, C=0.001, B=10.0, pos_weight=2.0): self.pos = np.zeros((0, dim), dtype=np.float32) self.neg = np.zeros((0, dim), dtype=np.float32) self.B = B self.C = C self.cls = cls self.pos_weight = pos_weight self.dim = dim self.feature_scale = feature_scale self.svm = svm.LinearSVC(C=C, class_weight={1: 2, -1: 1}, intercept_scaling=B, verbose=1, penalty='l2', loss='l1', random_state=cfg.RNG_SEED, dual=True) self.pos_cur = 0 self.num_neg_added = 0 self.retrain_limit = 2000 self.evict_thresh = -1.1 self.loss_history = [] def alloc_pos(self, count): self.pos_cur = 0 self.pos = np.zeros((count, self.dim), dtype=np.float32) def append_pos(self, feat): num = feat.shape[0] self.pos[self.pos_cur:self.pos_cur + num, :] = feat self.pos_cur += num def train(self): print('>>> Updating {} detector <<<'.format(self.cls)) num_pos = self.pos.shape[0] num_neg = self.neg.shape[0] print('Cache holds {} pos examples and {} neg examples'. format(num_pos, num_neg)) X = np.vstack((self.pos, self.neg)) * self.feature_scale y = np.hstack((np.ones(num_pos), -np.ones(num_neg))) self.svm.fit(X, y) w = self.svm.coef_ b = self.svm.intercept_[0] scores = self.svm.decision_function(X) pos_scores = scores[:num_pos] neg_scores = scores[num_pos:] pos_loss = (self.C * self.pos_weight * np.maximum(0, 1 - pos_scores).sum()) neg_loss = self.C * np.maximum(0, 1 + neg_scores).sum() reg_loss = 0.5 * np.dot(w.ravel(), w.ravel()) + 0.5 * b ** 2 tot_loss = pos_loss + neg_loss + reg_loss self.loss_history.append((tot_loss, pos_loss, neg_loss, reg_loss)) for i, losses in enumerate(self.loss_history): print((' {:d}: obj val: {:.3f} = {:.3f} ' '(pos) + {:.3f} (neg) + {:.3f} (reg)').format(i, *losses)) # Sanity check scores_ret = ( X * 1.0 / self.feature_scale).dot(w.T * self.feature_scale) + b assert np.allclose(scores, scores_ret[:, 0], atol=1e-5), \ "Scores from returned model don't match decision function" return ((w * self.feature_scale, b), pos_scores, neg_scores) def append_neg_and_retrain(self, feat=None, force=False): if feat is not None: num = feat.shape[0] self.neg = np.vstack((self.neg, feat)) self.num_neg_added += num if self.num_neg_added > self.retrain_limit or force: self.num_neg_added = 0 new_w_b, pos_scores, neg_scores = self.train() # scores = np.dot(self.neg, new_w_b[0].T) + new_w_b[1] # easy_inds = np.where(neg_scores < self.evict_thresh)[0] not_easy_inds = np.where(neg_scores >= self.evict_thresh)[0] if len(not_easy_inds) > 0: self.neg = self.neg[not_easy_inds, :] # self.neg = np.delete(self.neg, easy_inds) print(' Pruning easy negatives') print(' Cache holds {} pos examples and {} neg examples'. format(self.pos.shape[0], self.neg.shape[0])) print(' {} pos support vectors'.format((pos_scores <= 1).sum())) print(' {} neg support vectors'.format((neg_scores >= -1).sum())) return new_w_b else: return None def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train SVMs (old skool)') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--def', dest='prototxt', help='prototxt file defining the network', default=None, type=str) parser.add_argument('--net', dest='caffemodel', help='model to test', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to train on', default='voc_2007_trainval', type=str) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args if __name__ == '__main__': # Must turn this off to prevent issues when digging into the net blobs to # pull out features (tricky!) cfg.DEDUP_BOXES = 0 # Must turn this on because we use the test im_detect() method to harvest # hard negatives cfg.TEST.SVM = True args = parse_args() print('Called with args:') print(args) if args.cfg_file is not None: cfg_from_file(args.cfg_file) print('Using config:') pprint.pprint(cfg) # fix the random seed for reproducibility np.random.seed(cfg.RNG_SEED) # set up caffe caffe.set_mode_gpu() if args.gpu_id is not None: caffe.set_device(args.gpu_id) net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST) net.name = os.path.splitext(os.path.basename(args.caffemodel))[0] out = os.path.splitext(os.path.basename(args.caffemodel))[0] + '_svm' out_dir = os.path.dirname(args.caffemodel) imdb = get_imdb(args.imdb_name) print 'Loaded dataset `{:s}` for training'.format(imdb.name) # enhance roidb to contain flipped examples if cfg.TRAIN.USE_FLIPPED: print 'Appending horizontally-flipped training examples...' imdb.append_flipped_images() print 'done' SVMTrainer(net, imdb).train() filename = '{}/{}.caffemodel'.format(out_dir, out) net.save(filename) print 'Wrote svm model to: {:s}'.format(filename)
13,480
37.081921
80
py
crpn
crpn-master/tools/gen_crpn.py
#!/usr/bin/env python from __future__ import division import _init_paths import caffe from caffe import layers as L, params as P from fast_rcnn.config import cfg def conv_relu(bottom, nout, ks=3, stride=1, pad=1): conv = L.Convolution(bottom, kernel_size=ks, stride=stride, num_output=nout, pad=pad, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)]) return conv, L.ReLU(conv, in_place=True) def conv_relu_fix(bottom, nout, ks=3, stride=1, pad=1): conv = L.Convolution(bottom, kernel_size=ks, stride=stride, num_output=nout, pad=pad, param=[dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0)]) return conv, L.ReLU(conv, in_place=True) def max_pool(bottom, ks=2, stride=2): return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride) def network(split): num_chns = int(360 / cfg.LD_INTERVAL) + 1 net = caffe.NetSpec() if split == 'train': pymodule = 'roi_data_layer.layer' pylayer = 'RoIDataLayer' pydata_params = dict(num_classes=2) net.data, net.im_info, net.gt_boxes = L.Python( module=pymodule, layer=pylayer, ntop=3, param_str=str(pydata_params)) else: net.data = L.Input(name='data', input_param=dict(shape=dict(dim=[1, 3, 512, 512]))) net.im_info = L.Input(name='im_info', input_param=dict(shape=dict(dim=[1, 3]))) # Backbone net.conv1_1, net.relu1_1 = conv_relu(net.data, 64, pad=1) net.conv1_2, net.relu1_2 = conv_relu(net.relu1_1, 64) net.pool1 = max_pool(net.relu1_2) net.conv2_1, net.relu2_1 = conv_relu(net.pool1, 128) net.conv2_2, net.relu2_2 = conv_relu(net.relu2_1, 128) net.pool2 = max_pool(net.relu2_2) net.conv3_1, net.relu3_1 = conv_relu(net.pool2, 256) net.conv3_2, net.relu3_2 = conv_relu(net.relu3_1, 256) net.conv3_3, net.relu3_3 = conv_relu(net.relu3_2, 256) net.pool3 = max_pool(net.relu3_3) net.conv4_1, net.relu4_1 = conv_relu(net.pool3, 512) net.conv4_2, net.relu4_2 = conv_relu(net.relu4_1, 512) net.conv4_3, net.relu4_3 = conv_relu(net.relu4_2, 512) net.pool4 = max_pool(net.relu4_3) net.conv5_1, net.relu5_1 = conv_relu(net.pool4, 512) net.conv5_2, net.relu5_2 = conv_relu(net.relu5_1, 512) net.conv5_3, net.relu5_3 = conv_relu(net.relu5_2, 512) # net.pool_5 = max_pool(net.relu5_3) # Hyper Feature net.downsample = L.Convolution( net.conv3_3, num_output=64, kernel_size=3, pad=1, stride=2, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='xavier'), bias_filler=dict(type='constant')) net.relu_downsample = L.ReLU(net.downsample, in_place=True) net.upsample = L.Deconvolution( net.conv5_3, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], convolution_param=dict(num_output=512, kernel_size=2, stride=2, weight_filler=dict(type='xavier'), bias_filler=dict(type='constant'))) net.relu_upsample = L.ReLU(net.upsample, in_place=True) net.fuse = L.Concat(net.downsample, net.upsample, net.conv4_3, name='concat', concat_param=dict({'concat_dim': 1})) net.conv_hyper = L.Convolution( net.fuse, num_output=512, kernel_size=3, pad=1, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='xavier'), bias_filler=dict(type='constant')) net.relu_conv_hyper = L.ReLU(net.conv_hyper, in_place=True) net.conv_rpn = L.Convolution( net.conv_hyper, num_output=128, kernel_size=3, pad=1, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='xavier'), bias_filler=dict(type='constant')) net.conv_rpn_relu = L.ReLU(net.conv_rpn, in_place=True) net.rpn_score_tl = L.Convolution( net.conv_rpn, num_output=num_chns, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) net.rpn_score_tr = L.Convolution( net.conv_rpn, num_output=num_chns, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) net.rpn_score_br = L.Convolution( net.conv_rpn, num_output=num_chns, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) net.rpn_score_bl = L.Convolution( net.conv_rpn, num_output=num_chns, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) net.rpn_prob_tl = L.Softmax(net.rpn_score_tl) net.rpn_prob_tr = L.Softmax(net.rpn_score_tr) net.rpn_prob_br = L.Softmax(net.rpn_score_br) net.rpn_prob_bl = L.Softmax(net.rpn_score_bl) if split == 'train': pymodule = 'rpn.labelmap_layer' pylayer = 'LabelMapLayer' net.rpn_label_tl, net.rpn_label_tr, net.rpn_label_br, net.rpn_label_bl = L.Python( net.conv_rpn, net.im_info, net.gt_boxes, module=pymodule, layer=pylayer, ntop=4) net.loss_rpn_tl = L.BalancedSoftmaxWithLoss( net.rpn_score_tl, net.rpn_label_tl, propagate_down=[1, 0], loss_param=dict(normalize=True, ignore_label=-1)) net.loss_rpn_tr = L.BalancedSoftmaxWithLoss( net.rpn_score_tr, net.rpn_label_tr, propagate_down=[1, 0], loss_param=dict(normalize=True, ignore_label=-1)) net.loss_rpn_br = L.BalancedSoftmaxWithLoss( net.rpn_score_br, net.rpn_label_br, propagate_down=[1, 0], loss_param=dict(normalize=True, ignore_label=-1)) net.loss_rpn_bl = L.BalancedSoftmaxWithLoss( net.rpn_score_bl, net.rpn_label_bl, propagate_down=[1, 0], loss_param=dict(normalize=True, ignore_label=-1)) pymodule = 'rpn.proposal_layer' pylayer = 'ProposalLayer' pydata_params = dict(feat_stride=8) net.quads = L.Python( net.im_info, net.rpn_prob_tl, net.rpn_prob_tr, net.rpn_prob_br, net.rpn_prob_bl, module=pymodule, layer=pylayer, ntop=1, param_str=str(pydata_params)) pymodule = 'rpn.proposal_target_layer' pylayer = 'ProposalTargetLayer' net.rois, net.labels, net.bbox_targets, net.bbox_inside_weights, net.bbox_outside_weights = L.Python( net.quads, net.gt_boxes, module=pymodule, layer=pylayer, name='roi-data', ntop=5) # RCNN net.dual_pool5 = L.RotateROIPooling( net.conv_hyper, net.rois, name='roi_pool5_dual', rotate_roi_pooling_param=dict(pooled_w=7, pooled_h=7, spatial_scale=0.125)) net.pool5_a, net.pool5_b = L.Slice(net.dual_pool5, slice_param=dict(axis=0), ntop=2, name='slice') net.pool5 = L.Eltwise(net.pool5_a, net.pool5_b, name='roi_pool5', eltwise_param=dict(operation=1)) net.fc6 = L.InnerProduct( net.pool5, param=[dict(lr_mult=1), dict(lr_mult=2)], inner_product_param=dict(num_output=4096, weight_filler=dict(type='xavier'), bias_filler=dict(type='constant'))) net.fc6_relu = L.ReLU(net.fc6, in_place=True) net.drop6 = L.Dropout(net.fc6, dropout_ratio=0.5, in_place=True) net.fc7 = L.InnerProduct( net.fc6, param=[dict(lr_mult=1), dict(lr_mult=2)], inner_product_param=dict(num_output=4096, weight_filler=dict(type='xavier'), bias_filler=dict(type='constant'))) net.fc7_relu = L.ReLU(net.fc7, in_place=True) net.drop7 = L.Dropout(net.fc7, dropout_ratio=0.5, in_place=True) net.cls_score = L.InnerProduct( net.fc7, param=[dict(lr_mult=1), dict(lr_mult=2)], inner_product_param=dict(num_output=2, weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0))) net.bbox_pred = L.InnerProduct( net.fc7, param=[dict(lr_mult=1), dict(lr_mult=2)], inner_product_param=dict(num_output=16, weight_filler=dict(type='gaussian', std=0.001), bias_filler=dict(type='constant', value=0))) net.loss_cls = L.SoftmaxWithLoss(net.cls_score, net.labels, propagate_down=[1, 0], loss_weight=1) net.loss_bbox = L.SmoothL1Loss(net.bbox_pred, net.bbox_targets, net.bbox_inside_weights, net.bbox_outside_weights, loss_weight=1) if split == 'test': pymodule = 'rpn.proposal_layer' pylayer = 'ProposalLayer' pydata_params = dict(feat_stride=8) net.quads, net.rois = L.Python( net.im_info, net.rpn_prob_tl, net.rpn_prob_tr, net.rpn_prob_br, net.rpn_prob_bl, module=pymodule, layer=pylayer, ntop=2, param_str=str(pydata_params)) # RCNN net.dual_pool5 = L.RotateROIPooling( net.conv_hyper, net.rois, name='roi_pool5_dual', rotate_roi_pooling_param=dict(pooled_w=7, pooled_h=7, spatial_scale=0.125)) net.pool5_a, net.pool5_b = L.Slice(net.dual_pool5, slice_param=dict(axis=0), ntop=2, name='slice') net.pool5 = L.Eltwise(net.pool5_a, net.pool5_b, name='roi_pool5', eltwise_param=dict(operation=1)) net.fc6 = L.InnerProduct( net.pool5, param=[dict(lr_mult=1), dict(lr_mult=2)], inner_product_param=dict(num_output=4096, weight_filler=dict(type='xavier'), bias_filler=dict(type='constant'))) net.fc6_relu = L.ReLU(net.fc6, in_place=True) net.drop6 = L.Dropout(net.fc6, dropout_ratio=0.5, in_place=True) net.fc7 = L.InnerProduct( net.fc6, param=[dict(lr_mult=1), dict(lr_mult=2)], inner_product_param=dict(num_output=4096, weight_filler=dict(type='xavier'), bias_filler=dict(type='constant'))) net.fc7_relu = L.ReLU(net.fc7, in_place=True) net.drop7 = L.Dropout(net.fc7, dropout_ratio=0.5, in_place=True) net.cls_score = L.InnerProduct( net.fc7, param=[dict(lr_mult=1), dict(lr_mult=2)], inner_product_param=dict(num_output=2, weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0))) net.bbox_pred = L.InnerProduct( net.fc7, param=[dict(lr_mult=1), dict(lr_mult=2)], inner_product_param=dict(num_output=16, weight_filler=dict(type='gaussian', std=0.001), bias_filler=dict(type='constant', value=0))) net.cls_prob = L.Softmax(net.cls_score) return net.to_proto() def make_net(): with open('train.pt', 'w') as f: f.write(str(network('train'))) with open('test.pt', 'w') as f: f.write(str(network('test'))) if __name__ == '__main__': make_net()
11,040
52.081731
119
py
crpn
crpn-master/tools/rpn_generate.py
#!/usr/bin/env python # -------------------------------------------------------- # Fast/er/ R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Generate RPN proposals.""" import _init_paths import numpy as np from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list, get_output_dir from datasets.factory import get_imdb from rpn.generate import imdb_proposals import cPickle import caffe import argparse import pprint import time, os, sys def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use', default=0, type=int) parser.add_argument('--def', dest='prototxt', help='prototxt file defining the network', default=None, type=str) parser.add_argument('--net', dest='caffemodel', help='model to test', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--wait', dest='wait', help='wait until net file exists', default=True, type=bool) parser.add_argument('--imdb', dest='imdb_name', help='dataset to test', default='voc_2007_test', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() print('Called with args:') print(args) if args.cfg_file is not None: cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) cfg.GPU_ID = args.gpu_id # RPN test settings cfg.TEST.RPN_PRE_NMS_TOP_N = -1 cfg.TEST.RPN_POST_NMS_TOP_N = 2000 print('Using config:') pprint.pprint(cfg) while not os.path.exists(args.caffemodel) and args.wait: print('Waiting for {} to exist...'.format(args.caffemodel)) time.sleep(10) caffe.set_mode_gpu() caffe.set_device(args.gpu_id) net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST) net.name = os.path.splitext(os.path.basename(args.caffemodel))[0] imdb = get_imdb(args.imdb_name) imdb_boxes = imdb_proposals(net, imdb) output_dir = get_output_dir(imdb, net) rpn_file = os.path.join(output_dir, net.name + '_rpn_proposals.pkl') with open(rpn_file, 'wb') as f: cPickle.dump(imdb_boxes, f, cPickle.HIGHEST_PROTOCOL) print 'Wrote RPN proposals to {}'.format(rpn_file)
2,994
31.554348
78
py
crpn
crpn-master/tools/generate_net.py
#!/usr/bin/env python from __future__ import division import _init_paths import caffe from caffe import layers as L, params as P from caffe.coord_map import crop def conv_relu(bottom, nout, ks=3, stride=1, pad=1): conv = L.Convolution(bottom, kernel_size=ks, stride=stride, num_output=nout, pad=pad, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)]) return conv, L.ReLU(conv, in_place=True) def max_pool(bottom, ks=2, stride=2): return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride) def network(split): n = caffe.NetSpec() if split == 'train': pymodule = 'roi_data_layer.layer' pylayer = 'RoIDataLayer' pydata_params = dict(num_classes=2) n.data, n.im_info, n.gt_boxes = L.Python(module=pymodule, layer=pylayer, ntop=3, param_str=str(pydata_params)) else: n.data = L.Input(name='data', input_param=dict(shape=dict(dim=[1, 3, 512, 512]))) n.im_info = L.Input(name='im_info', input_param=dict(shape=dict(dim=[1, 3]))) # the base net: vgg16 n.conv1_1, n.relu1_1 = conv_relu(n.data, 64, pad=1) n.conv1_2, n.relu1_2 = conv_relu(n.relu1_1, 64) n.pool1 = max_pool(n.relu1_2) n.conv2_1, n.relu2_1 = conv_relu(n.pool1, 128) n.conv2_2, n.relu2_2 = conv_relu(n.relu2_1, 128) n.pool2 = max_pool(n.relu2_2) n.conv3_1, n.relu3_1 = conv_relu(n.pool2, 256) n.conv3_2, n.relu3_2 = conv_relu(n.relu3_1, 256) n.conv3_3, n.relu3_3 = conv_relu(n.relu3_2, 256) n.pool3 = max_pool(n.relu3_3) n.conv4_1, n.relu4_1 = conv_relu(n.pool3, 512) n.conv4_2, n.relu4_2 = conv_relu(n.relu4_1, 512) n.conv4_3, n.relu4_3 = conv_relu(n.relu4_2, 512) n.pool4 = max_pool(n.relu4_3) n.conv5_1, n.relu5_1 = conv_relu(n.pool4, 512) n.conv5_2, n.relu5_2 = conv_relu(n.relu5_1, 512) n.conv5_3, n.relu5_3 = conv_relu(n.relu5_2, 512) # n.pool5 = max_pool(n.relu5_3) # FEATURE MAP # # n.conv_rpn = L.Convolution( # n.conv5_3, num_output=256, kernel_size=1, pad=0, # param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], # weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) # n.conv_rpn_relu = L.ReLU(n.conv_rpn, in_place=True) # reduct dims n.conv5_4 = L.Convolution( n.conv5_3, num_output=256, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='xavier'), bias_filler=dict(type='constant')) n.conv5_4_relu = L.ReLU(n.conv5_4, in_place=True) # upsample reference from RON n.upsample5 = L.Deconvolution( n.conv5_4, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], convolution_param=dict(num_output=256, kernel_size=2, stride=2, weight_filler=dict(type='xavier'), bias_filler=dict(type='constant'))) n.upsample5_relu = L.ReLU(n.upsample5, in_place=True) # reduct dims n.conv4_4 = L.Convolution( n.conv4_3, num_output=256, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='xavier'), bias_filler=dict(type='constant')) n.conv4_4_relu = L.ReLU(n.conv4_4, in_place=True) # concat n.concat = L.Concat(n.upsample5, n.conv4_4, name='concat', concat_param=dict({'concat_dim': 1})) n.conv_hyper = L.Convolution( n.concat, num_output=256, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='xavier'), bias_filler=dict(type='constant')) n.conv_hyper_relu = L.ReLU(n.conv_hyper, in_place=True) # conv n.conv_rpn = L.Convolution( n.conv_hyper, num_output=256, kernel_size=3, pad=1, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='xavier'), bias_filler=dict(type='constant')) n.conv_rpn_relu = L.ReLU(n.conv_rpn, in_place=True) # CROSS ENTROPY VERSION # # top_left n.rpn_score_tl = L.Convolution( n.conv_rpn, num_output=1, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) n.rpn_score_tr = L.Convolution( n.conv_rpn, num_output=1, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) n.rpn_score_br = L.Convolution( n.conv_rpn, num_output=1, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) n.rpn_score_bl = L.Convolution( n.conv_rpn, num_output=1, kernel_size=1, pad=0, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0)) if split == 'train': pymodule = 'rpn.cornermap_layer' pylayer = 'CornerMapLayer' n.rpn_map_tl, n.rpn_map_tr, n.rpn_map_br, n.rpn_map_bl = \ L.Python(n.conv_rpn, n.im_info, n.gt_boxes, module=pymodule, layer=pylayer, ntop=4) n.loss_rpn_tl = L.SigmoidCrossEntropyLoss( n.rpn_score_tl, n.rpn_map_tl, propagate_down=[1, 0], loss_param=dict(normalize=True, ignore_label=-1)) n.loss_rpn_tr = L.SigmoidCrossEntropyLoss( n.rpn_score_tr, n.rpn_map_tr, propagate_down=[1, 0], loss_param=dict(normalize=True, ignore_label=-1)) n.loss_rpn_br = L.SigmoidCrossEntropyLoss( n.rpn_score_br, n.rpn_map_br, propagate_down=[1, 0], loss_param=dict(normalize=True, ignore_label=-1)) n.loss_rpn_bl = L.SigmoidCrossEntropyLoss( n.rpn_score_bl, n.rpn_map_bl, propagate_down=[1, 0], loss_param=dict(normalize=True, ignore_label=-1)) if split == 'test': n.rpn_prob_tl = L.Sigmoid(n.rpn_score_tl) n.rpn_prob_tr = L.Sigmoid(n.rpn_score_tr) n.rpn_prob_br = L.Sigmoid(n.rpn_score_br) n.rpn_prob_bl = L.Sigmoid(n.rpn_score_bl) pymodule = 'rpn.quad_layer' pylayer = 'QuadLayer' n.quads, n.rois, n.cls_prob = L.Python(n.rpn_prob_tl, n.rpn_prob_tr, n.rpn_prob_br, n.rpn_prob_bl, module=pymodule, layer=pylayer, ntop=3) # CROSS ENTROPY VERSION # return n.to_proto() def make_net(): with open('train.pt', 'w') as f: f.write(str(network('train'))) with open('test.pt', 'w') as f: f.write(str(network('test'))) if __name__ == '__main__': make_net()
6,908
44.453947
118
py
crpn
crpn-master/tools/train_net.py
#!/usr/bin/env python # -------------------------------------------------------- # 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 on a region of interest database.""" import _init_paths from fast_rcnn.train import get_training_roidb, train_net from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list, get_output_dir from datasets.factory import get_imdb import datasets.imdb import caffe import argparse import pprint import numpy as np import sys def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--solver', dest='solver', help='solver prototxt', default=None, type=str) parser.add_argument('--iters', dest='max_iters', help='number of iterations to train', default=40000, type=int) parser.add_argument('--weights', dest='pretrained_model', help='initialize with pretrained model weights', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to train on', default='voc_2007_trainval', type=str) parser.add_argument('--rand', dest='randomize', help='randomize (do not use a fixed seed)', action='store_true') parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args def combined_roidb(imdb_names): def get_roidb(imdb_name): imdb = get_imdb(imdb_name) print 'Loaded dataset `{:s}` for training'.format(imdb.name) imdb.set_proposal_method(cfg.TRAIN.PROPOSAL_METHOD) print 'Set proposal method: {:s}'.format(cfg.TRAIN.PROPOSAL_METHOD) roidb = get_training_roidb(imdb) return roidb roidbs = [get_roidb(s) for s in imdb_names.split('+')] roidb = roidbs[0] if len(roidbs) > 1: for r in roidbs[1:]: roidb.extend(r) imdb = datasets.imdb.imdb(imdb_names) else: imdb = get_imdb(imdb_names) return imdb, roidb if __name__ == '__main__': args = parse_args() print('Called with args:') print(args) if args.cfg_file is not None: cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) cfg.GPU_ID = args.gpu_id print('Using config:') pprint.pprint(cfg) if not args.randomize: # fix the random seeds (numpy and caffe) for reproducibility np.random.seed(cfg.RNG_SEED) caffe.set_random_seed(cfg.RNG_SEED) # set up caffe caffe.set_mode_gpu() caffe.set_device(args.gpu_id) imdb, roidb = combined_roidb(args.imdb_name) print '{:d} roidb entries'.format(len(roidb)) output_dir = get_output_dir(imdb) print 'Output will be saved to `{:s}`'.format(output_dir) train_net(args.solver, roidb, output_dir, pretrained_model=args.pretrained_model, max_iters=args.max_iters)
3,747
32.168142
78
py
crpn
crpn-master/caffe-fast-rcnn/tools/extra/summarize.py
#!/usr/bin/env python """Net summarization tool. This tool summarizes the structure of a net in a concise but comprehensive tabular listing, taking a prototxt file as input. Use this tool to check at a glance that the computation you've specified is the computation you expect. """ from caffe.proto import caffe_pb2 from google import protobuf import re import argparse # ANSI codes for coloring blobs (used cyclically) COLORS = ['92', '93', '94', '95', '97', '96', '42', '43;30', '100', '444', '103;30', '107;30'] DISCONNECTED_COLOR = '41' def read_net(filename): net = caffe_pb2.NetParameter() with open(filename) as f: protobuf.text_format.Parse(f.read(), net) return net def format_param(param): out = [] if len(param.name) > 0: out.append(param.name) if param.lr_mult != 1: out.append('x{}'.format(param.lr_mult)) if param.decay_mult != 1: out.append('Dx{}'.format(param.decay_mult)) return ' '.join(out) def printed_len(s): return len(re.sub(r'\033\[[\d;]+m', '', s)) def print_table(table, max_width): """Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.""" max_widths = [max_width] * len(table[0]) column_widths = [max(printed_len(row[j]) + 1 for row in table) for j in range(len(table[0]))] column_widths = [min(w, max_w) for w, max_w in zip(column_widths, max_widths)] for row in table: row_str = '' right_col = 0 for cell, width in zip(row, column_widths): right_col += width row_str += cell + ' ' row_str += ' ' * max(right_col - printed_len(row_str), 0) print row_str def summarize_net(net): disconnected_tops = set() for lr in net.layer: disconnected_tops |= set(lr.top) disconnected_tops -= set(lr.bottom) table = [] colors = {} for lr in net.layer: tops = [] for ind, top in enumerate(lr.top): color = colors.setdefault(top, COLORS[len(colors) % len(COLORS)]) if top in disconnected_tops: top = '\033[1;4m' + top if len(lr.loss_weight) > 0: top = '{} * {}'.format(lr.loss_weight[ind], top) tops.append('\033[{}m{}\033[0m'.format(color, top)) top_str = ', '.join(tops) bottoms = [] for bottom in lr.bottom: color = colors.get(bottom, DISCONNECTED_COLOR) bottoms.append('\033[{}m{}\033[0m'.format(color, bottom)) bottom_str = ', '.join(bottoms) if lr.type == 'Python': type_str = lr.python_param.module + '.' + lr.python_param.layer else: type_str = lr.type # Summarize conv/pool parameters. # TODO support rectangular/ND parameters conv_param = lr.convolution_param if (lr.type in ['Convolution', 'Deconvolution'] and len(conv_param.kernel_size) == 1): arg_str = str(conv_param.kernel_size[0]) if len(conv_param.stride) > 0 and conv_param.stride[0] != 1: arg_str += '/' + str(conv_param.stride[0]) if len(conv_param.pad) > 0 and conv_param.pad[0] != 0: arg_str += '+' + str(conv_param.pad[0]) arg_str += ' ' + str(conv_param.num_output) if conv_param.group != 1: arg_str += '/' + str(conv_param.group) elif lr.type == 'Pooling': arg_str = str(lr.pooling_param.kernel_size) if lr.pooling_param.stride != 1: arg_str += '/' + str(lr.pooling_param.stride) if lr.pooling_param.pad != 0: arg_str += '+' + str(lr.pooling_param.pad) else: arg_str = '' if len(lr.param) > 0: param_strs = map(format_param, lr.param) if max(map(len, param_strs)) > 0: param_str = '({})'.format(', '.join(param_strs)) else: param_str = '' else: param_str = '' table.append([lr.name, type_str, param_str, bottom_str, '->', top_str, arg_str]) return table def main(): parser = argparse.ArgumentParser(description="Print a concise summary of net computation.") parser.add_argument('filename', help='net prototxt file to summarize') parser.add_argument('-w', '--max-width', help='maximum field width', type=int, default=30) args = parser.parse_args() net = read_net(args.filename) table = summarize_net(net) print_table(table, max_width=args.max_width) if __name__ == '__main__': main()
4,880
33.617021
95
py
crpn
crpn-master/caffe-fast-rcnn/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, verbose=args.verbose) if __name__ == '__main__': main()
7,136
32.824645
86
py
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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 for index, input in enumerate(inputs): if not isinstance(input, Top): raise TypeError('%s input %d is not a Top (type is %s)' % (type_name, index, type(input))) 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,277
34.835498
88
py
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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, has_nccl 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
552
60.444444
216
py
crpn
crpn-master/caffe-fast-rcnn/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_layer_dict(self): """ An OrderedDict (bottom to top, i.e., input to output) of network layers indexed by name """ if not hasattr(self, '_layer_dict'): self._layer_dict = OrderedDict(zip(self._layer_names, self.layers)) return self._layer_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(self.top_names[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(self.bottom_names[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.layer_dict = _Net_layer_dict 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,615
32.572254
89
py
crpn
crpn-master/caffe-fast-rcnn/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) else 1, separator, layer.convolution_param.stride[0] if len(layer.convolution_param.stride) else 1, separator, layer.convolution_param.pad[0] if len(layer.convolution_param.pad) 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,789
34.877551
112
py
crpn
crpn-master/caffe-fast-rcnn/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.astype(float).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,743
32.1875
110
py
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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_blob' 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_blob' 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_layer_dict(self): layer_dict = self.net.layer_dict self.assertEqual(list(layer_dict.keys()), list(self.net._layer_names)) for i, name in enumerate(self.net._layer_names): self.assertEqual(layer_dict[name].type, self.net.layers[i].type) def test_forward_backward(self): self.net.forward() self.net.backward() def test_forward_start_end(self): conv_blob=self.net.blobs['conv']; ip_blob=self.net.blobs['ip_blob']; sample_data=np.random.uniform(size=conv_blob.data.shape); sample_data=sample_data.astype(np.float32); conv_blob.data[:]=sample_data; forward_blob=self.net.forward(start='ip',end='ip'); self.assertIn('ip_blob',forward_blob); manual_forward=[]; for i in range(0,conv_blob.data.shape[0]): dot=np.dot(self.net.params['ip'][0].data, conv_blob.data[i].reshape(-1)); manual_forward.append(dot+self.net.params['ip'][1].data); manual_forward=np.array(manual_forward); np.testing.assert_allclose(ip_blob.data,manual_forward,rtol=1e-3); def test_backward_start_end(self): conv_blob=self.net.blobs['conv']; ip_blob=self.net.blobs['ip_blob']; sample_data=np.random.uniform(size=ip_blob.data.shape) sample_data=sample_data.astype(np.float32); ip_blob.diff[:]=sample_data; backward_blob=self.net.backward(start='ip',end='ip'); self.assertIn('conv',backward_blob); manual_backward=[]; for i in range(0,conv_blob.data.shape[0]): dot=np.dot(self.net.params['ip'][0].data.transpose(), sample_data[i].reshape(-1)); manual_backward.append(dot); manual_backward=np.array(manual_backward); manual_backward=manual_backward.reshape(conv_blob.data.shape); np.testing.assert_allclose(conv_blob.diff,manual_backward,rtol=1e-3); 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_blob']), ('loss', ['loss'])])) self.assertEqual(self.net.bottom_names, OrderedDict([('data', []), ('conv', ['data']), ('ip', ['conv']), ('loss', ['ip_blob', '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'])
11,640
28.848718
82
py
crpn
crpn-master/caffe-fast-rcnn/python/caffe/test/test_draw.py
import os import unittest from google.protobuf import text_format import caffe.draw from caffe.proto import caffe_pb2 def getFilenames(): """Yields files in the source tree which are Net prototxts.""" result = [] root_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..')) assert os.path.exists(root_dir) for dirname in ('models', 'examples'): dirname = os.path.join(root_dir, dirname) assert os.path.exists(dirname) for cwd, _, filenames in os.walk(dirname): for filename in filenames: filename = os.path.join(cwd, filename) if filename.endswith('.prototxt') and 'solver' not in filename: yield os.path.join(dirname, filename) class TestDraw(unittest.TestCase): def test_draw_net(self): for filename in getFilenames(): net = caffe_pb2.NetParameter() with open(filename) as infile: text_format.Merge(infile.read(), net) caffe.draw.draw_net(net, 'LR') if __name__ == "__main__": unittest.main()
1,114
28.342105
79
py
crpn
crpn-master/caffe-fast-rcnn/python/caffe/test/test_nccl.py
import sys import unittest import caffe class TestNCCL(unittest.TestCase): def test_newuid(self): """ Test that NCCL uids are of the proper type according to python version """ if caffe.has_nccl(): uid = caffe.NCCL.new_uid() if sys.version_info.major >= 3: self.assertTrue(isinstance(uid, bytes)) else: self.assertTrue(isinstance(uid, str))
457
21.9
55
py
crpn
crpn-master/caffe-fast-rcnn/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) def test_type_error(self): """Test that a TypeError is raised when a Function input isn't a Top.""" data = L.DummyData(ntop=2) # data is a 2-tuple of Tops r = r"^Silence input 0 is not a Top \(type is <(type|class) 'tuple'>\)$" with self.assertRaisesRegexp(TypeError, r): L.Silence(data, ntop=0) # should raise: data is a tuple, not a Top L.Silence(*data, ntop=0) # shouldn't raise: each elt of data is a Top
3,756
40.744444
80
py
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/scripts/cpp_lint.py
#!/usr/bin/env python # # 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 import six from six import iteritems, itervalues from six.moves import xrange _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 iteritems(self.errors_by_category): 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 six.PY2: 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 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(itervalues(matching_punctuation)) # 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. if six.PY2: 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,569
37.483792
93
py
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-master/caffe-fast-rcnn/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
crpn
crpn-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): """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)) 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() 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): """Set the roidb to be used by this layer during training.""" self._roidb = roidb self._shuffle_roidb_inds() if cfg.TRAIN.USE_PREFETCH: self._blob_queue = Queue(10) self._prefetch_process = BlobFetcher(self._blob_queue, self._roidb, self._num_classes) 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) 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) 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 top[idx].reshape(1, self._num_classes * 4) 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, self._num_classes * 4) self._name_to_top_map['bbox_inside_weights'] = idx idx += 1 top[idx].reshape(1, self._num_classes * 4) 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] # Reshape net's input blobs 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): super(BlobFetcher, self).__init__() self._queue = queue self._roidb = roidb self._num_classes = num_classes self._perm = None self._cur = 0 self._shuffle_roidb_inds() # fix the random seed for reproducibility np.random.seed(cfg.RNG_SEED) 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,450
36.631313
81
py
crpn
crpn-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 cv2 from fast_rcnn.config import cfg from utils.blob import prep_im_for_blob, im_list_to_blob from fast_rcnn.nms_wrapper import nms from quad.sort_points import sort_points def get_minibatch(roidb, num_classes): """Given a roidb, construct a minibatch sampled from it.""" num_images = len(roidb) # 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), \ 'num_images ({}) must divide BATCH_SIZE ({})'. \ format(num_images, cfg.TRAIN.BATCH_SIZE) rois_per_image = 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, x3, y3, x4, y4, cls) gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0] gt_boxes = np.empty((len(gt_inds), 9), dtype=np.float32) gt_boxes[:, :8] = roidb[0]['boxes'][gt_inds, :] * np.hstack((im_scales[0], im_scales[0])) gt_boxes[:, 8] = roidb[0]['gt_classes'][gt_inds] # sort points gt_boxes[:, :8] = sort_points(gt_boxes[:, :8]) blobs['gt_boxes'] = gt_boxes blobs['im_info'] = np.array( [np.hstack((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_classes), 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): # print roidb[i]['image'] 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, cfg.TRAIN.SCALE_MULTIPLE_OF) 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] bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32) bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32) inds = np.where(clss > 0)[0] 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()
8,409
39.432692
97
py
crpn
crpn-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).""" import os import cv2 import numpy as np import caffe import cPickle import argparse from fast_rcnn.config import cfg, get_output_dir from fast_rcnn.bbox_transform import clip_boxes, bbox_transform_inv from quad.quad_transform import clip_quads, quad_transform_inv from quad.quad_convert import quad_2_aabb from utils.timer import Timer from fast_rcnn.nms_wrapper import nms from utils.blob import im_list_to_blob from quad.sort_points import sort_points 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: if target_size != cfg.TEST.MAX_SIZE: 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) # Make width and height be multiples of a specified number im_scale_x = np.floor(im.shape[1] * im_scale / cfg.TEST.SCALE_MULTIPLE_OF) \ * cfg.TEST.SCALE_MULTIPLE_OF / im.shape[1] im_scale_y = np.floor(im.shape[0] * im_scale / cfg.TEST.SCALE_MULTIPLE_OF) \ * cfg.TEST.SCALE_MULTIPLE_OF / im.shape[0] im = cv2.resize(im_orig, None, None, fx=im_scale_x, fy=im_scale_y, interpolation=cv2.INTER_LINEAR) im_scale_factors.append(np.array([im_scale_x, im_scale_y, im_scale_x, im_scale_y])) processed_ims.append(im) else: im_scale_x = float(target_size) / float(im_shape[1]) im_scale_y = float(target_size) / float(im_shape[0]) im = cv2.resize(im_orig, (target_size, target_size), interpolation=cv2.INTER_LINEAR) im_scale_factors.append(np.array([im_scale_x, im_scale_y, im_scale_x, im_scale_y])) 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): """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 """ blobs, im_scales = _get_blobs(im, boxes) # 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, :] if cfg.TEST.HAS_RPN: im_blob = blobs['data'] blobs['im_info'] = np.array( [np.hstack((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 cfg.TEST.HAS_RPN: net.blobs['im_info'].reshape(*(blobs['im_info'].shape)) else: net.blobs['rois'].reshape(*(blobs['rois'].shape)) # do forward forward_kwargs = {'data': blobs['data'].astype(np.float32, copy=False)} if cfg.TEST.HAS_RPN: forward_kwargs['im_info'] = blobs['im_info'].astype(np.float32, copy=False) else: forward_kwargs['rois'] = blobs['rois'].astype(np.float32, copy=False) blobs_out = net.forward(**forward_kwargs) if cfg.TEST.HAS_RPN: assert len(im_scales) == 1, "Only single-image batch implemented" rois = net.blobs['quads'].data.copy() # unscale back to raw image space boxes = rois[:, 1:9] / np.hstack((im_scales[0], im_scales[0])).astype(np.float32) 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 = quad_transform_inv(boxes, box_deltas) pred_boxes = clip_quads(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, :] return scores, pred_boxes def vis_detections(im, class_name, dets, thresh=0.3): """Visual debugging of detections.""" import matplotlib.pyplot as plt if dets.shape[1] == 5: im = im[:, :, (2, 1, 0)] for i in xrange(np.minimum(10, dets.shape[0])): bbox = dets[i, :4] score = dets[i, -1] if score > thresh: plt.cla() plt.imshow(im) 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() else: quads = dets[:, :8] for pts in quads: # im = cv2.polylines(im, pts, True, (0, 255, 0), 3) cv2.line(im, (pts[0], pts[1]), (pts[2], pts[3]), (0, 255, 0), 3) cv2.line(im, (pts[2], pts[3]), (pts[4], pts[5]), (0, 255, 0), 3) cv2.line(im, (pts[4], pts[5]), (pts[6], pts[7]), (0, 255, 0), 3) cv2.line(im, (pts[6], pts[7]), (pts[0], pts[1]), (0, 255, 0), 3) im = im[:, :, (2, 1, 0)] plt.cla() plt.imshow(im) plt.show() # cv2.imshow('detections', im) # cv2.waitKey(0) # cv2.destroyAllWindows() 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=300, thresh=0.5, vis=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) # 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 = im_detect(net, im, box_proposals) _t['im_detect'].toc() _t['misc'].tic() # vis = True # 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] cls_boxes = boxes[inds, j*8:(j+1)*8] cls_boxes = sort_points(cls_boxes) cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])).astype(np.float32, copy=False) 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][:, -1] 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][:, -1] >= 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) det_file = os.path.join(output_dir, 'detections.pkl') 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)
12,911
38.127273
110
py
crpn
crpn-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,) # Resize test images so that its width and height are multiples of ... __C.TRAIN.SCALE_MULTIPLE_OF = 1 # 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 = False # 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, 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, 0.0, 0.0, 0.0, 0.0) __C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1) # 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 # # 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,) # Resize test images so that its width and height are multiples of ... __C.TEST.SCALE_MULTIPLE_OF = 1 # 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 # 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 # # 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 # # Parameters for CRPN # # Prob thres of corner candidate for training __C.TRAIN.PT_THRESH = 0.1 # ... for testing __C.TEST.PT_THRESH = 0.5 # Max number of corner candidates __C.PT_MAX_NUM = 32 # Size of corner NMS __C.PT_NMS_RANGE = 5 # NMS threshold used on corners __C.PT_NMS_THRESH = 0.36 # Interval of Link Direction __C.LD_INTERVAL = 15 # Threshold of Unmantched Link __C.LD_UM_THRESH = 1 # Use Dual RoI Pooling module __C.DUAL_ROI = True def get_output_dir(imdb, net=None): """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 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
9,936
29.764706
91
py
crpn
crpn-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 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: pb2.text_format.Merge(f.read(), self.solver_param) self.solver.net.layers[0].set_roidb(roidb) 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 = (cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS and net.params.has_key('bbox_pred')) if scale_bbox_params: # 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) 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: # restore net to original state net.params['bbox_pred'][0].data[...] = orig_0 net.params['bbox_pred'][1].data[...] = 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
6,076
36.282209
79
py
crpn
crpn-master/lib/rpn/proposal_layer.py
# -------------------------------------------------------- # CRPN # Written by Linjie Deng # -------------------------------------------------------- import yaml import caffe import numpy as np from fast_rcnn.config import cfg from fast_rcnn.nms_wrapper import nms from quad.quad_convert import whctrs, mkanchors, quad_2_aabb, obb_2_quad, dual_roi from quad.quad_2_obb import quad_2_obb DEBUG = False class Corner(object): # Corner property def __init__(self, name): self.name = name # position self.pos = None # probability self.prb = None # class of link direction self.cls = None class ProposalLayer(caffe.Layer): # Corner-based Region Proposal Network # Input: prob map of each corner # Output: quadrilateral region proposals def setup(self, bottom, top): # top: (ind, x1, y1, x2, y2, x3, y3, x4, y4) layer_params = yaml.load(self.param_str) self._feat_stride = layer_params['feat_stride'] num_rois = 2 if cfg.DUAL_ROI else 1 top[0].reshape(num_rois, 9) if len(top) > 1: top[1].reshape(num_rois, 5) def forward(self, bottom, top): # params cfg_key = self.phase # either 'TRAIN' or 'TEST' if cfg_key == 0: cfg_ = cfg.TRAIN else: cfg_ = cfg.TEST # corner params pt_thres = cfg_.PT_THRESH pt_max_num = cfg.PT_MAX_NUM pt_nms_range = cfg.PT_NMS_RANGE pt_nms_thres = cfg.PT_NMS_THRESH # proposal params ld_interval = cfg.LD_INTERVAL ld_um_thres = cfg.LD_UM_THRESH # rpn params # min_size = cfg_.RPN_MIN_SIZE nms_thresh = cfg_.RPN_NMS_THRESH pre_nms_topN = cfg_.RPN_PRE_NMS_TOP_N post_nms_topN = cfg_.RPN_POST_NMS_TOP_N im_info = bottom[0].data[0, :] score_tl = bottom[1].data[0, :].transpose((1, 2, 0)) score_tr = bottom[2].data[0, :].transpose((1, 2, 0)) score_br = bottom[3].data[0, :].transpose((1, 2, 0)) score_bl = bottom[4].data[0, :].transpose((1, 2, 0)) scores = np.concatenate([score_tl[:, :, :, np.newaxis], score_tr[:, :, :, np.newaxis], score_br[:, :, :, np.newaxis], score_bl[:, :, :, np.newaxis]], axis=3) map_info = scores.shape[:2] # 1. sample corner candidates from prob maps tl, tr, br, bl = _corner_sampling(scores, pt_thres, pt_max_num, pt_nms_range, pt_nms_thres) # 2. assemble corner candidates into proposals proposals = _proposal_sampling(tl, tr, br, bl, map_info, ld_interval, ld_um_thres) # 3. filter proposals = filter_quads(proposals) scores = proposals[:, 8] proposals = proposals[:, :8] # 3. rescale quads into raw image space proposals = proposals * self._feat_stride # 4. quadrilateral non-max surpression order = scores.ravel().argsort()[::-1] if pre_nms_topN > 0: order = order[:pre_nms_topN] proposals = proposals[order, :] scores = scores[order] keep = nms(np.hstack((proposals, scores[:, np.newaxis])).astype(np.float32, copy=False), nms_thresh) proposals = proposals[keep, :] scores = scores[keep] if post_nms_topN > 0: proposals = proposals[:post_nms_topN, :] scores = scores[:post_nms_topN] if proposals.shape[0] == 0: # add whole image to avoid error print 'NO PROPOSALS!' proposals = np.array([[0, 0, im_info[1], 0, im_info[1], im_info[0], 0, im_info[0]]]) scores = np.array([0.0]) # output # top[0]: quads(x1, y1, x2, y2, x3, y3, x4, y4) # top[1]: rois(xmin, ymin, xmax, ymax, theta) # top[2]: scores batch_inds = np.zeros((proposals.shape[0], 1), dtype=np.float32) blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False))) top[0].reshape(*blob.shape) top[0].data[...] = blob if len(top) > 1: if cfg.DUAL_ROI: rois = quad_2_obb(np.array(proposals, dtype=np.float32)) rois = dual_roi(rois) else: rois = quad_2_obb(np.array(proposals, dtype=np.float32)) batch_inds = np.zeros((rois.shape[0], 1), dtype=np.float32) blob = np.hstack((batch_inds, rois.astype(np.float32, copy=False))) top[1].reshape(*blob.shape) top[1].data[...] = blob if len(top) > 2: scores = np.vstack((scores, scores)).transpose() top[2].reshape(*scores.shape) top[2].data[...] = scores 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 _map_2_corner(pred_map, thresh, max_num, nms_range, nms_thres): pos_map = 1 - pred_map[:, :, 0] pts_cls = np.argmax(pred_map[:, :, 1:], 2) + 1 ctr_y, ctr_x = np.where(pos_map >= thresh) ctr_pts = np.vstack((ctr_x, ctr_y)).transpose() ws = np.ones(ctr_x.shape) * nms_range hs = np.ones(ctr_y.shape) * nms_range anchors = np.hstack((mkanchors(ws, hs, ctr_x, ctr_y), get_value(ctr_pts, pos_map))) keep = nms(anchors, nms_thres) if max_num > 0: keep = keep[:max_num] pos = ctr_pts[keep, :] prb = pos_map cls = pts_cls return pos, prb, cls def _corner_sampling(maps, thresh, max_num, nms_range, nms_thres): tl = Corner('top_left') tl.pos, tl.prb, tl.cls = _map_2_corner(maps[:, :, :, 0], thresh, max_num, nms_range, nms_thres) tr = Corner('top_right') tr.pos, tr.prb, tr.cls = _map_2_corner(maps[:, :, :, 1], thresh, max_num, nms_range, nms_thres) br = Corner('bot_right') br.pos, br.prb, br.cls = _map_2_corner(maps[:, :, :, 2], thresh, max_num, nms_range, nms_thres) bl = Corner('bot_left') bl.pos, bl.prb, bl.cls = _map_2_corner(maps[:, :, :, 3], thresh, max_num, nms_range, nms_thres) return tl, tr, br, bl def _gen_diags(a, b, theta_invl=15, max_diff=1): max_label = round(360.0 / theta_invl) idx_a = np.arange(0, a.pos.shape[0]) idx_b = np.arange(0, b.pos.shape[0]) idx_a, idx_b = np.meshgrid(idx_a, idx_b) idx_a = idx_a.ravel() idx_b = idx_b.ravel() diag_pos = np.hstack((a.pos[idx_a, :], b.pos[idx_b, :])) # keep = np.where((diag_pos[:, 0] != diag_pos[:, 2]) | (diag_pos[:, 1] != diag_pos[:, 3]))[0] diag_pos = diag_pos[keep, :] prac_label = compute_link(diag_pos[:, 0:2], diag_pos[:, 2:4], theta_invl) pred_label = get_value(diag_pos[:, 0:2], a.cls) diff_label_a = diff_link(prac_label, pred_label, max_label) # prac_label = np.mod(prac_label + max_label / 2, max_label) pred_label = get_value(diag_pos[:, 2:4], b.cls) diff_label_b = diff_link(prac_label, pred_label, max_label) keep = np.where((diff_label_a <= max_diff) & (diff_label_b <= max_diff))[0] diag_pos = diag_pos[keep, :] diag_prb = np.hstack((get_value(diag_pos[:, 0:2], a.prb), get_value(diag_pos[:, 2:4], b.prb))) return diag_pos, diag_prb def _gen_trias(diag_pos, diag_prb, c, theta_invl=15, max_diff=1): max_label = 360 / theta_invl idx_a = np.arange(0, diag_pos.shape[0]) idx_b = np.arange(0, c.pos.shape[0]) idx_a, idx_b = np.meshgrid(idx_a, idx_b) idx_a = idx_a.ravel() idx_b = idx_b.ravel() tria_pos = np.hstack((diag_pos[idx_a, :], c.pos[idx_b, :])) tria_prb = np.hstack((diag_prb[idx_a, :], get_value(c.pos[idx_b, :], c.prb))) # areas = compute_tria_area(tria_pos[:, 0:2], tria_pos[:, 2:4], tria_pos[:, 4:6]) keep = np.where(areas != 0)[0] tria_pos = tria_pos[keep, :] tria_prb = tria_prb[keep, :] ws, hs, ctr_x, ctr_y = whctrs(tria_pos[:, 0:4]) prac_theta = compute_theta(tria_pos[:, 4:6], np.vstack((ctr_x, ctr_y)).transpose()) prac_label = np.floor(prac_theta / theta_invl) + 1 pred_label = get_value(tria_pos[:, 4:6], c.cls) diff_label = diff_link(prac_label, pred_label, max_label) keep = np.where(diff_label <= max_diff)[0] tria_pos = tria_pos[keep, :] tria_prb = tria_prb[keep, :] prac_theta = prac_theta[keep] # prac_theta = np.mod(prac_theta + 180.0, 360.0) / 180.0 * np.pi len_diag = np.sqrt(np.sum(np.square(tria_pos[:, 0:2] - tria_pos[:, 2:4]), axis=1)) / 2. dist_x = len_diag * np.cos(prac_theta[:, 0]) dist_y = len_diag * np.sin(prac_theta[:, 0]) ws, hs, ctr_x, ctr_y = whctrs(tria_pos[:, 0:4]) tria_pos[:, 4:6] = np.vstack((ctr_x + dist_x, ctr_y - dist_y)).astype(np.int32, copy=False).transpose() return tria_pos, tria_prb def _get_last_one(tria, d): map_shape = d.prb.shape[:2] ws, hs, ctr_x, ctr_y = whctrs(tria[:, 0:4]) pos = np.vstack((2 * ctr_x - tria[:, 4], 2 * ctr_y - tria[:, 5])).transpose() pos[:, 0] = np.maximum(np.minimum(pos[:, 0], map_shape[1] - 1), 0) pos[:, 1] = np.maximum(np.minimum(pos[:, 1], map_shape[0] - 1), 0) pos = np.array(pos, dtype=np.int32) prb = get_value(pos, d.prb) return pos, prb def _clip_trias(tria_pos, tria_prb, c, map_info): tria_pos[:, 4] = np.maximum(np.minimum(tria_pos[:, 4], map_info[1] - 1), 0) tria_pos[:, 5] = np.maximum(np.minimum(tria_pos[:, 5], map_info[0] - 1), 0) tria_prb[:, 2:] = get_value(tria_pos[:, 4:6], c.prb) return tria_pos, tria_prb def _proposal_sampling(tl, tr, br, bl, map_info, theta_invl=15, max_diff=1): # DIAG: [top_left, bot_right] diag_pos, diag_prb = _gen_diags(tl, br, theta_invl, max_diff) # TRIA: [DIAG, top_right] tria_pos, tria_prb = _gen_trias(diag_pos, diag_prb, tr, theta_invl, max_diff) # QUAD: [TRIA, bot_left] temp_pos, temp_prb = _get_last_one(tria_pos, bl) # refine top_right tria_pos, tria_prb = _clip_trias(tria_pos, tria_prb, tr, map_info) # assemble score = compute_score(np.hstack((tria_prb, temp_prb))) quads = np.hstack((tria_pos[:, 0:2], tria_pos[:, 4:6], tria_pos[:, 2:4], temp_pos)) quads = np.hstack((quads, score[:, np.newaxis])) # TRIA: [DIAG, bot_left] tria_pos, tria_prb = _gen_trias(diag_pos, diag_prb, bl, theta_invl, max_diff) # QUAD: [TRIA, top_right] temp_pos, temp_prb = _get_last_one(tria_pos, tr) # refine bot_left tria_pos, tria_prb = _clip_trias(tria_pos, tria_prb, bl, map_info) # assemble score = compute_score(np.hstack((tria_prb, temp_prb))) quad = np.hstack((tria_pos[:, 0:2], temp_pos, tria_pos[:, 2:4], tria_pos[:, 4:6])) quad = np.hstack((quad, score[:, np.newaxis])) quads = np.vstack((quads, quad)) # DIAG: [bot_left, top_right] diag_pos, diag_prb = _gen_diags(bl, tr, theta_invl, max_diff) # TRIA: [DIAG, top_left] tria_pos, tria_prb = _gen_trias(diag_pos, diag_prb, tl, theta_invl, max_diff) # QUAD: [TRIA, bot_right] temp_pos, temp_prb = _get_last_one(tria_pos, br) # refine top_left tria_pos, tria_prb = _clip_trias(tria_pos, tria_prb, tl, map_info) # assemble score = compute_score(np.hstack((tria_prb, temp_prb))) quad = np.hstack((tria_pos[:, 4:6], tria_pos[:, 2:4], temp_pos, tria_pos[:, 0:2])) quad = np.hstack((quad, score[:, np.newaxis])) quads = np.vstack((quads, quad)) # TRIA: [DIAG, bor_right] tria_pos, tria_prb = _gen_trias(diag_pos, diag_prb, br, theta_invl, max_diff) # QUAD: [TRIA, top_left] temp_pos, temp_prb = _get_last_one(tria_pos, tl) # refine bor_right tria_pos, tria_prb = _clip_trias(tria_pos, tria_prb, br, map_info) # assemble score = compute_score(np.hstack((tria_prb, temp_prb))) quad = np.hstack((tria_pos[:, 0:2], temp_pos, tria_pos[:, 2:4], tria_pos[:, 4:6])) quad = np.hstack((quad, score[:, np.newaxis])) quads = np.vstack((quads, quad)) return quads def get_value(pts, maps): vals = maps[pts[:, 1], pts[:, 0]] return vals[:, np.newaxis] def compute_score(scores): score = scores[:, 0] * scores[:, 1] * scores[:, 2] * scores[:, 3] return score def compute_theta(p1, p2): dx = p2[:, 0] - p1[:, 0] dy = p2[:, 1] - p1[:, 1] val = dx / np.sqrt(dx * dx + dy * dy) val = np.maximum(np.minimum(val, 1), -1) theta = np.arccos(val) / np.pi * 180 idx = np.where(dy > 0)[0] theta[idx] = 360 - theta[idx] return theta[:, np.newaxis] def compute_link(p1, p2, interval): theta = compute_theta(p1, p2) label = np.floor(theta / interval) + 1 return label def diff_link(t1, t2, max_orient): dt = np.abs(t2 - t1) dt = np.minimum(dt, max_orient - dt) return dt def compute_tria_area(p1, p2, p3): area = (p2[:, 0] - p1[:, 0]) * (p3[:, 1] - p1[:, 1]) - \ (p2[:, 1] - p1[:, 1]) * (p3[:, 0] - p1[:, 0]) return area def filter_quads(quads): area_1 = compute_tria_area(quads[:, 0:2], quads[:, 2:4], quads[:, 4:6]) area_2 = compute_tria_area(quads[:, 0:2], quads[:, 2:4], quads[:, 6:8]) area_3 = compute_tria_area(quads[:, 0:2], quads[:, 4:6], quads[:, 6:8]) area_4 = compute_tria_area(quads[:, 2:4], quads[:, 4:6], quads[:, 6:8]) areas = area_1 * area_2 * area_3 * area_4 keep = np.where(areas != 0)[0] quads = quads[keep, :] return quads
13,357
38.173021
108
py