repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
GANFingerprints
GANFingerprints-master/CramerGAN/gan/core/resnet/ops/conv2d.py
""" Based on https://github.com/igul222/improved_wgan_training/blob/master/ """ from ... import resnet as lib import numpy as np import tensorflow as tf _default_weightnorm = False def enable_default_weightnorm(): global _default_weightnorm _default_weightnorm = True _weights_stdev = None def set_weights_stdev(weights_stdev): global _weights_stdev _weights_stdev = weights_stdev def unset_weights_stdev(): global _weights_stdev _weights_stdev = None def Conv2D(name, input_dim, output_dim, filter_size, inputs, he_init=True, mask_type=None, stride=1, weightnorm=None, biases=True, gain=1.): """ inputs: tensor of shape (batch size, num channels, height, width) mask_type: one of None, 'a', 'b' returns: tensor of shape (batch size, num channels, height, width) """ with tf.name_scope(name) as scope: if mask_type is not None: mask_type, mask_n_channels = mask_type mask = np.ones( (filter_size, filter_size, input_dim, output_dim), dtype='float32' ) center = filter_size // 2 # Mask out future locations # filter shape is (height, width, input channels, output channels) mask[center+1:, :, :, :] = 0. mask[center, center+1:, :, :] = 0. # Mask out future channels for i in range(mask_n_channels): for j in range(mask_n_channels): if (mask_type=='a' and i >= j) or (mask_type=='b' and i > j): mask[ center, center, i::mask_n_channels, j::mask_n_channels ] = 0. def uniform(stdev, size): return np.random.uniform( low=-stdev * np.sqrt(3), high=stdev * np.sqrt(3), size=size ).astype('float32') fan_in = input_dim * filter_size**2 fan_out = output_dim * filter_size**2 / (stride**2) if mask_type is not None: # only approximately correct fan_in /= 2. fan_out /= 2. if he_init: filters_stdev = np.sqrt(4./(fan_in+fan_out)) else: # Normalized init (Glorot & Bengio) filters_stdev = np.sqrt(2./(fan_in+fan_out)) if _weights_stdev is not None: filter_values = uniform( _weights_stdev, (filter_size, filter_size, input_dim, output_dim) ) else: filter_values = uniform( filters_stdev, (filter_size, filter_size, input_dim, output_dim) ) filter_values *= gain filters = lib.param(name+'.Filters', filter_values) if weightnorm==None: weightnorm = _default_weightnorm if weightnorm: norm_values = np.sqrt(np.sum(np.square(filter_values), axis=(0,1,2))) target_norms = lib.param( name + '.g', norm_values ) with tf.name_scope('weightnorm') as scope: norms = tf.sqrt(tf.reduce_sum(tf.square(filters), reduction_indices=[0,1,2])) filters = filters * (target_norms / norms) if mask_type is not None: with tf.name_scope('filter_mask'): filters = filters * mask result = tf.nn.conv2d( input=inputs, filter=filters, strides=[1, 1, stride, stride], padding='SAME', data_format='NCHW' ) if biases: _biases = lib.param( name+'.Biases', np.zeros(output_dim, dtype='float32') ) result = tf.nn.bias_add(result, _biases, data_format='NCHW') return result
3,910
30.039683
140
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/core/resnet/ops/cond_batchnorm.py
import resnet as lib import numpy as np import tensorflow as tf def Batchnorm(name, axes, inputs, is_training=None, stats_iter=None, update_moving_stats=True, fused=True, labels=None, n_labels=None): """conditional batchnorm (dumoulin et al 2016) for BCHW conv filtermaps""" if axes != [0,2,3]: raise Exception('unsupported') mean, var = tf.nn.moments(inputs, axes, keep_dims=True) shape = mean.get_shape().as_list() # shape is [1,n,1,1] offset_m = lib.param(name+'.offset', np.zeros([n_labels,shape[1]], dtype='float32')) scale_m = lib.param(name+'.scale', np.ones([n_labels,shape[1]], dtype='float32')) offset = tf.nn.embedding_lookup(offset_m, labels) scale = tf.nn.embedding_lookup(scale_m, labels) result = tf.nn.batch_normalization(inputs, mean, var, offset[:,:,None,None], scale[:,:,None,None], 1e-5) return result
871
50.294118
135
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/core/resnet/ops/batchnorm.py
""" Based on https://github.com/igul222/improved_wgan_training/blob/master/ """ from ... import resnet as lib import numpy as np import tensorflow as tf def Batchnorm(name, axes, inputs, is_training=None, stats_iter=None, update_moving_stats=True, fused=True): if ((axes == [0,2,3]) or (axes == [0,2])) and fused==True: if axes==[0,2]: inputs = tf.expand_dims(inputs, 3) # Old (working but pretty slow) implementation: ########## # inputs = tf.transpose(inputs, [0,2,3,1]) # mean, var = tf.nn.moments(inputs, [0,1,2], keep_dims=False) # offset = lib.param(name+'.offset', np.zeros(mean.get_shape()[-1], dtype='float32')) # scale = lib.param(name+'.scale', np.ones(var.get_shape()[-1], dtype='float32')) # result = tf.nn.batch_normalization(inputs, mean, var, offset, scale, 1e-4) # return tf.transpose(result, [0,3,1,2]) # New (super fast but untested) implementation: offset = lib.param(name+'.offset', np.zeros(inputs.get_shape()[1], dtype='float32')) scale = lib.param(name+'.scale', np.ones(inputs.get_shape()[1], dtype='float32')) moving_mean = lib.param(name+'.moving_mean', np.zeros(inputs.get_shape()[1], dtype='float32'), trainable=False) moving_variance = lib.param(name+'.moving_variance', np.ones(inputs.get_shape()[1], dtype='float32'), trainable=False) def _fused_batch_norm_training(): return tf.nn.fused_batch_norm(inputs, scale, offset, epsilon=1e-5, data_format='NCHW') def _fused_batch_norm_inference(): # Version which blends in the current item's statistics batch_size = tf.cast(tf.shape(inputs)[0], 'float32') mean, var = tf.nn.moments(inputs, [2,3], keep_dims=True) mean = ((1./batch_size)*mean) + (((batch_size-1.)/batch_size)*moving_mean)[None,:,None,None] var = ((1./batch_size)*var) + (((batch_size-1.)/batch_size)*moving_variance)[None,:,None,None] return tf.nn.batch_normalization(inputs, mean, var, offset[None,:,None,None], scale[None,:,None,None], 1e-5), mean, var # Standard version # return tf.nn.fused_batch_norm( # inputs, # scale, # offset, # epsilon=1e-2, # mean=moving_mean, # variance=moving_variance, # is_training=False, # data_format='NCHW' # ) if is_training is None: outputs, batch_mean, batch_var = _fused_batch_norm_training() else: outputs, batch_mean, batch_var = tf.cond(is_training, _fused_batch_norm_training, _fused_batch_norm_inference) if update_moving_stats: no_updates = lambda: outputs def _force_updates(): """Internal function forces updates moving_vars if is_training.""" float_stats_iter = tf.cast(stats_iter, tf.float32) update_moving_mean = tf.assign(moving_mean, ((float_stats_iter/(float_stats_iter+1))*moving_mean) + ((1/(float_stats_iter+1))*batch_mean)) update_moving_variance = tf.assign(moving_variance, ((float_stats_iter/(float_stats_iter+1))*moving_variance) + ((1/(float_stats_iter+1))*batch_var)) with tf.control_dependencies([update_moving_mean, update_moving_variance]): return tf.identity(outputs) outputs = tf.cond(is_training, _force_updates, no_updates) if axes == [0,2]: return outputs[:,:,:,0] # collapse last dim else: return outputs else: # raise Exception('old BN') # TODO we can probably use nn.fused_batch_norm here too for speedup mean, var = tf.nn.moments(inputs, axes, keep_dims=True) shape = mean.get_shape().as_list() if 0 not in axes: print("WARNING ({}): didn't find 0 in axes, but not using separate BN params for each item in batch".format(name)) shape[0] = 1 offset = lib.param(name+'.offset', np.zeros(shape, dtype='float32')) scale = lib.param(name+'.scale', np.ones(shape, dtype='float32')) result = tf.nn.batch_normalization(inputs, mean, var, offset, scale, 1e-5) return result
4,463
48.6
169
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/core/resnet/ops/deconv2d.py
import resnet as lib import numpy as np import tensorflow as tf _default_weightnorm = False def enable_default_weightnorm(): global _default_weightnorm _default_weightnorm = True _weights_stdev = None def set_weights_stdev(weights_stdev): global _weights_stdev _weights_stdev = weights_stdev def unset_weights_stdev(): global _weights_stdev _weights_stdev = None def Deconv2D( name, input_dim, output_dim, filter_size, inputs, he_init=True, weightnorm=None, biases=True, gain=1., mask_type=None, ): """ inputs: tensor of shape (batch size, height, width, input_dim) returns: tensor of shape (batch size, 2*height, 2*width, output_dim) """ with tf.name_scope(name) as scope: if mask_type != None: raise Exception('Unsupported configuration') def uniform(stdev, size): return np.random.uniform( low=-stdev * np.sqrt(3), high=stdev * np.sqrt(3), size=size ).astype('float32') stride = 2 fan_in = input_dim * filter_size**2 / (stride**2) fan_out = output_dim * filter_size**2 if he_init: filters_stdev = np.sqrt(4./(fan_in+fan_out)) else: # Normalized init (Glorot & Bengio) filters_stdev = np.sqrt(2./(fan_in+fan_out)) if _weights_stdev is not None: filter_values = uniform( _weights_stdev, (filter_size, filter_size, output_dim, input_dim) ) else: filter_values = uniform( filters_stdev, (filter_size, filter_size, output_dim, input_dim) ) filter_values *= gain filters = lib.param( name+'.Filters', filter_values ) if weightnorm==None: weightnorm = _default_weightnorm if weightnorm: norm_values = np.sqrt(np.sum(np.square(filter_values), axis=(0,1,3))) target_norms = lib.param( name + '.g', norm_values ) with tf.name_scope('weightnorm') as scope: norms = tf.sqrt(tf.reduce_sum(tf.square(filters), reduction_indices=[0,1,3])) filters = filters * tf.expand_dims(target_norms / norms, 1) inputs = tf.transpose(inputs, [0,2,3,1], name='NCHW_to_NHWC') input_shape = tf.shape(inputs) try: # tf pre-1.0 (top) vs 1.0 (bottom) output_shape = tf.pack([input_shape[0], 2*input_shape[1], 2*input_shape[2], output_dim]) except Exception as e: output_shape = tf.stack([input_shape[0], 2*input_shape[1], 2*input_shape[2], output_dim]) result = tf.nn.conv2d_transpose( value=inputs, filter=filters, output_shape=output_shape, strides=[1, 2, 2, 1], padding='SAME' ) if biases: _biases = lib.param( name+'.Biases', np.zeros(output_dim, dtype='float32') ) result = tf.nn.bias_add(result, _biases) result = tf.transpose(result, [0,3,1,2], name='NHWC_to_NCHW') return result
3,277
27.258621
101
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/core/resnet/ops/layernorm.py
""" Based on https://github.com/igul222/improved_wgan_training/blob/master/ """ from ... import resnet as lib import numpy as np import tensorflow as tf def Layernorm(name, norm_axes, inputs): mean, var = tf.nn.moments(inputs, norm_axes, keep_dims=True) # Assume the 'neurons' axis is the first of norm_axes. This is the case for fully-connected and BCHW conv layers. n_neurons = inputs.get_shape().as_list()[norm_axes[0]] offset = lib.param(name+'.offset', np.zeros(n_neurons, dtype='float32')) scale = lib.param(name+'.scale', np.ones(n_neurons, dtype='float32')) # Add broadcasting dims to offset and scale (e.g. BCHW conv data) offset = tf.reshape(offset, [-1] + [1 for i in range(len(norm_axes)-1)]) scale = tf.reshape(scale, [-1] + [1 for i in range(len(norm_axes)-1)]) result = tf.nn.batch_normalization(inputs, mean, var, offset, scale, 1e-5) return result
911
37
117
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/core/resnet/ops/conv1d.py
import tflib as lib import numpy as np import tensorflow as tf _default_weightnorm = False def enable_default_weightnorm(): global _default_weightnorm _default_weightnorm = True def Conv1D(name, input_dim, output_dim, filter_size, inputs, he_init=True, mask_type=None, stride=1, weightnorm=None, biases=True, gain=1.): """ inputs: tensor of shape (batch size, num channels, width) mask_type: one of None, 'a', 'b' returns: tensor of shape (batch size, num channels, width) """ with tf.name_scope(name) as scope: if mask_type is not None: mask_type, mask_n_channels = mask_type mask = np.ones( (filter_size, input_dim, output_dim), dtype='float32' ) center = filter_size // 2 # Mask out future locations # filter shape is (width, input channels, output channels) mask[center+1:, :, :] = 0. # Mask out future channels for i in range(mask_n_channels): for j in range(mask_n_channels): if (mask_type=='a' and i >= j) or (mask_type=='b' and i > j): mask[ center, i::mask_n_channels, j::mask_n_channels ] = 0. def uniform(stdev, size): return np.random.uniform( low=-stdev * np.sqrt(3), high=stdev * np.sqrt(3), size=size ).astype('float32') fan_in = input_dim * filter_size fan_out = output_dim * filter_size / stride if mask_type is not None: # only approximately correct fan_in /= 2. fan_out /= 2. if he_init: filters_stdev = np.sqrt(4./(fan_in+fan_out)) else: # Normalized init (Glorot & Bengio) filters_stdev = np.sqrt(2./(fan_in+fan_out)) filter_values = uniform( filters_stdev, (filter_size, input_dim, output_dim) ) # print "WARNING IGNORING GAIN" filter_values *= gain filters = lib.param(name+'.Filters', filter_values) if weightnorm==None: weightnorm = _default_weightnorm if weightnorm: norm_values = np.sqrt(np.sum(np.square(filter_values), axis=(0,1))) target_norms = lib.param( name + '.g', norm_values ) with tf.name_scope('weightnorm') as scope: norms = tf.sqrt(tf.reduce_sum(tf.square(filters), reduction_indices=[0,1])) filters = filters * (target_norms / norms) if mask_type is not None: with tf.name_scope('filter_mask'): filters = filters * mask result = tf.nn.conv1d( value=inputs, filters=filters, stride=stride, padding='SAME', data_format='NCHW' ) if biases: _biases = lib.param( name+'.Biases', np.zeros([output_dim], dtype='float32') ) # result = result + _biases result = tf.expand_dims(result, 3) result = tf.nn.bias_add(result, _biases, data_format='NCHW') result = tf.squeeze(result) return result
3,401
30.211009
140
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/core/resnet/ops/linear.py
import resnet as lib import numpy as np import tensorflow as tf _default_weightnorm = False def enable_default_weightnorm(): global _default_weightnorm _default_weightnorm = True def disable_default_weightnorm(): global _default_weightnorm _default_weightnorm = False _weights_stdev = None def set_weights_stdev(weights_stdev): global _weights_stdev _weights_stdev = weights_stdev def unset_weights_stdev(): global _weights_stdev _weights_stdev = None def Linear( name, input_dim, output_dim, inputs, biases=True, initialization=None, weightnorm=None, gain=1. ): """ initialization: None, `lecun`, 'glorot', `he`, 'glorot_he', `orthogonal`, `("uniform", range)` """ with tf.name_scope(name) as scope: def uniform(stdev, size): if _weights_stdev is not None: stdev = _weights_stdev return np.random.uniform( low=-stdev * np.sqrt(3), high=stdev * np.sqrt(3), size=size ).astype('float32') if initialization == 'lecun':# and input_dim != output_dim): # disabling orth. init for now because it's too slow weight_values = uniform( np.sqrt(1./input_dim), (input_dim, output_dim) ) elif initialization == 'glorot' or (initialization == None): weight_values = uniform( np.sqrt(2./(input_dim+output_dim)), (input_dim, output_dim) ) elif initialization == 'he': weight_values = uniform( np.sqrt(2./input_dim), (input_dim, output_dim) ) elif initialization == 'glorot_he': weight_values = uniform( np.sqrt(4./(input_dim+output_dim)), (input_dim, output_dim) ) elif initialization == 'orthogonal' or \ (initialization == None and input_dim == output_dim): # From lasagne def sample(shape): if len(shape) < 2: raise RuntimeError("Only shapes of length 2 or more are " "supported.") flat_shape = (shape[0], np.prod(shape[1:])) # TODO: why normal and not uniform? a = np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) # pick the one with the correct shape q = u if u.shape == flat_shape else v q = q.reshape(shape) return q.astype('float32') weight_values = sample((input_dim, output_dim)) elif initialization[0] == 'uniform': weight_values = np.random.uniform( low=-initialization[1], high=initialization[1], size=(input_dim, output_dim) ).astype('float32') else: raise Exception('Invalid initialization!') weight_values *= gain weight = lib.param( name + '.W', weight_values ) if weightnorm==None: weightnorm = _default_weightnorm if weightnorm: norm_values = np.sqrt(np.sum(np.square(weight_values), axis=0)) target_norms = lib.param( name + '.g', norm_values ) with tf.name_scope('weightnorm') as scope: norms = tf.sqrt(tf.reduce_sum(tf.square(weight), reduction_indices=[0])) weight = weight * (target_norms / norms) if inputs.get_shape().ndims == 2: result = tf.matmul(inputs, weight) else: reshaped_inputs = tf.reshape(inputs, [-1, input_dim]) result = tf.matmul(reshaped_inputs, weight) result = tf.reshape(result, tf.pack(tf.unpack(tf.shape(inputs))[:-1] + [output_dim])) if biases: result = tf.nn.bias_add( result, lib.param( name + '.b', np.zeros((output_dim,), dtype='float32') ) ) return result
4,325
29.041667
98
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/core/resnet/ops/__init__.py
0
0
0
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/utils/timer.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 19 13:42:24 2018 @author: mikolajbinkowski """ import time class Timer(object): def __init__(self, start_time=time.time(), limit=100): self.start_time = start_time self.limit = limit def __call__(self, step, mess='', prints=True): if prints and (step % self.limit != 0) and (step > 10): return message = '[%8d][%s] %s' % (step, hms(self.start_time), mess) if prints: print(message) else: return message def hms(start_time): t = int(time.time() - start_time) m, s = t//60, t % 60 h, m = m//60, m % 60 if h > 0: return '%2dh%02dm%02ds' % (h, m, s) elif m > 0: return '%5dm%02ds' % (m, s) else: return '%8ds' % s
843
23.823529
69
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/utils/get_test_images.py
import tensorflow as tf import numpy as np import os os.chdir(os.path.join(os.getcwd(), '..', '..')) import core.pipeline import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='lsun', help='dataset to sample from') parser.add_argument('--data-path', default='~/', help='path to read raw images from') parser.add_argument('--save-path', default=None, help='path to save numpy array of images') parser.add_argument('-N', type=int, default=25000, help='number of samples to save') parser.add_argument('--output-size', type=int, default=64, help='size of the sampled pictures') parser.add_argument('--channels', type=int, default=3, help='number of channels in sampled pictures') args = parser.parse_args() if args.save_path is None: args.save_path = args.data_path Pipeline_class = pipeline.get_pipeline(args.dataset) with tf.Session() as sess: pipe = Pipeline(args.output_size, args.channels, 1000, args.save_path) ims = pipe.connect() sampled = [] while len(sampled) < args.N/1000.: sampled.append(sess.run(ims)) print(len(sampled)) sampled = np.concatenate(sampled, axis=0) print(sampled.shape) sampled = sampled[:args.N] path = os.path.join(args.save_path, '%s-$d-test.npy') np.save(sampled, path) print('%d %dx%d %s images saved in %s.' % (args.N, args.output_size, args.output_size, args.dataset, path))
1,553
41
115
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/utils/scorer.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 10 17:23:38 2018 @author: mikolajbinkowski """ import time, os, scipy, sys import numpy as np from core import mmd import compute_scores as cs class Scorer(object): def __init__(self, dataset, lr_scheduler=True, stdout=sys.stdout): self.stdout = stdout self.dataset = dataset if dataset == 'mnist': self.model = cs.LeNet() self.size = 100000 self.frequency = 500 else: self.model = cs.Inception() self.size = 25000 self.frequency = 2000 self.output = [] if lr_scheduler: self.three_sample = [] self.three_sample_chances = 0 self.lr_scheduler = lr_scheduler def set_train_codes(self, gan): suffix = '' if (gan.output_size <= 32) else ('-%d' % gan.output_size) path = os.path.join(gan.data_dir, '%s-codes%s.npy' % (self.dataset, suffix)) if os.path.exists(path): self.train_codes = np.load(path) print('[*] Train codes loaded. ') return print('[!] Codes not found. Featurizing...') ims = [] while len(ims) < self.size // gan.batch_size: ims.append(gan.sess.run(gan.images)) ims = np.concatenate(ims, axis=0)[:self.size] _, self.train_codes = cs.featurize(ims * 255., self.model, get_preds=True, get_codes=True, output=self.stdout) np.save(path, self.train_codes) print('[*] %d train images featurized and saved in <%s>' % (self.size, path)) def compute(self, gan, step): if step % self.frequency != 0: return if not hasattr(self, 'train_codes'): print('[ ] Getting train codes...') self.set_train_codes(gan) tt = time.time() gan.timer(step, "Scoring start") output = {} images4score = gan.get_samples(n=self.size, save=False) if self.dataset == 'mnist': #LeNet model takes [-.5, .5] pics images4score -= .5 if (images4score.max() > .5) or (images4score.min() < -.5): print('WARNING! LeNet min/max violated: min = %f, max = %f. Clipping values.' % (images4score.min(), images4score.max())) images4score = images4score.clip(-.5, .5) else: #Inception model takes [0 , 255] pics images4score *= 255.0 if (images4score.max() > 255.) or (images4score.min() < .0): print('WARNING! Inception min/max violated: min = %f, max = %f. Clipping values.' % (images4score.min(), images4score.max())) images4score = images4score.clip(0., 255.) preds, codes = cs.featurize(images4score, self.model, get_preds=True, get_codes=True, output=self.stdout) gan.timer(step, "featurizing finished") output['inception'] = scores = cs.inception_score(preds) gan.timer(step, "Inception mean (std): %f (%f)" % (np.mean(scores), np.std(scores))) output['fid'] = scores = cs.fid_score(codes, self.train_codes, output=self.stdout, split_method='bootstrap', splits=3) gan.timer(step, "FID mean (std): %f (%f)" % (np.mean(scores), np.std(scores))) ret = cs.polynomial_mmd_averages(codes, self.train_codes, output=self.stdout, n_subsets=10, subset_size=1000, ret_var=False) output['mmd2'] = mmd2s = ret gan.timer(step, "KID mean (std): %f (%f)" % (mmd2s.mean(), mmd2s.std())) if len(self.output) > 0: if np.min([sc['mmd2'].mean() for sc in self.output]) > output['mmd2'].mean(): print('Saving best model ...') gan.save_checkpoint() self.output.append(output) filepath = os.path.join(gan.sample_dir, 'score%d.npz' % step) np.savez(filepath, **output) if self.lr_scheduler: n = 10 if self.dataset == 'mnist': n = 10 nc = 3 bs = 2048 new_Y = codes[:bs] X = self.train_codes[:bs] print('No. of copmuted 3-sample statics: %d' % len(self.three_sample)) if len(self.three_sample) >= n: saved_Z = self.three_sample[0] mmd2_diff, test_stat, Y_related_sums = \ mmd.np_diff_polynomial_mmd2_and_ratio_with_saving(X, new_Y, saved_Z) p_val = scipy.stats.norm.cdf(test_stat) gan.timer(step, "3-sample test stat = %.1f" % test_stat) gan.timer(step, "3-sample p-value = %.1f" % p_val) if p_val > .1: self.three_sample_chances += 1 if self.three_sample_chances >= nc: # no confidence that new Y sample is closer to X than old Z is gan.sess.run(gan.lr_decay_op) print('No improvement in last %d tests. Decreasing learning rate to %f' % \ (nc, gan.sess.run(gan.lr))) self.three_sample = (self.three_sample + [Y_related_sums])[-nc:] # reset memorized sums self.three_sample_chances = 0 else: print('No improvement in last %d test(s). Keeping learning rate at %f' % \ (self.three_sample_chances, gan.sess.run(gan.lr))) else: # we're confident that new_Y is better than old_Z is print('Keeping learning rate at %f' % gan.sess.run(gan.lr)) self.three_sample = self.three_sample[1:] + [Y_related_sums] self.three_sample_chances = 0 else: # add new sums to memory self.three_sample.append( mmd.np_diff_polynomial_mmd2_and_ratio_with_saving(X, new_Y, None) ) gan.timer(step, "computing stats for 3-sample test finished") print('current learning rate: %f' % gan.sess.run(gan.lr)) gan.timer(step, "Scoring end, total time = %.1f s" % (time.time() - tt))
6,569
44.625
141
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/utils/misc.py
""" Some codes from https://github.com/Newmu/dcgan_code Released under the MIT license. """ from __future__ import division import random import pprint import scipy.misc import numpy as np from time import gmtime, strftime import tensorflow as tf from six.moves import xrange pp = pprint.PrettyPrinter() def inverse_transform(images): return (images+1.)/2. def save_images(images, size, image_path): merged = merge(inverse_transform(images), size) return scipy.misc.imsave(image_path, merged) def merge(images, size): h, w = images.shape[1], images.shape[2] img = np.zeros((h * size[0], w * size[1], 3)) for idx, image in enumerate(images): i = idx % size[1] j = idx // size[1] img[j*h:j*h+h, i*w:i*w+w, :] = image return img def center_crop(x, crop_h, crop_w, resize_h=64, resize_w=64): if crop_w is None: crop_w = crop_h h, w = x.shape[:2] j = int(round((h - crop_h)/2.)) i = int(round((w - crop_w)/2.)) return scipy.misc.imresize(x[j:j+crop_h, i:i+crop_w], [resize_h, resize_w]) def make_gif(images, fname, duration=2, true_image=False): import moviepy.editor as mpy def make_frame(t): try: x = images[int(len(images)/duration*t)] except: x = images[-1] if true_image: return x.astype(np.uint8) else: return ((x+1)/2*255).astype(np.uint8) clip = mpy.VideoClip(make_frame, duration=duration) clip.write_gif(fname, fps=len(images) / duration) def visualize(sess, dcgan, config, option): if option == 0: z_sample = np.random.uniform(-0.5, 0.5, size=(config.batch_size, dcgan.z_dim)) samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) time0 = strftime("%Y-%m-%d %H:%M:%S", gmtime()) save_images(samples, [8, 8], './samples/test_%s.png' % time0) elif option == 1: values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(100): print(" [*] %d" % idx) z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) save_images(samples, [8, 8], './samples/test_arange_%s.png' % (idx)) elif option == 2: values = np.arange(0, 1, 1./config.batch_size) for idx in [random.randint(0, 99) for _ in xrange(100)]: print(" [*] %d" % idx) z = np.random.uniform(-0.2, 0.2, size=(dcgan.z_dim)) z_sample = np.tile(z, (config.batch_size, 1)) #z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) make_gif(samples, './samples/test_gif_%s.gif' % (idx)) elif option == 3: values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(100): print(" [*] %d" % idx) z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) make_gif(samples, './samples/test_gif_%s.gif' % (idx)) elif option == 4: image_set = [] values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(100): print(" [*] %d" % idx) z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] image_set.append(sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})) make_gif(image_set[-1], './samples/test_gif_%s.gif' % (idx)) new_image_set = [ merge(np.array([images[idx] for images in image_set]), [10, 10]) for idx in range(64) + range(63, -1, -1)] make_gif(new_image_set, './samples/test_gif_merged.gif', duration=8) def unpickle(file): import _pickle as cPickle fo = open(file, 'rb') dict = cPickle.load(fo, encoding='latin1') fo.close() return dict def center_and_scale(im, size=64) : size = int(size) arr = np.array(im) scale = min(im.size)/float(size) new_size = np.array(im.size)/scale im.thumbnail(new_size) arr = np.array(im) assert min(arr.shape[:2]) == size, "shape error: " + repr(arr.shape) + ", lower dim should be " + repr(size) # l0 = int((arr.shape[0] - size)//2) # l1 = int((arr.shape[1] - size)//2) l0 = np.random.choice(np.arange(arr.shape[0] - size + 1), 1)[0] l1 = np.random.choice(np.arange(arr.shape[1] - size + 1), 1)[0] arr = arr[l0:l0 + size, l1: l1 + size, :] sh = (size, size, 3) assert arr.shape == sh, "shape error: " + repr(arr.shape) + ", should be " + repr(sh) return np.asarray(arr/255., dtype=np.float32) def center_and_scale_new(im, size=64, assumed_input_size=256, channels=3): if assumed_input_size is not None: ratio = int(assumed_input_size/size) decoded = tf.image.decode_jpeg(im, channels=channels, ratio=ratio) cropped = tf.random_crop(decoded, size=[size, size, 3]) return tf.to_float(cropped)/255. size = int(size) decoded = tf.image.decode_jpeg(im, channels=channels) s = tf.reduce_min(tf.shape(decoded)[:2]) cropped = tf.random_crop(decoded, size=[s, s, 3]) scaled = tf.image.resize_images(cropped, [size, size]) return tf.to_float(scaled)/255. def read_and_scale(file, size=64): from PIL import Image im = Image.open(file) return center_and_scale(im, size=size) def variable_summary(var, name): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" # with tf.get_variable_scope(): if var is None: print("Variable Summary: None value for variable '%s'" % name) return var = tf.clip_by_value(var, -1000., 1000.) mean = tf.reduce_mean(var) with tf.name_scope('absdev'): stddev = tf.reduce_mean(tf.abs(var - mean)) # tf.summary.scalar(name + '_absdev', stddev) # tf.summary.scalar(name + '_norm', tf.sqrt(tf.reduce_mean(tf.square(var)))) # tf.summary.histogram(name + '_histogram', var) def variable_summaries(variable_dict): for name, var in variable_dict.items(): variable_summary(var, name) def conv_sizes(size, layers, stride=2): s = [int(size)] for l in range(layers): s.append(int(np.ceil(float(s[-1])/float(stride)))) return tuple(s) def get_image(image_path, input_height, input_width, resize_height=64, resize_width=64, crop=True, grayscale=False): image = imread(image_path, grayscale) return transform(image, input_height, input_width, resize_height, resize_width, crop) def imread(path, grayscale = False): if (grayscale): return scipy.misc.imread(path, flatten = True).astype(np.float) else: return scipy.misc.imread(path).astype(np.float) def merge_images(images, size): return inverse_transform(images) def imsave(images, size, path): image = np.squeeze(merge(images, size)) return scipy.misc.imsave(path, image) def transform(image, input_height, input_width, resize_height=64, resize_width=64, crop=True): if crop: cropped_image = center_crop(image, input_height, input_width, resize_height, resize_width) else: cropped_image = scipy.misc.imresize(image, [resize_height, resize_width]) return np.array(cropped_image)/255. def tf_read_jpeg(files, base_size=160, target_size=64, batch_size=128, capacity=4000, num_threads=4, random_crop=9): filename_queue = tf.train.string_input_producer(files) reader = tf.WholeFileReader() _, raw = reader.read(filename_queue) decoded = tf.image.decode_jpeg(raw, channels=3) # HWC bs = base_size + 2 * random_crop cropped = tf.image.resize_image_with_crop_or_pad(decoded, bs, bs) if random_crop > 0: cropped = tf.image.random_flip_left_right(cropped) cropped = tf.random_crop(cropped, [base_size, base_size, 3]) ims = tf.train.shuffle_batch( [cropped], batch_size=batch_size, capacity=capacity, min_after_dequeue=capacity//4, num_threads=4, enqueue_many=False ) resized = tf.image.resize_bilinear(ims, (target_size, target_size)) images = tf.cast(resized, tf.float32)/255. return images def PIL_read_jpeg(files, base_size=160, target_size=64, batch_size=128, capacity=4000, num_threads=4): from PIL import Image def read_single(f): img = Image.open(f) w, h = img.size assert w >= base_size, 'wrong width' assert h >= base_size, 'wrong height' l, r = (w - base_size)//2, (h - base_size)//2 img.crop((l, r, l + base_size, r + base_size)) img.resize((target_size, target_size), Image.ANTIALIAS) return np.asarray(img, tf.float32)/255. filename_queue = tf.train.string_input_producer(files, shuffle=True) single_file = filename_queue.dequeue() single_sample = tf.py_func(read_single, [single_file], tf.float32) single_sample.set_shape([target_size, target_size, 3]) images = tf.train.shuffle_batch( [single_sample], batch_size=batch_size, capacity=capacity, min_after_dequeue=capacity//4, num_threads=4, enqueue_many=False ) return images
9,739
33.661922
112
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/utils/utils.py
""" Some codes from https://github.com/Newmu/dcgan_code Released under the MIT license. """ from __future__ import division import random import pprint import scipy.misc import numpy as np from time import gmtime, strftime import tensorflow as tf from six.moves import xrange pp = pprint.PrettyPrinter() def inverse_transform(images): return (images+1.)/2. def save_images(images, size, image_path): merged = merge(inverse_transform(images), size) return scipy.misc.imsave(image_path, merged) def merge(images, size): h, w = images.shape[1], images.shape[2] img = np.zeros((h * size[0], w * size[1], 3)) for idx, image in enumerate(images): i = idx % size[1] j = idx // size[1] img[j*h:j*h+h, i*w:i*w+w, :] = image return img def center_crop(x, crop_h, crop_w, resize_h=64, resize_w=64): if crop_w is None: crop_w = crop_h h, w = x.shape[:2] j = int(round((h - crop_h)/2.)) i = int(round((w - crop_w)/2.)) return scipy.misc.imresize(x[j:j+crop_h, i:i+crop_w], [resize_h, resize_w]) def make_gif(images, fname, duration=2, true_image=False): import moviepy.editor as mpy def make_frame(t): try: x = images[int(len(images)/duration*t)] except: x = images[-1] if true_image: return x.astype(np.uint8) else: return ((x+1)/2*255).astype(np.uint8) clip = mpy.VideoClip(make_frame, duration=duration) clip.write_gif(fname, fps=len(images) / duration) def visualize(sess, dcgan, config, option): if option == 0: z_sample = np.random.uniform(-0.5, 0.5, size=(config.batch_size, dcgan.z_dim)) samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) time0 = strftime("%Y-%m-%d %H:%M:%S", gmtime()) save_images(samples, [8, 8], './samples/test_%s.png' % time0) elif option == 1: values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(100): print(" [*] %d" % idx) z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) save_images(samples, [8, 8], './samples/test_arange_%s.png' % (idx)) elif option == 2: values = np.arange(0, 1, 1./config.batch_size) for idx in [random.randint(0, 99) for _ in xrange(100)]: print(" [*] %d" % idx) z = np.random.uniform(-0.2, 0.2, size=(dcgan.z_dim)) z_sample = np.tile(z, (config.batch_size, 1)) #z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) make_gif(samples, './samples/test_gif_%s.gif' % (idx)) elif option == 3: values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(100): print(" [*] %d" % idx) z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) make_gif(samples, './samples/test_gif_%s.gif' % (idx)) elif option == 4: image_set = [] values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(100): print(" [*] %d" % idx) z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] image_set.append(sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})) make_gif(image_set[-1], './samples/test_gif_%s.gif' % (idx)) new_image_set = [ merge(np.array([images[idx] for images in image_set]), [10, 10]) for idx in range(64) + range(63, -1, -1)] make_gif(new_image_set, './samples/test_gif_merged.gif', duration=8) def unpickle(file): import _pickle as cPickle fo = open(file, 'rb') dict = cPickle.load(fo, encoding='latin1') fo.close() return dict def center_and_scale(im, size=64) : size = int(size) arr = np.array(im) scale = min(im.size)/float(size) new_size = np.array(im.size)/scale im.thumbnail(new_size) arr = np.array(im) assert min(arr.shape[:2]) == size, "shape error: " + repr(arr.shape) + ", lower dim should be " + repr(size) # l0 = int((arr.shape[0] - size)//2) # l1 = int((arr.shape[1] - size)//2) l0 = np.random.choice(np.arange(arr.shape[0] - size + 1), 1)[0] l1 = np.random.choice(np.arange(arr.shape[1] - size + 1), 1)[0] arr = arr[l0:l0 + size, l1: l1 + size, :] sh = (size, size, 3) assert arr.shape == sh, "shape error: " + repr(arr.shape) + ", should be " + repr(sh) return np.asarray(arr/255., dtype=np.float32) def center_and_scale_new(im, size=64, assumed_input_size=256, channels=3): if assumed_input_size is not None: ratio = int(assumed_input_size/size) decoded = tf.image.decode_jpeg(im, channels=channels, ratio=ratio) cropped = tf.random_crop(decoded, size=[size, size, 3]) return tf.to_float(cropped)/255. size = int(size) decoded = tf.image.decode_jpeg(im, channels=channels) s = tf.reduce_min(tf.shape(decoded)[:2]) cropped = tf.random_crop(decoded, size=[s, s, 3]) scaled = tf.image.resize_images(cropped, [size, size]) return tf.to_float(scaled)/255. def read_and_scale(file, size=64): from PIL import Image im = Image.open(file) return center_and_scale(im, size=size) def variable_summary(var, name): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" # with tf.get_variable_scope(): if var is None: print("Variable Summary: None value for variable '%s'" % name) return var = tf.clip_by_value(var, -1000., 1000.) mean = tf.reduce_mean(var) with tf.name_scope('absdev'): stddev = tf.reduce_mean(tf.abs(var - mean)) tf.summary.scalar(name + '_absdev', stddev) # tf.summary.scalar(name + '_norm', tf.sqrt(tf.reduce_mean(tf.square(var)))) tf.summary.histogram(name + '_histogram', var) def variable_summaries(variable_dict): for name, var in variable_dict.items(): variable_summary(var, name) def conv_sizes(size, layers, stride=2): s = [int(size)] for l in range(layers): s.append(int(np.ceil(float(s[-1])/float(stride)))) return tuple(s) def get_image(image_path, input_height, input_width, resize_height=64, resize_width=64, crop=True, grayscale=False): image = imread(image_path, grayscale) return transform(image, input_height, input_width, resize_height, resize_width, crop) def imread(path, grayscale = False): if (grayscale): return scipy.misc.imread(path, flatten = True).astype(np.float) else: return scipy.misc.imread(path).astype(np.float) def merge_images(images, size): return inverse_transform(images) def imsave(images, size, path): image = np.squeeze(merge(images, size)) return scipy.misc.imsave(path, image) def transform(image, input_height, input_width, resize_height=64, resize_width=64, crop=True): if crop: cropped_image = center_crop(image, input_height, input_width, resize_height, resize_width) else: cropped_image = scipy.misc.imresize(image, [resize_height, resize_width]) return np.array(cropped_image)/255. def tf_read_jpeg(files, base_size=160, target_size=64, batch_size=128, capacity=4000, num_threads=4, random_crop=9): filename_queue = tf.train.string_input_producer(files) reader = tf.WholeFileReader() _, raw = reader.read(filename_queue) decoded = tf.image.decode_jpeg(raw, channels=3) # HWC bs = base_size + 2 * random_crop cropped = tf.image.resize_image_with_crop_or_pad(decoded, bs, bs) if random_crop > 0: cropped = tf.image.random_flip_left_right(cropped) cropped = tf.random_crop(cropped, [base_size, base_size, 3]) ims = tf.train.shuffle_batch( [cropped], batch_size=batch_size, capacity=capacity, min_after_dequeue=capacity//4, num_threads=4, enqueue_many=False ) resized = tf.image.resize_bilinear(ims, (target_size, target_size)) images = tf.cast(resized, tf.float32)/255. return images def PIL_read_jpeg(files, base_size=160, target_size=64, batch_size=128, capacity=4000, num_threads=4): from PIL import Image def read_single(f): img = Image.open(f) w, h = img.size assert w >= base_size, 'wrong width' assert h >= base_size, 'wrong height' l, r = (w - base_size)//2, (h - base_size)//2 img.crop((l, r, l + base_size, r + base_size)) img.resize((target_size, target_size), Image.ANTIALIAS) return np.asarray(img, tf.float32)/255. filename_queue = tf.train.string_input_producer(files, shuffle=True) single_file = filename_queue.dequeue() single_sample = tf.py_func(read_single, [single_file], tf.float32) single_sample.set_shape([target_size, target_size, 3]) images = tf.train.shuffle_batch( [single_sample], batch_size=batch_size, capacity=capacity, min_after_dequeue=capacity//4, num_threads=4, enqueue_many=False ) return images
9,736
33.775
112
py
GANFingerprints
GANFingerprints-master/CramerGAN/gan/utils/__init__.py
__all__ = ['scorer', 'timer', 'misc']
38
18.5
37
py
GANFingerprints
GANFingerprints-master/ProGAN/tfutil.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import sys import inspect import importlib import imp import numpy as np from collections import OrderedDict import tensorflow as tf #---------------------------------------------------------------------------- # Convenience. def run(*args, **kwargs): # Run the specified ops in the default session. return tf.get_default_session().run(*args, **kwargs) def is_tf_expression(x): return isinstance(x, tf.Tensor) or isinstance(x, tf.Variable) or isinstance(x, tf.Operation) def shape_to_list(shape): return [dim.value for dim in shape] def flatten(x): with tf.name_scope('Flatten'): return tf.reshape(x, [-1]) def log2(x): with tf.name_scope('Log2'): return tf.log(x) * np.float32(1.0 / np.log(2.0)) def exp2(x): with tf.name_scope('Exp2'): return tf.exp(x * np.float32(np.log(2.0))) def lerp(a, b, t): with tf.name_scope('Lerp'): return a + (b - a) * t def lerp_clip(a, b, t): with tf.name_scope('LerpClip'): return a + (b - a) * tf.clip_by_value(t, 0.0, 1.0) def absolute_name_scope(scope): # Forcefully enter the specified name scope, ignoring any surrounding scopes. return tf.name_scope(scope + '/') #---------------------------------------------------------------------------- # Initialize TensorFlow graph and session using good default settings. def init_tf(config_dict=dict()): if tf.get_default_session() is None: tf.set_random_seed(np.random.randint(1 << 31)) create_session(config_dict, force_as_default=True) #---------------------------------------------------------------------------- # Create tf.Session based on config dict of the form # {'gpu_options.allow_growth': True} def create_session(config_dict=dict(), force_as_default=False): config = tf.ConfigProto() for key, value in config_dict.items(): fields = key.split('.') obj = config for field in fields[:-1]: obj = getattr(obj, field) setattr(obj, fields[-1], value) session = tf.Session(config=config) if force_as_default: session._default_session = session.as_default() session._default_session.enforce_nesting = False session._default_session.__enter__() return session #---------------------------------------------------------------------------- # Initialize all tf.Variables that have not already been initialized. # Equivalent to the following, but more efficient and does not bloat the tf graph: # tf.variables_initializer(tf.report_unitialized_variables()).run() def init_uninited_vars(vars=None): if vars is None: vars = tf.global_variables() test_vars = []; test_ops = [] with tf.control_dependencies(None): # ignore surrounding control_dependencies for var in vars: assert is_tf_expression(var) try: tf.get_default_graph().get_tensor_by_name(var.name.replace(':0', '/IsVariableInitialized:0')) except KeyError: # Op does not exist => variable may be uninitialized. test_vars.append(var) with absolute_name_scope(var.name.split(':')[0]): test_ops.append(tf.is_variable_initialized(var)) init_vars = [var for var, inited in zip(test_vars, run(test_ops)) if not inited] run([var.initializer for var in init_vars]) #---------------------------------------------------------------------------- # Set the values of given tf.Variables. # Equivalent to the following, but more efficient and does not bloat the tf graph: # tfutil.run([tf.assign(var, value) for var, value in var_to_value_dict.items()] def set_vars(var_to_value_dict): ops = [] feed_dict = {} for var, value in var_to_value_dict.items(): assert is_tf_expression(var) try: setter = tf.get_default_graph().get_tensor_by_name(var.name.replace(':0', '/setter:0')) # look for existing op except KeyError: with absolute_name_scope(var.name.split(':')[0]): with tf.control_dependencies(None): # ignore surrounding control_dependencies setter = tf.assign(var, tf.placeholder(var.dtype, var.shape, 'new_value'), name='setter') # create new setter ops.append(setter) feed_dict[setter.op.inputs[1]] = value run(ops, feed_dict) #---------------------------------------------------------------------------- # Autosummary creates an identity op that internally keeps track of the input # values and automatically shows up in TensorBoard. The reported value # represents an average over input components. The average is accumulated # constantly over time and flushed when save_summaries() is called. # # Notes: # - The output tensor must be used as an input for something else in the # graph. Otherwise, the autosummary op will not get executed, and the average # value will not get accumulated. # - It is perfectly fine to include autosummaries with the same name in # several places throughout the graph, even if they are executed concurrently. # - It is ok to also pass in a python scalar or numpy array. In this case, it # is added to the average immediately. _autosummary_vars = OrderedDict() # name => [var, ...] _autosummary_immediate = OrderedDict() # name => update_op, update_value _autosummary_finalized = False def autosummary(name, value): id = name.replace('/', '_') if is_tf_expression(value): with tf.name_scope('summary_' + id), tf.device(value.device): update_op = _create_autosummary_var(name, value) with tf.control_dependencies([update_op]): return tf.identity(value) else: # python scalar or numpy array if name not in _autosummary_immediate: with absolute_name_scope('Autosummary/' + id), tf.device(None), tf.control_dependencies(None): update_value = tf.placeholder(tf.float32) update_op = _create_autosummary_var(name, update_value) _autosummary_immediate[name] = update_op, update_value update_op, update_value = _autosummary_immediate[name] run(update_op, {update_value: np.float32(value)}) return value # Create the necessary ops to include autosummaries in TensorBoard report. # Note: This should be done only once per graph. def finalize_autosummaries(): global _autosummary_finalized if _autosummary_finalized: return _autosummary_finalized = True init_uninited_vars([var for vars in _autosummary_vars.values() for var in vars]) with tf.device(None), tf.control_dependencies(None): for name, vars in _autosummary_vars.items(): id = name.replace('/', '_') with absolute_name_scope('Autosummary/' + id): sum = tf.add_n(vars) avg = sum[0] / sum[1] with tf.control_dependencies([avg]): # read before resetting reset_ops = [tf.assign(var, tf.zeros(2)) for var in vars] with tf.name_scope(None), tf.control_dependencies(reset_ops): # reset before reporting tf.summary.scalar(name, avg) # Internal helper for creating autosummary accumulators. def _create_autosummary_var(name, value_expr): assert not _autosummary_finalized v = tf.cast(value_expr, tf.float32) if v.shape.ndims is 0: v = [v, np.float32(1.0)] elif v.shape.ndims is 1: v = [tf.reduce_sum(v), tf.cast(tf.shape(v)[0], tf.float32)] else: v = [tf.reduce_sum(v), tf.reduce_prod(tf.cast(tf.shape(v), tf.float32))] v = tf.cond(tf.is_finite(v[0]), lambda: tf.stack(v), lambda: tf.zeros(2)) with tf.control_dependencies(None): var = tf.Variable(tf.zeros(2)) # [numerator, denominator] update_op = tf.cond(tf.is_variable_initialized(var), lambda: tf.assign_add(var, v), lambda: tf.assign(var, v)) if name in _autosummary_vars: _autosummary_vars[name].append(var) else: _autosummary_vars[name] = [var] return update_op #---------------------------------------------------------------------------- # Call filewriter.add_summary() with all summaries in the default graph, # automatically finalizing and merging them on the first call. _summary_merge_op = None def save_summaries(filewriter, global_step=None): global _summary_merge_op if _summary_merge_op is None: finalize_autosummaries() with tf.device(None), tf.control_dependencies(None): _summary_merge_op = tf.summary.merge_all() filewriter.add_summary(_summary_merge_op.eval(), global_step) #---------------------------------------------------------------------------- # Utilities for importing modules and objects by name. def import_module(module_or_obj_name): parts = module_or_obj_name.split('.') parts[0] = {'np': 'numpy', 'tf': 'tensorflow'}.get(parts[0], parts[0]) for i in range(len(parts), 0, -1): try: module = importlib.import_module('.'.join(parts[:i])) relative_obj_name = '.'.join(parts[i:]) return module, relative_obj_name except ImportError: pass raise ImportError(module_or_obj_name) def find_obj_in_module(module, relative_obj_name): obj = module for part in relative_obj_name.split('.'): obj = getattr(obj, part) return obj def import_obj(obj_name): module, relative_obj_name = import_module(obj_name) return find_obj_in_module(module, relative_obj_name) def call_func_by_name(*args, func=None, **kwargs): assert func is not None return import_obj(func)(*args, **kwargs) #---------------------------------------------------------------------------- # Wrapper for tf.train.Optimizer that automatically takes care of: # - Gradient averaging for multi-GPU training. # - Dynamic loss scaling and typecasts for FP16 training. # - Ignoring corrupted gradients that contain NaNs/Infs. # - Reporting statistics. # - Well-chosen default settings. class Optimizer: def __init__( self, name = 'Train', tf_optimizer = 'tf.train.AdamOptimizer', learning_rate = 0.001, use_loss_scaling = False, loss_scaling_init = 64.0, loss_scaling_inc = 0.0005, loss_scaling_dec = 1.0, **kwargs): # Init fields. self.name = name self.learning_rate = tf.convert_to_tensor(learning_rate) self.id = self.name.replace('/', '.') self.scope = tf.get_default_graph().unique_name(self.id) self.optimizer_class = import_obj(tf_optimizer) self.optimizer_kwargs = dict(kwargs) self.use_loss_scaling = use_loss_scaling self.loss_scaling_init = loss_scaling_init self.loss_scaling_inc = loss_scaling_inc self.loss_scaling_dec = loss_scaling_dec self._grad_shapes = None # [shape, ...] self._dev_opt = OrderedDict() # device => optimizer self._dev_grads = OrderedDict() # device => [[(grad, var), ...], ...] self._dev_ls_var = OrderedDict() # device => variable (log2 of loss scaling factor) self._updates_applied = False # Register the gradients of the given loss function with respect to the given variables. # Intended to be called once per GPU. def register_gradients(self, loss, vars): assert not self._updates_applied # Validate arguments. if isinstance(vars, dict): vars = list(vars.values()) # allow passing in Network.trainables as vars assert isinstance(vars, list) and len(vars) >= 1 assert all(is_tf_expression(expr) for expr in vars + [loss]) if self._grad_shapes is None: self._grad_shapes = [shape_to_list(var.shape) for var in vars] assert len(vars) == len(self._grad_shapes) assert all(shape_to_list(var.shape) == var_shape for var, var_shape in zip(vars, self._grad_shapes)) dev = loss.device assert all(var.device == dev for var in vars) # Register device and compute gradients. with tf.name_scope(self.id + '_grad'), tf.device(dev): if dev not in self._dev_opt: opt_name = self.scope.replace('/', '_') + '_opt%d' % len(self._dev_opt) self._dev_opt[dev] = self.optimizer_class(name=opt_name, learning_rate=self.learning_rate, **self.optimizer_kwargs) self._dev_grads[dev] = [] loss = self.apply_loss_scaling(tf.cast(loss, tf.float32)) grads = self._dev_opt[dev].compute_gradients(loss, vars, gate_gradients=tf.train.Optimizer.GATE_NONE) # disable gating to reduce memory usage grads = [(g, v) if g is not None else (tf.zeros_like(v), v) for g, v in grads] # replace disconnected gradients with zeros self._dev_grads[dev].append(grads) # Construct training op to update the registered variables based on their gradients. def apply_updates(self): assert not self._updates_applied self._updates_applied = True devices = list(self._dev_grads.keys()) total_grads = sum(len(grads) for grads in self._dev_grads.values()) assert len(devices) >= 1 and total_grads >= 1 ops = [] with absolute_name_scope(self.scope): # Cast gradients to FP32 and calculate partial sum within each device. dev_grads = OrderedDict() # device => [(grad, var), ...] for dev_idx, dev in enumerate(devices): with tf.name_scope('ProcessGrads%d' % dev_idx), tf.device(dev): sums = [] for gv in zip(*self._dev_grads[dev]): assert all(v is gv[0][1] for g, v in gv) g = [tf.cast(g, tf.float32) for g, v in gv] g = g[0] if len(g) == 1 else tf.add_n(g) sums.append((g, gv[0][1])) dev_grads[dev] = sums # Sum gradients across devices. if len(devices) > 1: with tf.name_scope('SumAcrossGPUs'), tf.device(None): for var_idx, grad_shape in enumerate(self._grad_shapes): g = [dev_grads[dev][var_idx][0] for dev in devices] if np.prod(grad_shape): # nccl does not support zero-sized tensors g = tf.contrib.nccl.all_sum(g) for dev, gg in zip(devices, g): dev_grads[dev][var_idx] = (gg, dev_grads[dev][var_idx][1]) # Apply updates separately on each device. for dev_idx, (dev, grads) in enumerate(dev_grads.items()): with tf.name_scope('ApplyGrads%d' % dev_idx), tf.device(dev): # Scale gradients as needed. if self.use_loss_scaling or total_grads > 1: with tf.name_scope('Scale'): coef = tf.constant(np.float32(1.0 / total_grads), name='coef') coef = self.undo_loss_scaling(coef) grads = [(g * coef, v) for g, v in grads] # Check for overflows. with tf.name_scope('CheckOverflow'): grad_ok = tf.reduce_all(tf.stack([tf.reduce_all(tf.is_finite(g)) for g, v in grads])) # Update weights and adjust loss scaling. with tf.name_scope('UpdateWeights'): opt = self._dev_opt[dev] ls_var = self.get_loss_scaling_var(dev) if not self.use_loss_scaling: ops.append(tf.cond(grad_ok, lambda: opt.apply_gradients(grads), tf.no_op)) else: ops.append(tf.cond(grad_ok, lambda: tf.group(tf.assign_add(ls_var, self.loss_scaling_inc), opt.apply_gradients(grads)), lambda: tf.group(tf.assign_sub(ls_var, self.loss_scaling_dec)))) # Report statistics on the last device. if dev == devices[-1]: with tf.name_scope('Statistics'): ops.append(autosummary(self.id + '/learning_rate', self.learning_rate)) ops.append(autosummary(self.id + '/overflow_frequency', tf.where(grad_ok, 0, 1))) if self.use_loss_scaling: ops.append(autosummary(self.id + '/loss_scaling_log2', ls_var)) # Initialize variables and group everything into a single op. self.reset_optimizer_state() init_uninited_vars(list(self._dev_ls_var.values())) return tf.group(*ops, name='TrainingOp') # Reset internal state of the underlying optimizer. def reset_optimizer_state(self): run([var.initializer for opt in self._dev_opt.values() for var in opt.variables()]) # Get or create variable representing log2 of the current dynamic loss scaling factor. def get_loss_scaling_var(self, device): if not self.use_loss_scaling: return None if device not in self._dev_ls_var: with absolute_name_scope(self.scope + '/LossScalingVars'), tf.control_dependencies(None): self._dev_ls_var[device] = tf.Variable(np.float32(self.loss_scaling_init), name='loss_scaling_var') return self._dev_ls_var[device] # Apply dynamic loss scaling for the given expression. def apply_loss_scaling(self, value): assert is_tf_expression(value) if not self.use_loss_scaling: return value return value * exp2(self.get_loss_scaling_var(value.device)) # Undo the effect of dynamic loss scaling for the given expression. def undo_loss_scaling(self, value): assert is_tf_expression(value) if not self.use_loss_scaling: return value return value * exp2(-self.get_loss_scaling_var(value.device)) #---------------------------------------------------------------------------- # Generic network abstraction. # # Acts as a convenience wrapper for a parameterized network construction # function, providing several utility methods and convenient access to # the inputs/outputs/weights. # # Network objects can be safely pickled and unpickled for long-term # archival purposes. The pickling works reliably as long as the underlying # network construction function is defined in a standalone Python module # that has no side effects or application-specific imports. network_import_handlers = [] # Custom import handlers for dealing with legacy data in pickle import. _network_import_modules = [] # Temporary modules create during pickle import. class Network: def __init__(self, name=None, # Network name. Used to select TensorFlow name and variable scopes. func=None, # Fully qualified name of the underlying network construction function. **static_kwargs): # Keyword arguments to be passed in to the network construction function. self._init_fields() self.name = name self.static_kwargs = dict(static_kwargs) # Init build func. module, self._build_func_name = import_module(func) self._build_module_src = inspect.getsource(module) self._build_func = find_obj_in_module(module, self._build_func_name) # Init graph. self._init_graph() self.reset_vars() def _init_fields(self): self.name = None # User-specified name, defaults to build func name if None. self.scope = None # Unique TF graph scope, derived from the user-specified name. self.static_kwargs = dict() # Arguments passed to the user-supplied build func. self.num_inputs = 0 # Number of input tensors. self.num_outputs = 0 # Number of output tensors. self.input_shapes = [[]] # Input tensor shapes (NC or NCHW), including minibatch dimension. self.output_shapes = [[]] # Output tensor shapes (NC or NCHW), including minibatch dimension. self.input_shape = [] # Short-hand for input_shapes[0]. self.output_shape = [] # Short-hand for output_shapes[0]. self.input_templates = [] # Input placeholders in the template graph. self.output_templates = [] # Output tensors in the template graph. self.input_names = [] # Name string for each input. self.output_names = [] # Name string for each output. self.vars = OrderedDict() # All variables (localname => var). self.trainables = OrderedDict() # Trainable variables (localname => var). self._build_func = None # User-supplied build function that constructs the network. self._build_func_name = None # Name of the build function. self._build_module_src = None # Full source code of the module containing the build function. self._run_cache = dict() # Cached graph data for Network.run(). def _init_graph(self): # Collect inputs. self.input_names = [] for param in inspect.signature(self._build_func).parameters.values(): if param.kind == param.POSITIONAL_OR_KEYWORD and param.default is param.empty: self.input_names.append(param.name) self.num_inputs = len(self.input_names) assert self.num_inputs >= 1 # Choose name and scope. if self.name is None: self.name = self._build_func_name self.scope = tf.get_default_graph().unique_name(self.name.replace('/', '_'), mark_as_used=False) # Build template graph. with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE): assert tf.get_variable_scope().name == self.scope with absolute_name_scope(self.scope): # ignore surrounding name_scope with tf.control_dependencies(None): # ignore surrounding control_dependencies self.input_templates = [tf.placeholder(tf.float32, name=name) for name in self.input_names] out_expr = self._build_func(*self.input_templates, is_template_graph=True, **self.static_kwargs) # Collect outputs. assert is_tf_expression(out_expr) or isinstance(out_expr, tuple) self.output_templates = [out_expr] if is_tf_expression(out_expr) else list(out_expr) self.output_names = [t.name.split('/')[-1].split(':')[0] for t in self.output_templates] self.num_outputs = len(self.output_templates) assert self.num_outputs >= 1 # Populate remaining fields. self.input_shapes = [shape_to_list(t.shape) for t in self.input_templates] self.output_shapes = [shape_to_list(t.shape) for t in self.output_templates] self.input_shape = self.input_shapes[0] self.output_shape = self.output_shapes[0] self.vars = OrderedDict([(self.get_var_localname(var), var) for var in tf.global_variables(self.scope + '/')]) self.trainables = OrderedDict([(self.get_var_localname(var), var) for var in tf.trainable_variables(self.scope + '/')]) # Run initializers for all variables defined by this network. def reset_vars(self): run([var.initializer for var in self.vars.values()]) # Run initializers for all trainable variables defined by this network. def reset_trainables(self): run([var.initializer for var in self.trainables.values()]) # Get TensorFlow expression(s) for the output(s) of this network, given the inputs. def get_output_for(self, *in_expr, return_as_list=False, **dynamic_kwargs): assert len(in_expr) == self.num_inputs all_kwargs = dict(self.static_kwargs) all_kwargs.update(dynamic_kwargs) with tf.variable_scope(self.scope, reuse=True): assert tf.get_variable_scope().name == self.scope named_inputs = [tf.identity(expr, name=name) for expr, name in zip(in_expr, self.input_names)] out_expr = self._build_func(*named_inputs, **all_kwargs) assert is_tf_expression(out_expr) or isinstance(out_expr, tuple) if return_as_list: out_expr = [out_expr] if is_tf_expression(out_expr) else list(out_expr) return out_expr # Get the local name of a given variable, excluding any surrounding name scopes. def get_var_localname(self, var_or_globalname): assert is_tf_expression(var_or_globalname) or isinstance(var_or_globalname, str) globalname = var_or_globalname if isinstance(var_or_globalname, str) else var_or_globalname.name assert globalname.startswith(self.scope + '/') localname = globalname[len(self.scope) + 1:] localname = localname.split(':')[0] return localname # Find variable by local or global name. def find_var(self, var_or_localname): assert is_tf_expression(var_or_localname) or isinstance(var_or_localname, str) return self.vars[var_or_localname] if isinstance(var_or_localname, str) else var_or_localname # Get the value of a given variable as NumPy array. # Note: This method is very inefficient -- prefer to use tfutil.run(list_of_vars) whenever possible. def get_var(self, var_or_localname): return self.find_var(var_or_localname).eval() # Set the value of a given variable based on the given NumPy array. # Note: This method is very inefficient -- prefer to use tfutil.set_vars() whenever possible. def set_var(self, var_or_localname, new_value): return set_vars({self.find_var(var_or_localname): new_value}) # Pickle export. def __getstate__(self): return { 'version': 2, 'name': self.name, 'static_kwargs': self.static_kwargs, 'build_module_src': self._build_module_src, 'build_func_name': self._build_func_name, 'variables': list(zip(self.vars.keys(), run(list(self.vars.values()))))} # Pickle import. def __setstate__(self, state): self._init_fields() # Execute custom import handlers. for handler in network_import_handlers: state = handler(state) # Set basic fields. assert state['version'] == 2 self.name = state['name'] self.static_kwargs = state['static_kwargs'] self._build_module_src = state['build_module_src'] self._build_func_name = state['build_func_name'] # Parse imported module. module = imp.new_module('_tfutil_network_import_module_%d' % len(_network_import_modules)) exec(self._build_module_src, module.__dict__) self._build_func = find_obj_in_module(module, self._build_func_name) _network_import_modules.append(module) # avoid gc # Init graph. self._init_graph() self.reset_vars() set_vars({self.find_var(name): value for name, value in state['variables']}) # Create a clone of this network with its own copy of the variables. def clone(self, name=None): net = object.__new__(Network) net._init_fields() net.name = name if name is not None else self.name net.static_kwargs = dict(self.static_kwargs) net._build_module_src = self._build_module_src net._build_func_name = self._build_func_name net._build_func = self._build_func net._init_graph() net.copy_vars_from(self) return net # Copy the values of all variables from the given network. def copy_vars_from(self, src_net): assert isinstance(src_net, Network) name_to_value = run({name: src_net.find_var(name) for name in self.vars.keys()}) set_vars({self.find_var(name): value for name, value in name_to_value.items()}) # Copy the values of all trainable variables from the given network. def copy_trainables_from(self, src_net): assert isinstance(src_net, Network) name_to_value = run({name: src_net.find_var(name) for name in self.trainables.keys()}) set_vars({self.find_var(name): value for name, value in name_to_value.items()}) # Create new network with the given parameters, and copy all variables from this network. def convert(self, name=None, func=None, **static_kwargs): net = Network(name, func, **static_kwargs) net.copy_vars_from(self) return net # Construct a TensorFlow op that updates the variables of this network # to be slightly closer to those of the given network. def setup_as_moving_average_of(self, src_net, beta=0.99, beta_nontrainable=0.0): assert isinstance(src_net, Network) with absolute_name_scope(self.scope): with tf.name_scope('MovingAvg'): ops = [] for name, var in self.vars.items(): if name in src_net.vars: cur_beta = beta if name in self.trainables else beta_nontrainable new_value = lerp(src_net.vars[name], var, cur_beta) ops.append(var.assign(new_value)) return tf.group(*ops) # Run this network for the given NumPy array(s), and return the output(s) as NumPy array(s). def run(self, *in_arrays, return_as_list = False, # True = return a list of NumPy arrays, False = return a single NumPy array, or a tuple if there are multiple outputs. print_progress = False, # Print progress to the console? Useful for very large input arrays. minibatch_size = None, # Maximum minibatch size to use, None = disable batching. num_gpus = 1, # Number of GPUs to use. out_mul = 1.0, # Multiplicative constant to apply to the output(s). out_add = 0.0, # Additive constant to apply to the output(s). out_shrink = 1, # Shrink the spatial dimensions of the output(s) by the given factor. out_dtype = None, # Convert the output to the specified data type. **dynamic_kwargs): # Additional keyword arguments to pass into the network construction function. assert len(in_arrays) == self.num_inputs num_items = in_arrays[0].shape[0] if minibatch_size is None: minibatch_size = num_items key = str([list(sorted(dynamic_kwargs.items())), num_gpus, out_mul, out_add, out_shrink, out_dtype]) # Build graph. if key not in self._run_cache: with absolute_name_scope(self.scope + '/Run'), tf.control_dependencies(None): in_split = list(zip(*[tf.split(x, num_gpus) for x in self.input_templates])) out_split = [] for gpu in range(num_gpus): with tf.device('/gpu:%d' % gpu): out_expr = self.get_output_for(*in_split[gpu], return_as_list=True, **dynamic_kwargs) if out_mul != 1.0: out_expr = [x * out_mul for x in out_expr] if out_add != 0.0: out_expr = [x + out_add for x in out_expr] if out_shrink > 1: ksize = [1, 1, out_shrink, out_shrink] out_expr = [tf.nn.avg_pool(x, ksize=ksize, strides=ksize, padding='VALID', data_format='NCHW') for x in out_expr] if out_dtype is not None: if tf.as_dtype(out_dtype).is_integer: out_expr = [tf.round(x) for x in out_expr] out_expr = [tf.saturate_cast(x, out_dtype) for x in out_expr] out_split.append(out_expr) self._run_cache[key] = [tf.concat(outputs, axis=0) for outputs in zip(*out_split)] # Run minibatches. out_expr = self._run_cache[key] out_arrays = [np.empty([num_items] + shape_to_list(expr.shape)[1:], expr.dtype.name) for expr in out_expr] for mb_begin in range(0, num_items, minibatch_size): if print_progress: print('\r%d / %d' % (mb_begin, num_items), end='') mb_end = min(mb_begin + minibatch_size, num_items) mb_in = [src[mb_begin : mb_end] for src in in_arrays] mb_out = tf.get_default_session().run(out_expr, dict(zip(self.input_templates, mb_in))) for dst, src in zip(out_arrays, mb_out): dst[mb_begin : mb_end] = src # Done. if print_progress: print('\r%d / %d' % (num_items, num_items)) if not return_as_list: out_arrays = out_arrays[0] if len(out_arrays) == 1 else tuple(out_arrays) return out_arrays # Returns a list of (name, output_expr, trainable_vars) tuples corresponding to # individual layers of the network. Mainly intended to be used for reporting. def list_layers(self): patterns_to_ignore = ['/Setter', '/new_value', '/Shape', '/strided_slice', '/Cast', '/concat'] all_ops = tf.get_default_graph().get_operations() all_ops = [op for op in all_ops if not any(p in op.name for p in patterns_to_ignore)] layers = [] def recurse(scope, parent_ops, level): prefix = scope + '/' ops = [op for op in parent_ops if op.name == scope or op.name.startswith(prefix)] # Does not contain leaf nodes => expand immediate children. if level == 0 or all('/' in op.name[len(prefix):] for op in ops): visited = set() for op in ops: suffix = op.name[len(prefix):] if '/' in suffix: suffix = suffix[:suffix.index('/')] if suffix not in visited: recurse(prefix + suffix, ops, level + 1) visited.add(suffix) # Otherwise => interpret as a layer. else: layer_name = scope[len(self.scope)+1:] layer_output = ops[-1].outputs[0] layer_trainables = [op.outputs[0] for op in ops if op.type.startswith('Variable') and self.get_var_localname(op.name) in self.trainables] layers.append((layer_name, layer_output, layer_trainables)) recurse(self.scope, all_ops, 0) return layers # Print a summary table of the network structure. def print_layers(self, title=None, hide_layers_with_no_params=False): if title is None: title = self.name print() print('%-28s%-12s%-24s%-24s' % (title, 'Params', 'OutputShape', 'WeightShape')) print('%-28s%-12s%-24s%-24s' % (('---',) * 4)) total_params = 0 for layer_name, layer_output, layer_trainables in self.list_layers(): weights = [var for var in layer_trainables if var.name.endswith('/weight:0')] num_params = sum(np.prod(shape_to_list(var.shape)) for var in layer_trainables) total_params += num_params if hide_layers_with_no_params and num_params == 0: continue print('%-28s%-12s%-24s%-24s' % ( layer_name, num_params if num_params else '-', layer_output.shape, weights[0].shape if len(weights) == 1 else '-')) print('%-28s%-12s%-24s%-24s' % (('---',) * 4)) print('%-28s%-12s%-24s%-24s' % ('Total', total_params, '', '')) print() # Construct summary ops to include histograms of all trainable parameters in TensorBoard. def setup_weight_histograms(self, title=None): if title is None: title = self.name with tf.name_scope(None), tf.device(None), tf.control_dependencies(None): for localname, var in self.trainables.items(): if '/' in localname: p = localname.split('/') name = title + '_' + p[-1] + '/' + '_'.join(p[:-1]) else: name = title + '_toplevel/' + localname tf.summary.histogram(name, var) #----------------------------------------------------------------------------
37,013
48.352
154
py
GANFingerprints
GANFingerprints-master/ProGAN/legacy.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import pickle import inspect import numpy as np import tfutil import networks #---------------------------------------------------------------------------- # Custom unpickler that is able to load network pickles produced by # the old Theano implementation. class LegacyUnpickler(pickle.Unpickler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def find_class(self, module, name): if module == 'network' and name == 'Network': return tfutil.Network return super().find_class(module, name) #---------------------------------------------------------------------------- # Import handler for tfutil.Network that silently converts networks produced # by the old Theano implementation to a suitable format. theano_gan_remap = { 'G_paper': 'G_paper', 'G_progressive_8': 'G_paper', 'D_paper': 'D_paper', 'D_progressive_8': 'D_paper'} def patch_theano_gan(state): if 'version' in state or state['build_func_spec']['func'] not in theano_gan_remap: return state spec = dict(state['build_func_spec']) func = spec.pop('func') resolution = spec.get('resolution', 32) resolution_log2 = int(np.log2(resolution)) use_wscale = spec.get('use_wscale', True) assert spec.pop('label_size', 0) == 0 assert spec.pop('use_batchnorm', False) == False assert spec.pop('tanh_at_end', None) is None assert spec.pop('mbstat_func', 'Tstdeps') == 'Tstdeps' assert spec.pop('mbstat_avg', 'all') == 'all' assert spec.pop('mbdisc_kernels', None) is None spec.pop( 'use_gdrop', True) # doesn't make a difference assert spec.pop('use_layernorm', False) == False spec[ 'fused_scale'] = False spec[ 'mbstd_group_size'] = 16 vars = [] param_iter = iter(state['param_values']) relu = np.sqrt(2); linear = 1.0 def flatten2(w): return w.reshape(w.shape[0], -1) def he_std(gain, w): return gain / np.sqrt(np.prod(w.shape[:-1])) def wscale(gain, w): return w * next(param_iter) / he_std(gain, w) if use_wscale else w def layer(name, gain, w): return [(name + '/weight', wscale(gain, w)), (name + '/bias', next(param_iter))] if func.startswith('G'): vars += layer('4x4/Dense', relu/4, flatten2(next(param_iter).transpose(1,0,2,3))) vars += layer('4x4/Conv', relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1]) for res in range(3, resolution_log2 + 1): vars += layer('%dx%d/Conv0' % (2**res, 2**res), relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1]) vars += layer('%dx%d/Conv1' % (2**res, 2**res), relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1]) for lod in range(0, resolution_log2 - 1): vars += layer('ToRGB_lod%d' % lod, linear, next(param_iter)[np.newaxis, np.newaxis]) if func.startswith('D'): vars += layer('FromRGB_lod0', relu, next(param_iter)[np.newaxis, np.newaxis]) for res in range(resolution_log2, 2, -1): vars += layer('%dx%d/Conv0' % (2**res, 2**res), relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1]) vars += layer('%dx%d/Conv1' % (2**res, 2**res), relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1]) vars += layer('FromRGB_lod%d' % (resolution_log2 - (res - 1)), relu, next(param_iter)[np.newaxis, np.newaxis]) vars += layer('4x4/Conv', relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1]) vars += layer('4x4/Dense0', relu, flatten2(next(param_iter)[:,:,::-1,::-1]).transpose()) vars += layer('4x4/Dense1', linear, next(param_iter)) vars += [('lod', state['toplevel_params']['cur_lod'])] return { 'version': 2, 'name': func, 'build_module_src': inspect.getsource(networks), 'build_func_name': theano_gan_remap[func], 'static_kwargs': spec, 'variables': vars} tfutil.network_import_handlers.append(patch_theano_gan) #---------------------------------------------------------------------------- # Import handler for tfutil.Network that ignores unsupported/deprecated # networks produced by older versions of the code. def ignore_unknown_theano_network(state): if 'version' in state: return state print('Ignoring unknown Theano network:', state['build_func_spec']['func']) return { 'version': 2, 'name': 'Dummy', 'build_module_src': 'def dummy(input, **kwargs): input.set_shape([None, 1]); return input', 'build_func_name': 'dummy', 'static_kwargs': {}, 'variables': []} tfutil.network_import_handlers.append(ignore_unknown_theano_network) #----------------------------------------------------------------------------
5,249
43.491525
122
py
GANFingerprints
GANFingerprints-master/ProGAN/loss.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import numpy as np import tensorflow as tf import tfutil #---------------------------------------------------------------------------- # Convenience func that casts all of its arguments to tf.float32. def fp32(*values): if len(values) == 1 and isinstance(values[0], tuple): values = values[0] values = tuple(tf.cast(v, tf.float32) for v in values) return values if len(values) >= 2 else values[0] #---------------------------------------------------------------------------- # Generator loss function used in the paper (WGAN + AC-GAN). def G_wgan_acgan(G, D, opt, training_set, minibatch_size, cond_weight = 1.0): # Weight of the conditioning term. latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out, fake_labels_out = fp32(D.get_output_for(fake_images_out, is_training=True)) loss = -fake_scores_out if D.output_shapes[1][1] > 0: with tf.name_scope('LabelPenalty'): label_penalty_fakes = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=fake_labels_out) loss += label_penalty_fakes * cond_weight return loss #---------------------------------------------------------------------------- # Discriminator loss function used in the paper (WGAN-GP + AC-GAN). def D_wgangp_acgan(G, D, opt, training_set, minibatch_size, reals, labels, wgan_lambda = 10.0, # Weight for the gradient penalty term. wgan_epsilon = 0.001, # Weight for the epsilon term, \epsilon_{drift}. wgan_target = 1.0, # Target value for gradient magnitudes. cond_weight = 1.0): # Weight of the conditioning terms. latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out, real_labels_out = fp32(D.get_output_for(reals, is_training=True)) fake_scores_out, fake_labels_out = fp32(D.get_output_for(fake_images_out, is_training=True)) real_scores_out = tfutil.autosummary('Loss/real_scores', real_scores_out) fake_scores_out = tfutil.autosummary('Loss/fake_scores', fake_scores_out) loss = fake_scores_out - real_scores_out with tf.name_scope('GradientPenalty'): mixing_factors = tf.random_uniform([minibatch_size, 1, 1, 1], 0.0, 1.0, dtype=fake_images_out.dtype) mixed_images_out = tfutil.lerp(tf.cast(reals, fake_images_out.dtype), fake_images_out, mixing_factors) mixed_scores_out, mixed_labels_out = fp32(D.get_output_for(mixed_images_out, is_training=True)) mixed_scores_out = tfutil.autosummary('Loss/mixed_scores', mixed_scores_out) mixed_loss = opt.apply_loss_scaling(tf.reduce_sum(mixed_scores_out)) mixed_grads = opt.undo_loss_scaling(fp32(tf.gradients(mixed_loss, [mixed_images_out])[0])) mixed_norms = tf.sqrt(tf.reduce_sum(tf.square(mixed_grads), axis=[1,2,3])) mixed_norms = tfutil.autosummary('Loss/mixed_norms', mixed_norms) gradient_penalty = tf.square(mixed_norms - wgan_target) loss += gradient_penalty * (wgan_lambda / (wgan_target**2)) with tf.name_scope('EpsilonPenalty'): epsilon_penalty = tfutil.autosummary('Loss/epsilon_penalty', tf.square(real_scores_out)) loss += epsilon_penalty * wgan_epsilon if D.output_shapes[1][1] > 0: with tf.name_scope('LabelPenalty'): label_penalty_reals = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=real_labels_out) label_penalty_fakes = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=fake_labels_out) label_penalty_reals = tfutil.autosummary('Loss/label_penalty_reals', label_penalty_reals) label_penalty_fakes = tfutil.autosummary('Loss/label_penalty_fakes', label_penalty_fakes) loss += (label_penalty_reals + label_penalty_fakes) * cond_weight return loss #----------------------------------------------------------------------------
4,447
52.590361
115
py
GANFingerprints
GANFingerprints-master/ProGAN/misc.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import sys import glob import datetime import pickle import re import numpy as np from collections import OrderedDict import scipy.ndimage import PIL.Image import config import dataset import legacy #---------------------------------------------------------------------------- # Convenience wrappers for pickle that are able to load data produced by # older versions of the code. def load_pkl(filename): with open(filename, 'rb') as file: return legacy.LegacyUnpickler(file, encoding='latin1').load() def save_pkl(obj, filename): with open(filename, 'wb') as file: pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL) #---------------------------------------------------------------------------- # Image utils. def adjust_dynamic_range(data, drange_in, drange_out): if drange_in != drange_out: scale = (np.float32(drange_out[1]) - np.float32(drange_out[0])) / (np.float32(drange_in[1]) - np.float32(drange_in[0])) bias = (np.float32(drange_out[0]) - np.float32(drange_in[0]) * scale) data = data * scale + bias return data def create_image_grid(images, grid_size=None): assert images.ndim == 3 or images.ndim == 4 num, img_w, img_h = images.shape[0], images.shape[-1], images.shape[-2] if grid_size is not None: grid_w, grid_h = tuple(grid_size) else: grid_w = max(int(np.ceil(np.sqrt(num))), 1) grid_h = max((num - 1) // grid_w + 1, 1) grid = np.zeros(list(images.shape[1:-2]) + [grid_h * img_h, grid_w * img_w], dtype=images.dtype) for idx in range(num): x = (idx % grid_w) * img_w y = (idx // grid_w) * img_h grid[..., y : y + img_h, x : x + img_w] = images[idx] return grid def convert_to_pil_image(image, drange=[0,1]): assert image.ndim == 2 or image.ndim == 3 if image.ndim == 3: if image.shape[0] == 1: image = image[0] # grayscale CHW => HW else: image = image.transpose(1, 2, 0) # CHW -> HWC image = adjust_dynamic_range(image, drange, [0,255]) image = np.rint(image).clip(0, 255).astype(np.uint8) format = 'RGB' if image.ndim == 3 else 'L' return PIL.Image.fromarray(image, format) def save_image(image, filename, drange=[0,1], quality=95): img = convert_to_pil_image(image, drange) if '.jpg' in filename: img.save(filename,"JPEG", quality=quality, optimize=True) else: img.save(filename) def save_image_grid(images, filename, drange=[0,1], grid_size=None): convert_to_pil_image(create_image_grid(images, grid_size), drange).save(filename) #---------------------------------------------------------------------------- # Logging of stdout and stderr to a file. class OutputLogger(object): def __init__(self): self.file = None self.buffer = '' def set_log_file(self, filename, mode='wt'): assert self.file is None self.file = open(filename, mode) if self.buffer is not None: self.file.write(self.buffer) self.buffer = None def write(self, data): if self.file is not None: self.file.write(data) if self.buffer is not None: self.buffer += data def flush(self): if self.file is not None: self.file.flush() class TeeOutputStream(object): def __init__(self, child_streams, autoflush=False): self.child_streams = child_streams self.autoflush = autoflush def write(self, data): for stream in self.child_streams: stream.write(data) if self.autoflush: self.flush() def flush(self): for stream in self.child_streams: stream.flush() output_logger = None def init_output_logging(): global output_logger if output_logger is None: output_logger = OutputLogger() sys.stdout = TeeOutputStream([sys.stdout, output_logger], autoflush=True) sys.stderr = TeeOutputStream([sys.stderr, output_logger], autoflush=True) def set_output_log_file(filename, mode='wt'): if output_logger is not None: output_logger.set_log_file(filename, mode) #---------------------------------------------------------------------------- # Reporting results. def create_result_subdir(result_dir, desc): # Select run ID and create subdir. while True: run_id = 0 for fname in glob.glob(os.path.join(result_dir, '*')): try: fbase = os.path.basename(fname) ford = int(fbase[:fbase.find('-')]) run_id = max(run_id, ford + 1) except ValueError: pass result_subdir = os.path.join(result_dir, '%03d-%s' % (run_id, desc)) try: os.makedirs(result_subdir) break except OSError: if os.path.isdir(result_subdir): continue raise print("Saving results to", result_subdir) set_output_log_file(os.path.join(result_subdir, 'log.txt')) # Export config. try: with open(os.path.join(result_subdir, 'config.txt'), 'wt') as fout: for k, v in sorted(config.__dict__.items()): if not k.startswith('_'): fout.write("%s = %s\n" % (k, str(v))) except: pass return result_subdir def format_time(seconds): s = int(np.rint(seconds)) if s < 60: return '%ds' % (s) elif s < 60*60: return '%dm %02ds' % (s // 60, s % 60) elif s < 24*60*60: return '%dh %02dm %02ds' % (s // (60*60), (s // 60) % 60, s % 60) else: return '%dd %02dh %02dm' % (s // (24*60*60), (s // (60*60)) % 24, (s // 60) % 60) def time_to_seconds(string): idx_d = string.find('d') if idx_d > -1: d = int(string[:idx_d]) else: d = 0 idx_h = string.find('h') if idx_h > -1: if idx_h == 1: h = int(string[:idx_h]) else: h = int(string[idx_h-2:idx_h]) else: h = 0 idx_m = string.find('m') if idx_m > -1: m = int(string[idx_m-2:idx_m]) else: m = 0 idx_s = string.find('s') if idx_s > -1: s = int(string[idx_s-2:idx_s]) else: s = 0 return float(((d*24+h)*60+m)*60+s) #---------------------------------------------------------------------------- # Locating results. def locate_result_subdir(run_id_or_result_subdir): if isinstance(run_id_or_result_subdir, str) and os.path.isdir(run_id_or_result_subdir): return run_id_or_result_subdir searchdirs = [] searchdirs += [''] searchdirs += ['results'] searchdirs += ['networks'] searchdirs += ['models'] for searchdir in searchdirs: dir = config.result_dir if searchdir == '' else os.path.join(config.result_dir, searchdir) dir = os.path.join(dir, str(run_id_or_result_subdir)) if os.path.isdir(dir): return dir prefix = '%03d' % run_id_or_result_subdir if isinstance(run_id_or_result_subdir, int) else str(run_id_or_result_subdir) dirs = sorted(glob.glob(os.path.join(config.result_dir, searchdir, prefix + '-*'))) dirs = [dir for dir in dirs if os.path.isdir(dir)] if len(dirs) == 1: return dirs[0] raise IOError('Cannot locate result subdir for run', run_id_or_result_subdir) def locate_result_subdir_without_run_id(): searchdirs = [] searchdirs += [''] searchdirs += ['results'] searchdirs += ['networks'] searchdirs += ['models'] for searchdir in searchdirs: dir = config.result_dir if searchdir == '' else os.path.join(config.result_dir, searchdir) dirs = sorted(glob.glob(os.path.join(dir, '*-pgan*'))) dirs = [dir for dir in dirs if os.path.isdir(dir)] if len(dirs) > 0: return dirs[-1] raise IOError('Cannot locate result subdir for run') def list_network_pkls(run_id_or_result_subdir, include_final=True): if run_id_or_result_subdir is None: result_subdir = locate_result_subdir_without_run_id() else: result_subdir = locate_result_subdir(run_id_or_result_subdir) pkls = sorted(glob.glob(os.path.join(result_subdir, 'network-*.pkl'))) if len(pkls) >= 1 and os.path.basename(pkls[0]) == 'network-final.pkl': if include_final: pkls.append(pkls[0]) del pkls[0] return pkls def locate_network_pkl(run_id_or_result_subdir_or_network_pkl=None, snapshot=None): if isinstance(run_id_or_result_subdir_or_network_pkl, str) and os.path.isfile(run_id_or_result_subdir_or_network_pkl): return run_id_or_result_subdir_or_network_pkl pkls = list_network_pkls(run_id_or_result_subdir_or_network_pkl) if len(pkls) >= 1 and snapshot is None: return pkls[-1] for pkl in pkls: try: name = os.path.splitext(os.path.basename(pkl))[0] number = int(name.split('-')[-1]) if number == snapshot: return pkl except ValueError: pass except IndexError: pass raise IOError('Cannot locate network pkl for snapshot', snapshot) def get_id_string_for_network_pkl(network_pkl): p = network_pkl.replace('.pkl', '').replace('\\', '/').split('/') return '-'.join(p[max(len(p) - 2, 0):]) def resume_kimg_time(network_pkl): path, file = os.path.split(network_pkl) file = os.path.splitext(file)[0] kimg = str(int(file[-6:])) with open('%s/log.txt' % path, 'r') as f: lines = f.readlines() for line in lines: if 'tick' in line and 'kimg' in line and 'minibatch' in line and 'time' in line and 'sec/tick' in line and 'sec/kimg' in line and 'maintenance' in line and kimg in line: idx = line.find(kimg) kimg = float(line[idx:idx+len(kimg)+2]) idx = line.find('time') t = line[idx+5:idx+5+12] s = time_to_seconds(t) break return kimg, s #---------------------------------------------------------------------------- # Loading and using trained networks. def load_network_pkl(run_id_or_result_subdir_or_network_pkl=None, snapshot=None): return load_pkl(locate_network_pkl(run_id_or_result_subdir_or_network_pkl, snapshot)) def random_latents(num_latents, G, random_state=None): if random_state is not None: return random_state.randn(num_latents, *G.input_shape[1:]).astype(np.float32) else: return np.random.randn(num_latents, *G.input_shape[1:]).astype(np.float32) def load_dataset_for_previous_run(run_id, **kwargs): # => dataset_obj, mirror_augment result_subdir = locate_result_subdir(run_id) # Parse config.txt. parsed_cfg = dict() with open(os.path.join(result_subdir, 'config.txt'), 'rt') as f: for line in f: if line.startswith('dataset =') or line.startswith('train ='): exec(line, parsed_cfg, parsed_cfg) dataset_cfg = parsed_cfg.get('dataset', dict()) train_cfg = parsed_cfg.get('train', dict()) mirror_augment = train_cfg.get('mirror_augment', False) # Handle legacy options. if 'h5_path' in dataset_cfg: dataset_cfg['tfrecord_dir'] = dataset_cfg.pop('h5_path').replace('.h5', '') if 'mirror_augment' in dataset_cfg: mirror_augment = dataset_cfg.pop('mirror_augment') if 'max_labels' in dataset_cfg: v = dataset_cfg.pop('max_labels') if v is None: v = 0 if v == 'all': v = 'full' dataset_cfg['max_label_size'] = v if 'max_images' in dataset_cfg: dataset_cfg.pop('max_images') # Handle legacy dataset names. v = dataset_cfg['tfrecord_dir'] v = v.replace('-32x32', '').replace('-32', '') v = v.replace('-128x128', '').replace('-128', '') v = v.replace('-256x256', '').replace('-256', '') v = v.replace('-1024x1024', '').replace('-1024', '') v = v.replace('celeba-hq', 'celebahq') v = v.replace('cifar-10', 'cifar10') v = v.replace('cifar-100', 'cifar100') v = v.replace('mnist-rgb', 'mnistrgb') v = re.sub('lsun-100k-([^-]*)', 'lsun-\\1-100k', v) v = re.sub('lsun-full-([^-]*)', 'lsun-\\1-full', v) dataset_cfg['tfrecord_dir'] = v # Load dataset. dataset_cfg.update(kwargs) dataset_obj = dataset.load_dataset(data_dir=config.data_dir, **dataset_cfg) return dataset_obj, mirror_augment def apply_mirror_augment(minibatch): mask = np.random.rand(minibatch.shape[0]) < 0.5 minibatch = np.array(minibatch) minibatch[mask] = minibatch[mask, :, :, ::-1] return minibatch #---------------------------------------------------------------------------- # Text labels. _text_label_cache = OrderedDict() def draw_text_label(img, text, x, y, alignx=0.5, aligny=0.5, color=255, opacity=1.0, glow_opacity=1.0, **kwargs): color = np.array(color).flatten().astype(np.float32) assert img.ndim == 3 and img.shape[2] == color.size or color.size == 1 alpha, glow = setup_text_label(text, **kwargs) xx, yy = int(np.rint(x - alpha.shape[1] * alignx)), int(np.rint(y - alpha.shape[0] * aligny)) xb, yb = max(-xx, 0), max(-yy, 0) xe, ye = min(alpha.shape[1], img.shape[1] - xx), min(alpha.shape[0], img.shape[0] - yy) img = np.array(img) slice = img[yy+yb : yy+ye, xx+xb : xx+xe, :] slice[:] = slice * (1.0 - (1.0 - (1.0 - alpha[yb:ye, xb:xe]) * (1.0 - glow[yb:ye, xb:xe] * glow_opacity)) * opacity)[:, :, np.newaxis] slice[:] = slice + alpha[yb:ye, xb:xe, np.newaxis] * (color * opacity)[np.newaxis, np.newaxis, :] return img def setup_text_label(text, font='Calibri', fontsize=32, padding=6, glow_size=2.0, glow_coef=3.0, glow_exp=2.0, cache_size=100): # => (alpha, glow) # Lookup from cache. key = (text, font, fontsize, padding, glow_size, glow_coef, glow_exp) if key in _text_label_cache: value = _text_label_cache[key] del _text_label_cache[key] # LRU policy _text_label_cache[key] = value return value # Limit cache size. while len(_text_label_cache) >= cache_size: _text_label_cache.popitem(last=False) # Render text. import moviepy.editor # pip install moviepy alpha = moviepy.editor.TextClip(text, font=font, fontsize=fontsize).mask.make_frame(0) alpha = np.pad(alpha, padding, mode='constant', constant_values=0.0) glow = scipy.ndimage.gaussian_filter(alpha, glow_size) glow = 1.0 - np.maximum(1.0 - glow * glow_coef, 0.0) ** glow_exp # Add to cache. value = (alpha, glow) _text_label_cache[key] = value return value #----------------------------------------------------------------------------
15,001
35.950739
177
py
GANFingerprints
GANFingerprints-master/ProGAN/dataset.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import glob import numpy as np import tensorflow as tf import tfutil #---------------------------------------------------------------------------- # Parse individual image from a tfrecords file. def parse_tfrecord_tf(record): features = tf.parse_single_example(record, features={ 'shape': tf.FixedLenFeature([3], tf.int64), 'data': tf.FixedLenFeature([], tf.string)}) data = tf.decode_raw(features['data'], tf.uint8) return tf.reshape(data, features['shape']) def parse_tfrecord_np(record): ex = tf.train.Example() ex.ParseFromString(record) shape = ex.features.feature['shape'].int64_list.value data = ex.features.feature['data'].bytes_list.value[0] return np.fromstring(data, np.uint8).reshape(shape) #---------------------------------------------------------------------------- # Dataset class that loads data from tfrecords files. class TFRecordDataset: def __init__(self, tfrecord_dir, # Directory containing a collection of tfrecords files. resolution = None, # Dataset resolution, None = autodetect. label_file = None, # Relative path of the labels file, None = autodetect. max_label_size = 0, # 0 = no labels, 'full' = full labels, <int> = N first label components. repeat = True, # Repeat dataset indefinitely. shuffle_mb = 4096, # Shuffle data within specified window (megabytes), 0 = disable shuffling. prefetch_mb = 2048, # Amount of data to prefetch (megabytes), 0 = disable prefetching. buffer_mb = 256, # Read buffer size (megabytes). num_threads = 2): # Number of concurrent threads. self.tfrecord_dir = tfrecord_dir self.resolution = None self.resolution_log2 = None self.shape = [] # [channel, height, width] self.dtype = 'uint8' self.dynamic_range = [0, 255] self.label_file = label_file self.label_size = None # [component] self.label_dtype = None self._np_labels = None self._tf_minibatch_in = None self._tf_labels_var = None self._tf_labels_dataset = None self._tf_datasets = dict() self._tf_iterator = None self._tf_init_ops = dict() self._tf_minibatch_np = None self._cur_minibatch = -1 self._cur_lod = -1 # List tfrecords files and inspect their shapes. assert os.path.isdir(self.tfrecord_dir) tfr_files = sorted(glob.glob(os.path.join(self.tfrecord_dir, '*.tfrecords'))) assert len(tfr_files) >= 1 tfr_shapes = [] for tfr_file in tfr_files: tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE) for record in tf.python_io.tf_record_iterator(tfr_file, tfr_opt): tfr_shapes.append(parse_tfrecord_np(record).shape) break # Autodetect label filename. if self.label_file is None: guess = sorted(glob.glob(os.path.join(self.tfrecord_dir, '*.labels'))) if len(guess): self.label_file = guess[0] elif not os.path.isfile(self.label_file): guess = os.path.join(self.tfrecord_dir, self.label_file) if os.path.isfile(guess): self.label_file = guess # Determine shape and resolution. max_shape = max(tfr_shapes, key=lambda shape: np.prod(shape)) self.resolution = resolution if resolution is not None else max_shape[1] self.resolution_log2 = int(np.log2(self.resolution)) self.shape = [max_shape[0], self.resolution, self.resolution] tfr_lods = [self.resolution_log2 - int(np.log2(shape[1])) for shape in tfr_shapes] assert all(shape[0] == max_shape[0] for shape in tfr_shapes) assert all(shape[1] == shape[2] for shape in tfr_shapes) assert all(shape[1] == self.resolution // (2**lod) for shape, lod in zip(tfr_shapes, tfr_lods)) assert all(lod in tfr_lods for lod in range(self.resolution_log2 - 1)) # Load labels. assert max_label_size == 'full' or max_label_size >= 0 self._np_labels = np.zeros([1<<20, 0], dtype=np.float32) if self.label_file is not None and max_label_size != 0: self._np_labels = np.load(self.label_file) assert self._np_labels.ndim == 2 if max_label_size != 'full' and self._np_labels.shape[1] > max_label_size: self._np_labels = self._np_labels[:, :max_label_size] self.label_size = self._np_labels.shape[1] self.label_dtype = self._np_labels.dtype.name # Build TF expressions. with tf.name_scope('Dataset'), tf.device('/cpu:0'): self._tf_minibatch_in = tf.placeholder(tf.int64, name='minibatch_in', shape=[]) tf_labels_init = tf.zeros(self._np_labels.shape, self._np_labels.dtype) self._tf_labels_var = tf.Variable(tf_labels_init, name='labels_var') tfutil.set_vars({self._tf_labels_var: self._np_labels}) self._tf_labels_dataset = tf.data.Dataset.from_tensor_slices(self._tf_labels_var) for tfr_file, tfr_shape, tfr_lod in zip(tfr_files, tfr_shapes, tfr_lods): if tfr_lod < 0: continue dset = tf.data.TFRecordDataset(tfr_file, compression_type='', buffer_size=buffer_mb<<20) dset = dset.map(parse_tfrecord_tf, num_parallel_calls=num_threads) dset = tf.data.Dataset.zip((dset, self._tf_labels_dataset)) bytes_per_item = np.prod(tfr_shape) * np.dtype(self.dtype).itemsize if shuffle_mb > 0: dset = dset.shuffle(((shuffle_mb << 20) - 1) // bytes_per_item + 1) if repeat: dset = dset.repeat() if prefetch_mb > 0: dset = dset.prefetch(((prefetch_mb << 20) - 1) // bytes_per_item + 1) dset = dset.batch(self._tf_minibatch_in) self._tf_datasets[tfr_lod] = dset self._tf_iterator = tf.data.Iterator.from_structure(self._tf_datasets[0].output_types, self._tf_datasets[0].output_shapes) self._tf_init_ops = {lod: self._tf_iterator.make_initializer(dset) for lod, dset in self._tf_datasets.items()} # Use the given minibatch size and level-of-detail for the data returned by get_minibatch_tf(). def configure(self, minibatch_size, lod=0): lod = int(np.floor(lod)) assert minibatch_size >= 1 and lod in self._tf_datasets if self._cur_minibatch != minibatch_size or self._cur_lod != lod: self._tf_init_ops[lod].run({self._tf_minibatch_in: minibatch_size}) self._cur_minibatch = minibatch_size self._cur_lod = lod # Get next minibatch as TensorFlow expressions. def get_minibatch_tf(self): # => images, labels return self._tf_iterator.get_next() # Get next minibatch as NumPy arrays. def get_minibatch_np(self, minibatch_size, lod=0): # => images, labels self.configure(minibatch_size, lod) if self._tf_minibatch_np is None: self._tf_minibatch_np = self.get_minibatch_tf() return tfutil.run(self._tf_minibatch_np) # Get random labels as TensorFlow expression. def get_random_labels_tf(self, minibatch_size): # => labels if self.label_size > 0: return tf.gather(self._tf_labels_var, tf.random_uniform([minibatch_size], 0, self._np_labels.shape[0], dtype=tf.int32)) else: return tf.zeros([minibatch_size, 0], self.label_dtype) # Get random labels as NumPy array. def get_random_labels_np(self, minibatch_size): # => labels if self.label_size > 0: return self._np_labels[np.random.randint(self._np_labels.shape[0], size=[minibatch_size])] else: return np.zeros([minibatch_size, 0], self.label_dtype) #---------------------------------------------------------------------------- # Base class for datasets that are generated on the fly. class SyntheticDataset: def __init__(self, resolution=1024, num_channels=3, dtype='uint8', dynamic_range=[0,255], label_size=0, label_dtype='float32'): self.resolution = resolution self.resolution_log2 = int(np.log2(resolution)) self.shape = [num_channels, resolution, resolution] self.dtype = dtype self.dynamic_range = dynamic_range self.label_size = label_size self.label_dtype = label_dtype self._tf_minibatch_var = None self._tf_lod_var = None self._tf_minibatch_np = None self._tf_labels_np = None assert self.resolution == 2 ** self.resolution_log2 with tf.name_scope('Dataset'): self._tf_minibatch_var = tf.Variable(np.int32(0), name='minibatch_var') self._tf_lod_var = tf.Variable(np.int32(0), name='lod_var') def configure(self, minibatch_size, lod=0): lod = int(np.floor(lod)) assert minibatch_size >= 1 and lod >= 0 and lod <= self.resolution_log2 tfutil.set_vars({self._tf_minibatch_var: minibatch_size, self._tf_lod_var: lod}) def get_minibatch_tf(self): # => images, labels with tf.name_scope('SyntheticDataset'): shrink = tf.cast(2.0 ** tf.cast(self._tf_lod_var, tf.float32), tf.int32) shape = [self.shape[0], self.shape[1] // shrink, self.shape[2] // shrink] images = self._generate_images(self._tf_minibatch_var, self._tf_lod_var, shape) labels = self._generate_labels(self._tf_minibatch_var) return images, labels def get_minibatch_np(self, minibatch_size, lod=0): # => images, labels self.configure(minibatch_size, lod) if self._tf_minibatch_np is None: self._tf_minibatch_np = self.get_minibatch_tf() return tfutil.run(self._tf_minibatch_np) def get_random_labels_tf(self, minibatch_size): # => labels with tf.name_scope('SyntheticDataset'): return self._generate_labels(minibatch_size) def get_random_labels_np(self, minibatch_size): # => labels self.configure(minibatch_size) if self._tf_labels_np is None: self._tf_labels_np = self.get_random_labels_tf() return tfutil.run(self._tf_labels_np) def _generate_images(self, minibatch, lod, shape): # to be overridden by subclasses return tf.zeros([minibatch] + shape, self.dtype) def _generate_labels(self, minibatch): # to be overridden by subclasses return tf.zeros([minibatch, self.label_size], self.label_dtype) #---------------------------------------------------------------------------- # Helper func for constructing a dataset object using the given options. def load_dataset(class_name='dataset.TFRecordDataset', data_dir=None, verbose=False, **kwargs): adjusted_kwargs = dict(kwargs) if 'tfrecord_dir' in adjusted_kwargs and data_dir is not None: adjusted_kwargs['tfrecord_dir'] = os.path.join(data_dir, adjusted_kwargs['tfrecord_dir']) if verbose: print('Streaming data using %s...' % class_name) dataset = tfutil.import_obj(class_name)(**adjusted_kwargs) if verbose: print('Dataset shape =', np.int32(dataset.shape).tolist()) print('Dynamic range =', dataset.dynamic_range) print('Label size =', dataset.label_size) return dataset #----------------------------------------------------------------------------
12,111
49.049587
134
py
GANFingerprints
GANFingerprints-master/ProGAN/networks.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import numpy as np import tensorflow as tf # NOTE: Do not import any application-specific modules here! #---------------------------------------------------------------------------- def lerp(a, b, t): return a + (b - a) * t def lerp_clip(a, b, t): return a + (b - a) * tf.clip_by_value(t, 0.0, 1.0) def cset(cur_lambda, new_cond, new_lambda): return lambda: tf.cond(new_cond, new_lambda, cur_lambda) #---------------------------------------------------------------------------- # Get/create weight tensor for a convolutional or fully-connected layer. def get_weight(shape, gain=np.sqrt(2), use_wscale=False, fan_in=None): if fan_in is None: fan_in = np.prod(shape[:-1]) std = gain / np.sqrt(fan_in) # He init if use_wscale: wscale = tf.constant(np.float32(std), name='wscale') return tf.get_variable('weight', shape=shape, initializer=tf.initializers.random_normal()) * wscale else: return tf.get_variable('weight', shape=shape, initializer=tf.initializers.random_normal(0, std)) #---------------------------------------------------------------------------- # Fully-connected layer. def dense(x, fmaps, gain=np.sqrt(2), use_wscale=False): if len(x.shape) > 2: x = tf.reshape(x, [-1, np.prod([d.value for d in x.shape[1:]])]) w = get_weight([x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale) w = tf.cast(w, x.dtype) return tf.matmul(x, w) #---------------------------------------------------------------------------- # Convolutional layer. def conv2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False): assert kernel >= 1 and kernel % 2 == 1 w = get_weight([kernel, kernel, x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale) w = tf.cast(w, x.dtype) return tf.nn.conv2d(x, w, strides=[1,1,1,1], padding='SAME', data_format='NCHW') #---------------------------------------------------------------------------- # Apply bias to the given activation tensor. def apply_bias(x): b = tf.get_variable('bias', shape=[x.shape[1]], initializer=tf.initializers.zeros()) b = tf.cast(b, x.dtype) if len(x.shape) == 2: return x + b else: return x + tf.reshape(b, [1, -1, 1, 1]) #---------------------------------------------------------------------------- # Leaky ReLU activation. Same as tf.nn.leaky_relu, but supports FP16. def leaky_relu(x, alpha=0.2): with tf.name_scope('LeakyRelu'): alpha = tf.constant(alpha, dtype=x.dtype, name='alpha') return tf.maximum(x * alpha, x) #---------------------------------------------------------------------------- # Nearest-neighbor upscaling layer. def upscale2d(x, factor=2): assert isinstance(factor, int) and factor >= 1 if factor == 1: return x with tf.variable_scope('Upscale2D'): s = x.shape x = tf.reshape(x, [-1, s[1], s[2], 1, s[3], 1]) x = tf.tile(x, [1, 1, 1, factor, 1, factor]) x = tf.reshape(x, [-1, s[1], s[2] * factor, s[3] * factor]) return x #---------------------------------------------------------------------------- # Fused upscale2d + conv2d. # Faster and uses less memory than performing the operations separately. def upscale2d_conv2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False): assert kernel >= 1 and kernel % 2 == 1 w = get_weight([kernel, kernel, fmaps, x.shape[1].value], gain=gain, use_wscale=use_wscale, fan_in=(kernel**2)*x.shape[1].value) w = tf.pad(w, [[1,1], [1,1], [0,0], [0,0]], mode='CONSTANT') w = tf.add_n([w[1:, 1:], w[:-1, 1:], w[1:, :-1], w[:-1, :-1]]) w = tf.cast(w, x.dtype) os = [tf.shape(x)[0], fmaps, x.shape[2] * 2, x.shape[3] * 2] return tf.nn.conv2d_transpose(x, w, os, strides=[1,1,2,2], padding='SAME', data_format='NCHW') #---------------------------------------------------------------------------- # Box filter downscaling layer. def downscale2d(x, factor=2): assert isinstance(factor, int) and factor >= 1 if factor == 1: return x with tf.variable_scope('Downscale2D'): ksize = [1, 1, factor, factor] return tf.nn.avg_pool(x, ksize=ksize, strides=ksize, padding='VALID', data_format='NCHW') # NOTE: requires tf_config['graph_options.place_pruned_graph'] = True #---------------------------------------------------------------------------- # Fused conv2d + downscale2d. # Faster and uses less memory than performing the operations separately. def conv2d_downscale2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False): assert kernel >= 1 and kernel % 2 == 1 w = get_weight([kernel, kernel, x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale) w = tf.pad(w, [[1,1], [1,1], [0,0], [0,0]], mode='CONSTANT') w = tf.add_n([w[1:, 1:], w[:-1, 1:], w[1:, :-1], w[:-1, :-1]]) * 0.25 w = tf.cast(w, x.dtype) return tf.nn.conv2d(x, w, strides=[1,1,2,2], padding='SAME', data_format='NCHW') #---------------------------------------------------------------------------- # Pixelwise feature vector normalization. def pixel_norm(x, epsilon=1e-8): with tf.variable_scope('PixelNorm'): return x * tf.rsqrt(tf.reduce_mean(tf.square(x), axis=1, keepdims=True) + epsilon) #---------------------------------------------------------------------------- # Minibatch standard deviation. def minibatch_stddev_layer(x, group_size=4): with tf.variable_scope('MinibatchStddev'): group_size = tf.minimum(group_size, tf.shape(x)[0]) # Minibatch must be divisible by (or smaller than) group_size. s = x.shape # [NCHW] Input shape. y = tf.reshape(x, [group_size, -1, s[1], s[2], s[3]]) # [GMCHW] Split minibatch into M groups of size G. y = tf.cast(y, tf.float32) # [GMCHW] Cast to FP32. y -= tf.reduce_mean(y, axis=0, keepdims=True) # [GMCHW] Subtract mean over group. y = tf.reduce_mean(tf.square(y), axis=0) # [MCHW] Calc variance over group. y = tf.sqrt(y + 1e-8) # [MCHW] Calc stddev over group. y = tf.reduce_mean(y, axis=[1,2,3], keepdims=True) # [M111] Take average over fmaps and pixels. y = tf.cast(y, x.dtype) # [M111] Cast back to original data type. y = tf.tile(y, [group_size, 1, s[2], s[3]]) # [N1HW] Replicate over group and pixels. return tf.concat([x, y], axis=1) # [NCHW] Append as new fmap. #---------------------------------------------------------------------------- # Generator network used in the paper. def G_paper( latents_in, # First input: Latent vectors [minibatch, latent_size]. labels_in, # Second input: Labels [minibatch, label_size]. num_channels = 1, # Number of output color channels. Overridden based on dataset. resolution = 32, # Output resolution. Overridden based on dataset. label_size = 0, # Dimensionality of the labels, 0 if no labels. Overridden based on dataset. fmap_base = 8192, # Overall multiplier for the number of feature maps. fmap_decay = 1.0, # log2 feature map reduction when doubling the resolution. fmap_max = 512, # Maximum number of feature maps in any layer. latent_size = None, # Dimensionality of the latent vectors. None = min(fmap_base, fmap_max). normalize_latents = True, # Normalize latent vectors before feeding them to the network? use_wscale = True, # Enable equalized learning rate? use_pixelnorm = True, # Enable pixelwise feature vector normalization? pixelnorm_epsilon = 1e-8, # Constant epsilon for pixelwise feature vector normalization. use_leakyrelu = True, # True = leaky ReLU, False = ReLU. dtype = 'float32', # Data type to use for activations and outputs. fused_scale = True, # True = use fused upscale2d + conv2d, False = separate upscale2d layers. structure = None, # 'linear' = human-readable, 'recursive' = efficient, None = select automatically. is_template_graph = False, # True = template graph constructed by the Network class, False = actual evaluation. **kwargs): # Ignore unrecognized keyword args. resolution_log2 = int(np.log2(resolution)) assert resolution == 2**resolution_log2 and resolution >= 4 def nf(stage): return min(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_max) def PN(x): return pixel_norm(x, epsilon=pixelnorm_epsilon) if use_pixelnorm else x if latent_size is None: latent_size = nf(0) if structure is None: structure = 'linear' if is_template_graph else 'recursive' act = leaky_relu if use_leakyrelu else tf.nn.relu latents_in.set_shape([None, latent_size]) labels_in.set_shape([None, label_size]) combo_in = tf.cast(tf.concat([latents_in, labels_in], axis=1), dtype) lod_in = tf.cast(tf.get_variable('lod', initializer=np.float32(0.0), trainable=False), dtype) # Building blocks. def block(x, res): # res = 2..resolution_log2 with tf.variable_scope('%dx%d' % (2**res, 2**res)): if res == 2: # 4x4 if normalize_latents: x = pixel_norm(x, epsilon=pixelnorm_epsilon) with tf.variable_scope('Dense'): x = dense(x, fmaps=nf(res-1)*16, gain=np.sqrt(2)/4, use_wscale=use_wscale) # override gain to match the original Theano implementation x = tf.reshape(x, [-1, nf(res-1), 4, 4]) x = PN(act(apply_bias(x))) with tf.variable_scope('Conv'): x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))) else: # 8x8 and up if fused_scale: with tf.variable_scope('Conv0_up'): x = PN(act(apply_bias(upscale2d_conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))) else: x = upscale2d(x) with tf.variable_scope('Conv0'): x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))) with tf.variable_scope('Conv1'): x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))) return x def torgb(x, res): # res = 2..resolution_log2 lod = resolution_log2 - res with tf.variable_scope('ToRGB_lod%d' % lod): return apply_bias(conv2d(x, fmaps=num_channels, kernel=1, gain=1, use_wscale=use_wscale)) # Linear structure: simple but inefficient. if structure == 'linear': x = block(combo_in, 2) images_out = torgb(x, 2) for res in range(3, resolution_log2 + 1): lod = resolution_log2 - res x = block(x, res) img = torgb(x, res) images_out = upscale2d(images_out) with tf.variable_scope('Grow_lod%d' % lod): images_out = lerp_clip(img, images_out, lod_in - lod) # Recursive structure: complex but efficient. if structure == 'recursive': def grow(x, res, lod): y = block(x, res) img = lambda: upscale2d(torgb(y, res), 2**lod) if res > 2: img = cset(img, (lod_in > lod), lambda: upscale2d(lerp(torgb(y, res), upscale2d(torgb(x, res - 1)), lod_in - lod), 2**lod)) if lod > 0: img = cset(img, (lod_in < lod), lambda: grow(y, res + 1, lod - 1)) return img() images_out = grow(combo_in, 2, resolution_log2 - 2) assert images_out.dtype == tf.as_dtype(dtype) images_out = tf.identity(images_out, name='images_out') return images_out #---------------------------------------------------------------------------- # Discriminator network used in the paper. def D_paper( images_in, # Input: Images [minibatch, channel, height, width]. num_channels = 1, # Number of input color channels. Overridden based on dataset. resolution = 32, # Input resolution. Overridden based on dataset. label_size = 0, # Dimensionality of the labels, 0 if no labels. Overridden based on dataset. fmap_base = 8192, # Overall multiplier for the number of feature maps. fmap_decay = 1.0, # log2 feature map reduction when doubling the resolution. fmap_max = 512, # Maximum number of feature maps in any layer. use_wscale = True, # Enable equalized learning rate? mbstd_group_size = 4, # Group size for the minibatch standard deviation layer, 0 = disable. dtype = 'float32', # Data type to use for activations and outputs. fused_scale = True, # True = use fused conv2d + downscale2d, False = separate downscale2d layers. structure = None, # 'linear' = human-readable, 'recursive' = efficient, None = select automatically is_template_graph = False, # True = template graph constructed by the Network class, False = actual evaluation. **kwargs): # Ignore unrecognized keyword args. resolution_log2 = int(np.log2(resolution)) assert resolution == 2**resolution_log2 and resolution >= 4 def nf(stage): return min(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_max) if structure is None: structure = 'linear' if is_template_graph else 'recursive' act = leaky_relu images_in.set_shape([None, num_channels, resolution, resolution]) images_in = tf.cast(images_in, dtype) lod_in = tf.cast(tf.get_variable('lod', initializer=np.float32(0.0), trainable=False), dtype) # Building blocks. def fromrgb(x, res): # res = 2..resolution_log2 with tf.variable_scope('FromRGB_lod%d' % (resolution_log2 - res)): return act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=1, use_wscale=use_wscale))) def block(x, res): # res = 2..resolution_log2 with tf.variable_scope('%dx%d' % (2**res, 2**res)): if res >= 3: # 8x8 and up with tf.variable_scope('Conv0'): x = act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale))) if fused_scale: with tf.variable_scope('Conv1_down'): x = act(apply_bias(conv2d_downscale2d(x, fmaps=nf(res-2), kernel=3, use_wscale=use_wscale))) else: with tf.variable_scope('Conv1'): x = act(apply_bias(conv2d(x, fmaps=nf(res-2), kernel=3, use_wscale=use_wscale))) x = downscale2d(x) else: # 4x4 if mbstd_group_size > 1: x = minibatch_stddev_layer(x, mbstd_group_size) with tf.variable_scope('Conv'): x = act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale))) with tf.variable_scope('Dense0'): x = act(apply_bias(dense(x, fmaps=nf(res-2), use_wscale=use_wscale))) with tf.variable_scope('Dense1'): x = apply_bias(dense(x, fmaps=1+label_size, gain=1, use_wscale=use_wscale)) return x # Linear structure: simple but inefficient. if structure == 'linear': img = images_in x = fromrgb(img, resolution_log2) for res in range(resolution_log2, 2, -1): lod = resolution_log2 - res x = block(x, res) img = downscale2d(img) y = fromrgb(img, res - 1) with tf.variable_scope('Grow_lod%d' % lod): x = lerp_clip(x, y, lod_in - lod) combo_out = block(x, 2) # Recursive structure: complex but efficient. if structure == 'recursive': def grow(res, lod): x = lambda: fromrgb(downscale2d(images_in, 2**lod), res) if lod > 0: x = cset(x, (lod_in < lod), lambda: grow(res + 1, lod - 1)) x = block(x(), res); y = lambda: x if res > 2: y = cset(y, (lod_in > lod), lambda: lerp(x, fromrgb(downscale2d(images_in, 2**(lod+1)), res - 1), lod_in - lod)) return y() combo_out = grow(2, resolution_log2 - 2) assert combo_out.dtype == tf.as_dtype(dtype) scores_out = tf.identity(combo_out[:, :1], name='scores_out') labels_out = tf.identity(combo_out[:, 1:], name='labels_out') return scores_out, labels_out #----------------------------------------------------------------------------
17,216
53.484177
167
py
GANFingerprints
GANFingerprints-master/ProGAN/run.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import time import numpy as np import tensorflow as tf import config import tfutil import dataset import misc import argparse #---------------------------------------------------------------------------- # Choose the size and contents of the image snapshot grids that are exported # periodically during training. def setup_snapshot_image_grid(G, training_set, size = '1080p', # '1080p' = to be viewed on 1080p display, '4k' = to be viewed on 4k display. layout = 'random'): # 'random' = grid contents are selected randomly, 'row_per_class' = each row corresponds to one class label. # Select size. gw = 1; gh = 1 if size == '1080p': gw = np.clip(1920 // G.output_shape[3], 3, 32) gh = np.clip(1080 // G.output_shape[2], 2, 32) if size == '4k': gw = np.clip(3840 // G.output_shape[3], 7, 32) gh = np.clip(2160 // G.output_shape[2], 4, 32) # Fill in reals and labels. reals = np.zeros([gw * gh] + training_set.shape, dtype=training_set.dtype) labels = np.zeros([gw * gh, training_set.label_size], dtype=training_set.label_dtype) for idx in range(gw * gh): x = idx % gw; y = idx // gw while True: real, label = training_set.get_minibatch_np(1) if layout == 'row_per_class' and training_set.label_size > 0: if label[0, y % training_set.label_size] == 0.0: continue reals[idx] = real[0] labels[idx] = label[0] break # Generate latents. latents = misc.random_latents(gw * gh, G) return (gw, gh), reals, labels, latents #---------------------------------------------------------------------------- # Just-in-time processing of training images before feeding them to the networks. def process_reals(x, lod, mirror_augment, drange_data, drange_net): with tf.name_scope('ProcessReals'): with tf.name_scope('DynamicRange'): x = tf.cast(x, tf.float32) x = misc.adjust_dynamic_range(x, drange_data, drange_net) if mirror_augment: with tf.name_scope('MirrorAugment'): s = tf.shape(x) mask = tf.random_uniform([s[0], 1, 1, 1], 0.0, 1.0) mask = tf.tile(mask, [1, s[1], s[2], s[3]]) x = tf.where(mask < 0.5, x, tf.reverse(x, axis=[3])) with tf.name_scope('FadeLOD'): # Smooth crossfade between consecutive levels-of-detail. s = tf.shape(x) y = tf.reshape(x, [-1, s[1], s[2]//2, 2, s[3]//2, 2]) y = tf.reduce_mean(y, axis=[3, 5], keepdims=True) y = tf.tile(y, [1, 1, 1, 2, 1, 2]) y = tf.reshape(y, [-1, s[1], s[2], s[3]]) x = tfutil.lerp(x, y, lod - tf.floor(lod)) with tf.name_scope('UpscaleLOD'): # Upscale to match the expected input/output size of the networks. s = tf.shape(x) factor = tf.cast(2 ** tf.floor(lod), tf.int32) x = tf.reshape(x, [-1, s[1], s[2], 1, s[3], 1]) x = tf.tile(x, [1, 1, 1, factor, 1, factor]) x = tf.reshape(x, [-1, s[1], s[2] * factor, s[3] * factor]) return x #---------------------------------------------------------------------------- # Class for evaluating and storing the values of time-varying training parameters. class TrainingSchedule: def __init__( self, cur_nimg, training_set, lod_initial_resolution = 4, # Image resolution used at the beginning. lod_training_kimg = 600, # Thousands of real images to show before doubling the resolution. lod_transition_kimg = 600, # Thousands of real images to show when fading in new layers. minibatch_base = 16, # Maximum minibatch size, divided evenly among GPUs. minibatch_dict = {}, # Resolution-specific overrides. max_minibatch_per_gpu = {}, # Resolution-specific maximum minibatch size per GPU. G_lrate_base = 0.001, # Learning rate for the generator. G_lrate_dict = {}, # Resolution-specific overrides. D_lrate_base = 0.001, # Learning rate for the discriminator. D_lrate_dict = {}, # Resolution-specific overrides. tick_kimg_base = 1, # Default interval of progress snapshots. tick_kimg_dict = {}): # Resolution-specific overrides. # Training phase. self.kimg = cur_nimg / 1000.0 phase_dur = lod_training_kimg + lod_transition_kimg phase_idx = int(np.floor(self.kimg / phase_dur)) if phase_dur > 0 else 0 phase_kimg = self.kimg - phase_idx * phase_dur # Level-of-detail and resolution. self.lod = training_set.resolution_log2 self.lod -= np.floor(np.log2(lod_initial_resolution)) self.lod -= phase_idx if lod_transition_kimg > 0: self.lod -= max(phase_kimg - lod_training_kimg, 0.0) / lod_transition_kimg self.lod = max(self.lod, 0.0) self.resolution = 2 ** (training_set.resolution_log2 - int(np.floor(self.lod))) # Minibatch size. self.minibatch = minibatch_dict.get(self.resolution, minibatch_base) self.minibatch -= self.minibatch % config.num_gpus if self.resolution in max_minibatch_per_gpu: self.minibatch = min(self.minibatch, max_minibatch_per_gpu[self.resolution] * config.num_gpus) # Other parameters. self.G_lrate = G_lrate_dict.get(self.resolution, G_lrate_base) self.D_lrate = D_lrate_dict.get(self.resolution, D_lrate_base) self.tick_kimg = tick_kimg_dict.get(self.resolution, tick_kimg_base) #---------------------------------------------------------------------------- # Main training script. # To run, comment/uncomment appropriate lines in config.py and launch train.py. def train_progressive_gan( G_smoothing = 0.999, # Exponential running average of generator weights. D_repeats = 1, # How many times the discriminator is trained per G iteration. minibatch_repeats = 4, # Number of minibatches to run before adjusting training parameters. reset_opt_for_new_lod = True, # Reset optimizer internal state (e.g. Adam moments) when new layers are introduced? total_kimg = 15000, # Total length of the training, measured in thousands of real images. mirror_augment = False, # Enable mirror augment? drange_net = [-1,1], # Dynamic range used when feeding image data to the networks. image_snapshot_ticks = 20, # How often to export image snapshots? network_snapshot_ticks = 100, # How often to export network snapshots? save_tf_graph = False, # Include full TensorFlow computation graph in the tfevents file? save_weight_histograms = False, # Include weight histograms in the tfevents file? resume = True): maintenance_start_time = time.time() training_set = dataset.load_dataset(data_dir=config.data_dir, verbose=True, **config.dataset) # Construct networks. with tf.device('/gpu:0'): if resume: try: network_pkl = misc.locate_network_pkl() resume_kimg, resume_time = misc.resume_kimg_time(network_pkl) print('Loading networks from "%s"...' % network_pkl) G, D, Gs = misc.load_pkl(network_pkl) except: print('Constructing networks...') resume_kimg = 0.0 resume_time = 0.0 G = tfutil.Network('G', num_channels=training_set.shape[0], resolution=training_set.shape[1], label_size=training_set.label_size, **config.G) D = tfutil.Network('D', num_channels=training_set.shape[0], resolution=training_set.shape[1], label_size=training_set.label_size, **config.D) Gs = G.clone('Gs') else: print('Constructing networks...') resume_kimg = 0.0 resume_time = 0.0 G = tfutil.Network('G', num_channels=training_set.shape[0], resolution=training_set.shape[1], label_size=training_set.label_size, **config.G) D = tfutil.Network('D', num_channels=training_set.shape[0], resolution=training_set.shape[1], label_size=training_set.label_size, **config.D) Gs = G.clone('Gs') Gs_update_op = Gs.setup_as_moving_average_of(G, beta=G_smoothing) G.print_layers(); D.print_layers() print('Building TensorFlow graph...') with tf.name_scope('Inputs'): lod_in = tf.placeholder(tf.float32, name='lod_in', shape=[]) lrate_in = tf.placeholder(tf.float32, name='lrate_in', shape=[]) minibatch_in = tf.placeholder(tf.int32, name='minibatch_in', shape=[]) minibatch_split = minibatch_in // config.num_gpus reals, labels = training_set.get_minibatch_tf() reals_split = tf.split(reals, config.num_gpus) labels_split = tf.split(labels, config.num_gpus) G_opt = tfutil.Optimizer(name='TrainG', learning_rate=lrate_in, **config.G_opt) D_opt = tfutil.Optimizer(name='TrainD', learning_rate=lrate_in, **config.D_opt) for gpu in range(config.num_gpus): with tf.name_scope('GPU%d' % gpu), tf.device('/gpu:%d' % gpu): G_gpu = G if gpu == 0 else G.clone(G.name + '_shadow') D_gpu = D if gpu == 0 else D.clone(D.name + '_shadow') lod_assign_ops = [tf.assign(G_gpu.find_var('lod'), lod_in), tf.assign(D_gpu.find_var('lod'), lod_in)] reals_gpu = process_reals(reals_split[gpu], lod_in, mirror_augment, training_set.dynamic_range, drange_net) labels_gpu = labels_split[gpu] with tf.name_scope('G_loss'), tf.control_dependencies(lod_assign_ops): G_loss = tfutil.call_func_by_name(G=G_gpu, D=D_gpu, opt=G_opt, training_set=training_set, minibatch_size=minibatch_split, **config.G_loss) with tf.name_scope('D_loss'), tf.control_dependencies(lod_assign_ops): D_loss = tfutil.call_func_by_name(G=G_gpu, D=D_gpu, opt=D_opt, training_set=training_set, minibatch_size=minibatch_split, reals=reals_gpu, labels=labels_gpu, **config.D_loss) G_opt.register_gradients(tf.reduce_mean(G_loss), G_gpu.trainables) D_opt.register_gradients(tf.reduce_mean(D_loss), D_gpu.trainables) G_train_op = G_opt.apply_updates() D_train_op = D_opt.apply_updates() print('Setting up snapshot image grid...') grid_size, grid_reals, grid_labels, grid_latents = setup_snapshot_image_grid(G, training_set, **config.grid) sched = TrainingSchedule(total_kimg * 1000, training_set, **config.sched) grid_fakes = Gs.run(grid_latents, grid_labels, minibatch_size=sched.minibatch//config.num_gpus) print('Setting up result dir...') result_subdir = misc.create_result_subdir(config.result_dir, config.desc) misc.save_image_grid(grid_reals, os.path.join(result_subdir, 'reals.png'), drange=training_set.dynamic_range, grid_size=grid_size) misc.save_image_grid(grid_fakes, os.path.join(result_subdir, 'fakes-init.png'), drange=drange_net, grid_size=grid_size) summary_log = tf.summary.FileWriter(result_subdir) if save_tf_graph: summary_log.add_graph(tf.get_default_graph()) if save_weight_histograms: G.setup_weight_histograms(); D.setup_weight_histograms() print('Training...') cur_nimg = int(resume_kimg * 1000) cur_tick = 0 tick_start_nimg = cur_nimg tick_start_time = time.time() train_start_time = tick_start_time - resume_time prev_lod = -1.0 while cur_nimg < total_kimg * 1000: # Choose training parameters and configure training ops. sched = TrainingSchedule(cur_nimg, training_set, **config.sched) training_set.configure(sched.minibatch, sched.lod) if reset_opt_for_new_lod: if np.floor(sched.lod) != np.floor(prev_lod) or np.ceil(sched.lod) != np.ceil(prev_lod): G_opt.reset_optimizer_state(); D_opt.reset_optimizer_state() prev_lod = sched.lod # Run training ops. for repeat in range(minibatch_repeats): for _ in range(D_repeats): tfutil.run([D_train_op, Gs_update_op], {lod_in: sched.lod, lrate_in: sched.D_lrate, minibatch_in: sched.minibatch}) cur_nimg += sched.minibatch tfutil.run([G_train_op], {lod_in: sched.lod, lrate_in: sched.G_lrate, minibatch_in: sched.minibatch}) # Perform maintenance tasks once per tick. done = (cur_nimg >= total_kimg * 1000) if cur_nimg >= tick_start_nimg + sched.tick_kimg * 1000 or done: cur_tick += 1 cur_time = time.time() tick_kimg = (cur_nimg - tick_start_nimg) / 1000.0 tick_start_nimg = cur_nimg tick_time = cur_time - tick_start_time total_time = cur_time - train_start_time maintenance_time = tick_start_time - maintenance_start_time maintenance_start_time = cur_time # Report progress. print('tick %-5d kimg %-8.1f lod %-5.2f minibatch %-4d time %-12s sec/tick %-7.1f sec/kimg %-7.2f maintenance %.1f' % ( tfutil.autosummary('Progress/tick', cur_tick), tfutil.autosummary('Progress/kimg', cur_nimg / 1000.0), tfutil.autosummary('Progress/lod', sched.lod), tfutil.autosummary('Progress/minibatch', sched.minibatch), misc.format_time(tfutil.autosummary('Timing/total_sec', total_time)), tfutil.autosummary('Timing/sec_per_tick', tick_time), tfutil.autosummary('Timing/sec_per_kimg', tick_time / tick_kimg), tfutil.autosummary('Timing/maintenance_sec', maintenance_time))) tfutil.autosummary('Timing/total_hours', total_time / (60.0 * 60.0)) tfutil.autosummary('Timing/total_days', total_time / (24.0 * 60.0 * 60.0)) tfutil.save_summaries(summary_log, cur_nimg) # Save snapshots. if cur_tick % image_snapshot_ticks == 0 or done: grid_fakes = Gs.run(grid_latents, grid_labels, minibatch_size=sched.minibatch//config.num_gpus) misc.save_image_grid(grid_fakes, os.path.join(result_subdir, 'fakes%06d.png' % (cur_nimg // 1000)), drange=drange_net, grid_size=grid_size) if cur_tick % network_snapshot_ticks == 0 or done: misc.save_pkl((G, D, Gs), os.path.join(result_subdir, 'network-snapshot-%06d.pkl' % (cur_nimg // 1000))) # Record start time of the next tick. tick_start_time = time.time() # Write final results. misc.save_image_grid(grid_fakes, os.path.join(result_subdir, 'fakes-final.png'), drange=drange_net, grid_size=grid_size) misc.save_pkl((G, D, Gs), os.path.join(result_subdir, 'network-final.pkl')) summary_log.close() open(os.path.join(result_subdir, '_training-done.txt'), 'wt').close() #---------------------------------------------------------------------------- # Main entry point. # Calls the function indicated in config.py. if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--app', type=str, default=' ') #------------------- training arguments ------------------- parser.add_argument('--training_data_dir', type=str, default=' ') # The prepared training dataset directory that can be efficiently called by the code parser.add_argument('--out_model_dir', type=str, default=' ') # The output directory containing trained models, training configureation, training log, and training snapshots parser.add_argument('--training_seed', type=int, default=1000) # The random seed that differentiates training instances #------------------- image generation arguments ------------------- parser.add_argument('--model_path', type=str, default=' ') # The pre-trained GAN model parser.add_argument('--out_image_dir', type=str, default=' ') # The outpupt directory containing generated images parser.add_argument('--num_pngs', type=int, default=1) # The number of generated images parser.add_argument('--gen_seed', type=int, default=9999) # The random seed to differentiate generation instances args = parser.parse_args() if args.app == 'train': assert args.training_data_dir != ' ' and args.out_model_dir != ' ' misc.init_output_logging() np.random.seed(args.training_seed) print('Initializing TensorFlow...') os.environ.update(config.env) tfutil.init_tf(config.tf_config) if args.training_data_dir[-1] == '/': args.training_data_dir = args.training_data_dir[:-1] idx = args.training_data_dir.rfind('/') config.data_dir = args.training_data_dir[:idx] config.dataset = config.EasyDict(tfrecord_dir=args.training_data_dir[idx+1:]) app = config.EasyDict(func='run.train_progressive_gan', mirror_augment=False, total_kimg=12000) config.result_dir = args.out_model_dir elif args.app == 'gen': assert args.model_path != ' ' and args.out_image_dir != ' ' misc.init_output_logging() np.random.seed(args.gen_seed) print('Initializing TensorFlow...') os.environ.update(config.env) tfutil.init_tf(config.tf_config) app = config.EasyDict(func='util_scripts.generate_fake_images', pkl_path=args.model_path, out_dir=args.out_image_dir, num_pngs=args.num_pngs, random_seed=args.gen_seed) tfutil.call_func_by_name(**app)
18,100
54.185976
190
py
GANFingerprints
GANFingerprints-master/ProGAN/config.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. #---------------------------------------------------------------------------- # Convenience class that behaves exactly like dict(), but allows accessing # the keys and values using the attribute syntax, i.e., "mydict.key = value". class EasyDict(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __getattr__(self, name): return self[name] def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): del self[name] #---------------------------------------------------------------------------- # Paths. data_dir = 'datasets' training_data = 'celeba_align_png_cropped' #training_data = 'lsun_bedroom_200k_png' result_dir = 'models/%s' % training_data #---------------------------------------------------------------------------- # TensorFlow options. tf_config = EasyDict() # TensorFlow session config, set by tfutil.init_tf(). env = EasyDict() # Environment variables, set by the main program in train.py. tf_config['graph_options.place_pruned_graph'] = True # False (default) = Check that all ops are available on the designated device. True = Skip the check for ops that are not used. tf_config['gpu_options.allow_growth'] = False # False (default) = Allocate all GPU memory at the beginning. True = Allocate only as much GPU memory as needed. env.CUDA_VISIBLE_DEVICES = '0' # Unspecified (default) = Use all available GPUs. List of ints = CUDA device numbers to use. env.TF_CPP_MIN_LOG_LEVEL = '1' # 0 (default) = Print all available debug info from TensorFlow. 1 = Print warnings and errors, but disable debug info. #---------------------------------------------------------------------------- # Official training configs, targeted mainly for CelebA-HQ. # To run, comment/uncomment the lines as appropriate and launch train.py. desc = 'pgan' # Description string included in result subdir name. random_seed = 1000 # Global random seed. train = EasyDict(func='run.train_progressive_gan') # Options for main training func. G = EasyDict(func='networks.G_paper') # Options for generator network. D = EasyDict(func='networks.D_paper') # Options for discriminator network. G_opt = EasyDict(beta1=0.0, beta2=0.99, epsilon=1e-8) # Options for generator optimizer. D_opt = EasyDict(beta1=0.0, beta2=0.99, epsilon=1e-8) # Options for discriminator optimizer. G_loss = EasyDict(func='loss.G_wgan_acgan') # Options for generator loss. D_loss = EasyDict(func='loss.D_wgangp_acgan') # Options for discriminator loss. sched = EasyDict() # Options for train.TrainingSchedule. grid = EasyDict(size='1080p', layout='random') # Options for train.setup_snapshot_image_grid(). # Dataset (choose one). desc += '-celeba'; dataset = EasyDict(tfrecord_dir=training_data); train.mirror_augment = False #desc += '-lsun_bedroom'; dataset = EasyDict(tfrecord_dir=training_data); train.mirror_augment = False # Config presets (choose one). Note: the official settings are optimal. It is not the larger batch size the better. desc += '-preset-v2-1gpu'; num_gpus = 1; sched.minibatch_base = 32; sched.minibatch_dict = {4: 512, 8: 256, 16: 128, 32: 64, 64: 32}; sched.lod_training_kimg = 600; sched.lod_transition_kimg = 600; train.total_kimg = 12000; sched.G_lrate_dict = {128: 0.0015, 256: 0.002, 512: 0.003, 1024: 0.003}; sched.D_lrate_dict = EasyDict(sched.G_lrate_dict) # Numerical precision (choose one). desc += '-fp32'; sched.max_minibatch_per_gpu = {256: 16, 512: 8, 1024: 4}
4,119
64.396825
346
py
GANFingerprints
GANFingerprints-master/ProGAN/dataset_tool.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import sys import glob import argparse import threading import six.moves.queue as Queue import traceback import numpy as np import tensorflow as tf import PIL.Image import tfutil import dataset #---------------------------------------------------------------------------- def error(msg): print('Error: ' + msg) exit(1) #---------------------------------------------------------------------------- class TFRecordExporter: def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval=10): self.tfrecord_dir = tfrecord_dir self.tfr_prefix = os.path.join(self.tfrecord_dir, os.path.basename(self.tfrecord_dir)) self.expected_images = expected_images self.cur_images = 0 self.shape = None self.resolution_log2 = None self.tfr_writers = [] self.print_progress = print_progress self.progress_interval = progress_interval if self.print_progress: print('Creating dataset "%s"' % tfrecord_dir) if not os.path.isdir(self.tfrecord_dir): os.makedirs(self.tfrecord_dir) assert(os.path.isdir(self.tfrecord_dir)) def close(self): if self.print_progress: print('%-40s\r' % 'Flushing data...', end='', flush=True) for tfr_writer in self.tfr_writers: tfr_writer.close() self.tfr_writers = [] if self.print_progress: print('%-40s\r' % '', end='', flush=True) print('Added %d images.' % self.cur_images) def choose_shuffled_order(self): # Note: Images and labels must be added in shuffled order. order = np.arange(self.expected_images) np.random.RandomState(123).shuffle(order) return order def add_image(self, img): if self.print_progress and self.cur_images % self.progress_interval == 0: print('%d / %d\r' % (self.cur_images, self.expected_images), end='', flush=True) if self.shape is None: self.shape = img.shape self.resolution_log2 = int(np.log2(self.shape[1])) assert self.shape[0] in [1, 3] assert self.shape[1] == self.shape[2] assert self.shape[1] == 2**self.resolution_log2 tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE) for lod in range(self.resolution_log2 - 1): tfr_file = self.tfr_prefix + '-r%02d.tfrecords' % (self.resolution_log2 - lod) self.tfr_writers.append(tf.python_io.TFRecordWriter(tfr_file, tfr_opt)) assert img.shape == self.shape for lod, tfr_writer in enumerate(self.tfr_writers): if lod: img = img.astype(np.float32) img = (img[:, 0::2, 0::2] + img[:, 0::2, 1::2] + img[:, 1::2, 0::2] + img[:, 1::2, 1::2]) * 0.25 quant = np.rint(img).clip(0, 255).astype(np.uint8) ex = tf.train.Example(features=tf.train.Features(feature={ 'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=quant.shape)), 'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[quant.tostring()]))})) tfr_writer.write(ex.SerializeToString()) self.cur_images += 1 def add_labels(self, labels): if self.print_progress: print('%-40s\r' % 'Saving labels...', end='', flush=True) assert labels.shape[0] == self.cur_images with open(self.tfr_prefix + '-rxx.labels', 'wb') as f: np.save(f, labels.astype(np.float32)) def __enter__(self): return self def __exit__(self, *args): self.close() #---------------------------------------------------------------------------- class ExceptionInfo(object): def __init__(self): self.value = sys.exc_info()[1] self.traceback = traceback.format_exc() #---------------------------------------------------------------------------- class WorkerThread(threading.Thread): def __init__(self, task_queue): threading.Thread.__init__(self) self.task_queue = task_queue def run(self): while True: func, args, result_queue = self.task_queue.get() if func is None: break try: result = func(*args) except: result = ExceptionInfo() result_queue.put((result, args)) #---------------------------------------------------------------------------- class ThreadPool(object): def __init__(self, num_threads): assert num_threads >= 1 self.task_queue = Queue.Queue() self.result_queues = dict() self.num_threads = num_threads for idx in range(self.num_threads): thread = WorkerThread(self.task_queue) thread.daemon = True thread.start() def add_task(self, func, args=()): assert hasattr(func, '__call__') # must be a function if func not in self.result_queues: self.result_queues[func] = Queue.Queue() self.task_queue.put((func, args, self.result_queues[func])) def get_result(self, func): # returns (result, args) result, args = self.result_queues[func].get() if isinstance(result, ExceptionInfo): print('\n\nWorker thread caught an exception:\n' + result.traceback) raise result.value return result, args def finish(self): for idx in range(self.num_threads): self.task_queue.put((None, (), None)) def __enter__(self): # for 'with' statement return self def __exit__(self, *excinfo): self.finish() def process_items_concurrently(self, item_iterator, process_func=lambda x: x, pre_func=lambda x: x, post_func=lambda x: x, max_items_in_flight=None): if max_items_in_flight is None: max_items_in_flight = self.num_threads * 4 assert max_items_in_flight >= 1 results = [] retire_idx = [0] def task_func(prepared, idx): return process_func(prepared) def retire_result(): processed, (prepared, idx) = self.get_result(task_func) results[idx] = processed while retire_idx[0] < len(results) and results[retire_idx[0]] is not None: yield post_func(results[retire_idx[0]]) results[retire_idx[0]] = None retire_idx[0] += 1 for idx, item in enumerate(item_iterator): prepared = pre_func(item) results.append(None) self.add_task(func=task_func, args=(prepared, idx)) while retire_idx[0] < idx - max_items_in_flight + 2: for res in retire_result(): yield res while retire_idx[0] < len(results): for res in retire_result(): yield res #---------------------------------------------------------------------------- def display(tfrecord_dir): print('Loading dataset "%s"' % tfrecord_dir) tfutil.init_tf({'gpu_options.allow_growth': True}) dset = dataset.TFRecordDataset(tfrecord_dir, max_label_size='full', repeat=False, shuffle_mb=0) tfutil.init_uninited_vars() idx = 0 while True: try: images, labels = dset.get_minibatch_np(1) except tf.errors.OutOfRangeError: break if idx == 0: print('Displaying images') import cv2 # pip install opencv-python cv2.namedWindow('dataset_tool') print('Press SPACE or ENTER to advance, ESC to exit') print('\nidx = %-8d\nlabel = %s' % (idx, labels[0].tolist())) cv2.imshow('dataset_tool', images[0].transpose(1, 2, 0)[:, :, ::-1]) # CHW => HWC, RGB => BGR idx += 1 if cv2.waitKey() == 27: break print('\nDisplayed %d images.' % idx) #---------------------------------------------------------------------------- def extract(tfrecord_dir, output_dir): print('Loading dataset "%s"' % tfrecord_dir) tfutil.init_tf({'gpu_options.allow_growth': True}) dset = dataset.TFRecordDataset(tfrecord_dir, max_label_size=0, repeat=False, shuffle_mb=0) tfutil.init_uninited_vars() print('Extracting images to "%s"' % output_dir) if not os.path.isdir(output_dir): os.makedirs(output_dir) idx = 0 while True: if idx % 10 == 0: print('%d\r' % idx, end='', flush=True) try: images, labels = dset.get_minibatch_np(1) except tf.errors.OutOfRangeError: break if images.shape[1] == 1: img = PIL.Image.fromarray(images[0][0], 'L') else: img = PIL.Image.fromarray(images[0].transpose(1, 2, 0), 'RGB') img.save(os.path.join(output_dir, 'img%08d.png' % idx)) idx += 1 print('Extracted %d images.' % idx) #---------------------------------------------------------------------------- def compare(tfrecord_dir_a, tfrecord_dir_b, ignore_labels): max_label_size = 0 if ignore_labels else 'full' print('Loading dataset "%s"' % tfrecord_dir_a) tfutil.init_tf({'gpu_options.allow_growth': True}) dset_a = dataset.TFRecordDataset(tfrecord_dir_a, max_label_size=max_label_size, repeat=False, shuffle_mb=0) print('Loading dataset "%s"' % tfrecord_dir_b) dset_b = dataset.TFRecordDataset(tfrecord_dir_b, max_label_size=max_label_size, repeat=False, shuffle_mb=0) tfutil.init_uninited_vars() print('Comparing datasets') idx = 0 identical_images = 0 identical_labels = 0 while True: if idx % 100 == 0: print('%d\r' % idx, end='', flush=True) try: images_a, labels_a = dset_a.get_minibatch_np(1) except tf.errors.OutOfRangeError: images_a, labels_a = None, None try: images_b, labels_b = dset_b.get_minibatch_np(1) except tf.errors.OutOfRangeError: images_b, labels_b = None, None if images_a is None or images_b is None: if images_a is not None or images_b is not None: print('Datasets contain different number of images') break if images_a.shape == images_b.shape and np.all(images_a == images_b): identical_images += 1 else: print('Image %d is different' % idx) if labels_a.shape == labels_b.shape and np.all(labels_a == labels_b): identical_labels += 1 else: print('Label %d is different' % idx) idx += 1 print('Identical images: %d / %d' % (identical_images, idx)) if not ignore_labels: print('Identical labels: %d / %d' % (identical_labels, idx)) #---------------------------------------------------------------------------- def create_mnist(tfrecord_dir, mnist_dir): print('Loading MNIST from "%s"' % mnist_dir) import gzip with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file: images = np.frombuffer(file.read(), np.uint8, offset=16) with gzip.open(os.path.join(mnist_dir, 'train-labels-idx1-ubyte.gz'), 'rb') as file: labels = np.frombuffer(file.read(), np.uint8, offset=8) images = images.reshape(-1, 1, 28, 28) images = np.pad(images, [(0,0), (0,0), (2,2), (2,2)], 'constant', constant_values=0) assert images.shape == (60000, 1, 32, 32) and images.dtype == np.uint8 assert labels.shape == (60000,) and labels.dtype == np.uint8 assert np.min(images) == 0 and np.max(images) == 255 assert np.min(labels) == 0 and np.max(labels) == 9 onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32) onehot[np.arange(labels.size), labels] = 1.0 with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr: order = tfr.choose_shuffled_order() for idx in range(order.size): tfr.add_image(images[order[idx]]) tfr.add_labels(onehot[order]) #---------------------------------------------------------------------------- def create_mnistrgb(tfrecord_dir, mnist_dir, num_images=1000000, random_seed=123): print('Loading MNIST from "%s"' % mnist_dir) import gzip with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file: images = np.frombuffer(file.read(), np.uint8, offset=16) images = images.reshape(-1, 28, 28) images = np.pad(images, [(0,0), (2,2), (2,2)], 'constant', constant_values=0) assert images.shape == (60000, 32, 32) and images.dtype == np.uint8 assert np.min(images) == 0 and np.max(images) == 255 with TFRecordExporter(tfrecord_dir, num_images) as tfr: rnd = np.random.RandomState(random_seed) for idx in range(num_images): tfr.add_image(images[rnd.randint(images.shape[0], size=3)]) #---------------------------------------------------------------------------- def create_cifar10(tfrecord_dir, cifar10_dir): print('Loading CIFAR-10 from "%s"' % cifar10_dir) import pickle images = [] labels = [] for batch in range(1, 6): with open(os.path.join(cifar10_dir, 'data_batch_%d' % batch), 'rb') as file: data = pickle.load(file, encoding='latin1') images.append(data['data'].reshape(-1, 3, 32, 32)) labels.append(data['labels']) images = np.concatenate(images) labels = np.concatenate(labels) assert images.shape == (50000, 3, 32, 32) and images.dtype == np.uint8 assert labels.shape == (50000,) and labels.dtype == np.int32 assert np.min(images) == 0 and np.max(images) == 255 assert np.min(labels) == 0 and np.max(labels) == 9 onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32) onehot[np.arange(labels.size), labels] = 1.0 with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr: order = tfr.choose_shuffled_order() for idx in range(order.size): tfr.add_image(images[order[idx]]) tfr.add_labels(onehot[order]) #---------------------------------------------------------------------------- def create_cifar100(tfrecord_dir, cifar100_dir): print('Loading CIFAR-100 from "%s"' % cifar100_dir) import pickle with open(os.path.join(cifar100_dir, 'train'), 'rb') as file: data = pickle.load(file, encoding='latin1') images = data['data'].reshape(-1, 3, 32, 32) labels = np.array(data['fine_labels']) assert images.shape == (50000, 3, 32, 32) and images.dtype == np.uint8 assert labels.shape == (50000,) and labels.dtype == np.int32 assert np.min(images) == 0 and np.max(images) == 255 assert np.min(labels) == 0 and np.max(labels) == 99 onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32) onehot[np.arange(labels.size), labels] = 1.0 with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr: order = tfr.choose_shuffled_order() for idx in range(order.size): tfr.add_image(images[order[idx]]) tfr.add_labels(onehot[order]) #---------------------------------------------------------------------------- def create_svhn(tfrecord_dir, svhn_dir): print('Loading SVHN from "%s"' % svhn_dir) import pickle images = [] labels = [] for batch in range(1, 4): with open(os.path.join(svhn_dir, 'train_%d.pkl' % batch), 'rb') as file: data = pickle.load(file, encoding='latin1') images.append(data[0]) labels.append(data[1]) images = np.concatenate(images) labels = np.concatenate(labels) assert images.shape == (73257, 3, 32, 32) and images.dtype == np.uint8 assert labels.shape == (73257,) and labels.dtype == np.uint8 assert np.min(images) == 0 and np.max(images) == 255 assert np.min(labels) == 0 and np.max(labels) == 9 onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32) onehot[np.arange(labels.size), labels] = 1.0 with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr: order = tfr.choose_shuffled_order() for idx in range(order.size): tfr.add_image(images[order[idx]]) tfr.add_labels(onehot[order]) #---------------------------------------------------------------------------- def create_lsun(tfrecord_dir, lmdb_dir, resolution=256, max_images=None): print('Loading LSUN dataset from "%s"' % lmdb_dir) import lmdb # pip install lmdb import cv2 # pip install opencv-python import io with lmdb.open(lmdb_dir, readonly=True).begin(write=False) as txn: total_images = txn.stat()['entries'] if max_images is None: max_images = total_images with TFRecordExporter(tfrecord_dir, max_images) as tfr: for idx, (key, value) in enumerate(txn.cursor()): try: try: img = cv2.imdecode(np.fromstring(value, dtype=np.uint8), 1) if img is None: raise IOError('cv2.imdecode failed') img = img[:, :, ::-1] # BGR => RGB except IOError: img = np.asarray(PIL.Image.open(io.BytesIO(value))) crop = np.min(img.shape[:2]) img = img[(img.shape[0] - crop) // 2 : (img.shape[0] + crop) // 2, (img.shape[1] - crop) // 2 : (img.shape[1] + crop) // 2] img = PIL.Image.fromarray(img, 'RGB') img = img.resize((resolution, resolution), PIL.Image.ANTIALIAS) img = np.asarray(img) img = img.transpose(2, 0, 1) # HWC => CHW tfr.add_image(img) except: print(sys.exc_info()[1]) if tfr.cur_images == max_images: break #---------------------------------------------------------------------------- def create_celeba(tfrecord_dir, celeba_dir, cx=89, cy=121, shuffle=1, num_images=0, num_shifts=0): print('Loading CelebA from "%s"' % celeba_dir) glob_pattern = os.path.join(celeba_dir, '*.png') image_filenames = sorted(glob.glob(glob_pattern)) if num_images == 0: image_filenames_new = list(image_filenames) elif num_images != 0 and num_shifts == 0: image_filenames_new = image_filenames[:num_images] elif num_images != 0 and num_shifts != 0: image_filenames_new = image_filenames[:num_images-num_shifts] + image_filenames[-num_shifts:] with TFRecordExporter(tfrecord_dir, len(image_filenames_new)) as tfr: order = tfr.choose_shuffled_order() if shuffle else np.arange(len(image_filenames_new)) for idx in range(order.size): img = np.asarray(PIL.Image.open(image_filenames_new[order[idx]])) assert img.shape == (218, 178, 3) img = img[cy - 64 : cy + 64, cx - 64 : cx + 64] img = img.transpose(2, 0, 1) # HWC => CHW tfr.add_image(img) #---------------------------------------------------------------------------- def create_celebahq(tfrecord_dir, celeba_dir, delta_dir, num_threads=4, num_tasks=100): print('Loading CelebA from "%s"' % celeba_dir) expected_images = 202599 if len(glob.glob(os.path.join(celeba_dir, 'img_celeba', '*.jpg'))) != expected_images: error('Expected to find %d images' % expected_images) with open(os.path.join(celeba_dir, 'Anno', 'list_landmarks_celeba.txt'), 'rt') as file: landmarks = [[float(value) for value in line.split()[1:]] for line in file.readlines()[2:]] landmarks = np.float32(landmarks).reshape(-1, 5, 2) print('Loading CelebA-HQ deltas from "%s"' % delta_dir) import scipy.ndimage import hashlib import bz2 import zipfile import base64 import cryptography.hazmat.primitives.hashes import cryptography.hazmat.backends import cryptography.hazmat.primitives.kdf.pbkdf2 import cryptography.fernet expected_zips = 30 if len(glob.glob(os.path.join(delta_dir, 'delta*.zip'))) != expected_zips: error('Expected to find %d zips' % expected_zips) with open(os.path.join(delta_dir, 'image_list.txt'), 'rt') as file: lines = [line.split() for line in file] fields = dict() for idx, field in enumerate(lines[0]): type = int if field.endswith('idx') else str fields[field] = [type(line[idx]) for line in lines[1:]] indices = np.array(fields['idx']) # Must use pillow version 3.1.1 for everything to work correctly. if getattr(PIL, 'PILLOW_VERSION', '') != '3.1.1': error('create_celebahq requires pillow version 3.1.1') # conda install pillow=3.1.1 # Must use libjpeg version 8d for everything to work correctly. img = np.array(PIL.Image.open(os.path.join(celeba_dir, 'img_celeba', '000001.jpg'))) md5 = hashlib.md5() md5.update(img.tobytes()) if md5.hexdigest() != '9cad8178d6cb0196b36f7b34bc5eb6d3': error('create_celebahq requires libjpeg version 8d') # conda install jpeg=8d def rot90(v): return np.array([-v[1], v[0]]) def process_func(idx): # Load original image. orig_idx = fields['orig_idx'][idx] orig_file = fields['orig_file'][idx] orig_path = os.path.join(celeba_dir, 'img_celeba', orig_file) img = PIL.Image.open(orig_path) # Choose oriented crop rectangle. lm = landmarks[orig_idx] eye_avg = (lm[0] + lm[1]) * 0.5 + 0.5 mouth_avg = (lm[3] + lm[4]) * 0.5 + 0.5 eye_to_eye = lm[1] - lm[0] eye_to_mouth = mouth_avg - eye_avg x = eye_to_eye - rot90(eye_to_mouth) x /= np.hypot(*x) x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8) y = rot90(x) c = eye_avg + eye_to_mouth * 0.1 quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y]) zoom = 1024 / (np.hypot(*x) * 2) # Shrink. shrink = int(np.floor(0.5 / zoom)) if shrink > 1: size = (int(np.round(float(img.size[0]) / shrink)), int(np.round(float(img.size[1]) / shrink))) img = img.resize(size, PIL.Image.ANTIALIAS) quad /= shrink zoom *= shrink # Crop. border = max(int(np.round(1024 * 0.1 / zoom)), 3) crop = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1])))) crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]), min(crop[3] + border, img.size[1])) if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]: img = img.crop(crop) quad -= crop[0:2] # Simulate super-resolution. superres = int(np.exp2(np.ceil(np.log2(zoom)))) if superres > 1: img = img.resize((img.size[0] * superres, img.size[1] * superres), PIL.Image.ANTIALIAS) quad *= superres zoom /= superres # Pad. pad = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1])))) pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0), max(pad[3] - img.size[1] + border, 0)) if max(pad) > border - 4: pad = np.maximum(pad, int(np.round(1024 * 0.3 / zoom))) img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect') h, w, _ = img.shape y, x, _ = np.mgrid[:h, :w, :1] mask = 1.0 - np.minimum(np.minimum(np.float32(x) / pad[0], np.float32(y) / pad[1]), np.minimum(np.float32(w-1-x) / pad[2], np.float32(h-1-y) / pad[3])) blur = 1024 * 0.02 / zoom img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0) img += (np.median(img, axis=(0,1)) - img) * np.clip(mask, 0.0, 1.0) img = PIL.Image.fromarray(np.uint8(np.clip(np.round(img), 0, 255)), 'RGB') quad += pad[0:2] # Transform. img = img.transform((4096, 4096), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR) img = img.resize((1024, 1024), PIL.Image.ANTIALIAS) img = np.asarray(img).transpose(2, 0, 1) # Verify MD5. md5 = hashlib.md5() md5.update(img.tobytes()) assert md5.hexdigest() == fields['proc_md5'][idx] # Load delta image and original JPG. with zipfile.ZipFile(os.path.join(delta_dir, 'deltas%05d.zip' % (idx - idx % 1000)), 'r') as zip: delta_bytes = zip.read('delta%05d.dat' % idx) with open(orig_path, 'rb') as file: orig_bytes = file.read() # Decrypt delta image, using original JPG data as decryption key. algorithm = cryptography.hazmat.primitives.hashes.SHA256() backend = cryptography.hazmat.backends.default_backend() salt = bytes(orig_file, 'ascii') kdf = cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC(algorithm=algorithm, length=32, salt=salt, iterations=100000, backend=backend) key = base64.urlsafe_b64encode(kdf.derive(orig_bytes)) delta = np.frombuffer(bz2.decompress(cryptography.fernet.Fernet(key).decrypt(delta_bytes)), dtype=np.uint8).reshape(3, 1024, 1024) # Apply delta image. img = img + delta # Verify MD5. md5 = hashlib.md5() md5.update(img.tobytes()) assert md5.hexdigest() == fields['final_md5'][idx] return img with TFRecordExporter(tfrecord_dir, indices.size) as tfr: order = tfr.choose_shuffled_order() with ThreadPool(num_threads) as pool: for img in pool.process_items_concurrently(indices[order].tolist(), process_func=process_func, max_items_in_flight=num_tasks): tfr.add_image(img) #---------------------------------------------------------------------------- def create_from_images(tfrecord_dir, image_dir, shuffle=1, num_images=0, num_shifts=0): print('Loading images from "%s"' % image_dir) image_filenames = sorted(glob.glob(os.path.join(image_dir, '*'))) if len(image_filenames) == 0: error('No input images found') if num_images == 0: image_filenames_new = list(image_filenames) elif num_images != 0 and num_shifts == 0: image_filenames_new = image_filenames[:num_images] elif num_images != 0 and num_shifts != 0: image_filenames_new = image_filenames[:num_images-num_shifts] + image_filenames[-num_shifts:] img = np.asarray(PIL.Image.open(image_filenames_new[0])) resolution = img.shape[0] channels = img.shape[2] if img.ndim == 3 else 1 if img.shape[1] != resolution: error('Input images must have the same width and height') if resolution != 2 ** int(np.floor(np.log2(resolution))): error('Input image resolution must be a power-of-two') if channels not in [1, 3]: error('Input images must be stored as RGB or grayscale') with TFRecordExporter(tfrecord_dir, len(image_filenames_new)) as tfr: order = tfr.choose_shuffled_order() if shuffle else np.arange(len(image_filenames_new)) for idx in range(order.size): img = np.asarray(PIL.Image.open(image_filenames_new[order[idx]])) if channels == 1: img = img[np.newaxis, :, :] # HW => CHW else: img = img.transpose(2, 0, 1) # HWC => CHW tfr.add_image(img) #---------------------------------------------------------------------------- def create_from_hdf5(tfrecord_dir, hdf5_filename, shuffle): print('Loading HDF5 archive from "%s"' % hdf5_filename) import h5py # conda install h5py with h5py.File(hdf5_filename, 'r') as hdf5_file: hdf5_data = max([value for key, value in hdf5_file.items() if key.startswith('data')], key=lambda lod: lod.shape[3]) with TFRecordExporter(tfrecord_dir, hdf5_data.shape[0]) as tfr: order = tfr.choose_shuffled_order() if shuffle else np.arange(hdf5_data.shape[0]) for idx in range(order.size): tfr.add_image(hdf5_data[order[idx]]) npy_filename = os.path.splitext(hdf5_filename)[0] + '-labels.npy' if os.path.isfile(npy_filename): tfr.add_labels(np.load(npy_filename)[order]) #---------------------------------------------------------------------------- def execute_cmdline(argv): prog = argv[0] parser = argparse.ArgumentParser( prog = prog, description = 'Tool for creating, extracting, and visualizing Progressive GAN datasets.', epilog = 'Type "%s <command> -h" for more information.' % prog) subparsers = parser.add_subparsers(dest='command') subparsers.required = True def add_command(cmd, desc, example=None): epilog = 'Example: %s %s' % (prog, example) if example is not None else None return subparsers.add_parser(cmd, description=desc, help=desc, epilog=epilog) p = add_command( 'display', 'Display images in dataset.', 'display datasets/mnist') p.add_argument( 'tfrecord_dir', help='Directory containing dataset') p = add_command( 'extract', 'Extract images from dataset.', 'extract datasets/mnist mnist-images') p.add_argument( 'tfrecord_dir', help='Directory containing dataset') p.add_argument( 'output_dir', help='Directory to extract the images into') p = add_command( 'compare', 'Compare two datasets.', 'compare datasets/mydataset datasets/mnist') p.add_argument( 'tfrecord_dir_a', help='Directory containing first dataset') p.add_argument( 'tfrecord_dir_b', help='Directory containing second dataset') p.add_argument( '--ignore_labels', help='Ignore labels (default: 0)', type=int, default=0) p = add_command( 'create_mnist', 'Create dataset for MNIST.', 'create_mnist datasets/mnist ~/downloads/mnist') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'mnist_dir', help='Directory containing MNIST') p = add_command( 'create_mnistrgb', 'Create dataset for MNIST-RGB.', 'create_mnistrgb datasets/mnistrgb ~/downloads/mnist') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'mnist_dir', help='Directory containing MNIST') p.add_argument( '--num_images', help='Number of composite images to create (default: 1000000)', type=int, default=1000000) p.add_argument( '--random_seed', help='Random seed (default: 123)', type=int, default=123) p = add_command( 'create_cifar10', 'Create dataset for CIFAR-10.', 'create_cifar10 datasets/cifar10 ~/downloads/cifar10') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'cifar10_dir', help='Directory containing CIFAR-10') p = add_command( 'create_cifar100', 'Create dataset for CIFAR-100.', 'create_cifar100 datasets/cifar100 ~/downloads/cifar100') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'cifar100_dir', help='Directory containing CIFAR-100') p = add_command( 'create_svhn', 'Create dataset for SVHN.', 'create_svhn datasets/svhn ~/downloads/svhn') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'svhn_dir', help='Directory containing SVHN') p = add_command( 'create_lsun', 'Create dataset for single LSUN category.', 'create_lsun datasets/lsun-car-100k ~/downloads/lsun/car_lmdb --resolution 256 --max_images 100000') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'lmdb_dir', help='Directory containing LMDB database') p.add_argument( '--resolution', help='Output resolution (default: 256)', type=int, default=256) p.add_argument( '--max_images', help='Maximum number of images (default: none)', type=int, default=None) p = add_command( 'create_celeba', 'Create dataset for CelebA.', 'create_celeba datasets/celeba ~/downloads/celeba') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'celeba_dir', help='Directory containing CelebA') p.add_argument( '--cx', help='Center X coordinate (default: 89)', type=int, default=89) p.add_argument( '--cy', help='Center Y coordinate (default: 121)', type=int, default=121) p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1) p.add_argument( '--num_images', help='Number of images to be considered (default: all)', type=int, default=0) p.add_argument( '--num_shifts', help='Number of image index shifts to be considered (default: 0)', type=int, default=0) p = add_command( 'create_celebahq', 'Create dataset for CelebA-HQ.', 'create_celebahq datasets/celebahq ~/downloads/celeba ~/downloads/celeba-hq-deltas') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'celeba_dir', help='Directory containing CelebA') p.add_argument( 'delta_dir', help='Directory containing CelebA-HQ deltas') p.add_argument( '--num_threads', help='Number of concurrent threads (default: 4)', type=int, default=4) p.add_argument( '--num_tasks', help='Number of concurrent processing tasks (default: 100)', type=int, default=100) p = add_command( 'create_from_images', 'Create dataset from a directory full of images.', 'create_from_images datasets/mydataset myimagedir') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'image_dir', help='Directory containing the images') p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1) p.add_argument( '--num_images', help='Number of images to be considered (default: all)', type=int, default=0) p.add_argument( '--num_shifts', help='Number of image index shifts to be considered (default: 0)', type=int, default=0) p = add_command( 'create_from_hdf5', 'Create dataset from legacy HDF5 archive.', 'create_from_hdf5 datasets/celebahq ~/downloads/celeba-hq-1024x1024.h5') p.add_argument( 'tfrecord_dir', help='New dataset directory to be created') p.add_argument( 'hdf5_filename', help='HDF5 archive containing the images') p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1) args = parser.parse_args(argv[1:] if len(argv) > 1 else ['-h']) func = globals()[args.command] del args.command func(**vars(args)) #---------------------------------------------------------------------------- if __name__ == "__main__": execute_cmdline(sys.argv) #----------------------------------------------------------------------------
36,317
46.976222
163
py
GANFingerprints
GANFingerprints-master/ProGAN/util_scripts.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import numpy as np import config import misc #---------------------------------------------------------------------------- # Generate random images or image grids using a previously trained network. # To run, uncomment the appropriate line in config.py and launch train.py. def generate_fake_images(pkl_path, out_dir, num_pngs, image_shrink=1, random_seed=1000, minibatch_size=1): random_state = np.random.RandomState(random_seed) if not os.path.isdir(out_dir): os.makedirs(out_dir) print('Loading network...') G, D, Gs = misc.load_network_pkl(pkl_path) latents = misc.random_latents(num_pngs, Gs, random_state=random_state) labels = np.zeros([latents.shape[0], 0], np.float32) images = Gs.run(latents, labels, minibatch_size=config.num_gpus*256, num_gpus=config.num_gpus, out_mul=127.5, out_add=127.5, out_shrink=image_shrink, out_dtype=np.uint8) for png_idx in range(num_pngs): print('Generating png to %s: %d / %d...' % (out_dir, png_idx, num_pngs), end='\r') if not os.path.exists(os.path.join(out_dir, 'ProGAN_%08d.png' % png_idx)): misc.save_image_grid(images[png_idx:png_idx+1], os.path.join(out_dir, 'ProGAN_%08d.png' % png_idx), [0,255], [1,1]) print()
1,590
47.212121
173
py
GANFingerprints
GANFingerprints-master/ProGAN/metrics/sliced_wasserstein.py
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import numpy as np import scipy.ndimage #---------------------------------------------------------------------------- def get_descriptors_for_minibatch(minibatch, nhood_size, nhoods_per_image): S = minibatch.shape # (minibatch, channel, height, width) assert len(S) == 4 and S[1] == 3 N = nhoods_per_image * S[0] H = nhood_size // 2 nhood, chan, x, y = np.ogrid[0:N, 0:3, -H:H+1, -H:H+1] img = nhood // nhoods_per_image x = x + np.random.randint(H, S[3] - H, size=(N, 1, 1, 1)) y = y + np.random.randint(H, S[2] - H, size=(N, 1, 1, 1)) idx = ((img * S[1] + chan) * S[2] + y) * S[3] + x return minibatch.flat[idx] #---------------------------------------------------------------------------- def finalize_descriptors(desc): if isinstance(desc, list): desc = np.concatenate(desc, axis=0) assert desc.ndim == 4 # (neighborhood, channel, height, width) desc -= np.mean(desc, axis=(0, 2, 3), keepdims=True) desc /= np.std(desc, axis=(0, 2, 3), keepdims=True) desc = desc.reshape(desc.shape[0], -1) return desc #---------------------------------------------------------------------------- def sliced_wasserstein(A, B, dir_repeats, dirs_per_repeat): assert A.ndim == 2 and A.shape == B.shape # (neighborhood, descriptor_component) results = [] for repeat in range(dir_repeats): dirs = np.random.randn(A.shape[1], dirs_per_repeat) # (descriptor_component, direction) dirs /= np.sqrt(np.sum(np.square(dirs), axis=0, keepdims=True)) # normalize descriptor components for each direction dirs = dirs.astype(np.float32) projA = np.matmul(A, dirs) # (neighborhood, direction) projB = np.matmul(B, dirs) projA = np.sort(projA, axis=0) # sort neighborhood projections for each direction projB = np.sort(projB, axis=0) dists = np.abs(projA - projB) # pointwise wasserstein distances results.append(np.mean(dists)) # average over neighborhoods and directions return np.mean(results) # average over repeats #---------------------------------------------------------------------------- def downscale_minibatch(minibatch, lod): if lod == 0: return minibatch t = minibatch.astype(np.float32) for i in range(lod): t = (t[:, :, 0::2, 0::2] + t[:, :, 0::2, 1::2] + t[:, :, 1::2, 0::2] + t[:, :, 1::2, 1::2]) * 0.25 return np.round(t).clip(0, 255).astype(np.uint8) #---------------------------------------------------------------------------- gaussian_filter = np.float32([ [1, 4, 6, 4, 1], [4, 16, 24, 16, 4], [6, 24, 36, 24, 6], [4, 16, 24, 16, 4], [1, 4, 6, 4, 1]]) / 256.0 def pyr_down(minibatch): # matches cv2.pyrDown() assert minibatch.ndim == 4 return scipy.ndimage.convolve(minibatch, gaussian_filter[np.newaxis, np.newaxis, :, :], mode='mirror')[:, :, ::2, ::2] def pyr_up(minibatch): # matches cv2.pyrUp() assert minibatch.ndim == 4 S = minibatch.shape res = np.zeros((S[0], S[1], S[2] * 2, S[3] * 2), minibatch.dtype) res[:, :, ::2, ::2] = minibatch return scipy.ndimage.convolve(res, gaussian_filter[np.newaxis, np.newaxis, :, :] * 4.0, mode='mirror') def generate_laplacian_pyramid(minibatch, num_levels): pyramid = [np.float32(minibatch)] for i in range(1, num_levels): pyramid.append(pyr_down(pyramid[-1])) pyramid[-2] -= pyr_up(pyramid[-1]) return pyramid def reconstruct_laplacian_pyramid(pyramid): minibatch = pyramid[-1] for level in pyramid[-2::-1]: minibatch = pyr_up(minibatch) + level return minibatch #---------------------------------------------------------------------------- class API: def __init__(self, num_images, image_shape, image_dtype, minibatch_size): self.nhood_size = 7 self.nhoods_per_image = 128 self.dir_repeats = 4 self.dirs_per_repeat = 128 self.resolutions = [] res = image_shape[1] while res >= 16: self.resolutions.append(res) res //= 2 def get_metric_names(self): return ['SWDx1e3_%d' % res for res in self.resolutions] + ['SWDx1e3_avg'] def get_metric_formatting(self): return ['%-13.4f'] * len(self.get_metric_names()) def begin(self, mode): assert mode in ['warmup', 'reals', 'fakes'] self.descriptors = [[] for res in self.resolutions] def feed(self, mode, minibatch): for lod, level in enumerate(generate_laplacian_pyramid(minibatch, len(self.resolutions))): desc = get_descriptors_for_minibatch(level, self.nhood_size, self.nhoods_per_image) self.descriptors[lod].append(desc) def end(self, mode): desc = [finalize_descriptors(d) for d in self.descriptors] del self.descriptors if mode in ['warmup', 'reals']: self.desc_real = desc dist = [sliced_wasserstein(dreal, dfake, self.dir_repeats, self.dirs_per_repeat) for dreal, dfake in zip(self.desc_real, desc)] del desc dist = [d * 1e3 for d in dist] # multiply by 10^3 return dist + [np.mean(dist)] #----------------------------------------------------------------------------
5,788
41.566176
135
py
GANFingerprints
GANFingerprints-master/ProGAN/metrics/frechet_inception_distance.py
#!/usr/bin/env python3 # # Copyright 2017 Martin Heusel # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Adapted from the original implementation by Martin Heusel. # Source https://github.com/bioinf-jku/TTUR/blob/master/fid.py ''' Calculates the Frechet Inception Distance (FID) to evalulate GANs. The FID metric calculates the distance between two distributions of images. Typically, we have summary statistics (mean & covariance matrix) of one of these distributions, while the 2nd distribution is given by a GAN. When run as a stand-alone program, it compares the distribution of images that are stored as PNG/JPEG at a specified location with a distribution given by summary statistics (in pickle format). The FID is calculated by assuming that X_1 and X_2 are the activations of the pool_3 layer of the inception net for generated samples and real world samples respectivly. See --help to see further details. ''' from __future__ import absolute_import, division, print_function import numpy as np import scipy as sp import os import gzip, pickle import tensorflow as tf from scipy.misc import imread import pathlib import urllib class InvalidFIDException(Exception): pass def create_inception_graph(pth): """Creates a graph from saved GraphDef file.""" # Creates graph from saved graph_def.pb. with tf.gfile.FastGFile( pth, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString( f.read()) _ = tf.import_graph_def( graph_def, name='FID_Inception_Net') #------------------------------------------------------------------------------- # code for handling inception net derived from # https://github.com/openai/improved-gan/blob/master/inception_score/model.py def _get_inception_layer(sess): """Prepares inception net for batched usage and returns pool_3 layer. """ layername = 'FID_Inception_Net/pool_3:0' pool3 = sess.graph.get_tensor_by_name(layername) ops = pool3.graph.get_operations() for op_idx, op in enumerate(ops): for o in op.outputs: shape = o.get_shape() if shape._dims is not None: shape = [s.value for s in shape] new_shape = [] for j, s in enumerate(shape): if s == 1 and j == 0: new_shape.append(None) else: new_shape.append(s) try: o._shape = tf.TensorShape(new_shape) except ValueError: o._shape_val = tf.TensorShape(new_shape) # EDIT: added for compatibility with tensorflow 1.6.0 return pool3 #------------------------------------------------------------------------------- def get_activations(images, sess, batch_size=50, verbose=False): """Calculates the activations of the pool_3 layer for all images. Params: -- images : Numpy array of dimension (n_images, hi, wi, 3). The values must lie between 0 and 256. -- sess : current session -- batch_size : the images numpy array is split into batches with batch size batch_size. A reasonable batch size depends on the disposable hardware. -- verbose : If set to True and parameter out_step is given, the number of calculated batches is reported. Returns: -- A numpy array of dimension (num images, 2048) that contains the activations of the given tensor when feeding inception with the query tensor. """ inception_layer = _get_inception_layer(sess) d0 = images.shape[0] if batch_size > d0: print("warning: batch size is bigger than the data size. setting batch size to data size") batch_size = d0 n_batches = d0//batch_size n_used_imgs = n_batches*batch_size pred_arr = np.empty((n_used_imgs,2048)) for i in range(n_batches): if verbose: print("\rPropagating batch %d/%d" % (i+1, n_batches), end="", flush=True) start = i*batch_size end = start + batch_size batch = images[start:end] pred = sess.run(inception_layer, {'FID_Inception_Net/ExpandDims:0': batch}) pred_arr[start:end] = pred.reshape(batch_size,-1) if verbose: print(" done") return pred_arr #------------------------------------------------------------------------------- def calculate_frechet_distance(mu1, sigma1, mu2, sigma2): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Params: -- mu1 : Numpy array containing the activations of the pool_3 layer of the inception net ( like returned by the function 'get_predictions') -- mu2 : The sample mean over activations of the pool_3 layer, precalcualted on an representive data set. -- sigma2: The covariance matrix over activations of the pool_3 layer, precalcualted on an representive data set. Returns: -- dist : The Frechet Distance. Raises: -- InvalidFIDException if nan occures. """ m = np.square(mu1 - mu2).sum() #s = sp.linalg.sqrtm(np.dot(sigma1, sigma2)) # EDIT: commented out s, _ = sp.linalg.sqrtm(np.dot(sigma1, sigma2), disp=False) # EDIT: added dist = m + np.trace(sigma1+sigma2 - 2*s) #if np.isnan(dist): # EDIT: commented out # raise InvalidFIDException("nan occured in distance calculation.") # EDIT: commented out #return dist # EDIT: commented out return np.real(dist) # EDIT: added #------------------------------------------------------------------------------- def calculate_activation_statistics(images, sess, batch_size=50, verbose=False): """Calculation of the statistics used by the FID. Params: -- images : Numpy array of dimension (n_images, hi, wi, 3). The values must lie between 0 and 255. -- sess : current session -- batch_size : the images numpy array is split into batches with batch size batch_size. A reasonable batch size depends on the available hardware. -- verbose : If set to True and parameter out_step is given, the number of calculated batches is reported. Returns: -- mu : The mean over samples of the activations of the pool_3 layer of the incption model. -- sigma : The covariance matrix of the activations of the pool_3 layer of the incption model. """ act = get_activations(images, sess, batch_size, verbose) mu = np.mean(act, axis=0) sigma = np.cov(act, rowvar=False) return mu, sigma #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # The following functions aren't needed for calculating the FID # they're just here to make this module work as a stand-alone script # for calculating FID scores #------------------------------------------------------------------------------- def check_or_download_inception(inception_path): ''' Checks if the path to the inception file is valid, or downloads the file if it is not present. ''' INCEPTION_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' if inception_path is None: inception_path = '/tmp' inception_path = pathlib.Path(inception_path) model_file = inception_path / 'classify_image_graph_def.pb' if not model_file.exists(): print("Downloading Inception model") from urllib import request import tarfile fn, _ = request.urlretrieve(INCEPTION_URL) with tarfile.open(fn, mode='r') as f: f.extract('classify_image_graph_def.pb', str(model_file.parent)) return str(model_file) def _handle_path(path, sess): if path.endswith('.npz'): f = np.load(path) m, s = f['mu'][:], f['sigma'][:] f.close() else: path = pathlib.Path(path) files = list(path.glob('*.jpg')) + list(path.glob('*.png')) x = np.array([imread(str(fn)).astype(np.float32) for fn in files]) m, s = calculate_activation_statistics(x, sess) return m, s def calculate_fid_given_paths(paths, inception_path): ''' Calculates the FID of two paths. ''' inception_path = check_or_download_inception(inception_path) for p in paths: if not os.path.exists(p): raise RuntimeError("Invalid path: %s" % p) create_inception_graph(str(inception_path)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) m1, s1 = _handle_path(paths[0], sess) m2, s2 = _handle_path(paths[1], sess) fid_value = calculate_frechet_distance(m1, s1, m2, s2) return fid_value if __name__ == "__main__": from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("path", type=str, nargs=2, help='Path to the generated images or to .npz statistic files') parser.add_argument("-i", "--inception", type=str, default=None, help='Path to Inception model (will be downloaded if not provided)') parser.add_argument("--gpu", default="", type=str, help='GPU to use (leave blank for CPU only)') args = parser.parse_args() os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu fid_value = calculate_fid_given_paths(args.path, args.inception) print("FID: ", fid_value) #---------------------------------------------------------------------------- # EDIT: added class API: def __init__(self, num_images, image_shape, image_dtype, minibatch_size): import config self.network_dir = os.path.join(config.result_dir, '_inception_fid') self.network_file = check_or_download_inception(self.network_dir) self.sess = tf.get_default_session() create_inception_graph(self.network_file) def get_metric_names(self): return ['FID'] def get_metric_formatting(self): return ['%-10.4f'] def begin(self, mode): assert mode in ['warmup', 'reals', 'fakes'] self.activations = [] def feed(self, mode, minibatch): act = get_activations(minibatch.transpose(0,2,3,1), self.sess, batch_size=minibatch.shape[0]) self.activations.append(act) def end(self, mode): act = np.concatenate(self.activations) mu = np.mean(act, axis=0) sigma = np.cov(act, rowvar=False) if mode in ['warmup', 'reals']: self.mu_real = mu self.sigma_real = sigma fid = calculate_frechet_distance(mu, sigma, self.mu_real, self.sigma_real) return [fid] #----------------------------------------------------------------------------
11,441
39.574468
110
py
GANFingerprints
GANFingerprints-master/ProGAN/metrics/ms_ssim.py
#!/usr/bin/python # # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # Adapted from the original implementation by The TensorFlow Authors. # Source: https://github.com/tensorflow/models/blob/master/research/compression/image_encoder/msssim.py import numpy as np from scipy import signal from scipy.ndimage.filters import convolve def _FSpecialGauss(size, sigma): """Function to mimic the 'fspecial' gaussian MATLAB function.""" radius = size // 2 offset = 0.0 start, stop = -radius, radius + 1 if size % 2 == 0: offset = 0.5 stop -= 1 x, y = np.mgrid[offset + start:stop, offset + start:stop] assert len(x) == size g = np.exp(-((x**2 + y**2)/(2.0 * sigma**2))) return g / g.sum() def _SSIMForMultiScale(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03): """Return the Structural Similarity Map between `img1` and `img2`. This function attempts to match the functionality of ssim_index_new.m by Zhou Wang: http://www.cns.nyu.edu/~lcv/ssim/msssim.zip Arguments: img1: Numpy array holding the first RGB image batch. img2: Numpy array holding the second RGB image batch. max_val: the dynamic range of the images (i.e., the difference between the maximum the and minimum allowed values). filter_size: Size of blur kernel to use (will be reduced for small images). filter_sigma: Standard deviation for Gaussian blur kernel (will be reduced for small images). k1: Constant used to maintain stability in the SSIM calculation (0.01 in the original paper). k2: Constant used to maintain stability in the SSIM calculation (0.03 in the original paper). Returns: Pair containing the mean SSIM and contrast sensitivity between `img1` and `img2`. Raises: RuntimeError: If input images don't have the same shape or don't have four dimensions: [batch_size, height, width, depth]. """ if img1.shape != img2.shape: raise RuntimeError('Input images must have the same shape (%s vs. %s).' % (img1.shape, img2.shape)) if img1.ndim != 4: raise RuntimeError('Input images must have four dimensions, not %d' % img1.ndim) img1 = img1.astype(np.float32) img2 = img2.astype(np.float32) _, height, width, _ = img1.shape # Filter size can't be larger than height or width of images. size = min(filter_size, height, width) # Scale down sigma if a smaller filter size is used. sigma = size * filter_sigma / filter_size if filter_size else 0 if filter_size: window = np.reshape(_FSpecialGauss(size, sigma), (1, size, size, 1)) mu1 = signal.fftconvolve(img1, window, mode='valid') mu2 = signal.fftconvolve(img2, window, mode='valid') sigma11 = signal.fftconvolve(img1 * img1, window, mode='valid') sigma22 = signal.fftconvolve(img2 * img2, window, mode='valid') sigma12 = signal.fftconvolve(img1 * img2, window, mode='valid') else: # Empty blur kernel so no need to convolve. mu1, mu2 = img1, img2 sigma11 = img1 * img1 sigma22 = img2 * img2 sigma12 = img1 * img2 mu11 = mu1 * mu1 mu22 = mu2 * mu2 mu12 = mu1 * mu2 sigma11 -= mu11 sigma22 -= mu22 sigma12 -= mu12 # Calculate intermediate values used by both ssim and cs_map. c1 = (k1 * max_val) ** 2 c2 = (k2 * max_val) ** 2 v1 = 2.0 * sigma12 + c2 v2 = sigma11 + sigma22 + c2 ssim = np.mean((((2.0 * mu12 + c1) * v1) / ((mu11 + mu22 + c1) * v2)), axis=(1, 2, 3)) # Return for each image individually. cs = np.mean(v1 / v2, axis=(1, 2, 3)) return ssim, cs def _HoxDownsample(img): return (img[:, 0::2, 0::2, :] + img[:, 1::2, 0::2, :] + img[:, 0::2, 1::2, :] + img[:, 1::2, 1::2, :]) * 0.25 def msssim(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03, weights=None): """Return the MS-SSIM score between `img1` and `img2`. This function implements Multi-Scale Structural Similarity (MS-SSIM) Image Quality Assessment according to Zhou Wang's paper, "Multi-scale structural similarity for image quality assessment" (2003). Link: https://ece.uwaterloo.ca/~z70wang/publications/msssim.pdf Author's MATLAB implementation: http://www.cns.nyu.edu/~lcv/ssim/msssim.zip Arguments: img1: Numpy array holding the first RGB image batch. img2: Numpy array holding the second RGB image batch. max_val: the dynamic range of the images (i.e., the difference between the maximum the and minimum allowed values). filter_size: Size of blur kernel to use (will be reduced for small images). filter_sigma: Standard deviation for Gaussian blur kernel (will be reduced for small images). k1: Constant used to maintain stability in the SSIM calculation (0.01 in the original paper). k2: Constant used to maintain stability in the SSIM calculation (0.03 in the original paper). weights: List of weights for each level; if none, use five levels and the weights from the original paper. Returns: MS-SSIM score between `img1` and `img2`. Raises: RuntimeError: If input images don't have the same shape or don't have four dimensions: [batch_size, height, width, depth]. """ if img1.shape != img2.shape: raise RuntimeError('Input images must have the same shape (%s vs. %s).' % (img1.shape, img2.shape)) if img1.ndim != 4: raise RuntimeError('Input images must have four dimensions, not %d' % img1.ndim) # Note: default weights don't sum to 1.0 but do match the paper / matlab code. weights = np.array(weights if weights else [0.0448, 0.2856, 0.3001, 0.2363, 0.1333]) levels = weights.size downsample_filter = np.ones((1, 2, 2, 1)) / 4.0 im1, im2 = [x.astype(np.float32) for x in [img1, img2]] mssim = [] mcs = [] for _ in range(levels): ssim, cs = _SSIMForMultiScale( im1, im2, max_val=max_val, filter_size=filter_size, filter_sigma=filter_sigma, k1=k1, k2=k2) mssim.append(ssim) mcs.append(cs) im1, im2 = [_HoxDownsample(x) for x in [im1, im2]] # Clip to zero. Otherwise we get NaNs. mssim = np.clip(np.asarray(mssim), 0.0, np.inf) mcs = np.clip(np.asarray(mcs), 0.0, np.inf) # Average over images only at the end. return np.mean(np.prod(mcs[:-1, :] ** weights[:-1, np.newaxis], axis=0) * (mssim[-1, :] ** weights[-1])) #---------------------------------------------------------------------------- # EDIT: added class API: def __init__(self, num_images, image_shape, image_dtype, minibatch_size): assert num_images % 2 == 0 and minibatch_size % 2 == 0 self.num_pairs = num_images // 2 def get_metric_names(self): return ['MS-SSIM'] def get_metric_formatting(self): return ['%-10.4f'] def begin(self, mode): assert mode in ['warmup', 'reals', 'fakes'] self.sum = 0.0 def feed(self, mode, minibatch): images = minibatch.transpose(0, 2, 3, 1) score = msssim(images[0::2], images[1::2]) self.sum += score * (images.shape[0] // 2) def end(self, mode): avg = self.sum / self.num_pairs return [avg] #----------------------------------------------------------------------------
8,160
39.60199
128
py
GANFingerprints
GANFingerprints-master/ProGAN/metrics/inception_score.py
# Copyright 2016 Wojciech Zaremba # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Adapted from the original implementation by Wojciech Zaremba. # Source: https://github.com/openai/improved-gan/blob/master/inception_score/model.py from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import sys import tarfile import numpy as np from six.moves import urllib import tensorflow as tf import glob import scipy.misc import math import sys MODEL_DIR = '/tmp/imagenet' DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' softmax = None # Call this function with list of images. Each of elements should be a # numpy array with values ranging from 0 to 255. def get_inception_score(images, splits=10): assert(type(images) == list) assert(type(images[0]) == np.ndarray) assert(len(images[0].shape) == 3) #assert(np.max(images[0]) > 10) # EDIT: commented out #assert(np.min(images[0]) >= 0.0) inps = [] for img in images: img = img.astype(np.float32) inps.append(np.expand_dims(img, 0)) bs = 100 with tf.Session() as sess: preds = [] n_batches = int(math.ceil(float(len(inps)) / float(bs))) for i in range(n_batches): #sys.stdout.write(".") # EDIT: commented out #sys.stdout.flush() inp = inps[(i * bs):min((i + 1) * bs, len(inps))] inp = np.concatenate(inp, 0) pred = sess.run(softmax, {'ExpandDims:0': inp}) preds.append(pred) preds = np.concatenate(preds, 0) scores = [] for i in range(splits): part = preds[(i * preds.shape[0] // splits):((i + 1) * preds.shape[0] // splits), :] kl = part * (np.log(part) - np.log(np.expand_dims(np.mean(part, 0), 0))) kl = np.mean(np.sum(kl, 1)) scores.append(np.exp(kl)) return np.mean(scores), np.std(scores) # This function is called automatically. def _init_inception(): global softmax if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) filename = DATA_URL.split('/')[-1] filepath = os.path.join(MODEL_DIR, filename) if not os.path.exists(filepath): def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %s %.1f%%' % ( filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress) print() statinfo = os.stat(filepath) print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.') tarfile.open(filepath, 'r:gz').extractall(MODEL_DIR) # EDIT: increased indent with tf.gfile.FastGFile(os.path.join( MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') # Works with an arbitrary minibatch size. with tf.Session() as sess: pool3 = sess.graph.get_tensor_by_name('pool_3:0') ops = pool3.graph.get_operations() for op_idx, op in enumerate(ops): for o in op.outputs: shape = o.get_shape() shape = [s.value for s in shape] new_shape = [] for j, s in enumerate(shape): if s == 1 and j == 0: new_shape.append(None) else: new_shape.append(s) try: o._shape = tf.TensorShape(new_shape) except ValueError: o._shape_val = tf.TensorShape(new_shape) # EDIT: added for compatibility with tensorflow 1.6.0 w = sess.graph.get_operation_by_name("softmax/logits/MatMul").inputs[1] logits = tf.matmul(tf.squeeze(pool3), w) softmax = tf.nn.softmax(logits) #if softmax is None: # EDIT: commented out # _init_inception() # EDIT: commented out #---------------------------------------------------------------------------- # EDIT: added class API: def __init__(self, num_images, image_shape, image_dtype, minibatch_size): import config globals()['MODEL_DIR'] = os.path.join(config.result_dir, '_inception') self.sess = tf.get_default_session() _init_inception() def get_metric_names(self): return ['IS_mean', 'IS_std'] def get_metric_formatting(self): return ['%-10.4f', '%-10.4f'] def begin(self, mode): assert mode in ['warmup', 'reals', 'fakes'] self.images = [] def feed(self, mode, minibatch): self.images.append(minibatch.transpose(0, 2, 3, 1)) def end(self, mode): images = list(np.concatenate(self.images)) with self.sess.as_default(): mean, std = get_inception_score(images) return [mean, std] #----------------------------------------------------------------------------
5,305
34.851351
110
py
GANFingerprints
GANFingerprints-master/ProGAN/metrics/__init__.py
# empty
8
3.5
7
py
flock
flock-master/hierarchical/plan.py
import numpy as np import math class Plan: ''' Set field 1 of condition: Must be a Test Set field 2 of condition: Must be an Action Set field 3 of condition: Must be an Action Add action (to top level): Must be an Action or Condition ''' legal = {} def __init__(self): self.Conditionals = [DirectionCondition] self.Expressions = [DirectionExpression] self.Observations = [self.get_sheep_cm, self.get_nearest_wolf, self.get_own_pos, self.get_goal] self.Actions = [DirectionAction("N"), DirectionAction("E"), DirectionAction("S"), DirectionAction("W"), DirectionAction("Stay")] self.this_conditionals = [] self.this_expressions = [] self.sx = None self.sy = None self.wx = None self.wy = None self.pen = None self.wolf = None self.action = None def __str__(self): return str(self.action) def execute(self, wx, wy, sx, sy, pen_size, wolf_index): self.sx = sx self.sy = sy self.wx = wx self.wy = wy pen_coord = Coordinate(pen_size/2, pen_size/2) self.pen = pen_coord self.wolf = wolf_index return self.action.execute() ''' Prebuilt expressions: def get_wolf_direction_to(self, c2): return self.get_direction_to(self.get_own_pos(), c2) def get_wolf_direction_to_sheep(self): wdts = self.get_direction_to(self.get_own_pos(), self.get_sheep_cm()) #print "Wolf dir to sheep is", wdts return wdts def get_sheep_direction_to_pen(self): sdtp = self.get_direction_to(self.get_sheep_cm(), self.pen) #print "Sheep dir to pen is", sdtp return sdtp def get_closest_wolf_direction(self): return self.get_direction_to(self.get_own_pos(), self.get_nearest_wolf()) ''' ''' OBSERVATIONS Primitive functions: (return Coordinates) ''' def get_sheep_cm(self): x = np.sum(self.sx) / len(self.sx) y = np.sum(self.sy) / len(self.sy) return Coordinate(x, y) def get_nearest_wolf(self): mindist = float("inf") x = 0 y = 0 for i in range(len(self.wx)): if i != self.wolf: dist = self.wx[i]*self.wx[i] + self.wy[i]*self.wy[i] if dist < mindist: mindist = dist x = self.wx[i] y = self.wy[i] return Coordinate(x, y) def get_own_pos(self): return Coordinate(self.wx[self.wolf], self.wy[self.wolf]) def get_goal(self): return self.pen ''' EXPRESSIONS Directions ''' class DirectionExpression(): def __init__(self): self.obs1 = None self.obs2 = None self.depth = 0 self.marked = 0 self.obs_map = None self.ptemp = None # Awkward but necessary: def set_map(self, ptemp): self.ptemp = ptemp self.obs_map = {self.ptemp.get_sheep_cm:"Sheep center of mass", self.ptemp.get_nearest_wolf: "Nearest wolf", self.ptemp.get_own_pos: "Own position", self.ptemp.get_goal: "Goal position"} def __str__(self): ret = "Direction of " + self.obs_map[self.obs1] + " to " + self.obs_map[self.obs2] + '\n' return ret # Direction of coordinate c1 to c2 def evaluate(self): c1 = self.obs1() c2 = self.obs2() dx = abs(c2.x - c1.x) dy = abs(c2.y - c1.y) if c2.y > c1.y: if c2.x > c1.x: if dy > dx: return "N" else: return "E" else: if dy > dx: return "N" else: return "W" else: if c2.x > c1.x: if dy > dx: return "S" else: return "E" else: if dy > dx: return "S" else: return "W" ''' CONDITIONALS / CONDITIONS ''' class DirectionCondition: def __init__(self): self.expression = None self.options = {"N":None, "E":None, "S":None, "W":None} self.depth = 0 self.marked = 0 self.isAction = False def __str__(self): ret = "Evaluate:\n\t" + str(self.expression) + '\n' ret += "If this is N:\n\t" + str(self.options["N"]) + '\n' ret += "If this is E:\n\t" + str(self.options["E"]) + '\n' ret += "If this is S:\n\t" + str(self.options["S"]) + '\n' ret += "If this is W:\n\t" + str(self.options["W"]) + '\n' return ret def execute(self): val = self.expression.evaluate() return self.options[val].execute() ''' ACTIONS ''' class DirectionAction: def __init__(self, direction, velocity=1.0): self.dir = direction self.v = velocity self.depth = 0 self.isAction = True def __str__(self): if self.dir == "Stay": ret = "Stay" else: ret = "Move " + str(self.dir) + " with velocity " + str(self.v) + '\n' return ret def execute(self): if self.dir == "Stay": return(0, 0) elif self.dir == "N": return (0, self.v) elif self.dir == "E": return (self.v, 0) elif self.dir == "S": return (0, -1 * self.v) else: return (-1 * self.v, 0) #class DistanceCondition: #def __init__(self, test, ?) class Coordinate: def __init__(self, x, y): self.x = x self.y = y def main(): import run import TestPlan p = TestPlan.myPlan() r = run.Run() print r.fitness(p) if __name__ == "__main__": main()
5,927
20.794118
136
py
flock
flock-master/hierarchical/run.py
import random import numpy as np filename = "../simulator/test.txt" num_wolves = 6 num_sheep = 20 T = 500 fieldc = [100, 0, 0, 0, 0, 100, 100, 100] penc = [25, 0, 0, 0, 0, 25, 25, 25] field = "100 0 0 0 0 100 100 100" pen = "25 0 0 0 0 0 25 25 25" wall_force = 10 wall_dist = 10 sheep_attract = 1 sheep_repulse = 20 max_v = 1 wolf_distance = 40 wolf_force = 10 class Run: def __init__(self): self.sx = [random.random() * fieldc[0]/2 + fieldc[0]/2 for i in range(num_sheep)] self.sy = [random.random() * fieldc[0] for i in range(num_sheep)] self.wx = [random.random() * fieldc[0]/2 for i in range(num_wolves)] self.wy = [random.random() * fieldc[0] for i in range(num_wolves)] def plan(self): pass def update_sheep(self): fx = np.zeros(num_sheep) fy = np.zeros(num_sheep) for i in range(num_sheep): x =self.sx[i]; y =self.sy[i] if (x-wall_dist) < 0: fx[i] += wall_force / (x+.01) if (x+wall_dist) > 100: fx[i] += wall_force / (99-x+.01) * -1 if (y-wall_dist) < 0: fy[i] += wall_force / (y+.01) if (y+wall_dist) > 100: fy[i] += wall_force / (99-y+.01) * -1 for j in range(num_sheep): if i != j: xd =self.sx[j] - x yd =self.sy[j] - y sqdist = xd*xd+yd*yd if sqdist < wall_dist*wall_dist: fx[i] += sheep_repulse / (xd+.01) * -1 fy[i] += sheep_repulse / (yd+.01) * -1 else: fx[i] += xd/100.0 fy[i] += yd/100.0 for j in range(num_wolves): xd =self.wx[j] - x yd =self.wy[j] - y sqdist = xd*xd+yd*yd if sqdist < wolf_distance*wolf_distance: fx[i] += wolf_force * (1/(xd+.01)) * -1 fy[i] += wolf_force * (1/(yd+.01)) * -1 # IF SHEEP IS IN PEN, KEEP IT THERE! if x < 25 and y < 25: fx[i] = -100.0 fy[i] = -100.0 if fx[i] > 0: fx_f = np.min([fx[i], max_v]) else: fx_f = np.max([fx[i], -1 * max_v]) if fy[i] > 0: fy_f = np.min([fy[i], max_v]) else: fy_f = np.max([fy[i], -1 * max_v]) self.sx[i] += fx_f self.sy[i] += fy_f if self.sx[i] < 0: self.sx[i] = 0 if self.sy[i] < 0: self.sy[i] = 0 if self.sx[i] > 99: self.sx[i] = 99 if self.sy[i] > 99: self.sy[i] = 99 def update_wolves(self, plan): for i in range(num_wolves): (xv, yv) = plan.execute(self.wx, self.wy, self.sx, self.sy, 25, i) self.wx[i] += xv self.wy[i] += yv if self.wx[i] < 0: self.wx[i] = 0 if self.wy[i] < 0: self.wy[i] = 0 if self.wx[i] > 99: self.wx[i] = 99 if self.wy[i] > 99: self.wy[i] = 99 def fitness(self, plan, filename, save=True): if save: file = open("results/"+filename, 'w') file.write(field + '\n') file.write(pen + '\n') file.write(str(num_wolves) + ' ' + str(num_sheep) + ' ' + str(T) + '\n') for t in range(T): if save: for i in range(num_wolves): file.write(str(self.wx[i]) + ' ' + str(self.wy[i]) + ' ') for i in range(num_sheep): file.write(str(self.sx[i]) + ' ' + str(self.sy[i]) + ' ') file.write('\n') self.update_sheep() self.update_wolves(plan) # Calculate fitness: num = 0 for i in range(num_sheep): if self.sx[i] < 25 and self.sy[i] < 25: num += 1 #print str(num)+"/"+str(len(self.sx)) return num / float(num_sheep) def main(): r = Run() r.fitness(1) if __name__ == "__main__": main()
4,275
25.893082
89
py
flock
flock-master/hierarchical/evolve.py
''' Isaac Julien Evolution for decision tree model of shepherding problem Basic setup: Plan = Conditionals + Expressions + Actions + Observations Conditionals = Expression + Actions (based on evaluation of expression) - classified into DirectionConditionals only for now Expressions = evaluate to some Type of value - Right now, this value is a direction resulting a relation b/n coordinates Observations = return some Type of info - Coordinate only for now Actions - Move the wolf So conditionals, expressions, observations, and actions are TYPED - Right now, only types are: - DIRECTIONAL conditionals (could also add DISTANCE, for ex.) - DIRECTIONAL expressions (Note: they must match the conditional type) - COORDINATE observations - Actions are always the same type though (~"void") Generating random plans: --------------------------------------------------------------------- - need to pick a conditional first - choose 1 of C conditionals UAR -- call this c - choose expression for c UAR out of expressions - if we're at max depth, choose terminal expression - ow, choose compound OR terminal expression - Choose resulting actions for c - If we're at max depth, must choose an Action - Otherwise, can choose another Conditional OR an Action Crossover (t1, t2): --------------------------------------------------------------------- 1. Pick something from t1 to crossover - Pick from [Conditional, Expression, Observation, Action] UAR 2. Then pick a specific one 3. Pick the SAME type from t2 4. Switch them and kill ti if depth of ti is now too great Mutation(t): --------------------------------------------------------------------- 1. Pick something to mutate, UAR as in xover 2. Mutate: - Conditional: Substitue another conditional - Expression: Substitute another expression - Observation: substitute another observation - Must match type of observation - Action: substitute any other action Note: rationale for limiting depth of tree: shepherd only has so long to make a decision - must react so, limiting depth of trees = making quick, good (efficient) decision ''' import plan from plan import Plan import random import run from run import Run import copy import numpy as np class EvolutionProblem(): def __init__(self, POPULATION=20, MAXDEPTH=5, P_MUTATE=.1, P_XOVER=.3, GENS=20): self.pop = POPULATION # Population size self.max = MAXDEPTH # Max depth of tree self.p_mutate = P_MUTATE # Mutation probability self.p_xover = P_XOVER # Crossover probability self.gens = GENS # Number of generations def run(self): population = self.initial_population() for i in range(self.gens): print "Generation " + str(i) # Evaluate fitnesses of all in population: fitnesses = np.zeros(self.pop) best_fitness = 0.0 best = population[0] for j in range(self.pop): specimen = population[j] r = Run() fit = r.fitness(specimen, "", save=False) fitnesses[j] = fit if fit > best_fitness: best_fitness = fit best = specimen print "Mean fitness = " + str(np.mean(fitnesses)) print "Best individual: ----------------------------------------------------------------" try: print str(best) except: print "FAILED TO PRINT FOR SOME REASON!" b_fit = Run().fitness(specimen, "Best_of_gen_"+str(i), save=True) print "Fitness of best = " + str(b_fit) print "---------------------------------------------------------------------------------" children = [] numAdded= 0 elites = [] for j in range(self.pop): if fitnesses[j] > 0: children.append(population[j]) numAdded += 1 elites.append(j) while numAdded < self.pop: extra = population[random.randint(0, self.pop-1)] if random.random() < self.p_mutate: extra = self.mutate(extra) children.append(extra) numAdded += 1 for i in range(self.pop/2): pos1 = 2*i pos2 = 2*i + 1 if pos1 in elites or pos2 in elites: continue if random.random() < self.p_xover: new1, new2 = self.crossover(children[pos1], children[pos2]) children[pos1] = new1 children[pos2] = new2 population = children ''' Create initial population of plans: ''' def initial_population(self): init_pop = [] for i in range(self.pop): p = self.random_plan() init_pop.append(p) return init_pop ''' Return a mutation of p1 ''' def mutate(self, p1): # I <3 python copy() method!! :) mutant = copy.deepcopy(p1) # Make change: for c in mutant.this_conditionals: # Possible change observations for each conditional: if random.random() < self.p_mutate: c.expression.obs1 = random.choice(mutant.Observations) if random.random() < self.p_mutate: c.expression.obs2 = random.choice(mutant.Observations) # Possibly change action for each conditional: for possibility in c.options.keys(): if c.options[possibility].isAction: if random.random() < self.p_mutate: c.options[possibility] = random.choice(mutant.Actions) return mutant ''' Crossover plans p1 and p2: ''' def crossover(self, p1, p2): mutant1 = copy.deepcopy(p1) mutant2 = copy.deepcopy(p2) r = random.random() # Crossover at a conditional ONLY for now if r < 1.000: # Also, for now, NO CROSSOVER AT THE ROOT: c1 = random.choice(mutant1.this_conditionals) c2 = random.choice(mutant2.this_conditionals) key1 = random.choice(c1.options.keys()) key2 = random.choice(c2.options.keys()) new_c1_child = c2.options[key2] new_c2_child = c1.options[key1] c1.options[key1] = new_c1_child c2.options[key2] = new_c2_child # Remove if it was a conditional: self.clear(mutant1, new_c2_child) self.add(mutant1, new_c1_child) self.clear(mutant2, new_c1_child) self.add(mutant2, new_c2_child) return mutant1, mutant2 # Clear/Add plan from conditional def clear(self, p, c): if c.isAction: return else: p.this_conditionals.remove(c) for key in c.options.keys(): self.clear(p, c.options[key]) def add(self, p, c): if c.isAction: return else: p.this_conditionals.append(c) for key in c.options.keys(): self.add(p, c.options[key]) ''' Generate a random plan up to max depth: ''' def random_plan(self): p = Plan() # Choose start condition AND INSTANTIATE IT: start_condition = random.choice(p.Conditionals)() start_condition.height = 1 p.action = start_condition p.this_conditionals.append(start_condition) done = False while not done: done = True # Update conditionals if not marked (marked = already dealt with) # and stop when hitting the max depth for c in p.this_conditionals: if c.marked == 0: done = False c.marked = 1 # Add a random expression: expression = random.choice(p.Expressions)() expression.obs1 = random.choice(p.Observations) expression.obs2 = random.choice(p.Observations) expression.depth = c.depth + 1 expression.marked = 1 expression.set_map(p) c.expression = expression # Must add terminal actions if we hit the max depth (minus 2) if c.depth == self.max-2: for key in c.options.keys(): axn = random.choice(p.Actions) axn.depth = c.depth + 1 c.options[key] = axn # Otherwise, we can add either a terminal action OR another conditional: else: for key in c.options.keys(): condition_or_action = random.random() if condition_or_action < .5: new_c = random.choice(p.Conditionals)() new_c.depth = c.depth + 1 c.options[key] = new_c p.this_conditionals.append(new_c) else: c.options[key] = random.choice(p.Actions) return p def main(): population = 30 max = 4 pm = .5 px = .5 gens = 100 ep = EvolutionProblem(POPULATION=population, MAXDEPTH=max, P_MUTATE=pm, P_XOVER=px, GENS=gens) ep.run() if __name__ == "__main__": main()
9,713
28.797546
101
py
flock
flock-master/hierarchical/TestPlan.py
import plan from plan import * ''' Custom-made plan for wolves: ''' def myPlan(): p = Plan() NNN = DirectionAction("N") NNE = DirectionAction("N") NNS = DirectionAction("N") NNW = DirectionAction("N") NEN = DirectionAction("W") NEE = DirectionAction("W") NEW = DirectionAction("W") NES = DirectionAction("W") NSN = DirectionAction("N") NSE = DirectionAction("N") NSS = DirectionAction("N") NSW = DirectionAction("N") NWN = DirectionAction("E") NWE = DirectionAction("E") NWS = DirectionAction("E") NWW = DirectionAction("E") ENN = DirectionAction("S") ENE = DirectionAction("S") ENS = DirectionAction("S") ENW = DirectionAction("S") EEN = DirectionAction("E") EEE = DirectionAction("E") EES = DirectionAction("E") EEW = DirectionAction("E") ESN = DirectionAction("N") ESE = DirectionAction("N") ESS = DirectionAction("N") ESW = DirectionAction("N") EWN = DirectionAction("E") EWE = DirectionAction("E") EWS = DirectionAction("E") EWW = DirectionAction("E") SNN = DirectionAction("S") SNE = DirectionAction("S") SNS = DirectionAction("S") SNW = DirectionAction("S") SEN = DirectionAction("W") SEE = DirectionAction("W") SES = DirectionAction("W") SEW = DirectionAction("W") SSN = DirectionAction("S") SSE = DirectionAction("S") SSS = DirectionAction("S") SSW = DirectionAction("S") SWN = DirectionAction("E") SWE = DirectionAction("E") SWS = DirectionAction("E") SWW = DirectionAction("E") WNN = DirectionAction("S") WNE = DirectionAction("S") WNS = DirectionAction("S") WNW = DirectionAction("S") WEN = DirectionAction("W") WEE = DirectionAction("W") WES = DirectionAction("W") WEW = DirectionAction("W") WSN = DirectionAction("N") WSE = DirectionAction("N") WSS = DirectionAction("N") WSW = DirectionAction("N") WWN = DirectionAction("W") WWE = DirectionAction("W") WWS = DirectionAction("W") WWW = DirectionAction("W") NN = DirectionCondition(p.get_closest_wolf_direction, NNN, NNE, NNS, NNW) NE = DirectionCondition(p.get_closest_wolf_direction, NEN, NEE, NES, NEW) NS = DirectionCondition(p.get_closest_wolf_direction, NSN, NSE, NSS, NSW) NW = DirectionCondition(p.get_closest_wolf_direction, NWN, NWE, NWS, NWW) EN = DirectionCondition(p.get_closest_wolf_direction, ENN, ENE, ENS, ENW) EE = DirectionCondition(p.get_closest_wolf_direction, EEN, EEE, EES, EEW) ES = DirectionCondition(p.get_closest_wolf_direction, ESN, ESE, ESS, ESW) EW = DirectionCondition(p.get_closest_wolf_direction, EWN, EWE, EWS, EWW) SN = DirectionCondition(p.get_closest_wolf_direction, SNN, SNE, SNS, SNW) SE = DirectionCondition(p.get_closest_wolf_direction, SEN, SEE, SES, SEW) SS = DirectionCondition(p.get_closest_wolf_direction, SSN, SSE, SSS, SSW) SW = DirectionCondition(p.get_closest_wolf_direction, SWN, SWE, SWS, SWW) WN = DirectionCondition(p.get_closest_wolf_direction, WNN, WNE, WES, WEW) WE = DirectionCondition(p.get_closest_wolf_direction, WEN, WEE, WES, WEW) WS = DirectionCondition(p.get_closest_wolf_direction, WSN, WSE, WSS, WSW) WW = DirectionCondition(p.get_closest_wolf_direction, WWN, WWE, WWS, WWW) N = DirectionCondition(p.get_sheep_direction_to_pen, NN, NE, NS, NW) E = DirectionCondition(p.get_sheep_direction_to_pen, EN, EE, ES, EW) S = DirectionCondition(p.get_sheep_direction_to_pen, SN, SE, SS, SW) W = DirectionCondition(p.get_sheep_direction_to_pen, WN, WE, WS, WW) c = DirectionCondition(p.get_wolf_direction_to_sheep, N, E, S, W) p.action = c return p
3,741
31.53913
77
py
YAIB-cohorts
YAIB-cohorts-main/Python/sepsis.py
import os import argparse import pyarrow as pa import pyarrow.parquet as pq from src.cohort import Cohort, SelectionCriterion from src.steps import ( InputStep, LoadStep, AggStep, FilterStep, TransformStep, CustomStep, RenameStep, Pipeline, CombineStep ) from src.ricu import stay_windows from src.ricu_utils import ( stop_window_at, n_obs_per_row, longest_rle, make_grid_mapper, make_patient_mapper, make_prevalence_calculator, make_outcome_windower ) outc_var = "sep3_alt" # this is a custom definition of sepsis that differs from that defined by ricu static_vars = ["age", "sex", "height", "weight"] dynamic_vars = ["alb", "alp", "alt", "ast", "be", "bicar", "bili", "bili_dir", "bnd", "bun", "ca", "cai", "ck", "ckmb", "cl", "crea", "crp", "dbp", "fgn", "fio2", "glu", "hgb", "hr", "inr_pt", "k", "lact", "lymph", "map", "mch", "mchc", "mcv", "methb", "mg", "na", "neut", "o2sat", "pco2", "ph", "phos", "plt", "po2", "ptt", "resp", "sbp", "temp", "tnt", "urine", "wbc"] def create_sepsis_task(args): print('Start creating the sepsis task.') print(' Preload variables') sepsis_args = {} if args.src in ['eicu', 'eicu_demo', 'hirid']: sepsis_args['si_mode'] = "abx" load_sepsis = LoadStep(outc_var, args.src, cache=True, **sepsis_args) sepsis = load_sepsis.perform() load_static = LoadStep(static_vars, args.src, cache=True) load_dynamic = LoadStep(dynamic_vars, args.src, cache=True) print(' Define observation times') patients = stay_windows(args.src) patients = stop_window_at(patients, end=24*7) print(' Define exclusion criteria') # General exclusion criteria excl1 = SelectionCriterion('Invalid length of stay') excl1.add_step([ InputStep(patients), FilterStep('end', lambda x: x < 0) ]) excl2 = SelectionCriterion('Length of stay < 6h') excl2.add_step([ LoadStep('los_icu', args.src), FilterStep('los_icu', lambda x: x < 6 / 24) ]) excl3 = SelectionCriterion('Less than 4 hours with any measurement') excl3.add_step([ load_dynamic, AggStep('stay_id', 'count'), FilterStep('time', lambda x: x < 4) ]) excl4 = SelectionCriterion('More than 12 hour gap between measurements') excl4.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)), CustomStep(n_obs_per_row), TransformStep('n', lambda x: x > 0), AggStep('stay_id', longest_rle, 'n'), FilterStep('n', lambda x: x > 12) ]) excl5 = SelectionCriterion('Aged < 18 years') excl5.add_step([ LoadStep('age', args.src), FilterStep('age', lambda x: x < 18) ]) # Task-specific exclusion criteria sepsis_add6 = sepsis[sepsis['time'] >= 0].copy() sepsis_add6['time'] += 6 patients = stop_window_at(patients, end=sepsis_add6) get_first_sepsis = Pipeline("Get sepsis patients") get_first_sepsis.add_step([ load_sepsis, AggStep('stay_id', 'max') ]) load_hospital_id = LoadStep('hospital_id', src=args.src) excl6 = SelectionCriterion('Low sepsis prevalence') excl6.add_step([ CombineStep( steps=[get_first_sepsis, load_hospital_id], func=make_prevalence_calculator(outc_var) ), FilterStep('prevalence', lambda x: x == 0) ]) excl7 = SelectionCriterion('Sepsis onset before 6h in the ICU') excl7.add_step([ load_sepsis, AggStep(['stay_id'], lambda x: x.iloc[0]), FilterStep('time', lambda x: x < 6) ]) print(' Select cohort\n') cohort = Cohort(patients) cohort.add_criterion( [excl1, excl2, excl3, excl4, excl5, excl6, excl7] if args.src in ['eicu', 'eicu_demo'] else [excl1, excl2, excl3, excl4, excl5, excl7] ) print(cohort.criteria) patients, attrition = cohort.select() print('\n') print(' Load and format input data') outc_formatting = Pipeline("Prepare length of stay") outc_formatting.add_step([ load_sepsis, CustomStep(make_grid_mapper(patients)), RenameStep(outc_var, 'label'), CustomStep(make_outcome_windower(6)), TransformStep('label', lambda x: x.astype(int)) ]) outc = outc_formatting.apply() dyn_formatting = Pipeline("Prepare dynamic variables") dyn_formatting.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)) ]) dyn = dyn_formatting.apply() sta_formatting = Pipeline("Prepare static variables") sta_formatting.add_step([ load_static, CustomStep(make_patient_mapper(patients)) ]) sta = sta_formatting.apply() return (outc, dyn, sta), attrition if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--src', default='mimic_demo', help='name of datasource', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) parser.add_argument('--out_dir', default='../data/sepsis', help='path where to store extracted data', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) args = parser.parse_known_args()[0] (outc, dyn, sta), attrition = create_sepsis_task(args) save_dir = os.path.join(args.out_dir, args.src) os.makedirs(save_dir, exist_ok=True) pq.write_table(pa.Table.from_pandas(outc), os.path.join(save_dir, 'outc.parquet')) pq.write_table(pa.Table.from_pandas(dyn), os.path.join(save_dir, 'dyn.parquet')) pq.write_table(pa.Table.from_pandas(sta), os.path.join(save_dir, 'sta.parquet')) attrition.to_csv(os.path.join(save_dir, 'attrition.csv'))
5,841
34.840491
105
py
YAIB-cohorts
YAIB-cohorts-main/Python/aki.py
import os import argparse import pyarrow as pa import pyarrow.parquet as pq from src.cohort import Cohort, SelectionCriterion from src.steps import ( InputStep, LoadStep, AggStep, FilterStep, TransformStep, CustomStep, RenameStep, Pipeline, CombineStep ) from src.ricu import stay_windows from src.ricu_utils import ( stop_window_at, n_obs_per_row, longest_rle, make_grid_mapper, make_patient_mapper, make_prevalence_calculator, make_outcome_windower ) outc_var = "aki" # this is a custom definition of sepsis that differs from that defined by ricu static_vars = ["age", "sex", "height", "weight"] dynamic_vars = ["alb", "alp", "alt", "ast", "be", "bicar", "bili", "bili_dir", "bnd", "bun", "ca", "cai", "ck", "ckmb", "cl", "crea", "crp", "dbp", "fgn", "fio2", "glu", "hgb", "hr", "inr_pt", "k", "lact", "lymph", "map", "mch", "mchc", "mcv", "methb", "mg", "na", "neut", "o2sat", "pco2", "ph", "phos", "plt", "po2", "ptt", "resp", "sbp", "temp", "tnt", "urine", "wbc"] def create_aki_task(args): print('Start creating the AKI task.') print(' Preload variables') load_aki = LoadStep(outc_var, args.src, cache=True) aki = load_aki.perform() load_static = LoadStep(static_vars, args.src, cache=True) load_dynamic = LoadStep(dynamic_vars, args.src, cache=True) print(' Define observation times') patients = stay_windows(args.src) patients = stop_window_at(patients, end=24*7) print(' Define exclusion criteria') # General exclusion criteria excl1 = SelectionCriterion('Invalid length of stay') excl1.add_step([ InputStep(patients), FilterStep('end', lambda x: x < 0) ]) excl2 = SelectionCriterion('Length of stay < 6h') excl2.add_step([ LoadStep('los_icu', args.src), FilterStep('los_icu', lambda x: x < 6 / 24) ]) excl3 = SelectionCriterion('Less than 4 hours with any measurement') excl3.add_step([ load_dynamic, AggStep('stay_id', 'count'), FilterStep('time', lambda x: x < 4) ]) excl4 = SelectionCriterion('More than 12 hour gap between measurements') excl4.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)), CustomStep(n_obs_per_row), TransformStep('n', lambda x: x > 0), AggStep('stay_id', longest_rle, 'n'), FilterStep('n', lambda x: x > 12) ]) excl5 = SelectionCriterion('Aged < 18 years') excl5.add_step([ LoadStep('age', args.src), FilterStep('age', lambda x: x < 18) ]) # Task-specific exclusion criteria aki_add6 = aki[aki['time'] >= 0].copy() aki_add6['time'] += 6 patients = stop_window_at(patients, end=aki_add6) get_first_aki = Pipeline("Get AKI patients") get_first_aki.add_step([ InputStep(aki), AggStep('stay_id', 'max') ]) load_hospital_id = LoadStep('hospital_id', src=args.src) excl6 = SelectionCriterion('Low AKI prevalence') excl6.add_step([ CombineStep( steps=[get_first_aki, load_hospital_id], func=make_prevalence_calculator(outc_var) ), FilterStep('prevalence', lambda x: x == 0) ]) excl7 = SelectionCriterion('AKI onset before 6h in the ICU') excl7.add_step([ InputStep(aki), AggStep(['stay_id'], 'first'), FilterStep('time', lambda x: x < 6) ]) def cummin_crea(x): x['crea'] = x.groupby('stay_id')['crea'].cummin() return x def get_baseline_candidates(x): x = x.copy() x['time_ge_0'] = x['time'] >= 0 x['num_in_icu'] = x.groupby('stay_id')['time_ge_0'].cumsum() return x[(x['time'] < 0) | (x['num_in_icu'] == 1)] excl8 = SelectionCriterion('Baseline creatinine > 4') excl8.add_step([ LoadStep('crea', src=args.src), CustomStep(cummin_crea), CustomStep(get_baseline_candidates), AggStep(['stay_id'], 'last'), FilterStep('crea', lambda x: x > 4) ]) print(' Select cohort\n') cohort = Cohort(patients) cohort.add_criterion( [excl1, excl2, excl3, excl4, excl5, excl6, excl7, excl8] if args.src in ['eicu', 'eicu_demo'] else [excl1, excl2, excl3, excl4, excl5, excl7, excl8] ) print(cohort.criteria) patients, attrition = cohort.select() print('\n') print(' Load and format input data') outc_formatting = Pipeline("Prepare length of stay") outc_formatting.add_step([ InputStep(aki), CustomStep(make_grid_mapper(patients)), RenameStep(outc_var, 'label'), CustomStep(make_outcome_windower(6)), TransformStep('label', lambda x: x.astype(int)) ]) outc = outc_formatting.apply() dyn_formatting = Pipeline("Prepare dynamic variables") dyn_formatting.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)) ]) dyn = dyn_formatting.apply() sta_formatting = Pipeline("Prepare static variables") sta_formatting.add_step([ load_static, CustomStep(make_patient_mapper(patients)) ]) sta = sta_formatting.apply() return (outc, dyn, sta), attrition if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--src', default='mimic_demo', help='name of datasource', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) parser.add_argument('--out_dir', default='../data/aki', help='path where to store extracted data', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) args = parser.parse_known_args()[0] (outc, dyn, sta), attrition = create_aki_task(args) save_dir = os.path.join(args.out_dir, args.src) os.makedirs(save_dir, exist_ok=True) pq.write_table(pa.Table.from_pandas(outc), os.path.join(save_dir, 'outc.parquet')) pq.write_table(pa.Table.from_pandas(dyn), os.path.join(save_dir, 'dyn.parquet')) pq.write_table(pa.Table.from_pandas(sta), os.path.join(save_dir, 'sta.parquet')) attrition.to_csv(os.path.join(save_dir, 'attrition.csv'))
6,292
34.156425
106
py
YAIB-cohorts
YAIB-cohorts-main/Python/los.py
import os import argparse import pyarrow as pa import pyarrow.parquet as pq import numpy as np from src.cohort import Cohort, SelectionCriterion from src.steps import ( InputStep, LoadStep, AggStep, FilterStep, TransformStep, CustomStep, DropStep, RenameStep, Pipeline ) from src.ricu import stay_windows, hours from src.ricu_utils import ( stop_window_at, make_grid_mapper, make_patient_mapper, n_obs_per_row, longest_rle ) outc_var = "los_icu" static_vars = ["age", "sex", "height", "weight"] dynamic_vars = ["alb", "alp", "alt", "ast", "be", "bicar", "bili", "bili_dir", "bnd", "bun", "ca", "cai", "ck", "ckmb", "cl", "crea", "crp", "dbp", "fgn", "fio2", "glu", "hgb", "hr", "inr_pt", "k", "lact", "lymph", "map", "mch", "mchc", "mcv", "methb", "mg", "na", "neut", "o2sat", "pco2", "ph", "phos", "plt", "po2", "ptt", "resp", "sbp", "temp", "tnt", "urine", "wbc"] def create_los_task(args): print('Start creating the length of stay task.') print(' Preload variables') load_los = Pipeline('Load and process kidney function') load_los.add_step([ LoadStep(outc_var, args.src), TransformStep(outc_var, lambda x: np.floor(x * 24)) ]) los = load_los.apply() load_static = LoadStep(static_vars, args.src, cache=True) load_dynamic = LoadStep(dynamic_vars, args.src, cache=True) print(' Define observation times') patients = stay_windows(args.src) patients = stop_window_at(patients, end=24*7) print(' Define exclusion criteria') excl1 = SelectionCriterion('Invalid length of stay') excl1.add_step([ InputStep(patients), FilterStep('end', lambda x: x < 0) ]) excl2 = SelectionCriterion('Length of stay < 6h') excl2.add_step([ LoadStep('los_icu', args.src), FilterStep('los_icu', lambda x: x < 6 / 24) ]) excl3 = SelectionCriterion('Less than 4 hours with any measurement') excl3.add_step([ load_dynamic, AggStep('stay_id', 'count'), FilterStep('time', lambda x: x < 4) ]) excl4 = SelectionCriterion('More than 12 hour gap between measurements') excl4.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)), CustomStep(n_obs_per_row), TransformStep('n', lambda x: x > 0), AggStep('stay_id', longest_rle, 'n'), FilterStep('n', lambda x: x > 12) ]) excl5 = SelectionCriterion('Aged < 18 years') excl5.add_step([ LoadStep('age', args.src), FilterStep('age', lambda x: x < 18) ]) print(' Select cohort\n') cohort = Cohort(patients) cohort.add_criterion([excl1, excl2, excl3, excl4, excl5]) print(cohort.criteria) patients, attrition = cohort.select() print('\n') print(' Load and format input data') def calculate_remaining_los(df): df['max_los'] = 7 * 24 df["los_icu"] = df['los_icu'] - df['time'] df["los_icu"] = df[['los_icu', 'max_los']].min(axis=1) return df.drop('max_los', axis=1) outc_formatting = Pipeline("Prepare length of stay") outc_formatting.add_step([ InputStep(los), CustomStep(make_grid_mapper(patients, match_time=False)), CustomStep(calculate_remaining_los), DropStep('time'), RenameStep(outc_var, 'label') ]) outc = outc_formatting.apply() dyn_formatting = Pipeline("Prepare dynamic variables") dyn_formatting.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)) ]) dyn = dyn_formatting.apply() sta_formatting = Pipeline("Prepare static variables") sta_formatting.add_step([ load_static, CustomStep(make_patient_mapper(patients)) ]) sta = sta_formatting.apply() return (outc, dyn, sta), attrition if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--src', default='mimic_demo', help='name of datasource', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) parser.add_argument('--out_dir', default='../data/los', help='path where to store extracted data', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) args = parser.parse_known_args()[0] (outc, dyn, sta), attrition = create_los_task(args) save_dir = os.path.join(args.out_dir, args.src) os.makedirs(save_dir, exist_ok=True) pq.write_table(pa.Table.from_pandas(outc), os.path.join(save_dir, 'outc.parquet')) pq.write_table(pa.Table.from_pandas(dyn), os.path.join(save_dir, 'dyn.parquet')) pq.write_table(pa.Table.from_pandas(sta), os.path.join(save_dir, 'sta.parquet')) attrition.to_csv(os.path.join(save_dir, 'attrition.csv'))
4,897
34.23741
102
py
YAIB-cohorts
YAIB-cohorts-main/Python/setup_env.py
from rpy2.robjects.packages import importr # Install renv for reproducible R package management utils = importr('utils') utils.chooseCRANmirror(ind=1) utils.install_packages('renv') # Use renv to install all necessary packages renv = importr('renv') renv.activate() renv.restore() utils.install_packages('units') # Additionally install demo data utils.install_packages("mimic.demo", repos="https://eth-mds.github.io/physionet-demo") utils.install_packages("eicu.demo", repos="https://eth-mds.github.io/physionet-demo")
522
29.764706
86
py
YAIB-cohorts
YAIB-cohorts-main/Python/kidney_function.py
import os import argparse import pyarrow as pa import pyarrow.parquet as pq from src.cohort import Cohort, SelectionCriterion from src.steps import ( InputStep, LoadStep, AggStep, FilterStep, TransformStep, CustomStep, DropStep, RenameStep, Pipeline ) from src.ricu import stay_windows, hours from src.ricu_utils import ( stop_window_at, make_grid_mapper, make_patient_mapper, n_obs_per_row, longest_rle ) outc_var = "crea" static_vars = ["age", "sex", "height", "weight"] dynamic_vars = ["alb", "alp", "alt", "ast", "be", "bicar", "bili", "bili_dir", "bnd", "bun", "ca", "cai", "ck", "ckmb", "cl", "crea", "crp", "dbp", "fgn", "fio2", "glu", "hgb", "hr", "inr_pt", "k", "lact", "lymph", "map", "mch", "mchc", "mcv", "methb", "mg", "na", "neut", "o2sat", "pco2", "ph", "phos", "plt", "po2", "ptt", "resp", "sbp", "temp", "tnt", "urine", "wbc"] def create_kf_task(args): print('Start creating the kidney function task.') print(' Preload variables') load_kf = Pipeline('Load and process kidney function') load_kf.add_step([ LoadStep(outc_var, args.src, cache=True), FilterStep('time', lambda x: (x > 24) & (x <= 48)), DropStep('time'), AggStep('stay_id', 'median'), ]) kf = load_kf.apply() load_static = LoadStep(static_vars, args.src, cache=True) load_dynamic = LoadStep(dynamic_vars, args.src, cache=True) print(' Define observation times') patients = stay_windows(args.src) patients = stop_window_at(patients, end=24) print(' Define exclusion criteria') # General exclusion criteria excl1 = SelectionCriterion('Invalid length of stay') excl1.add_step([ InputStep(patients), FilterStep('end', lambda x: x < 0) ]) excl2 = SelectionCriterion('Length of stay < 6h') excl2.add_step([ LoadStep('los_icu', args.src), FilterStep('los_icu', lambda x: x < 6 / 24) ]) excl3 = SelectionCriterion('Less than 4 hours with any measurement') excl3.add_step([ load_dynamic, AggStep('stay_id', 'count'), FilterStep('time', lambda x: x < 4) ]) excl4 = SelectionCriterion('More than 12 hour gap between measurements') excl4.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)), CustomStep(n_obs_per_row), TransformStep('n', lambda x: x > 0), AggStep('stay_id', longest_rle, 'n'), FilterStep('n', lambda x: x > 12) ]) excl5 = SelectionCriterion('Aged < 18 years') excl5.add_step([ LoadStep('age', args.src), FilterStep('age', lambda x: x < 18) ]) # Task-specific exclusion criteria excl6 = SelectionCriterion('Length of stay < 48h') excl6.add_step([ LoadStep('los_icu', src=args.src, cache=True), FilterStep('los_icu', lambda x: x < 48/24) ]) excl7 = SelectionCriterion('Had no creatinine measurement between 24 and 48 hoursn') excl7.add_step([ InputStep(kf), CustomStep(make_patient_mapper(patients)), FilterStep('crea', lambda x: x.isnull()) ]) print(' Select cohort\n') cohort = Cohort(patients) cohort.add_criterion([excl1, excl2, excl3, excl4, excl5, excl6, excl7]) print(cohort.criteria) patients, attrition = cohort.select() print('\n') print(' Load and format input data') outc_formatting = Pipeline("Prepare kidney function") outc_formatting.add_step([ InputStep(kf), CustomStep(make_patient_mapper(patients)), RenameStep(outc_var, 'label') ]) outc = outc_formatting.apply() dyn_formatting = Pipeline("Prepare dynamic variables") dyn_formatting.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)) ]) dyn = dyn_formatting.apply() sta_formatting = Pipeline("Prepare static variables") sta_formatting.add_step([ load_static, CustomStep(make_patient_mapper(patients)) ]) sta = sta_formatting.apply() return (outc, dyn, sta), attrition if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--src', default='mimic_demo', help='name of datasource', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) parser.add_argument('--out_dir', default='../data/kidney_function', help='path where to store extracted data', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) args = parser.parse_known_args()[0] (outc, dyn, sta), attrition = create_kf_task(args) save_dir = os.path.join(args.out_dir, args.src) os.makedirs(save_dir, exist_ok=True) pq.write_table(pa.Table.from_pandas(outc), os.path.join(save_dir, 'outc.parquet')) pq.write_table(pa.Table.from_pandas(dyn), os.path.join(save_dir, 'dyn.parquet')) pq.write_table(pa.Table.from_pandas(sta), os.path.join(save_dir, 'sta.parquet')) attrition.to_csv(os.path.join(save_dir, 'attrition.csv'))
5,167
34.156463
114
py
YAIB-cohorts
YAIB-cohorts-main/Python/mortality.py
import os import argparse import pyarrow as pa import pyarrow.parquet as pq from src.cohort import Cohort, SelectionCriterion from src.steps import ( InputStep, LoadStep, AggStep, FilterStep, TransformStep, CustomStep, DropStep, RenameStep, Pipeline ) from src.ricu import stay_windows, hours from src.ricu_utils import ( stop_window_at, make_grid_mapper, make_patient_mapper, n_obs_per_row, longest_rle ) outc_var = "death_icu" static_vars = ["age", "sex", "height", "weight"] dynamic_vars = ["alb", "alp", "alt", "ast", "be", "bicar", "bili", "bili_dir", "bnd", "bun", "ca", "cai", "ck", "ckmb", "cl", "crea", "crp", "dbp", "fgn", "fio2", "glu", "hgb", "hr", "inr_pt", "k", "lact", "lymph", "map", "mch", "mchc", "mcv", "methb", "mg", "na", "neut", "o2sat", "pco2", "ph", "phos", "plt", "po2", "ptt", "resp", "sbp", "temp", "tnt", "urine", "wbc"] def create_mortality_task(args): print('Start creating the mortality task.') print(' Preload variables') load_mortality = LoadStep(outc_var, args.src, cache=True) load_static = LoadStep(static_vars, args.src, cache=True) load_dynamic = LoadStep(dynamic_vars, args.src, cache=True) print(' Define observation times') time_of_death = load_mortality.perform() time_of_death = time_of_death[time_of_death[outc_var] == True] patients = stay_windows(args.src) patients = stop_window_at(patients, end=24) patients = stop_window_at(patients, end=time_of_death) print(' Define exclusion criteria') # General exclusion criteria excl1 = SelectionCriterion('Invalid length of stay') excl1.add_step([ InputStep(patients), FilterStep('end', lambda x: x < 0) ]) excl2 = SelectionCriterion('Length of stay < 6h') excl2.add_step([ LoadStep('los_icu', args.src), FilterStep('los_icu', lambda x: x < 6 / 24) ]) excl3 = SelectionCriterion('Less than 4 hours with any measurement') excl3.add_step([ load_dynamic, AggStep('stay_id', 'count'), FilterStep('time', lambda x: x < 4) ]) excl4 = SelectionCriterion('More than 12 hour gap between measurements') excl4.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)), CustomStep(n_obs_per_row), TransformStep('n', lambda x: x > 0), AggStep('stay_id', longest_rle, 'n'), FilterStep('n', lambda x: x > 12) ]) excl5 = SelectionCriterion('Aged < 18 years') excl5.add_step([ LoadStep('age', args.src), FilterStep('age', lambda x: x < 18) ]) # Task-specific exclusion criteria excl6 = SelectionCriterion('Died within the first 30 hours of ICU admission') excl6.add_step([ LoadStep('death_icu', src=args.src, interval=hours(1), cache=True), FilterStep('death_icu', lambda x: x == True), FilterStep('time', lambda x: x < 30) ]) excl7 = SelectionCriterion('Length of stay < 30h') excl7.add_step([ LoadStep('los_icu', src=args.src, cache=True), FilterStep('los_icu', lambda x: x < 30/24) ]) print(' Select cohort\n') cohort = Cohort(patients) cohort.add_criterion([excl1, excl2, excl3, excl4, excl5, excl6, excl7]) print(cohort.criteria) patients, attrition = cohort.select() print('\n') print(' Load and format input data') outc_formatting = Pipeline("Prepare mortality") outc_formatting.add_step([ load_mortality, DropStep('time'), CustomStep(make_patient_mapper(patients)), TransformStep(outc_var, lambda x: x.fillna(0).astype(int)), RenameStep(outc_var, 'label') ]) outc = outc_formatting.apply() dyn_formatting = Pipeline("Prepare dynamic variables") dyn_formatting.add_step([ load_dynamic, CustomStep(make_grid_mapper(patients, step_size=1)) ]) dyn = dyn_formatting.apply() sta_formatting = Pipeline("Prepare static variables") sta_formatting.add_step([ load_static, CustomStep(make_patient_mapper(patients)) ]) sta = sta_formatting.apply() return (outc, dyn, sta), attrition if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--src', default='mimic_demo', help='name of datasource', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) parser.add_argument('--out_dir', default='../data/mortality', help='path where to store extracted data', choices=['aumc', 'eicu', 'eicu_demo', 'hirid', 'mimic', 'mimic_demo', 'miiv']) args = parser.parse_known_args()[0] (outc, dyn, sta), attrition = create_mortality_task(args) save_dir = os.path.join(args.out_dir, args.src) os.makedirs(save_dir, exist_ok=True) pq.write_table(pa.Table.from_pandas(outc), os.path.join(save_dir, 'outc.parquet')) pq.write_table(pa.Table.from_pandas(dyn), os.path.join(save_dir, 'dyn.parquet')) pq.write_table(pa.Table.from_pandas(sta), os.path.join(save_dir, 'sta.parquet')) attrition.to_csv(os.path.join(save_dir, 'attrition.csv'))
5,256
35.255172
108
py
YAIB-cohorts
YAIB-cohorts-main/Python/src/ricu.py
import os from typing import List import pandas as pd import rpy2.robjects as ro from rpy2.robjects.packages import importr from .Rutils import as_data_frame, r_to_pandas # Load ricu ricu = importr('ricu') # ------------------------------------------------------------------------------ # Port existing and often used ricu functions rename_cols = ricu.rename_cols days = ricu.days hours = ricu.hours mins = ricu.mins secs = ricu.secs # ------------------------------------------------------------------------------ # Wrap or extend other ricu functionality def dictionary(dir: str = '../ricu-extensions/configs', **kwargs) -> ro.ListVector: """Wrapper around `ricu.load_dictionary` to load the default and custom ricu concepts Args: dir: Path to the root folder containing all concept-dicts. Defaults to 'config'. Returns: rpy2 ListVector of all concepts in the dictionary """ # TODO: make this load all .config files in the subfolders folders = [os.path.join(dir, subdir) for subdir in os.listdir(dir)] return ricu.load_dictionary(cfg_dirs=folders, **kwargs) def concepts(x: str | List[str], dict: ro.ListVector = dictionary()) -> ro.RObject: """Get one or more ricu concepts by name Args: x: name of one or more concepts dict: the ricu dictionary object (in R). Defaults to dictionary(). Returns: ricu concepts """ return dict.rx(ro.StrVector(x)) def stay_windows(src: str, interval: ro.IntVector = hours(1)) -> pd.DataFrame: """Load the observation times for all patients in a dataset Args: src: name of the dataset of interest interval: interval in which to provide `start` and `end` times. Defaults to hours(1). Returns: _description_ """ res = ricu.stay_windows(src, interval=interval) res = ricu.as_win_tbl(res, index_var="start", dur_var="end", interval=interval) res = ricu.rename_cols(res, "stay_id", ricu.id_var(res)) return r_to_pandas(as_data_frame(res))
2,031
30.261538
93
py
YAIB-cohorts
YAIB-cohorts-main/Python/src/steps.py
from abc import abstractmethod from typing import Any, List, Callable, Type import pandas as pd from .ricu import * from .Rutils import as_null, r_to_pandas class Step(): """Base class for a transformation step """ def __init__(self, cache=False) -> None: self.cache = cache self._performed = False def perform(self, input: Any = None, force: bool = False): """Perform the specified transformation step on the provided input. If caching is activated, the result of the step is stored (but not copied, so later changes will also change the stored information.) Args: input: Object used as input to the transformation. Defaults to None. force: Should the result be recalculated, even if a cached result is available? Defaults to False. Returns: Transformed input """ if self.cache and self._performed and not force: return self.res else: res = self.do_perform(input) self._performed = True if self.cache: self.res = res return res @abstractmethod def do_perform(self, input=None): """Called by `perform` to apply the actual transformation. Must be implemented by each class inheriting from Step. Args: input: Object used as input to the transformation. Defaults to None. """ pass def __repr__(self) -> str: return self.desc class InputStep(Step): """_summary_ Args: Step: _description_ """ def __init__(self, x, **kwargs) -> None: super().__init__(cache=False) self.desc = f"Use pre-loaded variable." self.x = x def do_perform(self, input): if input is not None: raise ValueError(f'Input step does not accept input, got {input}') return self.x class LoadStep(Step): def __init__(self, concept, src, cache=False, **kwargs) -> None: super().__init__(cache) self.desc = f"Load clinical concept {concept} from {src}." self.concept = concept if not isinstance(self.concept, list): self.concept = [self.concept] self.concept = concepts(self.concept) self.src = src self.kwargs = kwargs def do_perform(self, input): if input is not None: raise ValueError(f'Load step does not accept input, got {input}') res = ricu.load_concepts(self.concept, self.src, **self.kwargs) # Rename columns uniformly across datasets old = ricu.id_var(res) new = ['stay_id'] # TODO: only supports loading at the stay_id level if ricu.is_ts_tbl(res)[0]: old += ricu.index_var(res) new += ['time'] res = ricu.rename_cols(res, ro.StrVector(new), old) return r_to_pandas(as_data_frame(res)) class FilterStep(Step): def __init__(self, col: str, condition: Callable, cache=False) -> None: super().__init__(cache) self.desc = f"Filter table based on {col}." self.col = col self.condition = condition def do_perform(self, input: pd.DataFrame = None): if not isinstance(input, pd.DataFrame): raise ValueError(f'Filter step requires a pandas.DataFrame as input, got {input}.') return input[self.condition(input[self.col])] class DropStep(Step): def __init__(self, col: str | List[str], cache=False) -> None: super().__init__(cache) self.desc = f"Drop columns {col}." self.col = col def do_perform(self, input: pd.DataFrame = None): if not isinstance(input, pd.DataFrame): raise ValueError(f'Drop step requires a pandas.DataFrame as input, got {input}.') return input.drop(self.col, axis=1) class RenameStep(Step): def __init__(self, old: str | List[str], new: str | List[str], cache=False) -> None: super().__init__(cache) self.desc = f"Rename columns {old} to {new}." self.old = [old] if isinstance(old, str) else old self.new = [new] if isinstance(new, str) else new def do_perform(self, input: pd.DataFrame = None): if not isinstance(input, pd.DataFrame): raise ValueError(f'Rename step requires a pandas.DataFrame as input, got {input}.') mapper = {o: n for o, n in zip(self.old, self.new)} return input.rename(columns=mapper) class AggStep(Step): def __init__(self, by: str | List[str], func: str | Callable, col: str | List | None = None, cache=False) -> None: super().__init__(cache) funcname = func if isinstance(func, str) else func.__name__ self.desc = f'Aggregate table over {by} using {funcname}.' self.by = by self.col = col self.func = func def do_perform(self, input: pd.DataFrame = None): if not isinstance(input, pd.DataFrame): raise ValueError(f'Aggregation step requires a pandas.DataFrame as input, got {input}.') col = self.col if col is None: col = [c for c in input.columns if c not in self.by] return input.groupby(self.by)[col].aggregate(self.func).reset_index() class TransformStep(Step): def __init__(self, col: str | List, func: str | Callable, cache=False) -> None: super().__init__(cache) funcname = func if isinstance(func, str) else func.__name__ self.desc = f'Tranform column(s) {col} using {funcname}.' self.col = [col] if isinstance(col, str) else col self.func = func def do_perform(self, input: pd.DataFrame = None): if not isinstance(input, pd.DataFrame): raise ValueError(f'Transformation step requires a pandas.DataFrame as input, got {input}.') # TODO: make more elegant res = input.copy() for c in self.col: res[c] = self.func(res[c]) return res class CustomStep(Step): def __init__(self, func: Callable, cache=False) -> None: super().__init__(cache) self.desc = f'Custom step applying {func.__name__}.' self.func = func def do_perform(self, input=None): return self.func(input) class CombineStep(Step): def __init__(self, steps: Type["Pipeline"] | Step, func: Callable, cache=False, **kwargs) -> None: super().__init__(cache) self.desc = f'Combine steps using {func.__name__}.' self.steps = steps self.func = func self.kwargs = kwargs def do_perform(self, input=None): res = [] for step in self.steps: if isinstance(step, Pipeline): res.append(step.apply(input)) else: res.append(step.perform(input)) return self.func(res, **self.kwargs) class Pipeline(): def __init__(self, desc) -> None: self.desc = desc self.steps = [] def add_step(self, x: Step | List[Step]): """Add one or more transformation step to the pipeline Transformation steps are applied sequentially Args: x: single transformation step or list of steps """ if isinstance(x, Step): x = [x] self.steps += x def apply(self, input: Any = None) -> Any: """Apply all transformation steps sequentially Args: input: Optional input to the first step, if required. All subsequent steps receive the output of the previous step. Defaults to None. Returns: Result of the final step """ res = input for step in self.steps: res = step.perform(res) return res def __repr__(self) -> str: repr = f"<Pipeline>: {self.desc}\n" for i, step in enumerate(self.steps): repr += f" {i+1}. {str(step)}\n" return repr
7,939
32.221757
118
py
YAIB-cohorts
YAIB-cohorts-main/Python/src/cohort.py
from typing import List, Tuple from collections import namedtuple import pandas as pd from .steps import Pipeline fields = ['desc', 'n_input', 'n_criterion', 'n_excluded', 'n_left'] AttritionItem = namedtuple('AttritionItem', fields) class SelectionCriterion(Pipeline): """Single cohort selection criterion, either used as inclusion or exclusion criterion Args: desc: short readable description of the selection criterion, e.g., "aged < 18 years" type: Type of selection criterion. Defaults to "exclusion". """ def __init__(self, desc: str, type: str = "exclusion") -> None: super().__init__(desc) self._applied = False self.type = type @property def selected(self) -> pd.DataFrame: """Selected observations after applying the criterion Raises: ValueError: If the criterion was not been applied to data yet. Returns: _description_ """ if not self._applied: raise ValueError('SelectionCriterion must be applied first') return self._selected @property def n(self) -> int: """Number of selected observations Returns: _description_ """ return self.selected.shape[0] def apply(self, input=None) -> pd.DataFrame: """Apply all transformation steps sequentially to obtain a list of patients that fulfil the criterion. Args: input: Optional input to the first step, if required. All subsequent steps receive the output of the previous step. Defaults to None. Returns: pd.DataFrame with a single column `stay_id` of all selected observations. """ res = super().apply(input) self._applied = True self._selected = res[['stay_id']] return self.selected def __repr__(self) -> str: repr = f"<SelectionCriterion[{self.type}]>: {self.desc}" repr += f" [n={self.n}]" if self._applied else "" repr += "\n" for i, step in enumerate(self.steps): repr += f" {i+1}. {str(step)}\n" return repr class Cohort(): """Cohort definition Args: population: total patient population from which to select the cohort according to the selection criteria """ def __init__(self, population: pd.DataFrame) -> None: self.population = population.copy() self.criteria = [] def add_criterion(self, criterion: SelectionCriterion | List): """Add one or more criteria to the cohort Args: criterion: _description_ """ if isinstance(criterion, SelectionCriterion): criterion = [criterion] self.criteria += criterion def select(self) -> Tuple[pd.DataFrame, pd.DataFrame]: """Apply the selection criteria to the patient population Raises: TypeError: if criteria other than "inclusion" or "exclusion" are given Returns: the selected subset of the total patient population, an attrition table """ population = self.population attrition = [] for criterion in self.criteria: criterion.apply() if criterion.type == "exclusion": new_pop = population.merge(criterion.selected, how='left', on='stay_id', indicator=True) new_pop = new_pop[new_pop._merge == "left_only"] new_pop.drop('_merge', axis=1, inplace=True) elif criterion.type == "inclusion": new_pop = population.merge(criterion.selected, how='inner', on='stay_id') else: raise TypeError(f'Only SelectionCriterion of type "inclusion" or "exclusion" allowed, got {criterion.type}.') # Log the attrition attrition.append(AttritionItem( desc=criterion.desc, n_input=population.shape[0], n_criterion=criterion.n, n_excluded=population.shape[0]-new_pop.shape[0], n_left=new_pop.shape[0] )) population = new_pop attrition = pd.DataFrame(attrition) return population, attrition
4,300
32.084615
125
py
YAIB-cohorts
YAIB-cohorts-main/Python/src/__init__.py
0
0
0
py
YAIB-cohorts
YAIB-cohorts-main/Python/src/Rutils.py
import pandas as pd import rpy2 import rpy2.robjects as ro from rpy2.robjects import pandas2ri source = ro.r['source'] as_data_frame = ro.r['as.data.frame'] as_null = ro.r['as.null'] def r_to_pandas(df: ro.RObject) -> pd.DataFrame: """Convert an R data.frame to pandas.DataFrame Args: df: R data.frame to convert Returns: converted pandas.DataFrame """ with (ro.default_converter + pandas2ri.converter).context(): return replace_r_nas(ro.conversion.get_conversion().rpy2py(df)) def replace_r_nas(df: pd.DataFrame) -> pd.DataFrame: """Replace special R NA types with standard pandas NA Args: df: an R data.frame that was recently converted to pandas Returns: data with only standard pandas NA """ for col in df.columns: df[col] = df[col].apply(lambda val: pd.NA if isinstance(val, rpy2.rinterface_lib.sexp.NACharacterType) else val) return df
944
27.636364
120
py
YAIB-cohorts
YAIB-cohorts-main/Python/src/ricu_utils.py
from typing import Callable, List import numpy as np import pandas as pd def stop_window_at(x: pd.DataFrame, end: int | pd.DataFrame) -> pd.DataFrame: """Stop observation time at a given end date Args: x: observation times for each patient end: time at which to end observation, can either be a constant scalar for all patients or a pandas.DataFrame with a separate time per patient Raises: ValueError: `x` must contain the three columns `stay_id`, `start`, and `end` ValueError: if `end` is a pandas.DataFrame, it must contain a `time` column Returns: observation times truncated at end """ if np.all(x.columns != ['stay_id', 'start', 'end']): raise ValueError('`x` must be pandas.DataFrame with three columns: stay_id, start, end') if isinstance(end, pd.DataFrame): if not 'time' in end.columns: raise ValueError('if `end` is a pandas.DataFrame, it must contain a column named `time` specifying the censor time.') end = end.groupby('stay_id')['time'].min().reset_index() x = x.merge(end, on='stay_id', how='left') x['time'] = x['time'].fillna(np.inf) x['end'] = x[['end','time']].min(axis=1) x = x.drop('time', axis=1) else: x['end'] = x['end'].clip(upper=end) return x def make_grid_mapper(grid: pd.DataFrame, step_size: int = 1, match_time: bool = True) -> Callable: """Return a function that maps data to a grid For the use with CustomStep Factory Args: grid: the grid to map to, for example the observation times for each patient step_size: how granular should the grid be. Defaults to 1. match_time: should time be matched or should the data be joined on stay_id only. Defaults to True. Factory Returns: mapper function that takes a single pandas.DataFrame as input to be mapped """ grid = grid.copy() grid['time'] = grid.apply(lambda row: list(range(int(row['start']), int(row['end'])+1, step_size)), axis=1) grid = grid.drop(['start', 'end'], axis=1) grid = grid.explode('time') grid['time'] = grid['time'].astype(int) def map_to_grid(x: pd.DataFrame) -> pd.DataFrame: map_on = ['stay_id'] if match_time: map_on += ['time'] return x.merge(grid, on=map_on, how='right') return map_to_grid def make_patient_mapper(pop: pd.DataFrame) -> Callable: """Return a function that maps data to a patient population Factory Args: pop: the population to map to, i.e., a list of patient ids Factory Returns: mapper function that takes a single pandas.DataFrame as input to be mapped """ pop = pop[['stay_id']].copy() def map_to_patients(x: pd.DataFrame) -> pd.DataFrame: return x.merge(pop, on=['stay_id'], how='right') return map_to_patients def n_obs_per_row(x: pd.DataFrame) -> pd.DataFrame: """Count the number of non-NA observations per row Args: x: data to be counted Returns: a pandas.DataFrame with `stay_id`, `time` (if present), and `n` """ x = x.copy() ids = x.columns.intersection(['stay_id', 'time']) x['n'] = x.notna().sum(axis=1) - len(ids) return x[ids.append(pd.Index(['n']))] def longest_rle(x: pd.Series, value: bool | int | str = False) -> int: """Count the longest continuous run of a value Args: x: values in the order to be counted value: which value to look for. Defaults to False. Returns: run size """ lengths = (x != x.shift()).astype(int).cumsum() return lengths[x == value].value_counts().max() def make_prevalence_calculator(var: str) -> Callable: """Calculate the prevalence of a condition by hospital (e.g., sepsis) Factory Args: var: name of the ricu concept Factory Returns: callable prevalence calculator Args: List with two elements: - data for the ricu concept - hospital ids for each patient Returns: prevalence at each patient's hospital """ def calculate_prevalence(x: List[pd.DataFrame]) -> pd.DataFrame: data, hospital_ids = x cncpt_per_hosp = data.merge(hospital_ids, on='stay_id', how='right') cncpt_per_hosp[var] = ~cncpt_per_hosp[var].isnull() prev = cncpt_per_hosp.groupby('hospital_id')[var].mean().reset_index() prev = prev.rename(columns={var: 'prevalence'}) res = hospital_ids.merge(prev, on='hospital_id') return res.drop('hospital_id', axis=1) return calculate_prevalence def make_outcome_windower(window: int) -> Callable: def outcome_window(x: pd.DataFrame): x['label'] = x.groupby('stay_id')['label'].ffill(limit=window).bfill(limit=window).fillna(0) return x return outcome_window
4,894
34.729927
129
py
gym-minecraft
gym-minecraft-master/setup.py
from setuptools import setup, find_packages setup(name='gym_minecraft', version='0.0.2', description='OpenAI Gym environment for Minecraft based on Malmo', url='https://github.com/tambetm/gym-minecraft', author='Tambet Matiisen', author_email='tambet.matiisen@gmail.com', license='MIT License', packages=find_packages(), package_data={'': ['assets/*.xml']}, zip_safe=False, install_requires=['gym>=0.2.3', 'minecraft_py==0.0.2', 'pygame'], dependency_links=['git+https://github.com/tambetm/minecraft-py.git#egg=minecraft_py-0.0.2', 'http://www.pygame.org/ftp/pygame-1.9.1release.tar.gz#egg=pygame-1.9.1release'] )
705
40.529412
103
py
gym-minecraft
gym-minecraft-master/examples/test.py
import gym import gym_minecraft import time env = gym.make('MinecraftBasic-v0') #env.configure(allowContinuousMovement=["move", "turn"]) env.configure(allowDiscreteMovement=["move", "turn"], log_level="INFO") #env.configure(videoResolution=[160, 120]) #env.monitor.start("gym_random") for _ in xrange(10): t = time.time() env.reset() t2 = time.time() print "Startup time:", t2 - t done = False s = 0 while not done: obs, reward, done, info = env.step(env.action_space.sample()) env.render() #print "obs:", obs.shape #print "reward:", reward #print "done:", done #print "info", info s += 1 t3 = time.time() print (t3 - t2), "seconds total,", s, "steps total,", s / (t3 - t2), "steps/second" #env.monitor.close()
806
25.9
87
py
gym-minecraft
gym-minecraft-master/examples/test_multi.py
import gym import gym_minecraft env = gym.make('MinecraftBasic-v0') env.configure(client_pool=[("localhost", 10000), ("localhost", 10001), ("localhost", 10002)]) env.reset() done = False while not done: env.render() action = env.action_space.sample() obs, reward, done, info = env.step(action)
308
22.769231
93
py
gym-minecraft
gym-minecraft-master/gym_minecraft/__init__.py
from gym.envs.registration import register # Env registration # ========================== register( id='MinecraftDefaultWorld1-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'default_world_1.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 6060}, #timestep_limit=6060, reward_threshold=1000 ) register( id='MinecraftDefaultFlat1-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'default_flat_1.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 2020}, #timestep_limit=2020, reward_threshold=100 ) register( id='MinecraftTrickyArena1-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'tricky_arena_1.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 303}, #timestep_limit=303, reward_threshold=300 ) register( id='MinecraftEating1-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'eating_1.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 303}, #timestep_limit=303, reward_threshold=70 ) register( id='MinecraftCliffWalking1-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'cliff_walking_1.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 404}, #timestep_limit=404, reward_threshold=100 ) register( id='MinecraftMaze1-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'maze_1.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 606}, #timestep_limit=606, reward_threshold=1000 ) register( id='MinecraftMaze2-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'maze_2.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 2020}, #timestep_limit=2020, reward_threshold=1000 ) register( id='MinecraftBasic-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'basic.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 606}, #timestep_limit=606, reward_threshold=980 ) register( id='MinecraftObstacles-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'obstacles.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 909}, #timestep_limit=909, reward_threshold=2000 ) register( id='MinecraftSimpleRoomMaze-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'simpleRoomMaze.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 909}, #timestep_limit=909, reward_threshold=4000 ) register( id='MinecraftAttic-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'attic.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 606}, #timestep_limit=606, reward_threshold=1000 ) register( id='MinecraftVertical-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'vertical.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 909}, #timestep_limit=909, reward_threshold=8000 ) register( id='MinecraftComplexityUsage-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'complexity_usage.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 606}, #timestep_limit=606, reward_threshold=1000 ) register( id='MinecraftMedium-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'medium.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 1818}, #timestep_limit=1818, reward_threshold=16000 ) register( id='MinecraftHard-v0', entry_point='gym_minecraft.envs:MinecraftEnv', kwargs={'mission_file': 'hard.xml'}, #tags={'wrapper_config.TimeLimit.max_episode_steps': 2424}, #timestep_limit=2424, reward_threshold=32000 )
3,949
26.622378
63
py
gym-minecraft
gym-minecraft-master/gym_minecraft/envs/minecraft_env.py
import logging import time import os import numpy as np import json import xml.etree.ElementTree as ET import gym from gym import spaces, error try: import minecraft_py import MalmoPython except ImportError as e: raise error.DependencyNotInstalled("{}. (HINT: install minecraft_py from https://github.com/tambetm/minecraft-py".format(e)) logger = logging.getLogger(__name__) SINGLE_DIRECTION_DISCRETE_MOVEMENTS = [ "jumpeast", "jumpnorth", "jumpsouth", "jumpwest", "movenorth", "moveeast", "movesouth", "movewest", "jumpuse", "use", "attack", "jump" ] MULTIPLE_DIRECTION_DISCRETE_MOVEMENTS = [ "move", "turn", "look", "strafe", "jumpmove", "jumpstrafe" ] class MinecraftEnv(gym.Env): metadata = {'render.modes': ['human', 'rgb_array']} def __init__(self, mission_file): super(MinecraftEnv, self).__init__() self.agent_host = MalmoPython.AgentHost() assets_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../assets') mission_file = os.path.join(assets_dir, mission_file) self.load_mission_file(mission_file) self.client_pool = None self.mc_process = None self.screen = None def load_mission_file(self, mission_file): logger.info("Loading mission from " + mission_file) mission_xml = open(mission_file, 'r').read() self.load_mission_xml(mission_xml) def load_mission_xml(self, mission_xml): self.mission_spec = MalmoPython.MissionSpec(mission_xml, True) logger.info("Loaded mission: " + self.mission_spec.getSummary()) def init(self, client_pool=None, start_minecraft=None, continuous_discrete=True, add_noop_command=None, max_retries=90, retry_sleep=10, step_sleep=0.001, skip_steps=0, videoResolution=None, videoWithDepth=None, observeRecentCommands=None, observeHotBar=None, observeFullInventory=None, observeGrid=None, observeDistance=None, observeChat=None, allowContinuousMovement=None, allowDiscreteMovement=None, allowAbsoluteMovement=None, recordDestination=None, recordObservations=None, recordRewards=None, recordCommands=None, recordMP4=None, gameMode=None, forceWorldReset=None): self.max_retries = max_retries self.retry_sleep = retry_sleep self.step_sleep = step_sleep self.skip_steps = skip_steps self.forceWorldReset = forceWorldReset self.continuous_discrete = continuous_discrete self.add_noop_command = add_noop_command if videoResolution: if videoWithDepth: self.mission_spec.requestVideoWithDepth(*videoResolution) else: self.mission_spec.requestVideo(*videoResolution) if observeRecentCommands: self.mission_spec.observeRecentCommands() if observeHotBar: self.mission_spec.observeHotBar() if observeFullInventory: self.mission_spec.observeFullInventory() if observeGrid: self.mission_spec.observeGrid(*(observeGrid + ["grid"])) if observeDistance: self.mission_spec.observeDistance(*(observeDistance + ["dist"])) if observeChat: self.mission_spec.observeChat() if allowContinuousMovement or allowDiscreteMovement or allowAbsoluteMovement: # if there are any parameters, remove current command handlers first self.mission_spec.removeAllCommandHandlers() if allowContinuousMovement is True: self.mission_spec.allowAllContinuousMovementCommands() elif isinstance(allowContinuousMovement, list): for cmd in allowContinuousMovement: self.mission_spec.allowContinuousMovementCommand(cmd) if allowDiscreteMovement is True: self.mission_spec.allowAllDiscreteMovementCommands() elif isinstance(allowDiscreteMovement, list): for cmd in allowDiscreteMovement: self.mission_spec.allowDiscreteMovementCommand(cmd) if allowAbsoluteMovement is True: self.mission_spec.allowAllAbsoluteMovementCommands() elif isinstance(allowAbsoluteMovement, list): for cmd in allowAbsoluteMovement: self.mission_spec.allowAbsoluteMovementCommand(cmd) if start_minecraft: # start Minecraft process assigning port dynamically self.mc_process, port = minecraft_py.start() logger.info("Started Minecraft on port %d, overriding client_pool.", port) client_pool = [('127.0.0.1', port)] if client_pool: if not isinstance(client_pool, list): raise ValueError("client_pool must be list of tuples of (IP-address, port)") self.client_pool = MalmoPython.ClientPool() for client in client_pool: self.client_pool.add(MalmoPython.ClientInfo(*client)) # TODO: produce observation space dynamically based on requested features self.video_height = self.mission_spec.getVideoHeight(0) self.video_width = self.mission_spec.getVideoWidth(0) self.video_depth = self.mission_spec.getVideoChannels(0) self.observation_space = spaces.Box(low=0, high=255, shape=(self.video_height, self.video_width, self.video_depth)) # dummy image just for the first observation self.last_image = np.zeros((self.video_height, self.video_width, self.video_depth), dtype=np.uint8) self._create_action_space() # mission recording self.mission_record_spec = MalmoPython.MissionRecordSpec() # record nothing if recordDestination: self.mission_record_spec.setDestination(recordDestination) if recordRewards: self.mission_record_spec.recordRewards() if recordCommands: self.mission_record_spec.recordCommands() if recordMP4: self.mission_record_spec.recordMP4(*recordMP4) if gameMode: if gameMode == "spectator": self.mission_spec.setModeToSpectator() elif gameMode == "creative": self.mission_spec.setModeToCreative() elif gameMode == "survival": logger.warn("Cannot force survival mode, assuming it is the default.") else: assert False, "Unknown game mode: " + gameMode def _create_action_space(self): # collect different actions based on allowed commands continuous_actions = [] discrete_actions = [] multidiscrete_actions = [] multidiscrete_action_ranges = [] if self.add_noop_command: # add NOOP command discrete_actions.append("move 0\nturn 0") chs = self.mission_spec.getListOfCommandHandlers(0) for ch in chs: cmds = self.mission_spec.getAllowedCommands(0, ch) for cmd in cmds: logger.debug(ch + ":" + cmd) if ch == "ContinuousMovement": if cmd in ["move", "strafe", "pitch", "turn"]: if self.continuous_discrete: discrete_actions.append(cmd + " 1") discrete_actions.append(cmd + " -1") else: continuous_actions.append(cmd) elif cmd in ["crouch", "jump", "attack", "use"]: if self.continuous_discrete: discrete_actions.append(cmd + " 1") discrete_actions.append(cmd + " 0") else: multidiscrete_actions.append(cmd) multidiscrete_action_ranges.append(2) else: raise ValueError("Unknown continuous action " + cmd) elif ch == "DiscreteMovement": if cmd in SINGLE_DIRECTION_DISCRETE_MOVEMENTS: discrete_actions.append(cmd + " 1") elif cmd in MULTIPLE_DIRECTION_DISCRETE_MOVEMENTS: discrete_actions.append(cmd + " 1") discrete_actions.append(cmd + " -1") else: raise ValueError(False, "Unknown discrete action " + cmd) elif ch == "AbsoluteMovement": # TODO: support for AbsoluteMovement logger.warn("Absolute movement not supported, ignoring.") elif ch == "Inventory": # TODO: support for Inventory logger.warn("Inventory management not supported, ignoring.") else: logger.warn("Unknown commandhandler " + ch) # turn action lists into action spaces self.action_names = [] self.action_spaces = [] if len(discrete_actions) > 0: self.action_spaces.append(spaces.Discrete(len(discrete_actions))) self.action_names.append(discrete_actions) if len(continuous_actions) > 0: self.action_spaces.append(spaces.Box(-1, 1, (len(continuous_actions),))) self.action_names.append(continuous_actions) if len(multidiscrete_actions) > 0: self.action_spaces.append(spaces.MultiDiscrete(multidiscrete_action_ranges)) self.action_names.append(multidiscrete_actions) # if there is only one action space, don't wrap it in Tuple if len(self.action_spaces) == 1: self.action_space = self.action_spaces[0] else: self.action_space = spaces.Tuple(self.action_spaces) logger.debug(self.action_space) def reset(self): # force new world each time if self.forceWorldReset: self.mission_spec.forceWorldReset() # this seemed to increase probability of success in first try time.sleep(0.1) # Attempt to start a mission for retry in range(self.max_retries + 1): try: if self.client_pool: self.agent_host.startMission(self.mission_spec, self.client_pool, self.mission_record_spec, 0, "experiment_id") else: self.agent_host.startMission(self.mission_spec, self.mission_record_spec) break except RuntimeError as e: if retry == self.max_retries: logger.error("Error starting mission: "+str(e)) raise else: logger.warn("Error starting mission: "+str(e)) logger.info("Sleeping for %d seconds...", self.retry_sleep) time.sleep(self.retry_sleep) # Loop until mission starts: logger.info("Waiting for the mission to start") world_state = self.agent_host.getWorldState() while not world_state.has_mission_begun: time.sleep(0.1) world_state = self.agent_host.getWorldState() for error in world_state.errors: logger.warn(error.text) logger.info("Mission running") return self._get_video_frame(world_state) def _take_action(self, actions): # if there is only one action space, it wasn't wrapped in Tuple if len(self.action_spaces) == 1: actions = [actions] # send appropriate command for different actions for spc, cmds, acts in zip(self.action_spaces, self.action_names, actions): if isinstance(spc, spaces.Discrete): logger.debug(cmds[acts]) self.agent_host.sendCommand(cmds[acts]) elif isinstance(spc, spaces.Box): for cmd, val in zip(cmds, acts): logger.debug(cmd + " " + str(val)) self.agent_host.sendCommand(cmd + " " + str(val)) elif isinstance(spc, spaces.MultiDiscrete): for cmd, val in zip(cmds, acts): logger.debug(cmd + " " + str(val)) self.agent_host.sendCommand(cmd + " " + str(val)) else: logger.warn("Unknown action space for %s, ignoring." % cmds) def _get_world_state(self): # wait till we have got at least one observation or mission has ended while True: time.sleep(self.step_sleep) # wait for 1ms to not consume entire CPU world_state = self.agent_host.peekWorldState() if world_state.number_of_observations_since_last_state > self.skip_steps or not world_state.is_mission_running: break return self.agent_host.getWorldState() def _get_video_frame(self, world_state): # process the video frame if world_state.number_of_video_frames_since_last_state > 0: assert len(world_state.video_frames) == 1 frame = world_state.video_frames[0] image = np.frombuffer(frame.pixels, dtype=np.uint8) image = image.reshape((frame.height, frame.width, frame.channels)) #logger.debug(image) self.last_image = image else: # can happen only when mission ends before we get frame # then just use the last frame, it doesn't matter much anyway image = self.last_image return image def _get_observation(self, world_state): if world_state.number_of_observations_since_last_state > 0: missed = world_state.number_of_observations_since_last_state - len(world_state.observations) - self.skip_steps if missed > 0: logger.warn("Agent missed %d observation(s).", missed) assert len(world_state.observations) == 1 return json.loads(world_state.observations[0].text) else: return None def step(self, action): # take the action only if mission is still running world_state = self.agent_host.peekWorldState() if world_state.is_mission_running: # take action self._take_action(action) # wait for the new state world_state = self._get_world_state() # log errors and control messages for error in world_state.errors: logger.warn(error.text) for msg in world_state.mission_control_messages: logger.debug(msg.text) root = ET.fromstring(msg.text) if root.tag == '{http://ProjectMalmo.microsoft.com}MissionEnded': for el in root.findall('{http://ProjectMalmo.microsoft.com}HumanReadableStatus'): logger.info("Mission ended: %s", el.text) # sum rewards (actually there should be only one) reward = 0 for r in world_state.rewards: reward += r.getValue() # take the last frame from world state image = self._get_video_frame(world_state) # detect terminal state done = not world_state.is_mission_running # other auxiliary data info = {} info['has_mission_begun'] = world_state.has_mission_begun info['is_mission_running'] = world_state.is_mission_running info['number_of_video_frames_since_last_state'] = world_state.number_of_video_frames_since_last_state info['number_of_rewards_since_last_state'] = world_state.number_of_rewards_since_last_state info['number_of_observations_since_last_state'] = world_state.number_of_observations_since_last_state info['mission_control_messages'] = [msg.text for msg in world_state.mission_control_messages] info['observation'] = self._get_observation(world_state) return image, reward, done, info def render(self, mode='human', close=False): if mode == 'rgb_array': return self.last_image elif mode == 'human': try: import pygame except ImportError as e: raise error.DependencyNotInstalled("{}. (HINT: install pygame using `pip install pygame`".format(e)) if close: pygame.quit() else: if self.screen is None: pygame.init() self.screen = pygame.display.set_mode((self.video_width, self.video_height)) img = pygame.surfarray.make_surface(self.last_image.swapaxes(0, 1)) self.screen.blit(img, (0, 0)) pygame.display.update() else: raise error.UnsupportedMode("Unsupported render mode: " + mode) def _close(self): if hasattr(self, 'mc_process') and self.mc_process: minecraft_py.stop(self.mc_process) def _seed(self, seed=None): self.mission_spec.setWorldSeed(str(seed)) return [seed]
17,110
43.21447
131
py
gym-minecraft
gym-minecraft-master/gym_minecraft/envs/__init__.py
from gym_minecraft.envs.minecraft_env import *
47
23
46
py
SpectralANN
SpectralANN-main/MonteCarloTest.py
# -*- coding: utf-8 -*- """ Created on Mon Sep 20 11:22:43 2021 @author: Thibault """ import torch from ACANN import ACANN from torch.utils.data import DataLoader import numpy as np import matplotlib.pyplot as plt import inputParameters as config import pandas as pd from matplotlib.legend_handler import HandlerTuple from torch.utils.data import TensorDataset from scipy import integrate from scipy.interpolate import interp1d import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" #Load test data path = "C:/Users/Thibault/Documents/Universiteit/Honours/Deel 2, interdisciplinair/Code/NN/MonteCarloDataset/" filename = "gluon_bare_64x4_1801Conf_20000bootsamples.dat" # filename = "gluon_bare_80x4_1801Conf_18010bootsamples.dat" x = np.loadtxt(path+filename) #Load input parameters from inputParameters.py nbrWs = config.nbrWs nbrOfPoles = config.nbrOfPoles sizeOfTraining = config.trainingPoints sizeOfValidation = config.validationPoints outputSize = nbrWs + (4 * nbrOfPoles) + 1 pstart = config.pstart pend = config.pend nbrPoints = config.nbrPoints inputSize=nbrPoints print("NN input size {}, output size {} plus {} poles and sigma".format(inputSize,outputSize-4*nbrOfPoles-1,nbrOfPoles)) ps = np.linspace(pstart,pend,nbrPoints) psInterp = np.linspace(-1,1,nbrPoints) ws = np.linspace(0.01,10,nbrWs) # #Load the saved NN model (made in train_ACANN.py) saved = "savedNNmodel.pth" #Note: Make sure the dimensions are the same model = ACANN(inputSize,outputSize,6*[600],drop_p=0.1).double() model.load_state_dict(torch.load(saved)) model.eval() #Parse text file: propLists = [] currentList = [] lastP = 0 for i in range(len(x)): if x[i][0] < lastP-7: currentList.sort(key=lambda x: x[0]) currentList.append([10,0,currentList[-1][2]]) propLists.append(currentList) currentList = [x[i]] lastP = 0 else: currentList.append(x[i]) lastP = x[i][0] #Remove first (has more datapoints): propLists = propLists[1:] print("Loaded propagators") # maxAmount = 50 actualPropagators = [] NNinputs = [] for i in range(len(propLists)): psT = [item[0] for item in propLists[i]] dp2snoscale = [item[1] for item in propLists[i]] dp2sFunc = interp1d(psT,dp2snoscale) dp2sInter = dp2sFunc(ps) dp2s = [item/(dp2sInter[12]) for item in dp2sInter] actualPropagators.append(dp2s) NNinputs.append(dp2s) # if i > maxAmount: # break NNinputs = pd.DataFrame(NNinputs) testloader = DataLoader(TensorDataset((torch.tensor(NNinputs.values).double()).to("cuda:0"))) iterloader = iter(testloader) print("Data Loaded") #Use NN to predict predicList = [] with torch.no_grad(): for i in range(len(testloader)): propData = next(iterloader)[0] prediction = model.forward(propData) predicData = prediction.to("cpu").numpy() predicList.append(predicData) predicData = [] for i in range(len(predicList)): predicData.append(predicList[i][0]) def plotPolesForIndex(i,ax): polemarkers = ["o","^","*"] msizes = [7,9,11] for j in range(nbrOfPoles): #Only plot the poles cj = predicData[i][nbrWs + 4*j + 2] dj = predicData[i][nbrWs + 4*j + 3] ax.plot(cj,dj,polemarkers[j],color="cyan",label="Reconstructed poles",markersize=msizes[j]) ax.grid() ax.set_xlabel("Re(q)") ax.set_ylabel("Im(q)") ax.set_xlim([0.15,0.4]) ax.set_ylim([0.2,0.8]) def plotResiduesForIndex(i,ax): resmarkers = ["o","^","*"] msizes = [7,9,11] for j in range(nbrOfPoles): #Only plot the poles aj = predicData[i][nbrWs + 4*j] bj = predicData[i][nbrWs + 4*j + 1] ax.plot(aj,bj,marker=resmarkers[j],color="lawngreen",label="Reconstructed residues",markersize=msizes[j]) ax.grid() ax.set_xlabel("Re(R)") ax.set_ylabel("Im(R)") ax.set_xlim([-1.5,1.5]) ax.set_ylim([-0.2,1.2]) #Reconstruct propagator from reconstructed spectral function and poles: def poles(p,N,poleList): jsum = 0 for j in range(N): a = poleList[j*4] b = poleList[j*4+1] c = poleList[j*4+2] d = poleList[j*4+3] nom = 2*(a*(c+p)+b*d) denom = c**2 + 2*c*p + d**2 + p**2 jsum += nom/denom return jsum def reconstructProp(index): sigma = predicData[index][-1] wscutoff = min(range(len(ws)), key=lambda i: abs(ws[i]-sigma)) reconstructedPropSigma = [] for p in ps: spectrFunc = [] for i in range(wscutoff,len(ws)): spectrFunc.append(predicData[index][i]/(p**2+ws[i])) integral = integrate.simpson(spectrFunc,x=ws[wscutoff:]) prop = integral + poles(p**2,3, predicData[index][nbrWs:nbrWs+12]) reconstructedPropSigma.append(prop) rescaling = reconstructedPropSigma[12] for i in range(len(ps)): reconstructedPropSigma[i] = reconstructedPropSigma[i]/rescaling return reconstructedPropSigma def constraint15(index): sigma = predicData[index][-1] wscutoff = min(range(len(ws)), key=lambda i: abs(ws[i]-sigma)) res = integrate.simpson(predicData[index][wscutoff:nbrWs],x=ws[wscutoff:]) jsum = 0 for j in range(3): jsum += 2 * predicData[index][nbrWs+j*4] res += jsum if res < 0.5 and res > -0.5: return True return False def derivativeconstraint(index): dp0 = actualPropagators[index][0] dp1 = actualPropagators[index][1] rho0 = predicData[index][0] rho1 = predicData[index][1] derivativeRho = (rho1 - rho0)/(ws[1]-ws[0]) derivativeProp = (dp1 - dp0)/(ps[1]**2-ps[0]**2) # print((ps[1]**2-ps[0]**2),(ps[1]-ps[0])) derivativePoles = 0 for j in range(3): a = predicData[index][nbrWs+j*4] b = predicData[index][nbrWs+j*4+1] c = predicData[index][nbrWs+j*4+2] d = predicData[index][nbrWs+j*4+3] #Alternate but equivalent formula: derivativePoles += (-2*a*c**2 + 2*a*d**2 + 4*b*c*d)/((c**2 + d**2)**2) idealDerivative = -np.pi*derivativeRho - derivativePoles # idealDerivative = -derivativePoles if derivativeProp < idealDerivative - 1 or \ derivativeProp > idealDerivative + 1: return False return True def positivepropconstraint(index): if min(reconstructProp(index)) < 0: return False return True def testConstraints(index): if constraint15(index) and derivativeconstraint(index) and positivepropconstraint(index): return True return False getBestAndWorst = True if getBestAndWorst: #Get the best and worst test cases: maxMAEindex = 0 maxMAE = 0 minMAEindex = 0 minMAE = 100000 constraintsSatisfied1 = 0 constraintsSatisfied2 = 0 constraintsSatisfied3 = 0 constraintsSatisfiedAll = 0 fullSortedList = [] reconProps = [] for i in range(len(actualPropagators)): MAE = 0 #MAE on propagator reconProp = reconstructProp(i) reconProps.append(reconProp) combListProp = zip(actualPropagators[i],reconProp) for orig, recon in combListProp: MAE += abs(orig-recon) if MAE > maxMAE: maxMAE = MAE maxMAEindex = i if MAE < minMAE: minMAE = MAE minMAEindex = i fullSortedList.append((MAE,i)) if positivepropconstraint(i): constraintsSatisfied1 += 1 if derivativeconstraint(i): constraintsSatisfied2 += 1 if constraint15(i): constraintsSatisfied3 += 1 if testConstraints(i): constraintsSatisfiedAll += 1 print(str(constraintsSatisfied1)+"/"+str(len(NNinputs)), "recons satisfied constraint 1") print(str(constraintsSatisfied2)+"/"+str(len(NNinputs)), "recons satisfied constraint 2") print(str(constraintsSatisfied3)+"/"+str(len(NNinputs)), "recons satisfied constraint 3") print(str(constraintsSatisfiedAll)+"/"+str(len(NNinputs)), "recons satisfied all constraints") fullSortedList.sort() # print("Sorted all rhos") print("Min. MAE:",minMAE) print("Max. MAE:",maxMAE) percentile50th = fullSortedList[round(2*len(fullSortedList)/4)][1] print("index of the best, median, and worst:", \ [minMAEindex,percentile50th,maxMAEindex]) fig, ((ax11,ax12,ax13,ax14),(ax31,ax32,ax33,ax34), \ (ax51,ax52,ax53,ax54)) = plt.subplots(3,4) plotPolesForIndex(minMAEindex, ax13) plotPolesForIndex(percentile50th,ax33) plotPolesForIndex(maxMAEindex, ax53) plotResiduesForIndex(minMAEindex, ax14) plotResiduesForIndex(percentile50th,ax34) plotResiduesForIndex(maxMAEindex, ax54) indices = [minMAEindex,percentile50th,maxMAEindex] propaxes = [ax11,ax31,ax51] ps = np.linspace(pstart,pend,nbrPoints) for i in range(len(propaxes)): propaxes[i].plot(ps,actualPropagators[indices[i]],label="Propagator") propaxes[i].plot(ps,reconstructProp(indices[i]),"--",label="Reconstructed propagator",color="red") propaxes[i].set_xlabel("p") propaxes[i].set_ylabel("D(p²)") rhoaxes = [ax12,ax32,ax52] for i in range(len(rhoaxes)): #rhoaxes[i].plot(ws,predicData[indices[i]][:nbrWs],"--",label="Reconstructed spectral function",color="red") sigma = predicData[indices[i]][-1] rhoaxes[i].axvline(x=sigma,ymin=-10,ymax=10,color='orangered',linestyle='dotted',label='σ') rhoaxes[i].plot(ws,predicData[indices[i]][:nbrWs],"--",label="Reconstructed spectral function",color="red") sigma = predicData[indices[i]][-1] rhoaxes[i].set_xlabel("ω²") rhoaxes[i].set_ylabel("ρ(ω)") handles, labels = ax11.get_legend_handles_labels() ax11.legend(handles,labels,loc="upper center",bbox_to_anchor=(0.5,1.5)) # handles, labels = ax12.get_legend_handles_labels() # ax12.legend(handles,labels,loc="upper center",bbox_to_anchor=(0.5,1.5)) handles,labels = ax12.get_legend_handles_labels() reconTuple = (handles[1],handles[0]) labels = ["Reconstructed spectral function, σ"] ax12.legend((reconTuple,),labels, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=2,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.5),handlelength=4) handles,labels = ax13.get_legend_handles_labels() reconTuple = (handles[0],handles[1],handles[2]) labels = ["Reconstructed poles"] ax13.legend((reconTuple,),labels,scatterpoints=3, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=3,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.5),handlelength=4) handles,labels = ax14.get_legend_handles_labels() reconTuple = (handles[0],handles[1],handles[2]) labels = ["Reconstructed residues"] ax14.legend((reconTuple,),labels,scatterpoints=3, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=3,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.5),handlelength=4)
11,372
29.328
120
py
SpectralANN
SpectralANN-main/generatePropagators.py
# -*- coding: utf-8 -*- """ Created on Mon Jul 5 12:18:08 2021 @author: Thibault """ import numpy as np from scipy import integrate import itertools import pandas as pd import os from functools import lru_cache import time import random np.seterr('raise') cacheSize = 2048 random.seed(64) @lru_cache(maxsize=cacheSize) def rho1(w2,Z,m2,lam2,N1,ABCs): gamma = 13/22 # w2 = w ** 2 #Calculate the ksum ksum = 0 for k in range(N1): ksum += (ABCs[k][0]*w2) / (ABCs[k][1]*w2 + ((ABCs[k][2] - w2) ** 2)) #Multiply the ksum with -Z/ln(...) ln = np.log((w2 + m2) / lam2) ** (1 + gamma) mult = -Z / ln return mult * ksum #Approximates the pdf of a normal distribution (exact but cuts off at z=15) #Avoids huge exponents by cutting off the distribution after zlim def custompdf(w,mean,std): zlim = 7 z = (w-mean)/std if z < zlim and z > -zlim: return np.exp(-(w-mean)**2/(std)) else: return 0 #w = float #N2,N3 = ints #gabl = [[gam1,alfa1,beta1],[gam2,alfa2,beta2]...[gamN2,alfaN2,betaN2]] list of list of floats @lru_cache(maxsize=cacheSize) def rho2(w2,N2,gabl,N3,gabi): # w2 = w ** 2 lsum = 0 #Sum of normal distributions for l in range(N2): lsum += gabl[l][0] * custompdf(w2,gabl[l][1],gabl[l][2]) isum = 0 #Sum of derivatives of normal distributions for i in range(N3): isum += gabi[i][0] * w2 * custompdf(w2,gabi[i][1],gabi[i][2]) return lsum + isum @lru_cache(maxsize=cacheSize) def rho(w,Z,m2,lam2,N1,ABCs,N2,gabl,N3,gabi): return rho1(w,Z,m2,lam2,N1,ABCs) + rho2(w,N2,gabl,N3,gabi) #Correct form under the integral def rhoint(w,Z,m2,lam2,N1,ABCs,N2,gabl,N3,gabi,p2): return rho(w,Z,m2,lam2,N1,ABCs,N2,gabl,N3,gabi)/(w + p2) @lru_cache(maxsize=cacheSize) def poles(p2,N,abcds): jsum = 0 #Using alternate but equivalent form of pole sum (without i) for j in range(N): # nom = 2 * ( ajs[j] * (cjs[j] + p2) + bjs[j] * djs[j]) nom = 2 * ( abcds[j][0] * (abcds[j][2] + p2) + abcds[j][1] * abcds[j][3]) # denom=(cjs[j] ** 2) + (2 * cjs[j] * p2) # + (djs[j] ** 2) + (p2 ** 2) denom = (abcds[j][2] ** 2) + (2 * abcds[j][2] * p2) + \ (abcds[j][3] ** 2) + (p2 ** 2) jsum += nom/denom return jsum #Calculates the propagator out of the given parameters for the spectral # density function and complex conjugate poles def calcPropagator(Z,m2,lam2,N,abcds,N1,ABCs,N2,gabl,N3,gabi,sigma,p): try: #Integrate over w^2 p2 = p**2 res = integrate.quad(rhoint,0.01+sigma,10,args=(Z,m2,lam2,N1,ABCs,N2,gabl,N3,gabi,p2))[0] \ + poles(p2,N,abcds) except: print(Z,m2,lam2,ABCs,gabl,gabi,p2) raise RuntimeError("Error when calculating integral for propagator") return res #Returns true if the constraint is roughly satisfied (+-0.5) def constraint15(Z,m2,lam2,N1,ABCs,N2,gabl,N3,gabi,abcds): res = integrate.quad(rho,0.01+sigma,10,args=(Z,m2,lam2,N1,ABCs,N2,gabl,N3,gabi))[0] jsum = 0 for j in range(N): jsum += 2 * abcds[j][0] res += jsum if res < 0.5 and res > -0.5: return True return False #Returns true if the constraint is satisfied @lru_cache(maxsize=cacheSize) def derivativeConstraint(dp0,dp1,rho0,rho1,abcds,N,sig): # if sig == 0: derivativeRho = (rho1 - rho0)/(ws[1]-ws[0]) # else: # derivativeRho = 0 derivativeProp = (dp1 - dp0)/(ps[1]**2-ps[0]**2) derivativePoles = 0 for j in range(N): a = abcds[j][0] b = abcds[j][1] c = abcds[j][2] d = abcds[j][3] #Alternate but equivalent formula: derivativePoles += (-2*a*c**2 + 2*a*d**2 + 4*b*c*d)/((c**2 + d**2)**2) idealDerivative = -np.pi*derivativeRho - derivativePoles if derivativeProp < idealDerivative - 1 or \ derivativeProp > idealDerivative + 1: return False return True if __name__ == "__main__": path = "C:/Users/Thibault/Documents/Universiteit/Honours/Deel 2, interdisciplinair/Code/NN/Datasets/" #Desired training data size: desiredDataSize = 10000 pstart = 0 pend = 8.25 #8.25 -> p = 1 is exactly in ps nbrPoints = 100 ps = np.linspace(pstart,pend,nbrPoints) nbrWs = 200 #ws = w**2s: assumes the ws are already squared as they always appear in squared form ws = np.linspace(0.01,10,nbrWs) """ ####################################### Input Parameters: ####################################### """ sigmas = np.linspace(0,1,4) Zs = np.linspace(1,10,1) m2s = np.linspace(2,5,4) lam2s = np.linspace(1,4,4) Ns = [i for i in range(1,4)] N1s = [i for i in range(1,4)] N2s = [i for i in range(1,4)] N3s = [i for i in range(1,4)] def checkSingularity(w2,B,C): if B*w2 + C**2 -2*C*w2 + w2**2 <= 10**(-7): return True else: return False T = list(itertools.product(*[[-0.5,-0.16,0.16,0.5],[-5,-1.6,1.6,5],[-5,-1.6,1.6,5]])) noSingularitiesT = [] for ABC in T: singularityFound = False for w in ws: if checkSingularity(w,ABC[1],ABC[2]): singularityFound = True if not singularityFound: noSingularitiesT.append(ABC) # print("Kept", ABC[1],ABC[2]) # else: # print("Removed B={},C={} due to possible singularity".format(ABC[1],ABC[2])) ABCNs = [] for N1 in N1s: ABCs = list(itertools.combinations_with_replacement(noSingularitiesT,N1)) sampled_ABCs = [] for ABC in ABCs: if random.random() < 0.0015: sampled_ABCs.append(ABC) ABCNs.append(sampled_ABCs) #The first parameters in Eq. 5: T = list(itertools.product(*[[-0.5,-0.16,0.16,0.5],[1,2.3,3.6,5],[1,2.3,3.6,5]])) gablNs = [] for N2 in N2s: gabls = list(itertools.combinations_with_replacement(T,N2)) sampled_gabls = [] for gab in gabls: if random.random() < 0.0005: sampled_gabls.append(gab) gablNs.append(sampled_gabls) #The second parameters in Eq. 5: T = list(itertools.product(*[[-0.5,-0.16,0.16,0.5],[1,2.3,3.6,5],[1,2.3,3.6,5]])) gabiNs = [] for N3 in N3s: gabis = list(itertools.combinations_with_replacement(T,N3)) sampled_gabis = [] for gab in gabis: if random.random() < 0.0009: sampled_gabis.append(gab) gabiNs.append(sampled_gabis) #Complex poles: T = list(itertools.product(*[[-1,-0.33,0,0.33,1],[0,0.33,0.66,1], \ [0.2,0.25,0.3,0.35],[0.3,0.45,0.6,0.75]])) abcdNs = [] for N in Ns: abcds = list(itertools.combinations_with_replacement(T,N)) sampled_abcds = [] for abcd in abcds: # if random.random() < 0.000015: if random.random() < 0.000007: sampled_abcds.append(abcd) abcdNs.append(sampled_abcds) #Iterator over all possible combinations of parameters names = ["sig","Z","m2","lam2","abcd","ABC","gabl","gabi"] sub = [sigmas,Zs,m2s,lam2s,abcdNs[2],ABCNs[2],gablNs[2],gabiNs[2]] totalSize = 1 for i in range(len(sub)): totalSize = totalSize * len(sub[i]) print(names[i],len(sub[i])) print("\nMax number of data points:",totalSize) iterator = itertools.product(*sub) #Write data to these files (first deletes old ones) propTrain_csv = path+'DTrainingRaw.csv' if os.path.exists(propTrain_csv): os.remove(propTrain_csv) propValid_csv = path+'DValidationRaw.csv' if os.path.exists(propValid_csv): os.remove(propValid_csv) propTest_csv = path+'DTestRaw.csv' if os.path.exists(propTest_csv): os.remove(propTest_csv) rhoTrain_csv = path+'rhoTraining.csv' if os.path.exists(rhoTrain_csv): os.remove(rhoTrain_csv) rhoValid_csv = path+'rhoValidation.csv' if os.path.exists(rhoValid_csv): os.remove(rhoValid_csv) rhoTest_csv = path+'rhoTest.csv' if os.path.exists(rhoTest_csv): os.remove(rhoTest_csv) params_csv = path+'params.csv' if os.path.exists(params_csv): os.remove(params_csv) print("Generating data...") start = time.time() counter = 0 counterPos = 0 counterNeg = 0 counterAccepted = 0 propTempList = [] rhoTempList = [] paramTempList = [] counterConstraint15True = 0 counterConstraint15False = 0 print("Desired training data size:",desiredDataSize) print("Percentage of training set selected:",round(100*desiredDataSize/totalSize,4),"%") # Print iterations progress def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) printEnd - Optional : end character (e.g. "\r", "\r\n") (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd) # Print New Line on Complete if iteration == total: print() #Iterate over parameters (too large to fit entirely in memory) printProgressBar(0, desiredDataSize, prefix = 'Progress:', suffix = 'Complete', length = 50) """ ####################################### Calculate spectral function and propagator: ####################################### """ for item in iterator: #Random sampling over the resulting parameter combinations if random.random() <= 2.15*800*desiredDataSize/totalSize: # ^ multiplicity factor to account for unlawful combinations sigma = item[0] Z = item[1] m2 = item[2] lam2 = item[3] #Possible singularity if m2<lam2 -> skip this iteration if m2 < lam2: continue abcds = item[4] N = len(abcds) ABCs = item[5] N1 = len(ABCs) gabls = item[6] N2 = len(gabls) gabis = item[7] N3 = len(gabis) #Check constraint: if not constraint15(Z,m2,lam2,N1,ABCs,N2,gabls,N3,gabis,abcds): counterConstraint15False += 1 continue counterConstraint15True += 1 dps = [] negativeProp = False rescaling = calcPropagator(Z,m2,lam2,N,abcds,N1,ABCs,N2,gabls,N3,gabis,sigma,ps[12]) * 1 for i in range(len(ps)): prop = calcPropagator(Z,m2,lam2,N,abcds,N1,ABCs,N2,gabls,N3,gabis,sigma,ps[i]) / rescaling dps.append(prop) #Check for negative prop if prop < 0: negativeProp = True break #Check derivative constraint if i == 1: rhos0 = rho(ws[0],Z,m2,lam2,N1,ABCs,N2,gabls,N3,gabis)/rescaling rhos1 = rho(ws[1],Z,m2,lam2,N1,ABCs,N2,gabls,N3,gabis)/rescaling dp0 = dps[0] dp1 = dps[1] if not derivativeConstraint(dp0,dp1,rhos0,rhos1,abcds,N,sigma): negativeProp = True break #Skip if propagator is negative anywhere or derivative constraint is not satisfied if negativeProp: counterNeg += 1 continue else: counterPos += 1 #Calculate density function (already in cache so should be fast) rhos = [] for w in ws: rhos.append(rho(w,Z,m2,lam2,N1,ABCs,N2,gabls,N3,gabis)/rescaling) #Add poles to the list: (1 value at a time, add zeroes if not enough poles) for polecouple in abcds: for i in range(len(polecouple)): #rescale residues, not poles if i < 2: rhos.append(polecouple[i]/rescaling) else: rhos.append(polecouple[i]) nbrOfMissingPoles = 3 - len(abcds) missingPoles = 4 * nbrOfMissingPoles * [0] for missingPole in missingPoles: rhos.append(missingPole) #Add sigma at end of spectral function rhos.append(sigma) propTempList.append(dps) rhoTempList.append(rhos) paramTempList.append([sigma,Z,m2,lam2,abcds,ABCs,gabls,gabis]) counter += 1 #Write to csv in batches batchSize = 400 if counter % batchSize == 0: #3 out of every 4 points to the training set #1 out of every 4 points alternatively to validation and testing #75% train, 12.5% validation, 12.5% testing propTraining = np.array(propTempList)[np.mod(np.arange(batchSize),4) != 0] propValidation = propTempList[::8] propTest = propTempList[4::8] rhoTraining = np.array(rhoTempList)[np.mod(np.arange(batchSize),4) != 0] rhoValidation = rhoTempList[::8] rhoTest = rhoTempList[4::8] propTraindf = pd.DataFrame(propTraining) propTraindf.to_csv(propTrain_csv,index=False,header=False,mode='a') propValiddf = pd.DataFrame(propValidation) propValiddf.to_csv(propValid_csv,index=False,header=False,mode='a') propTestdf = pd.DataFrame(propTest) propTestdf.to_csv(propTest_csv,index=False,header=False,mode='a') rhoTraindf = pd.DataFrame(rhoTraining) rhoTraindf.to_csv(rhoTrain_csv,index=False,header=False,mode='a') rhoValiddf = pd.DataFrame(rhoValidation) rhoValiddf.to_csv(rhoValid_csv,index=False,header=False,mode='a') rhoTestdf = pd.DataFrame(rhoTest) rhoTestdf.to_csv(rhoTest_csv,index=False,header=False,mode='a') paramsdf = pd.DataFrame(paramTempList) paramsdf.to_csv(params_csv,index=False,header=False,mode='a') #Reset templists propTempList = [] rhoTempList = [] paramTempList = [] pointsPerSecond = round(batchSize/(time.time()-start),2) minsRemaining = round((desiredDataSize - counter*3/4) / (pointsPerSecond*60),2) printProgressBar(counter*3/4, desiredDataSize, prefix = 'Progress:', \ suffix = 'Complete,{} mins remaining, {} per sec'.format(minsRemaining,pointsPerSecond), length = 30) #Stop when desired data size is reached if counter*3/4 >= desiredDataSize: print("Reached desired data size") break start = time.time() print("Constraint15 true:", counterConstraint15True) print("Constraint15 false:", counterConstraint15False) print("Counter pos:", counterPos) print("Counter neg:", counterNeg) nbrOfTrainingPoints = round(counter*3/4 if counter % 400 == 0 else (counter - counter % 400)*3/4) nbrOfValidationPoints = round(counter/8 if counter % 400 == 0 else (counter - counter % 400)/8) print("\nData generation succesfull") print("{} training points".format(nbrOfTrainingPoints)) print("{} validation points".format(nbrOfValidationPoints)) print("{} testing points".format(nbrOfValidationPoints)) nbrOfPoles = 3 #Write input parameters to file: params = open("inputParameters.py","w") params.write("nbrOfPoles = {}\n".format(nbrOfPoles)) params.write("trainingPoints = {}\n".format(nbrOfTrainingPoints)) params.write("validationPoints = {}\n".format(nbrOfValidationPoints)) params.write("pstart = {}\n".format(pstart)) params.write("pend = {}\n".format(pend)) params.write("nbrPoints = {}\n".format(nbrPoints)) params.write("nbrWs = {}\n".format(nbrWs)) params.close()
17,733
33.840864
134
py
SpectralANN
SpectralANN-main/train_ACANN.py
from ACANN import ACANN from Database import Database from torch.nn.modules.loss import KLDivLoss,L1Loss,MSELoss from torch.optim import Adam,Rprop,Adamax, RMSprop,SGD,LBFGS,AdamW from torch.utils.data import DataLoader import torch import inputParameters as config import matplotlib.pyplot as plt import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" #Load input parameters from inputParameters.py inputSize = config.nbrPoints nbrWs = config.nbrWs nbrOfPoles = config.nbrOfPoles sizeOfTraining = config.trainingPoints sizeOfValidation = config.validationPoints outputSize = nbrWs + (4 * nbrOfPoles) + 1 print("outputsize:",outputSize) print("Input parameters loaded") print("Starting ACANN") # Create the network MAEsplot = [] # layers = [2,4,6,8,10] # neuronsPerLayer = [200,400,600,800] layers = [6] neuronsPerLayer = [600] for layer in layers: for neuronNbr in neuronsPerLayer: print(layer,"layers",neuronNbr,"neurons per layer") model = ACANN(inputSize,outputSize,layer*[neuronNbr],drop_p=0.1).double() epochs = 100 batch_size_train = 100 # Import the data path = "C:/Users/Thibault/Documents/Universiteit/Honours/Deel 2, interdisciplinair/Code/NN/Datasets/" train_data = Database(csv_target= path + "rhoTraining.csv",csv_input= path + "DTraining.csv",nb_data=epochs*batch_size_train).get_loader() validation_data=Database(csv_target= path + "rhoValidation.csv",csv_input= path + "DValidation.csv",nb_data=sizeOfValidation).get_loader() trainloader = DataLoader(train_data,batch_size=batch_size_train,shuffle=True) validationloader = DataLoader(validation_data,batch_size=batch_size_train,shuffle=True) # Define a function for computing the validation score def validation_score(nn_model): #Turn evaluation mode on (turns off dropout and batch normalization): nn_model.eval() #Loss function val_error=MSELoss() #Turn off gradient computation with torch.no_grad(): G_val,A_val=next(iter(validationloader)) prediction=nn_model.forward(G_val) #Prediction and A_val are tensors with lists of size batch_size #The lists contain (outputSize) data values score=val_error(prediction,A_val) #Turn training mode back on nn_model.train() return score.item() #Define the loss error = MSELoss() #Define the optimizer optimizer = Adam(model.parameters()) # Training parameters step=-1 print_every = epochs # Training best_valscore = 10000 MAEs = [] stop = False for e in range(epochs): if not stop: #Turn training mode on model.train() # Load a minibatch for D,rho in trainloader: step+=1 # restart the optimizer optimizer.zero_grad() # compute the loss prediction = model.forward(D) # print(prediction) loss = error(prediction,rho) # Compute the gradient and optimize loss.backward() optimizer.step() # Write the result if step % print_every == 0: step=0 print("Epoch {}/{} : ".format(e+1,epochs), "Training MAE = {} -".format(loss.item()), "Validation MAE = {}".format(validation_score(model))) MAEs.append(validation_score(model)) print("Saved model with validation MAE of", validation_score(model)) torch.save(model.state_dict(),'savedNNmodel.pth') plt.figure() plt.plot(list(range(1,len(MAEs)+1)),MAEs) plt.title("Validation loss") plt.xlabel("Epochs") plt.ylabel("MSE") MAEsplot.append(MAEs[-1]) print(MAEsplot)
4,320
35.008333
146
py
SpectralANN
SpectralANN-main/inputParameters.py
nbrOfPoles = 3 trainingPoints = 10200 validationPoints = 1700 pstart = 0 pend = 8.25 nbrPoints = 100 nbrWs = 200
113
13.25
23
py
SpectralANN
SpectralANN-main/robustnessCheck.py
# -*- coding: utf-8 -*- """ Created on Thu Sep 2 17:54:33 2021 @author: Thibault """ #1: add noise 20 times to same propagator #2: Convert to correct input #3: Input to NN #4: Calc average and stddev of spectral functions indices = [227, 1552, 112, 1243, 606] nbrOfSamples = 100 noiseSize = 1e-2 from Database import Database from torch.utils.data import DataLoader import inputParameters as config import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.legend_handler import HandlerTuple np.random.seed(64) #Load input parameters from inputParameters.py sizeOfTraining = config.trainingPoints sizeOfValidation = config.validationPoints pstart = config.pstart pend = config.pend nbrPoints = config.nbrPoints path = "C:/Users/Thibault/Documents/Universiteit/\ Honours/Deel 2, interdisciplinair/Code/NN/Datasets/" train_data = Database(csv_target= path + "rhoTraining.csv",\ csv_input= path + "DTrainingRaw.csv",nb_data=sizeOfTraining).get_loader() trainloader = DataLoader(train_data,batch_size=sizeOfTraining) print("Training data loaded") test_data = Database(csv_target= path + "rhoTest.csv",\ csv_input= path + "DTestRaw.csv",nb_data=sizeOfValidation).get_loader() testloader = DataLoader(test_data,batch_size=sizeOfValidation) print("Test data loaded") #get propagator data: alldatatensors = list(trainloader) alldata = alldatatensors[0][0].to("cpu").numpy() alldatatensorsTest = list(testloader) alldataTest = alldatatensorsTest[0][0].to("cpu").numpy() print(len(alldata),"training points") path = "C:/Users/Thibault/Documents/Universiteit/Honours/Deel 2, interdisciplinair/Code/NN/Datasets/" """ ######################## Test robustness of NN: ######################## """ import torch from ACANN import ACANN from Database import Database from torch.utils.data import DataLoader import numpy as np import inputParameters as config #Load input parameters from inputParameters.py nbrWs = config.nbrWs nbrOfPoles = config.nbrOfPoles sizeOfTraining = config.trainingPoints sizeOfValidation = config.validationPoints outputSize = nbrWs + (4 * nbrOfPoles) + 1 pstart = config.pstart pend = config.pend nbrPoints = config.nbrPoints inputSize = nbrPoints print("NN input size {}, output size {} plus {} poles".format(inputSize,outputSize-4*nbrOfPoles,nbrOfPoles)) #Load the saved NN model (made in train_ACANN.py) # saved = "savedNNmodel.pth" # #Note: Make sure the dimensions are the same # model = ACANN(inputSize,outputSize,6*[800],drop_p=0.05).double() saved = "savedNNmodel.pth" #Note: Make sure the dimensions are the same model = ACANN(inputSize,outputSize,6*[600],drop_p=0.1).double() model.load_state_dict(torch.load(saved)) model.eval() #Load test data path = "C:/Users/Thibault/Documents/Universiteit/Honours/Deel 2, interdisciplinair/Code/NN/Datasets/" test_data = Database(csv_target= path + "rhoTest.csv", \ csv_input= path + "DTestRaw.csv",nb_data=sizeOfValidation).get_loader() testloader = DataLoader(test_data,batch_size=sizeOfValidation) testloadList = list(testloader) rhovaluesList = testloadList[0][1].to("cpu").numpy() print(len(rhovaluesList),"testing points") prop_data = pd.read_csv(path+'DTestRaw.csv',header=None,nrows=sizeOfValidation) propList = prop_data.values.tolist() print(len(propList),"propagators") params_data = pd.read_csv(path+'params.csv',header=None,nrows=sizeOfTraining+2*sizeOfValidation) paramsList = params_data.values.tolist() print("Data Loaded") #Evaluate output: ps = np.linspace(pstart,pend,nbrPoints) ws = np.linspace(0.01,10,nbrWs) def getMeanAndStdReconstruction(index): noisyPropsPerIndex = [] for j in range(nbrOfSamples): noise = np.random.normal(1,noiseSize,nbrPoints) noisyPropsPerIndex.append(alldataTest[index] * noise) NNinputsTensor = [] for j in range(nbrOfSamples): NNinputsTensor.append(noisyPropsPerIndex[j]) NNinputsTensor = torch.DoubleTensor(np.array(NNinputsTensor)).cuda() #Use NN to predict with torch.no_grad(): prediction = model.forward(NNinputsTensor) predicData = prediction.to("cpu").numpy() filteredPredicData = [] for j in range(nbrOfSamples): if max(predicData[j][:nbrWs]) < 10: filteredPredicData.append(predicData[j]) poles = [] for j in range(len(filteredPredicData)): poles.append(filteredPredicData[j][nbrWs:]) means = np.mean(filteredPredicData,axis=0)[:nbrWs] stddevs = 5*np.std(filteredPredicData,axis=0)[:nbrWs] props = [] for j in range(len(filteredPredicData)): props.append(reconstructProp(filteredPredicData[j])) propmeans = np.mean(props,axis=0) propstddevs = 5*np.std(props,axis=0) return means, stddevs, poles, propmeans, propstddevs def poles(p,N,poleList): jsum = 0 for j in range(N): a = poleList[j*4] b = poleList[j*4+1] c = poleList[j*4+2] d = poleList[j*4+3] nom = 2*(a*(c+p)+b*d) denom = c**2 + 2*c*p + d**2 + p**2 jsum += nom/denom return jsum def reconstructProp(reconstruction): from scipy import integrate sigma = reconstruction[-1] #If negative, -> 0 #If more than 1 -> 1 wscutoff = min(range(len(ws)), key=lambda i: abs(ws[i]-sigma)) reconstructedPropSigma = [] for p in ps: spectrFunc = [] for i in range(wscutoff,len(ws)): spectrFunc.append(reconstruction[i]/(p**2+ws[i])) integral = integrate.simpson(spectrFunc,x=ws[wscutoff:]) prop = integral + poles(p**2,3, reconstruction[nbrWs:nbrWs+12]) reconstructedPropSigma.append(prop) rescaling = reconstructedPropSigma[12] for i in range(len(ps)): reconstructedPropSigma[i] = reconstructedPropSigma[i]/rescaling return reconstructedPropSigma fig, ((ax11,ax12,ax13,ax14),(ax21,ax22,ax23,ax24),(ax31,ax32,ax33,ax34), \ (ax41,ax42,ax43,ax44),(ax51,ax52,ax53,ax54)) = plt.subplots(5,4) propaxes = [ax11,ax21,ax31,ax41,ax51] spectralaxes = [ax12,ax22,ax32,ax42,ax52] polesaxes = [ax13,ax23,ax33,ax43,ax53] resaxes = [ax14,ax24,ax34,ax44,ax54] for i in range(len(indices)): means,stddevs,polesAndSigma,propmeans,propstddevs = getMeanAndStdReconstruction(indices[i]) propaxes[i].plot(ps,propList[indices[i]],label="Propagator") propaxes[i].plot(ps,propmeans,"--",label="Mean reconstruction",color="red") propaxes[i].fill_between(ps,propmeans-propstddevs,propmeans+propstddevs,alpha=0.2, facecolor="red", label='5*(Standard deviation)') propaxes[i].set_xlabel("p") propaxes[i].set_ylabel("D(p²)") # propaxes[i].set_xscale('log') #Plot spectral function: spectralaxes[i].set_xlabel("ω²") spectralaxes[i].set_ylabel("ρ(ω)") meansig = np.mean(polesAndSigma,axis=0)[-1] stdsig = np.std(polesAndSigma,axis=0)[-1] spectralaxes[i].axvline(x=meansig,ymin=-10,ymax=10,color='orangered',linestyle='dotted') spectralaxes[i].axvspan(meansig-5*stdsig,meansig+5*stdsig,alpha=0.2, facecolor="red") sigma = rhovaluesList[indices[i]][-1] spectralaxes[i].axvline(x=sigma,ymin=-10,ymax=10,color='dodgerblue',label='σ',linestyle='dotted') spectralaxes[i].plot(ws,rhovaluesList[indices[i]][:nbrWs],label="Spectral function, σ") spectralaxes[i].plot(ws,means,"--",label="Mean reconstruction",color="red") spectralaxes[i].fill_between(ws,means-stddevs,means+stddevs,alpha=0.2, facecolor="red", label='5*(Standard deviation)') #Plot poles: aksA,bksA,cksA,dksA = [], [], [], [] for j in range(len(polesAndSigma)): aks,bks,cks,dks = [], [], [], [] for k in range(3): aks.append(polesAndSigma[j][4*k]) bks.append(polesAndSigma[j][4*k + 1]) cks.append(polesAndSigma[j][4*k + 2]) dks.append(polesAndSigma[j][4*k + 3]) aksA.append(aks) bksA.append(bks) cksA.append(cks) dksA.append(dks) aM = np.mean(aksA,axis=0) bM = np.mean(bksA,axis=0) cM = np.mean(cksA,axis=0) dM = np.mean(dksA,axis=0) resmarkers = ["o","^","*"] msizes = [7,9,11] # from scipy.spatial import ConvexHull for j in range(3): #Plot all reconstructions: for k in range(len(aksA)): resaxes[i].plot(aksA[k][j],bksA[k][j],marker=resmarkers[j],markersize=msizes[j],color="red",alpha=0.1,label="All reconstructions") for k in range(len(aksA)): polesaxes[i].plot(cksA[k][j],dksA[k][j],marker=resmarkers[j],markersize=msizes[j],color="red",alpha=0.1,label="All reconstructions") for j in range(3): ajOrig = rhovaluesList[indices[i]][nbrWs + 4*j] bjOrig = rhovaluesList[indices[i]][nbrWs + 4*j + 1] resaxes[i].plot(ajOrig,bjOrig,marker=resmarkers[j],color="green",label="Original residues",markersize=msizes[j]) resaxes[i].plot(aM[j],bM[j],marker=resmarkers[j],color="lawngreen",label="Mean reconstruction",markersize=msizes[j]) #Plot convex hull: # aHull = [elem[j] for elem in aksA] # bHull = [elem[j] for elem in bksA] # points = np.asarray([list(elem) for elem in zip(aHull,bHull)]) # hull = ConvexHull(points) # resaxes[i].fill(points[hull.vertices,0],points[hull.vertices,1],'red',alpha=0.4) cjOrig = rhovaluesList[indices[i]][nbrWs + 4*j + 2] djOrig = rhovaluesList[indices[i]][nbrWs + 4*j + 3] polesaxes[i].plot(cjOrig,djOrig,resmarkers[j],color="blue",label="Original poles",markersize=msizes[j]) polesaxes[i].plot(cM[j],dM[j],resmarkers[j],color="cyan",label="Mean reconstruction",markersize=msizes[j]) #Plot convex hull: # cHull = [elem[j] for elem in cksA] # dHull = [elem[j] for elem in dksA] # points = np.asarray([list(elem) for elem in zip(cHull,dHull)]) # hull = ConvexHull(points) # polesaxes[i].fill(points[hull.vertices,0],points[hull.vertices,1],'red',alpha=0.4) resaxes[i].set_xlim([-1.5,1.5]) resaxes[i].set_ylim([-0.2,1.2]) resaxes[i].grid() resaxes[i].set_xlabel("Re(R)") resaxes[i].set_ylabel("Im(R)") polesaxes[i].set_xlim([0.15,0.4]) polesaxes[i].set_ylim([0.2,0.8]) polesaxes[i].grid() polesaxes[i].set_xlabel("Re(q)") polesaxes[i].set_ylabel("Im(q)") print("Mean, stddev of sigma:", np.mean(polesAndSigma,axis=0)[-1],np.std(polesAndSigma,axis=0)[-1]) handles, labels = ax11.get_legend_handles_labels() ax11.legend(handles,labels,loc="upper center",bbox_to_anchor=(0.5,1.7)) handles, labels = ax12.get_legend_handles_labels() ax12.legend(handles,labels,loc="upper center",bbox_to_anchor=(0.5,1.7)) handles,labels = ax12.get_legend_handles_labels() origTuple = (handles[1],handles[0]) reconTuple = (handles[2]) std = (handles[3]) labels = ["Spectral function, σ","Mean reconstruction", "5*(Standard deviation)"] ax12.legend((origTuple,reconTuple,std),labels, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=2,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.7),handlelength=4) handles,labels = ax13.get_legend_handles_labels() # print(handles) origTuple = (handles[-6],handles[-4],handles[-2]) reconTuple = (handles[-5],handles[-3],handles[-1]) allRecon = (handles[0],handles[int(round(len(handles)/2))],handles[-7]) labels = ["Original poles", "Mean reconstruction","All reconstructions"] ax13.legend((origTuple,reconTuple,allRecon),labels,scatterpoints=3, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=3,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.7),handlelength=4) handles,labels = ax14.get_legend_handles_labels() origTuple = (handles[-6],handles[-4],handles[-2]) reconTuple = (handles[-5],handles[-3],handles[-1]) allRecon = (handles[0],handles[int(round(len(handles)/2))],handles[-7]) labels = ["Original residues", "Mean reconstruction","All reconstructions"] ax14.legend((origTuple,reconTuple,allRecon),labels,scatterpoints=3, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=3,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.7),handlelength=4) # avgRhos.append(avgForIndex) # print(means) # print(NNinputs[0]) # plt.figure() # # plt.plot(ws,predicData[0][:nbrWs],label="Reconstructed spectral function") # plt.plot(ws,avgForIndex,label="Average reconstruction") # plt.plot(ws,rhovaluesList[314][:nbrWs],label="Original spectral function") # plt.legend()
12,731
33.597826
144
py
SpectralANN
SpectralANN-main/Database.py
from torch.utils.data import TensorDataset import pandas as pd import torch device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("Using",device) class Database(): def __init__(self, csv_target, csv_input, transform=None,nb_data=25000): """ Build the data set structure Args: csv_target (string): path to the target data (A(omega)) csv_input (string) : path to the input data (G(tau)) transform (callable, optional): Optional transform to be applied on a sample (eg: add noise). """ self.input_data = pd.read_csv(csv_input,header=None,nrows=nb_data) # print(self.input_data) self.target_data = pd.read_csv(csv_target,header=None,nrows=nb_data) self.transform = transform def get_loader(self): G=torch.tensor(self.input_data.values).double() # normalization_factor=34.1 # A=torch.tensor(self.target_data.values).double()/normalization_factor A=torch.tensor(self.target_data.values).double() return TensorDataset(G.to(device),A.to(device))
1,130
38
79
py
SpectralANN
SpectralANN-main/test_ACANN.py
# -*- coding: utf-8 -*- """ Created on Sun Jun 27 10:53:43 2021 @author: Thibault """ import torch from ACANN import ACANN from Database import Database from torch.utils.data import DataLoader import numpy as np import matplotlib.pyplot as plt import inputParameters as config import pandas as pd from matplotlib.legend_handler import HandlerTuple from scipy import integrate import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" #Load input parameters from inputParameters.py nbrWs = config.nbrWs nbrOfPoles = config.nbrOfPoles sizeOfTraining = config.trainingPoints sizeOfValidation = config.validationPoints outputSize = nbrWs + (4 * nbrOfPoles) + 1 pstart = config.pstart pend = config.pend nbrPoints = config.nbrPoints inputSize = nbrPoints print("NN input size {}, output size {} plus {} poles and sigma".format(inputSize,outputSize-4*nbrOfPoles-1,nbrOfPoles)) #Load the saved NN model (made in train_ACANN.py) saved = "savedNNmodel.pth" #Note: Make sure the dimensions are the same model = ACANN(inputSize,outputSize,6*[600],drop_p=0.1).double() model.load_state_dict(torch.load(saved)) model.eval() model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) print("Number of parameters:",params) #Load test data path = "C:/Users/Thibault/Documents/Universiteit/Honours/Deel 2, interdisciplinair/Code/NN/Datasets/" test_data = Database(csv_target= path + "rhoTest.csv", \ csv_input= path + "DTest.csv",nb_data=sizeOfValidation).get_loader() testloader = DataLoader(test_data,batch_size=sizeOfValidation) testloadList = list(testloader) #Convert tensor to numpy array: rhovaluesList = testloadList[0][1].to("cpu").numpy() print(len(rhovaluesList),"testing functions") prop_data = pd.read_csv(path+'DTest.csv',header=None,nrows=sizeOfValidation) propList = prop_data.values.tolist() # print(len(propList),"propagators") params_data = pd.read_csv(path+'params.csv',header=None,nrows=sizeOfTraining+2*sizeOfValidation) paramsList = params_data.values.tolist() print("Data Loaded") origProp = [] #Use NN to predict with torch.no_grad(): D_test,rho_test = next(iter(testloader)) # print(D_test) prediction = model.forward(D_test) # print("output:",prediction) predicData = prediction.to("cpu").numpy() # print("output:",predicData) origProp.append(D_test.to("cpu").numpy()) #Evaluate output: ps = np.linspace(pstart,pend,nbrPoints) ws = np.linspace(0.01,10,nbrWs) def plotPolesForIndex(i,ax): polemarkers = ["o","^","*"] msizes = [7,9,11] for j in range(nbrOfPoles): #Only plot the poles cj = predicData[i][nbrWs + 4*j + 2] dj = predicData[i][nbrWs + 4*j + 3] cjOrig = rhovaluesList[i][nbrWs + 4*j + 2] djOrig = rhovaluesList[i][nbrWs + 4*j + 3] if i != -1: ax.plot(cjOrig,djOrig,polemarkers[j],color="blue",label="Original poles",markersize=msizes[j]) ax.plot(cj,dj,polemarkers[j],color="cyan",label="Reconstructed poles",markersize=msizes[j]) ax.set_xlim([0.15,0.4]) ax.set_ylim([0.2,0.8]) ax.grid() ax.set_xlabel("Re(q)") ax.set_ylabel("Im(q)") def plotResiduesForIndex(i,ax): resmarkers = ["o","^","*"] msizes = [7,9,11] for j in range(nbrOfPoles): #Only plot the poles aj = predicData[i][nbrWs + 4*j] bj = predicData[i][nbrWs + 4*j + 1] ajOrig = rhovaluesList[i][nbrWs + 4*j] bjOrig = rhovaluesList[i][nbrWs + 4*j + 1] if i != -1: ax.plot(ajOrig,bjOrig,marker=resmarkers[j],color="green",label="Original residues",markersize=msizes[j]) ax.plot(aj,bj,marker=resmarkers[j],color="lawngreen",label="Reconstructed residues",markersize=msizes[j]) ax.set_xlim([-1.5,1.5]) ax.set_ylim([-0.2,1.2]) ax.grid() ax.set_xlabel("Re(R)") ax.set_ylabel("Im(R)") #Reconstruct propagator from reconstructed spectral function and poles: def poles(p,N,poleList): jsum = 0 for j in range(N): a = poleList[j*4] b = poleList[j*4+1] c = poleList[j*4+2] d = poleList[j*4+3] nom = 2*(a*(c+p)+b*d) denom = c**2 + 2*c*p + d**2 + p**2 jsum += nom/denom return jsum def reconstructProp(index): sigma = predicData[index][-1] wscutoff = min(range(len(ws)), key=lambda i: abs(ws[i]-sigma)) reconstructedPropSigma = [] for p in ps: spectrFunc = [] for i in range(wscutoff,len(ws)): spectrFunc.append(predicData[index][i]/(p**2+ws[i])) integral = integrate.simpson(spectrFunc,x=ws[wscutoff:]) prop = integral + poles(p**2,3, predicData[index][nbrWs:nbrWs+12]) reconstructedPropSigma.append(prop) rescaling = reconstructedPropSigma[12] for i in range(len(ps)): reconstructedPropSigma[i] = reconstructedPropSigma[i]/rescaling return reconstructedPropSigma def constraint15(index): sigma = predicData[index][-1] wscutoff = min(range(len(ws)), key=lambda i: abs(ws[i]-sigma)) res = integrate.simpson(predicData[index][wscutoff:nbrWs],x=ws[wscutoff:]) jsum = 0 for j in range(3): jsum += 2 * predicData[index][nbrWs+j*4] res += jsum if res < 0.5 and res > -0.5: return True return False def derivativeconstraint(index): dp0 = origProp[0][index][0] dp1 = origProp[0][index][1] rho0 = predicData[index][0] rho1 = predicData[index][1] derivativeRho = (rho1 - rho0)/(ws[1]-ws[0]) derivativeProp = (dp1 - dp0)/(ps[1]**2-ps[0]**2) derivativePoles = 0 for j in range(3): a = predicData[index][nbrWs+j*4] b = predicData[index][nbrWs+j*4+1] c = predicData[index][nbrWs+j*4+2] d = predicData[index][nbrWs+j*4+3] #Alternate but equivalent formula: derivativePoles += (-2*a*c**2 + 2*a*d**2 + 4*b*c*d)/((c**2 + d**2)**2) idealDerivative = -np.pi*derivativeRho - derivativePoles if derivativeProp < idealDerivative - 1 or \ derivativeProp > idealDerivative + 1: return False return True def positivepropconstraint(index): if min(reconstructProp(index)) < 0: return False return True def testConstraints(index): if constraint15(index) and derivativeconstraint(index) and positivepropconstraint(index): return True return False getBestAndWorst = True if getBestAndWorst: #Get the best and worst test cases: maxMAEindex = 0 maxMAE = 0 minMAEindex = 0 minMAE = 100000 constraintsSatisfied1 = 0 constraintsSatisfied2 = 0 constraintsSatisfied3 = 0 constraintsSatisfiedAll = 0 wssteps = ws[1] - ws[0] fullSortedList = [] for i in range(len(rhovaluesList)): MAE = 0 combListAll = zip(rhovaluesList[i],predicData[i]) scale = max(abs(rhovaluesList[i])) for orig, recon in combListAll: MAE += abs(orig-recon)/scale #MAE on spectral function only # combList = zip(rhovaluesList[i][:nbrWs],predicData[i][:nbrWs]) # scale = max(abs(rhovaluesList[i][:nbrWs])) # for orig, recon in combList: # MAE += abs(orig-recon)/scale #MAE on poles only # combList = zip(rhovaluesList[i][nbrWs:],predicData[i][nbrWs:]) # for orig, recon in combList: # MAE += abs(orig-recon) #MAE on propagator only # reconProp = reconstructProp(i) # combListProp = zip(propList[i],reconProp) # scale = abs(max(propList[i])) # for orig, recon in combListProp: # MAE += abs(orig-recon)/scale if MAE > maxMAE: maxMAE = MAE maxMAEindex = i if MAE < minMAE: minMAE = MAE minMAEindex = i fullSortedList.append((MAE,i)) if positivepropconstraint(i): constraintsSatisfied1 += 1 if derivativeconstraint(i): constraintsSatisfied2 += 1 if constraint15(i): constraintsSatisfied3 += 1 if testConstraints(i): constraintsSatisfiedAll += 1 fullSortedList.sort() # print("Sorted all rhos") print(str(constraintsSatisfied1)+"/"+str(len(rhovaluesList)), "recons satisfied constraint 1") print(str(constraintsSatisfied2)+"/"+str(len(rhovaluesList)), "recons satisfied constraint 2") print(str(constraintsSatisfied3)+"/"+str(len(rhovaluesList)), "recons satisfied constraint 3") print(str(constraintsSatisfiedAll)+"/"+str(len(rhovaluesList)), "recons satisfied all constraints") print("Min. MAE:",minMAE) print("Max. MAE:",maxMAE) percentile25th = fullSortedList[round(len(fullSortedList)/4)][1] percentile50th = fullSortedList[round(2*len(fullSortedList)/4)][1] percentile75th = fullSortedList[round(3*len(fullSortedList)/4)][1] print("index of the best,25prct,50prct,75prct,worst:", \ [minMAEindex,percentile25th,percentile50th,percentile75th,maxMAEindex]) listOfpoles = [] for i in range(len(fullSortedList)): nbrOfPoles = 0 for j in range(3): ajOrig = rhovaluesList[i][nbrWs + 4*j] bjOrig = rhovaluesList[i][nbrWs + 4*j + 1] if ajOrig != 0 or bjOrig != 0: nbrOfPoles += 1 if nbrOfPoles == 1: listOfpoles.append(i) print('1 pole:',listOfpoles) fig, ((ax11,ax12,ax13,ax14),(ax21,ax22,ax23,ax24),(ax31,ax32,ax33,ax34), \ (ax41,ax42,ax43,ax44),(ax51,ax52,ax53,ax54)) = plt.subplots(5,4) plotPolesForIndex(minMAEindex, ax13) plotPolesForIndex(percentile25th,ax23) plotPolesForIndex(percentile50th,ax33) plotPolesForIndex(percentile75th,ax43) plotPolesForIndex(maxMAEindex, ax53) plotResiduesForIndex(minMAEindex, ax14) plotResiduesForIndex(percentile25th,ax24) plotResiduesForIndex(percentile50th,ax34) plotResiduesForIndex(percentile75th,ax44) plotResiduesForIndex(maxMAEindex, ax54) indices = [minMAEindex,percentile25th,percentile50th,percentile75th,maxMAEindex] propaxes = [ax11,ax21,ax31,ax41,ax51] for i in range(len(propaxes)): propaxes[i].plot(ps,propList[indices[i]],label="Propagator") propaxes[i].plot(ps,reconstructProp(indices[i]),"--",label="Reconstructed propagator",color="red") propaxes[i].set_xlabel("p") propaxes[i].set_ylabel("D(p²)") rhoaxes = [ax12,ax22,ax32,ax42,ax52] for i in range(len(rhoaxes)): if indices[i] != -1: rhoaxes[i].plot(ws,rhovaluesList[indices[i]][:nbrWs],label="Spectral function") sigma = rhovaluesList[indices[i]][-1] rhoaxes[i].axvline(x=sigma,ymin=-10,ymax=10,color='dodgerblue',label='σ',linestyle='dotted') rhoaxes[i].plot(ws,predicData[indices[i]][:nbrWs],"--",label="Reconstructed spectral function, σ",color="red") sigma = predicData[indices[i]][-1] rhoaxes[i].axvline(x=sigma,ymin=-10,ymax=10,color='orangered',linestyle='dotted',label='Reconstructed σ') rhoaxes[i].set_xlabel("ω²") rhoaxes[i].set_ylabel("ρ(ω)") handles, labels = ax11.get_legend_handles_labels() ax11.legend(handles,labels,loc="upper center",bbox_to_anchor=(0.5,1.5)) handles,labels = ax12.get_legend_handles_labels() origTuple = (handles[0],handles[1]) reconTuple = (handles[2],handles[3]) labels = ["Spectral function, σ", "Reconstructed spectral function, σ"] ax12.legend((origTuple,reconTuple),labels, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=2,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.5),handlelength=4) handles,labels = ax13.get_legend_handles_labels() origTuple = (handles[0],handles[2],handles[4]) reconTuple = (handles[1],handles[3],handles[5]) labels = ["Original poles", "Reconstructed poles"] ax13.legend((origTuple,reconTuple),labels,scatterpoints=3, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=3,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.5),handlelength=4) handles,labels = ax14.get_legend_handles_labels() origTuple = (handles[0],handles[2],handles[4]) reconTuple = (handles[1],handles[3],handles[5]) labels = ["Original residues", "Reconstructed residues"] ax14.legend((origTuple,reconTuple),labels,scatterpoints=3, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=3,pad=1.3)}, loc="upper center",bbox_to_anchor=(0.5,1.5),handlelength=4) # fig.set_tight_layout(True)
12,953
32.734375
120
py
SpectralANN
SpectralANN-main/propagatorNoise.py
# -*- coding: utf-8 -*- """ Created on Tue Nov 30 15:06:14 2021 @author: Thibault """ from Database import Database from torch.utils.data import DataLoader import inputParameters as config import numpy as np import pandas as pd import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" noiseSize = 5e-3 #Load input parameters from inputParameters.py sizeOfTraining = config.trainingPoints sizeOfValidation = config.validationPoints pstart = config.pstart pend = config.pend nbrPoints = config.nbrPoints path = "C:/Users/Thibault/Documents/Universiteit/\ Honours/Deel 2, interdisciplinair/Code/NN/Datasets/" train_data = Database(csv_target= path + "rhoTraining.csv",\ csv_input= path + "DTrainingRaw.csv",nb_data=sizeOfTraining).get_loader() trainloader = DataLoader(train_data,batch_size=sizeOfTraining) print("Training data loaded") validation_data = Database(csv_target= path + "rhoValidation.csv",\ csv_input= path + "DValidationRaw.csv",nb_data=sizeOfValidation).get_loader() validationloader = DataLoader(validation_data,batch_size=sizeOfValidation) print("Validation data loaded") test_data = Database(csv_target= path + "rhoTest.csv",\ csv_input= path + "DTestRaw.csv",nb_data=sizeOfValidation).get_loader() testloader = DataLoader(test_data,batch_size=sizeOfValidation) print("Test data loaded") alldatatensors = list(trainloader) alldata = alldatatensors[0][0].to("cpu").numpy() alldatatensorsValid = list(validationloader) alldataValid = alldatatensorsValid[0][0].to("cpu").numpy() alldatatensorsTest = list(testloader) alldataTest = alldatatensorsTest[0][0].to("cpu").numpy() #Add noise: for i in range(len(alldata)): noise = np.random.normal(1,noiseSize,nbrPoints) alldata[i] = alldata[i] * noise for i in range(len(alldataValid)): noise = np.random.normal(1,noiseSize,nbrPoints) alldataValid[i] = alldataValid[i] * noise for i in range(len(alldataTest)): noise = np.random.normal(1,noiseSize,nbrPoints) alldataTest[i] = alldataTest[i] * noise print(len(alldata),"training points") path = "C:/Users/Thibault/Documents/Universiteit/Honours/Deel 2, interdisciplinair/Code/NN/Datasets/" #Write data to these files (first deletes old ones) propTrain_csv = path+'DTraining.csv' if os.path.exists(propTrain_csv): os.remove(propTrain_csv) propValid_csv = path+'DValidation.csv' if os.path.exists(propValid_csv): os.remove(propValid_csv) propTest_csv = path+'DTest.csv' if os.path.exists(propTest_csv): os.remove(propTest_csv) #Write data to files propTraindf = pd.DataFrame(alldata) propTraindf.to_csv(propTrain_csv,index=False,header=False,mode='a') propValiddf = pd.DataFrame(alldataValid) propValiddf.to_csv(propValid_csv,index=False,header=False,mode='a') propTestdf = pd.DataFrame(alldataTest) propTestdf.to_csv(propTest_csv,index=False,header=False,mode='a') print("Succesfully added artificial noise to training data.")
2,951
27.660194
101
py
SpectralANN
SpectralANN-main/ACANN.py
import torch.nn as nn import torch.nn.functional as F import torch device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class ACANN(nn.Module): def __init__(self,input_size,output_size,hidden_layers,drop_p=0.05): """ Builds ACANN network with arbitrary number of hidden layers. Arguments ---------- input_size : integer, size of the input output_size : integer, size of the output layer hidden_layers: list of integers, the sizes of the hidden layers drop_p: float in (0,1) , value of the dropout probability """ super().__init__() # Add the first layer : input_size into the first hidden layer self.layers = nn.ModuleList([nn.Linear(input_size,hidden_layers[0]).to(device)]) self.normalizations = nn.ModuleList([nn.BatchNorm1d(input_size).to(device)]) # Add the other layers layers_sizes = zip(hidden_layers[:-1],hidden_layers[1:]) self.layers.extend([nn.Linear(h1,h2).to(device) for h1,h2 in layers_sizes]) self.normalizations.extend([nn.BatchNorm1d(size).to(device) for size in hidden_layers]) self.output=nn.Linear(hidden_layers[-1],output_size).to(device) self.dropout = nn.Dropout(drop_p).to(device) def forward(self,x): # pass through each layers for layer,normalization in zip(self.layers,self.normalizations): x=normalization(x) x=F.relu(layer(x)) x=self.dropout(x) x=self.output(x) return x
1,617
29.528302
95
py
giants
giants-main/prepare_batch.py
import pandas as pd import numpy as np import os def create_batch_file(inlist, outdir, batchfile_path, local=False): # read in the list of targets f = pd.read_csv(inlist, delimiter=',') try: targets = np.array(f['tic']) except: targets = np.array(f['TIC']) # create the batch file for tic in targets: if local: command = f'python run_giants.py {tic} {outdir} --local \n' else: command = f'python run_giants.py {tic} {outdir} \n' with open(f'{batchfile_path}.tot', 'a+') as file: file.write(command) # create corresponding directories os.mkdir(f'{outdir}/timeseries') os.mkdir(f'{outdir}/fft') os.mkdir(f'{outdir}/plots') # create the transit stats file with open(os.path.join(outdir, "transit_stats.txt"), "a+") as file: file.write("ticid depth depth_snr period t0 dur scaled_residuals\n") if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Create a batch file to run giants on a list of targets.') parser.add_argument('inlist', type=str, help='Path to a list of TICIDs to run giants on.') parser.add_argument('outdir', type=str, help='Path to the output directory.') parser.add_argument('batchfile_name', type=str, help='Name of the batch file to be created.') parser.add_argument('--local', action='store_true', help='Flag to indicate whether to use local data.') args = parser.parse_args() create_batch_file(args.inlist, args.outdir, args.batchfile_name, args.local)
1,579
36.619048
107
py
giants
giants-main/setup.py
#!/usr/bin/env python import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup with open('requirements.txt') as f: install_requires = f.read().splitlines() setup(name='giants', version='0.0.1', description="", author='Samuel Grunblatt, Nicholas Saunders', license='', packages=['giants'], package_dir={'': 'src'}, package_data={'giants': ['data/downlinks.txt']}, install_requires=install_requires, )
519
22.636364
54
py
giants
giants-main/housekeeping.py
import os import time dirpath = '/home/nsaunders/.lightkurve-cache/tesscut/' while True: time.sleep(60) for f in os.listdir(dirpath): try: fn = os.path.join(dirpath, f) if os.stat(fn).st_mtime < time.time() - 60: os.remove(fn) print(f'Removed {f}') except: print(f'Could not remove {f}')
381
24.466667
55
py
giants
giants-main/run_giants.py
import sys import argparse import pandas as pd import numpy as np from giants.plotting import plot_summary from giants.target import Target if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run giants on a single target.') parser.add_argument('ticid', type=str, help='TICID of the target to run giants on.') parser.add_argument('outdir', type=str, help='Path to the output directory.') parser.add_argument('--local', action='store_true', help='Flag to indicate whether to use local data.') parser.add_argument('--save_data', action='store_true', help='Flag to indicate whether to save the data.') args = parser.parse_args() try: if args.local: lookup_table = pd.read_csv('/data/users/sgrunblatt/TESS_targetlists/TIC_lookup.csv') N = np.nan for i in range(len(lookup_table)): if (int(args.ticid) > lookup_table['TIC_start'].iloc[i]) and (int(args.ticid) > lookup_table['TIC_start'].iloc[i]): N = i if np.isnan(N): print(f'{args.ticid} not found in target lists!') csv_path = None else: csv_path = f'/data/users/sgrunblatt/TESS_targetlists/ticgiants_sublists/sublist{N}.csv' else: csv_path = None target = Target(ticid=args.ticid) if args.local: target.fetch_and_clean_data(lc_source='local') else: target.fetch_and_clean_data(lc_source='lightkurve') plot_summary(target, outdir=args.outdir, save_data=True) except: print(f'Target {sys.argv[1]} failed.')
1,652
36.568182
131
py
giants
giants-main/src/giants/target.py
import os import re import numpy as np import pandas as pd import scipy import lightkurve as lk import warnings from tess_stars2px import tess_stars2px_function_entry from astrocut import CutoutFactory from astroquery.mast import Catalogs from . import PACKAGEDIR from .plotting import plot_summary # suppress verbose astropy warnings and future warnings warnings.filterwarnings("ignore", module="astropy") warnings.filterwarnings("ignore", category=FutureWarning) __all__ = ['Target'] class Target(object): """ A class to hold a TESS target and its data. Parameters ---------- ticid : int TIC ID of the target silent : bool suppress print statements """ def __init__(self, ticid, silent=False): # parse TIC ID self.ticid = ticid if isinstance(self.ticid, str): self.ticid = int(re.search(r'\d+', str(self.ticid)).group()) self.PACKAGEDIR = PACKAGEDIR self.has_target_info = False self.silent = silent self.search_result = lk.search_tesscut(f'TIC {ticid}') self.get_target_info(self.ticid) self.available_sectors = self.check_available_sectors() def __repr__(self): return f'giants.Target: TIC {self.ticid} (available sectors: {", ".join([str(s) for s in self.available_sectors])})' def get_target_info(self, ticid): """ Get basic information about the target from the TIC catalog. Parameters ---------- ticid : int TIC ID of the target """ catalog_data = Catalogs.query_criteria(objectname=f'TIC {ticid}', catalog="Tic", radius=.0001, Bmag=[0,20]) self.ra = catalog_data['ra'][0] self.dec = catalog_data['dec'][0] self.coords = f'({self.ra:.2f}, {self.dec:.2f})' self.rstar = catalog_data['rad'][0] self.teff = catalog_data['Teff'][0] self.has_target_info = True def check_available_sectors(self, ticid=None): """ Helper function to check which sectors are available in the TESSCut search result. Parameters ---------- ticid : int TIC ID of the target Returns ------- available_sectors : list of ints list of available sectors """ if ticid is not None: temp_search_result = lk.search_tesscut(f'TIC {ticid}') else: temp_search_result = self.search_result available_sectors = [] for sector in temp_search_result.table['description']: available_sectors.append(int(re.search(r'\d+', sector).group())) # restrict to sectors greater than 53 and less than 56 # HACK for PHT available_sectors = [s for s in available_sectors if s > 53 and s < 56] return available_sectors def from_lightkurve(self, sectors=None, flatten=True, **kwargs): """ Use `lightkurve.search_tesscut` to query and download TESSCut 11x11 cutout for target. This function creates a background model and subtracts it off using `lightkurve.RegressionCorrector`. Parameters ---------- sectors : int, list of ints desired sector number or list of sector numbers flatten : bool optionally flatten the light curve **kwargs : dict additional keyword arguments to pass to `lightkurve.search_tesscut` Returns ------- lc : `lightkurve.LightCurve` object background-corrected flux time series """ # apply sector mask if sectors is not None: # make sure sectors is a list if isinstance(sectors, int): sectors = [sectors] search_result_mask = [] for sector in self.available_sectors: search_result_mask.append(sector in sectors) masked_search_result = self.search_result[search_result_mask] else: masked_search_result = self.search_result # download data tpfc = lk.TargetPixelFileCollection([]) for search_row in masked_search_result: try: tpfc.append(search_row.download(cutout_size=11)) except: continue # apply the pca background correction self.tpf = tpfc[0] lc = self.apply_pca_corrector(self.tpf) raw_lc = self.tpf.to_lightcurve(aperture_mask='threshold') self.lcc = lk.LightCurveCollection([lc]) self.breakpoints = [lc.time[-1].value] for tpf in tpfc[1:]: new_lc = self.apply_pca_corrector(tpf) new_raw_lc = tpf.to_lightcurve(aperture_mask='threshold') # flatten lc if flatten: lc = lc.flatten() # stitch together lc = lc.append(new_lc) raw_lc = raw_lc.append(new_raw_lc) self.lc = lc self.raw_lc = raw_lc return lc def from_local_data(self, local_data_path, sectors=None, flatten=False): """ Retrieve data from local data cube. Data cubes should be stored in the format 's0001-1-1.fits' Parameters ---------- local_data_path : str path to local data cube sectors : int, list of ints desired sector number or list of sector numbers flatten : bool optionally flatten the light curve Returns ------- lc : `lightkurve.LightCurve` object background-corrected flux time series """ self.get_target_info(self.ticid) obs = self.fetch_obs(self.ra, self.dec) sectors = obs[0] if not self.silent: print(f'Creating light curve for target {self.ticid} for sectors {sectors}.') my_cutter = CutoutFactory() local_data_path = '/data/users/nsaunders/cubes' # !! HACK available_obs = np.array(obs).T.reshape(len(obs[0]), len(obs)) tpfs = [] for obs_ in available_obs: try: cube_file = os.path.join(local_data_path, f's{obs_[0]:04d}-{obs_[1]}-{obs_[2]}.fits') cutout_file = my_cutter.cube_cut(cube_file, f'{self.ra} {self.dec}', 11, verbose=False) tpfs.append(lk.read(cutout_file)) os.remove(cutout_file) except: continue tpfc = lk.TargetPixelFileCollection(tpfs) self.tpf = tpfc[0] if flatten: lc = self.apply_pca_corrector(self.tpf).flatten(1001) else: lc = self.apply_pca_corrector(self.tpf) # store as LCC for plotting later self.lcc = lk.LightCurveCollection([lc]) self.breakpoints = [lc.time[-1]] for tpf in tpfc[1:]: if flatten: new_lc = self.apply_pca_corrector(tpf).flatten(1001) else: new_lc = self.apply_pca_corrector(tpf) self.breakpoints.append(new_lc.time[-1]) self.lcc.append(new_lc) lc = lc.append(new_lc) self.lc = lc return lc def fetch_obs(self, ra, dec): """ Query MAST for TESS observations of a given target. Parameters ---------- ra : float right ascension of target dec : float declination of target Returns ------- obs : list of lists list of observations, each of which is a list of [sector, camera, ccd] """ outID, outEclipLong, outEclipLat, outSec, outCam, outCcd, \ outColPix, outRowPix, scinfo = tess_stars2px_function_entry( self.ticid, float(ra), float(dec)) return outSec, outCam, outCcd def apply_pca_corrector(self, tpf, zero_point_background=False): """ De-trending algorithm for `lightkurve` version of FFI pipeline. The steps of this de-trending are: - Find a threshold aperture mask around the target - Create a design matrix with column vectors from pixel-level timeseries outside of the aperture - Perform Principle Component Analysis (PCA) on column vectors to find out background model vectors - Fit weights to these vectors to minimize squared difference between model and observations - Subtract noise model Parameters ---------- tpf : `lightkurve.TargetPixelFile` object target pixel file for desired target zero_point_background : bool optionally normalize light curve to the 5th percentile of model flux. can be useful for targets which raise warnings when flattened. default is False. Returns ------- corrected_lc : `lightkurve.LightCurve` object background-corrected light curve """ # remove the first 12 hours and last 12 hours of data tpf = tpf[tpf.time.value >= tpf.time.value[0] + 0.5] tpf = tpf[tpf.time.value <= tpf.time.value[-1] - 0.5] # define threshold aperture mask aper = tpf._parse_aperture_mask('threshold') raw_lc = tpf.to_lightcurve(aperture_mask=aper) # remove NaNs and negative flux values mask = (raw_lc.flux_err > 0) | (~np.isnan(raw_lc.flux)) self.raw_lc = raw_lc[mask] tpf = tpf[mask] # create design matrix from pixels outside of aperture regressors = tpf.flux[:, ~aper] dm = lk.DesignMatrix(regressors, name='regressors') # perform PCA on design matrix and append column of constants dm = dm.pca(10) dm = dm.append_constant() # fit weights to design matrix and remove background noise model corrector = lk.RegressionCorrector(self.raw_lc.normalize()) corrected_lc_unnormalized = corrector.correct(dm) model = corrector.model_lc # optionally normalize to the 5th percentile of model flux if zero_point_background: model -= np.percentile(model.flux, 5) corrected_lc = lk.LightCurve(time=model.time, flux=self.raw_lc.normalize().flux.value-model.flux, flux_err=self.raw_lc.flux_err.value) return corrected_lc def fetch_and_clean_data(self, lc_source='lightkurve', flatten=True, sectors=None, gauss_filter_lc=True, **kwargs): """ Query and download data, remove background signal and outliers. The light curve is stored as a object variable `Target.lc`. Parameters ---------- lc_source : str, 'lightkurve' or 'local' pipeline used to access data flatten : bool optionally flatten the light curve sectors : int, list of ints desired sector number or list of sector numbers gauss_filer_lc : bool optionally apply Gaussian smoothing with a ~2 day filter (good for planets, bad for stars) **kwargs : dict additional keyword arguments to pass to `lightkurve.search_tesscut` Returns ------- self : `Target` object returns self for chaining """ if lc_source == 'lightkurve': lc = self.from_lightkurve(sectors=sectors, flatten=flatten) elif lc_source == 'local': lc = self.from_local_data('/data/users/nsaunders/cubes') lc = self._clean_data(lc, gauss_filter_lc=gauss_filter_lc) return self def _clean_data(self, lc, gauss_filter_lc=True): """Hidden function to remove common sources of noise and outliers.""" # mask first 12h after momentum dump momdump = (lc.time.value > 1339) * (lc.time.value < 1341) # also the burn in burnin = np.zeros_like(lc.time.value, dtype=bool) burnin[:30] = True with open(os.path.join(self.PACKAGEDIR, 'data/downlinks.txt')) as f: downlinks = [float(val.strip()) for val in f.readlines()] """ # mask around downlinks for d in downlinks: if d in lc.time: burnin[d:d+15] = True """ # also 6 sigma outliers _, outliers = lc.remove_outliers(sigma=6, return_mask=True) mask = momdump | outliers | burnin lc = lc[~mask] lc.flux = lc.flux - 1 * lc.flux.unit if gauss_filter_lc: lc.flux = lc.flux - scipy.ndimage.filters.gaussian_filter(lc.flux, 100) *lc.flux.unit # <2-day (5muHz) filter # store cleaned lc self.lc = lc self.mask = mask return lc def save_to_fits(self, outdir=None, lc_source='local'): """ Pipeline to download and de-trend a target using the `lightkurve` implememtation. Downloads data, removes background, and saves as fits files. This function outputs: - {TICID}_s{SECTOR}_corr.fits : corrected light curve - {TICID}_s{SECTOR}_raw.fits : raw SAP flux light curve Parameters ---------- outdir : str or path location of fits output lc_source : str, 'lightkurve' or 'local' pipeline used to access data Returns ------- self : `Target` object returns self for chaining """ self.silent = True if outdir is None: outdir = os.path.join(self.PACKAGEDIR, 'outputs') for s in self.available_sectors: self.fetch_and_clean_data(lc_source='lightkurve', sectors=s, gauss_filter_lc=False) fname_corr = f'{self.ticid}_s{s:02d}_corr.fits' fname_raw = f'{self.ticid}_s{s:02d}_raw.fits' path_corr = os.path.join(outdir, fname_corr) path_raw = os.path.join(outdir, fname_raw) self.lc.flux += 1. self.lc.to_fits(path=path_corr, overwrite=True) self.raw_lc.to_fits(path=path_raw, overwrite=True) def create_summary_plot(self, **kwargs): plot_summary(self, **kwargs)
14,120
32.863309
142
py
giants
giants-main/src/giants/plotting.py
import os import numpy as np import scipy import matplotlib.pyplot as plt import matplotlib from astropy.stats import BoxLeastSquares from astropy.coordinates import SkyCoord, Angle import lightkurve as lk import astropy.units as u import pickle from astroquery.mast import Catalogs try: from .utils import build_ktransit_model, _individual_ktransit_dur except: from utils import build_ktransit_model, _individual_ktransit_dur __all__ = ['plot_summary'] def add_gaia_figure_elements(tpf, fig, magnitude_limit=18): """ Add Gaia DR2 sources to a TPF plot. Parameters ---------- tpf : lightkurve.TargetPixelFile Target pixel file to plot. fig : matplotlib.pyplot.figure Figure to plot on. magnitude_limit : float Magnitude limit to use for Gaia query. Returns ------- fig : matplotlib.pyplot.figure Figure with Gaia sources plotted. """ # Get the positions of the Gaia sources c1 = SkyCoord(tpf.ra, tpf.dec, frame='icrs', unit='deg') # Use pixel scale for query size pix_scale = 21.0 # We are querying with a diameter as the radius, overfilling by 2x. from astroquery.vizier import Vizier Vizier.ROW_LIMIT = -1 result = Vizier.query_region(c1, catalog=["I/345/gaia2"], radius=Angle(np.max(tpf.shape[1:]) * pix_scale, "arcsec")) no_targets_found_message = ValueError('Either no sources were found in the query region ' 'or Vizier is unavailable') too_few_found_message = ValueError('No sources found brighter than {:0.1f}'.format(magnitude_limit)) if result is None: raise no_targets_found_message elif len(result) == 0: raise too_few_found_message result = result["I/345/gaia2"].to_pandas() result = result[result.Gmag < magnitude_limit] if len(result) == 0: raise no_targets_found_message radecs = np.vstack([result['RA_ICRS'], result['DE_ICRS']]).T coords = tpf.wcs.all_world2pix(radecs, 0) ## TODO, is origin supposed to be zero or one? year = ((tpf.time[0].jd - 2457206.375) * u.day).to(u.year) pmra = ((np.nan_to_num(np.asarray(result.pmRA)) * u.milliarcsecond/u.year) * year).to(u.arcsec).value pmdec = ((np.nan_to_num(np.asarray(result.pmDE)) * u.milliarcsecond/u.year) * year).to(u.arcsec).value result.RA_ICRS += pmra result.DE_ICRS += pmdec # Gently size the points by their Gaia magnitude sizes = 50000.0 / 2**(result['Gmag']/2) plt.scatter(coords[:, 0]+tpf.column, coords[:, 1]+tpf.row, c='firebrick', alpha=0.5, edgecolors='r', s=sizes) plt.scatter(coords[:, 0]+tpf.column, coords[:, 1]+tpf.row, c='None', edgecolors='r', s=sizes) plt.xlim([tpf.column, tpf.column+tpf.shape[1]-1]) plt.ylim([tpf.row, tpf.row+tpf.shape[2]-1]) plt.axis('off') return fig def plot_summary(target, outdir='', save_data=False, save_fig=True): """ Produce a summary plot for a given target. Parameters ---------- target : giants.Target Target object to plot. outdir : str Path to the output directory. save_data : bool Flag to indicate whether to save the data. save_fig : bool Flag to indicate whether to save the figure. """ font = {'family' : 'sans', 'size' : 14} matplotlib.rc('font', **font) plt.style.use('seaborn-muted') dims=(18, 24) # fit BLS bls_results, bls_stats = get_bls_results(target.lc, target.ticid) period = bls_results.period[np.argmax(bls_results.power)] t0 = bls_results.transit_time[np.argmax(bls_results.power)] depth = bls_results.depth[np.argmax(bls_results.power)] depth_snr = depth / np.std(target.lc.flux.value) # generate ktransit fit model_lc, ktransit_model = fit_transit_model(target, period, t0) result = ktransit_model.fitresult[1:] kt_period = result[0] kt_t0 = result[2] dur = _individual_ktransit_dur(model_lc.time, model_lc.flux) scaled_residuals = np.median(fit_transit_model(target, period, t0)[1].residuals()) / np.std(target.lc.flux.value) """Create the figure.""" fig = plt.gcf() fig.suptitle(f'TIC {target.ticid}', fontweight='bold', size=24, y=0.93) # plot the light curve ax = plt.subplot2grid(dims, (0,0), colspan=24, rowspan=3) plot_raw_lc(target, model_lc, ax) # set title to include stellar params param_string = stellar_params(target) ax.set_title(param_string, size=20) # plot the folded light curve ax = plt.subplot2grid(dims, (4,0), colspan=16, rowspan=3) plot_folded(target.lc, period.value, t0.value, depth, ax) # plot the TPF ax = plt.subplot2grid(dims, (4,17), colspan=7, rowspan=7) plot_tpf(target, ax) # plot the odd and even transits ax = plt.subplot2grid(dims, (8,0), colspan=8, rowspan=3) plot_even(target.lc, period.value, t0.value, depth, ax) ax = plt.subplot2grid(dims, (8,8), colspan=8, rowspan=3) plot_odd(target.lc, period.value, t0.value, depth, ax) plt.subplots_adjust(wspace=0) ax.set_yticklabels([]) ax.set_ylabel('') # plot the transit model ax = plt.subplot2grid(dims, (12,0), colspan=8, rowspan=4) plot_tr_top(target.lc, model_lc, kt_period, kt_t0, ax) # plot the residuals ax = plt.subplot2grid(dims, (16,0), colspan=8, rowspan=2) plot_tr_bottom(target.lc, model_lc, kt_period, kt_t0, ax) plt.subplots_adjust(hspace=0) # plot the BLS periodogram ax = plt.subplot2grid(dims, (12,17), colspan=7, rowspan=3) plot_bls(target.lc, ax, results=bls_results) plt.subplots_adjust(hspace=0) # plot the FFT ax = plt.subplot2grid(dims, (15,17), colspan=7, rowspan=3) freq, fts = plot_fft(target.lc, ax) plt.subplots_adjust(hspace=0) # include the transit stats table ax = plt.subplot2grid(dims, (13,9), colspan=6, rowspan=4) if target.has_target_info: plot_table(target, ktransit_model, depth_snr, dur, scaled_residuals, ax) else: ax.axis('off') harmonic_del = bls_stats['harmonic_delta_log_likelihood'].value sde = (bls_results.power - np.mean(bls_results.power)) / np.std(bls_results.power) max_power = max(sde) fig = plt.gcf() fig.patch.set_facecolor('white') fig.set_size_inches([d-1 for d in dims[::-1]]) # save the transit stats with open(os.path.join(outdir, "transit_stats.txt"), "a+") as file: file.write(f"{target.ticid} {depth} {depth_snr} {period} {t0} {dur} {scaled_residuals} {harmonic_del} {max_power}\n") # save the data if save_data: try: np.savetxt(outdir+'/timeseries/'+str(target.ticid)+'.dat.ts', np.transpose([target.lc.time.value, target.lc.flux.value]), fmt='%.8f', delimiter=' ') np.savetxt(outdir+'/fft/'+str(target.ticid)+'.dat.ts.fft', np.transpose([freq, fts]), fmt='%.8f', delimiter=' ') except: np.savetxt(outdir+str(target.ticid)+'.dat.ts', np.transpose([target.lc.time.value, target.lc.flux.value]), fmt='%.8f', delimiter=' ') np.savetxt(outdir+str(target.ticid)+'.dat.ts.fft', np.transpose([freq, fts]), fmt='%.8f', delimiter=' ') if save_fig: try: fig.savefig(str(outdir)+'/plots/'+str(target.ticid)+'_summary.png', bbox_inches='tight') except: fig.savefig(str(outdir)+str(target.ticid)+'_summary.png', bbox_inches='tight') def fit_transit_model(target, period, t0): """ Fit a transit model to a given target using the ktransit package. Parameters ---------- target : giants.Target Target object to fit. period : float Orbital period of the planet. t0 : float Epoch of the first transit. Returns ------- model_lc : lightkurve.LightCurve Light curve of the transit model. ktransit_model : ktransit.ktransit.LCModel ktransit model object. """ ktransit_model = build_ktransit_model(target.ticid, target.lc, period, t0) model_lc = lk.LightCurve(time=target.lc.time, flux=ktransit_model.transitmodel) return model_lc, ktransit_model def plot_raw_lc(target, model_lc, ax=None): """ Plot the raw light curve of a given target. Parameters ---------- target : giants.Target Target object to plot. model_lc : lightkurve.LightCurve Light curve of the transit model. ax : matplotlib.pyplot.axis Axis to plot on. """ if ax is None: _, ax = plt.subplots(1) target.lc.scatter(ax=ax, c='k', s=50) ax.set_xlim(target.lc.time.value[0], target.lc.time.value[-1]) for b in target.breakpoints: try: ax.axvline(b.value, linestyle='--', color='r') except: ax.axvline(b, linestyle='--', color='r') depth = 0 - np.min(model_lc.flux.value) ax.set_ylim(np.min(model_lc.flux.value)-depth*2, depth*2) def plot_tr_top(flux_lc, model_lc, per, t0, ax): """ Plot the transit model on top of the raw light curve. Parameters ---------- flux_lc : lightkurve.LightCurve Light curve of the target. model_lc : lightkurve.LightCurve Light curve of the transit model. per : float Orbital period of the planet. t0 : float Epoch of the first transit. ax : matplotlib.pyplot.axis Axis to plot on. """ res_flux_ppm = (flux_lc.flux - model_lc.flux.reshape(len(flux_lc.flux))) * 1e6 res_lc = lk.LightCurve(time=model_lc.time, flux=res_flux_ppm) depth = 0 - np.min(model_lc.flux.value) ax.set_xticklabels([]) ax.set_xlim(-.1*per, .1*per) flux_lc.fold(per, t0).remove_outliers().scatter(ax=ax, c='gray', s=50) flux_lc.fold(per, t0).remove_outliers().bin(.1).scatter(ax=ax, c='dodgerblue', s=420) model_lc.fold(per, t0).plot(ax=ax, c='r', lw=3, zorder=10000) ax.set_ylim(np.min(model_lc.flux.value)-depth*2, depth*2) ax.set_ylabel('Normalized Flux') def plot_tr_bottom(flux_lc, model_lc, per, t0, ax): """ Plot the residuals of the transit model. Parameters ---------- flux_lc : lightkurve.LightCurve Light curve of the target. model_lc : lightkurve.LightCurve Light curve of the transit model. per : float Orbital period of the planet. t0 : float Epoch of the first transit. ax : matplotlib.pyplot.axis Axis to plot on. """ res_flux_ppm = (flux_lc.flux - model_lc.flux.reshape(len(flux_lc.flux))) * 1e6 res_lc = lk.LightCurve(time=model_lc.time, flux=res_flux_ppm) res_lc.fold(per, t0).remove_outliers().scatter(ax=ax, c='gray', s=50) res_lc.fold(per, t0).remove_outliers().bin(.1).scatter(ax=ax, c='dodgerblue', s=420) ax.axhline(0, c='k', linestyle='dashed') ax.set_xlim(-.1*per, .1*per) ax.set_ylabel('Residuals (ppm)') def plot_fft(lc, ax=None): """ Plot the FFT of a given light curve. Parameters ---------- lc : lightkurve.LightCurve Light curve to plot. ax : matplotlib.pyplot.axis Axis to plot on. Returns ------- freq : numpy.ndarray Frequencies of the FFT. fts : numpy.ndarray Power of the FFT. """ if ax is None: _, ax = plt.subplots(1) nyq=283. ls = lc.to_periodogram('ls') freq = ls.frequency.to(u.uHz).value fts = ls.power.value use = np.where(freq < nyq + 150) freq = freq[use] fts = fts[use] ax.loglog(freq, fts/np.max(fts), c='dodgerblue') ax.loglog(freq, scipy.ndimage.filters.gaussian_filter(fts/np.max(fts), 5), color='gold', lw=2.5) ax.loglog(freq, scipy.ndimage.filters.gaussian_filter(fts/np.max(fts), 50), color='r', lw=2.5) ax.axvline(283,-1,1, ls='--', color='k') ax.set_xlabel("Frequency [uHz]") ax.set_ylabel("Power") ax.set_xlim(10, 400) ax.set_ylim(1e-4, 1e0) return freq, fts def get_bls_results(lc, targetid='None'): """ Get the BLS results for a given light curve. Parameters ---------- lc : lightkurve.LightCurve Light curve to fit. Returns ------- results : astropy.stats.BoxLeastSquares Astropy BLS object. """ model = BoxLeastSquares(lc.time, lc.flux) results = model.power(np.linspace(1., 25., 1000), 0.16) stats = model.compute_stats(results.period[np.argmax(results.power)], results.duration[np.argmax(results.power)], results.transit_time[np.argmax(results.power)]) stats['period'] = results.period[np.argmax(results.power)] stats['duration'] = results.duration[np.argmax(results.power)] return results, stats def plot_bls(lc, ax, results=None): """ Plot the BLS periodogram for a given light curve. Parameters ---------- lc : lightkurve.LightCurve Light curve to plot. ax : matplotlib.pyplot.axis Axis to plot on. results : astropy.stats.BoxLeastSquares Astropy BLS object. """ if results is None: results, stats = get_bls_results(lc) period = results.period[np.argmax(results.power)] ax.plot(results.period, results.power, "k", lw=0.5) ax.set_xlim(results.period.min().value, results.period.max().value) ax.set_xlabel("period [days]") ax.set_ylabel("log likelihood") # Highlight the harmonics of the peak period ax.axvline(period.value, alpha=0.4, lw=4, c='cornflowerblue') for n in range(2, 10): ax.axvline(n*period.value, alpha=0.4, lw=1, linestyle="dashed", c='cornflowerblue') ax.axvline(period.value / n, alpha=0.4, lw=1, linestyle="dashed", c='cornflowerblue') def plot_folded(lc, period, t0, depth, ax): """ Plot the folded light curve for a given light curve. Parameters ---------- lc : lightkurve.LightCurve Light curve to plot. period : float Orbital period of the planet. t0 : float Epoch of the first transit. depth : float Depth of the transit. ax : matplotlib.pyplot.axis Axis to plot on. """ if ax is None: _, ax = plt.subplots(1) lc.fold(period, t0).scatter(ax=ax, c='gray', s=25, label=rf'$P={period:.2f}$ d') lc.fold(period, t0).bin(.1).plot(ax=ax, c='r', lw=2) ax.set_xlim(-.5*period, .5*period) ax.set_ylim(-3*depth, 2*depth) plt.grid(True) def plot_odd(lc, period, t0, depth, ax): """ Plot the odd transits for a given light curve. Parameters ---------- lc : lightkurve.LightCurve Light curve to plot. period : float Orbital period of the planet. t0 : float Epoch of the first transit. depth : float Depth of the transit. ax : matplotlib.pyplot.axis Axis to plot on. """ if ax is None: _, ax = plt.subplots(1) lc.fold(2*period, t0+period/2).scatter(ax=ax, c='gray', label='Odd Transit', s=25) lc.fold(2*period, t0+period/2).bin(.1).plot(ax=ax, c='r', lw=2) ax.set_xlim(0, period) ax.set_ylim(-3*depth, 2*depth) plt.grid(True) def plot_even(lc, period, t0, depth, ax): """ Plot the even transits for a given light curve. Parameters ---------- lc : lightkurve.LightCurve Light curve to plot. period : float Orbital period of the planet. t0 : float Epoch of the first transit. depth : float Depth of the transit. ax : matplotlib.pyplot.axis Axis to plot on. """ if ax is None: _, ax = plt.subplots(1) lc.fold(2*period, t0+period/2).scatter(ax=ax, c='gray', label='Even Transit', s=25) lc.fold(2*period, t0+period/2).bin(.1).plot(ax=ax, c='r', lw=2) ax.set_xlim(-period, 0) ax.set_ylim(-3*depth, 2*depth) plt.grid(True) def plot_tpf(target, ax): """ Plot the TPF for a given target. Parameters ---------- target : giants.Target Target object to plot. ax : matplotlib.pyplot.axis Axis to plot on. """ fnumber = 100 ax = target.tpf.plot(ax=ax, show_colorbar=True, frame=fnumber, title=f'TIC {target.ticid}, cadence {fnumber}') ax = add_gaia_figure_elements(target.tpf, ax) def plot_table(target, ktransit_model, depth_snr, dur, resid, ax): """ Include a table of transit parameters in the summary plot. Parameters ---------- target : giants.Target Target object to plot. ktransit_model : ktransit.ktransit.LCModel ktransit model object. depth_snr : float Depth SNR of the transit. dur : astropy.units.quantity.Quantity Duration of the transit. resid : float Scaled residuals of the transit. ax : matplotlib.pyplot.axis Axis to plot on. """ result = ktransit_model.fitresult[1:] col_labels = ['Period (days)', 'b', 't0', 'Rp/Rs', r'R$_P$ (R$_J$)', 'Duration (hours)', 'Depth SNR', 'Scaled Likelihood'] values = [f'{val:.3f}' for val in result] values.append(f'{float(values[-1]) * target.rstar * 9.731:.3f}') values.append(f'{dur.value:.3f}') values.append(f'{depth_snr:.3f}') values.append(f'{resid:.3f}') ax.axis('tight') ax.axis('off') tab = ax.table(list(zip(col_labels, values)), colLabels=None, loc='center', edges='open', fontsize=16) for r in range(0, len(col_labels)): cell = tab[r, 0] cell.set_height(0.175) cell = tab[r, 1] cell.set_height(0.175) def stellar_params(target): """ Retrieve stellar parameters for a given target. Parameters ---------- target : giants.Target Target object to plot. Returns ------- param_string : str String of stellar parameters. """ catalog_data = Catalogs.query_criteria(objectname=f'TIC {target.ticid}', catalog="Tic", radius=.0001, Bmag=[0,20]) ra = catalog_data['ra'][0] dec = catalog_data['dec'][0] coords = f'({ra:.2f}, {dec:.2f})' rstar = catalog_data['rad'][0] teff = catalog_data['Teff'][0] if np.isnan(rstar): rstar = '?' else: rstar = f'{rstar:.2f}' if np.isnan(teff): teff = '?' else: teff = f'{teff:.0f}' logg = catalog_data['logg'][0] if np.isnan(logg): logg = '?' else: logg = f'{logg:.2f}' V = catalog_data['Vmag'][0] param_string = rf'(RA, dec)={coords}, R_star={rstar} $R_\odot$, logg={logg}, Teff={teff} K, V={float(V):.2f}' return param_string
18,574
31.192374
160
py
giants
giants-main/src/giants/lomb.py
#!/usr/bin/env python """ Fast algorithm for spectral analysis of unevenly sampled data The Lomb-Scargle method performs spectral analysis on unevenly sampled data and is known to be a powerful way to find, and test the significance of, weak periodic signals. The method has previously been thought to be 'slow', requiring of order 10(2)N(2) operations to analyze N data points. We show that Fast Fourier Transforms (FFTs) can be used in a novel way to make the computation of order 10(2)N log N. Despite its use of the FFT, the algorithm is in no way equivalent to conventional FFT periodogram analysis. Keywords: DATA SAMPLING, FAST FOURIER TRANSFORMATIONS, SPECTRUM ANALYSIS, SIGNAL PROCESSING Example: > import numpy > import lomb > x = numpy.arange(10) > y = numpy.sin(x) > fx,fy, nout, jmax, prob = lomb.fasper(x,y, 6., 6.) Reference: Press, W. H. & Rybicki, G. B. 1989 ApJ vol. 338, p. 277-280. Fast algorithm for spectral analysis of unevenly sampled data bib code: 1989ApJ...338..277P """ from numpy import * from numpy.fft import * def __spread__(y, yy, n, x, m): """ Given an array yy(0:n-1), extirpolate (spread) a value y into m actual array elements that best approximate the "fictional" (i.e., possible noninteger) array element number x. The weights used are coefficients of the Lagrange interpolating polynomial Arguments: y : yy : n : x : m : Returns: """ nfac=[0,1,1,2,6,24,120,720,5040,40320,362880] if m > 10. : print( 'factorial table too small in spread' ) return ix=int(x) if x == float(ix): yy[ix]=yy[ix]+y else: ilo = int(x-0.5*float(m)+1.0) ilo = min( max( ilo , 1 ), n-m+1 ) ihi = ilo+m-1 nden = nfac[m] fac=x-ilo for j in range(ilo+1,ihi+1): fac = fac*(x-j) yy[ihi] = yy[ihi] + y*fac/(nden*(x-ihi)) for j in range(ihi-1,ilo-1,-1): nden=(nden/(j+1-ilo))*(j-ihi) yy[j] = yy[j] + y*fac/(nden*(x-j)) def fasper(x,y,ofac,hifac, MACC=4): """ function fasper Given abscissas x (which need not be equally spaced) and ordinates y, and given a desired oversampling factor ofac (a typical value being 4 or larger). this routine creates an array wk1 with a sequence of nout increasing frequencies (not angular frequencies) up to hifac times the "average" Nyquist frequency, and creates an array wk2 with the values of the Lomb normalized periodogram at those frequencies. The arrays x and y are not altered. This routine also returns jmax such that wk2(jmax) is the maximum element in wk2, and prob, an estimate of the significance of that maximum against the hypothesis of random noise. A small value of prob indicates that a significant periodic signal is present. Reference: Press, W. H. & Rybicki, G. B. 1989 ApJ vol. 338, p. 277-280. Fast algorithm for spectral analysis of unevenly sampled data (1989ApJ...338..277P) Arguments: X : Abscissas array, (e.g. an array of times). Y : Ordinates array, (e.g. corresponding counts). Ofac : Oversampling factor. Hifac : Hifac * "average" Nyquist frequency = highest frequency for which values of the Lomb normalized periodogram will be calculated. Returns: Wk1 : An array of Lomb periodogram frequencies. Wk2 : An array of corresponding values of the Lomb periodogram. Nout : Wk1 & Wk2 dimensions (number of calculated frequencies) Jmax : The array index corresponding to the MAX( Wk2 ). Prob : False Alarm Probability of the largest Periodogram value MACC : Number of interpolation points per 1/4 cycle of highest frequency History: 02/23/2009, v1.0, MF Translation of IDL code (orig. Numerical recipies) """ #Check dimensions of input arrays n = int(len(x)) if n != len(y): print( 'Incompatible arrays.' ) return nout = int(0.5*ofac*hifac*n) nfreqt = int(ofac*hifac*n*MACC) #Size the FFT as next power nfreq = 64 # of 2 above nfreqt. while nfreq < nfreqt: nfreq = 2*nfreq ndim = int(2*nfreq) #Compute the mean, variance ave = y.mean() ##sample variance because the divisor is N-1 var = ((y-y.mean())**2).sum()/(len(y)-1) # and range of the data. xmin = x.min() xmax = x.max() xdif = xmax-xmin #extirpolate the data into the workspaces wk1 = zeros(ndim, dtype='complex') wk2 = zeros(ndim, dtype='complex') fac = ndim/(xdif*ofac) fndim = ndim ck = ((x-xmin)*fac) % fndim ckk = (2.0*ck) % fndim for j in range(0, n): __spread__(y[j]-ave,wk1,ndim,ck[j],MACC) __spread__(1.0,wk2,ndim,ckk[j],MACC) #Take the Fast Fourier Transforms wk1 = ifft( wk1 )*len(wk1) wk2 = ifft( wk2 )*len(wk1) wk1 = wk1[1:nout+1] wk2 = wk2[1:nout+1] rwk1 = wk1.real iwk1 = wk1.imag rwk2 = wk2.real iwk2 = wk2.imag df = 1.0/(xdif*ofac) #Compute the Lomb value for each frequency hypo2 = 2.0 * abs( wk2 ) hc2wt = rwk2/hypo2 hs2wt = iwk2/hypo2 cwt = sqrt(0.5+hc2wt) swt = sign(hs2wt)*(sqrt(0.5-hc2wt)) den = 0.5*n+hc2wt*rwk2+hs2wt*iwk2 cterm = (cwt*rwk1+swt*iwk1)**2./den sterm = (cwt*iwk1-swt*rwk1)**2./(n-den) wk1 = df*(arange(nout, dtype='float')+1.) wk2 = (cterm+sterm)/(2.0*var) pmax = wk2.max() jmax = wk2.argmax() #Significance estimation #expy = exp(-wk2) #effm = 2.0*(nout)/ofac #sig = effm*expy #ind = (sig > 0.01).nonzero() #sig[ind] = 1.0-(1.0-expy[ind])**effm #Estimate significance of largest peak value expy = exp(-pmax) effm = 2.0*(nout)/ofac prob = effm*expy if prob > 0.01: prob = 1.0-(1.0-expy)**effm return wk1,wk2,nout,jmax,prob def getSignificance(wk1, wk2, nout, ofac): """ returns the peak false alarm probabilities Hence the lower is the probability and the more significant is the peak """ expy = exp(-wk2) effm = 2.0*(nout)/ofac sig = effm*expy ind = (sig > 0.01).nonzero() sig[ind] = 1.0-(1.0-expy[ind])**effm return sig
6,005
28.297561
73
py
giants
giants-main/src/giants/utils.py
import numpy as np from astropy.stats import BoxLeastSquares import lightkurve as lk import astropy.units as u from scipy.constants import G def _calculate_separation(m_star, period): """ Calculate the separation of a planet in a circular orbit around a star. Parameters ---------- m_star : float Mass of the star in solar masses. period : float Orbital period of the planet in days. Returns ------- a : float Semi-major axis of the planet in AU. """ a = (((G*m_star*u.solMass/(4*np.pi**2))*(period*u.day)**2)**(1/3)) return a.to(u.AU).value def get_cutout(ticid, cutout_size=9): """ Download a cutout of the TESS FFIs centered on a given TICID. Parameters ---------- ticid : int TICID of the target. cutout_size : int Size of the cutout in pixels. Default is 9. Returns ------- tpf : lightkurve.targetpixelfile.TessTargetPixelFile Cutout of the TESS FFIs centered on the target. """ tpf = lk.search_tesscut(ticid)[0].download(cutout_size=cutout_size) return tpf def build_ktransit_model(ticid, lc, period, t0, rprs=0.02, vary_transit=True): """ Create a ktransit model for a given target and fit it to the light curve. Parameters ---------- ticid : int TICID of the target. lc : lightkurve.lightcurve.TessLightCurve Light curve of the target. period : astropy.units.quantity.Quantity Orbital period of the planet. t0 : astropy.units.quantity.Quantity Time of first transit. rprs : float Radius of the planet in units of the stellar radius. Default is 0.02. Returns ------- fitT : ktransit.fittransit.FitTransit ktransit model fit to the light curve. """ from ktransit import FitTransit fitT = FitTransit() t0 = t0.value period = period.value fitT.add_guess_star(rho=0.022, zpt=0, ld1=0.6505,ld2=0.1041) fitT.add_guess_planet(T0=t0, period=period, impact=0.5, rprs=rprs) ferr = np.ones_like(lc.time.value) * 0.00001 fitT.add_data(time=lc.time.value,flux=lc.flux.value,ferr=ferr) vary_star = ['zpt'] # free stellar parameters if vary_transit: vary_planet = (['period', 'impact', # free planetary parameters 'T0', #'esinw', 'ecosw', 'rprs']) #'impact', # free planet parameters are the same for every planet you model else: vary_planet = (['rprs']) fitT.free_parameters(vary_star, vary_planet) fitT.do_fit() # run the fitting return fitT def _individual_ktransit_dur(time, data): """ Calculate the duration of a transit using ktransit. Parameters ---------- time : astropy.units.quantity.Quantity Time array of the light curve. data : astropy.units.quantity.Quantity Flux array of the light curve. Returns ------- dur : float Duration of the transit in hours. """ inds = np.where(data < np.median(data))[0] first_transit = np.split(inds, np.where(np.diff(inds) != 1)[0] + 1)[0] dur = (time[first_transit[-1]] - time[first_transit[0]]) * 24.0 return dur
3,255
27.313043
110
py
giants
giants-main/src/giants/__init__.py
import os PACKAGEDIR = os.path.abspath(os.path.dirname(__file__)) from .target import * from .plotting import * from .utils import *
133
21.333333
55
py
NeuralBKI
NeuralBKI-main/generate_results.py
# This file generates results for evaluation by loading semantic predictions from files. # Not intended for use on-board robot. import os import pdb import time import json import rospy import yaml os.environ["CUDA_LAUNCH_BLOCKING"] = "1" import numpy as np import copy from tqdm import tqdm # Torch imports import torch from torch import nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader from torch.utils.tensorboard import SummaryWriter # Custom Imports from Data.utils import * from Models.model_utils import * from Models.ConvBKI import * from Data.Rellis3D import Rellis3dDataset from Models.mapping_utils import * from Data.SemanticKitti import KittiDataset from Data.KittiOdometry import KittiOdomDataset import time MODEL_NAME = "ConvBKI_Single" # MODEL_NAME = "ConvBKI_Single_02_odom" print("Model is:", MODEL_NAME) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("device is ", device) # Model Parameters model_params_file = os.path.join(os.getcwd(), "Config", MODEL_NAME + ".yaml") with open(model_params_file, "r") as stream: try: model_params = yaml.safe_load(stream) dataset = model_params["dataset"] except yaml.YAMLError as exc: print(exc) # CONSTANTS SEED = model_params["seed"] NUM_FRAMES = model_params["num_frames"] MODEL_RUN_DIR = os.path.join("Models", "Runs", MODEL_NAME + "_" + dataset) NUM_WORKERS = model_params["num_workers"] FLOAT_TYPE = torch.float32 LABEL_TYPE = torch.uint8 MAP_METHOD = model_params["map_method"] LOAD_EPOCH = model_params["load_epoch"] LOAD_DIR = model_params["save_dir"] VISUALIZE = model_params["visualize"] MEAS_RESULT = model_params["meas_result"] GEN_PREDS = model_params["gen_preds"] FROM_CONT = model_params["from_continuous"] TO_CONT = model_params["to_continuous"] PRED_PATH = model_params["pred_path"] # Data Parameters data_params_file = os.path.join(os.getcwd(), "Config", dataset + ".yaml") with open(data_params_file, "r") as stream: try: data_params = yaml.safe_load(stream) NUM_CLASSES = data_params["num_classes"] colors = remap_colors(data_params["colors"]) DATA_DIR = data_params["data_dir"] ignore_labels = data_params["ignore_labels"] except yaml.YAMLError as exc: print(exc) print("Visualize Prediciton:", VISUALIZE) print("Measure Result:", MEAS_RESULT) print("Generate Prediction:", GEN_PREDS) print("") # Exit if measure result on test set if MEAS_RESULT and model_params["result_split"] == "test": print("Error! Measure result can only be ran on train/val sets, test set does not have ground truth labels.") exit() # Load data set if dataset == "rellis": test_ds = Rellis3dDataset(model_params["test"]["grid_params"], directory=DATA_DIR, device=device, num_frames=NUM_FRAMES, remap=True, use_aug=False, data_split="test") elif dataset == "semantic_kitti": if MEAS_RESULT: test_ds = KittiDataset(model_params["test"]["grid_params"], directory=DATA_DIR, device=device, num_frames=NUM_FRAMES, remap=True, use_aug=False, data_split=model_params["result_split"], from_continuous=FROM_CONT, to_continuous=TO_CONT, pred_path=PRED_PATH) else: test_ds = KittiDataset(model_params["test"]["grid_params"], directory=DATA_DIR, device=device, num_frames=NUM_FRAMES, remap=True, use_aug=False, data_split=model_params["result_split"], from_continuous=FROM_CONT, to_continuous=TO_CONT, pred_path=PRED_PATH) elif dataset == "kitti_odometry": if MEAS_RESULT: test_ds = KittiOdomDataset(model_params["train"]["grid_params"], directory=DATA_DIR, device=device, num_frames=NUM_FRAMES, remap=False, use_aug=False, data_split=model_params["result_split"], from_continuous=FROM_CONT, to_continuous=TO_CONT) else: test_ds = KittiOdomDataset(model_params["train"]["grid_params"], directory=DATA_DIR, device=device, num_frames=NUM_FRAMES, remap=False, use_aug=False, data_split=model_params["result_split"], from_continuous=FROM_CONT, to_continuous=TO_CONT) dataloader_test = DataLoader(test_ds, batch_size=1, shuffle=False, collate_fn=test_ds.collate_fn, num_workers=NUM_WORKERS, pin_memory=True) # Create map object grid_params = model_params["test"]["grid_params"] map_object = GlobalMap( torch.tensor([int(p) for p in grid_params['grid_size']], dtype=torch.long).to(device), # Grid size torch.tensor(grid_params['min_bound']).to(device), # Lower bound torch.tensor(grid_params['max_bound']).to(device), # Upper bound torch.load(os.path.join("Models", "Weights", LOAD_DIR, "filters" + str(LOAD_EPOCH) + ".pt")), # Filters model_params["filter_size"], # Filter size num_classes=NUM_CLASSES, ignore_labels = ignore_labels, # Classes device=device # Device ) if VISUALIZE: rospy.init_node('talker', anonymous=True) map_pub = rospy.Publisher('SemMap_global', MarkerArray, queue_size=10) next_map = MarkerArray() if GEN_PREDS: if not os.path.exists(MODEL_NAME): os.mkdir(MODEL_NAME) # Iteratively loop through each scan current_scene = None current_frame_id = None seq_dir = None frame_num = 0 total_class = torch.zeros(map_object.num_classes, device=device) total_int_bki = torch.zeros(map_object.num_classes, device=device) total_int_seg = torch.zeros(map_object.num_classes, device=device) total_un_bki = torch.zeros(map_object.num_classes, device=device) total_un_seg = torch.zeros(map_object.num_classes, device=device) total_t = 0.0 for idx in tqdm(range(len(test_ds))): with torch.no_grad(): # Load data get_gt = model_params["result_split"] == "train" or model_params["result_split"] == "val" pose, points, pred_labels, gt_labels, scene_id, frame_id = test_ds.get_test_item(idx, get_gt=get_gt) if VISUALIZE and MEAS_RESULT: if dataset == "semantic_kitti": not_void = (gt_labels != 0)[:, 0] points = points[not_void, :] pred_labels = pred_labels[not_void, :] gt_labels = gt_labels[not_void, :] if GEN_PREDS and seq_dir is None: seq_dir = os.path.join(MODEL_NAME, "sequences", str(scene_id).zfill(2), "predictions") # Reset if new subsequence if scene_id != current_scene or (frame_id - 1) != current_frame_id: map_object.reset_grid() if GEN_PREDS: seq_dir = os.path.join(MODEL_NAME, "sequences", str(scene_id).zfill(2), "predictions") frame_num = 0 if not os.path.exists(seq_dir): os.makedirs(seq_dir) # Update pose if not start_t = time.time() map_object.propagate(pose) # Add points to map labeled_pc = np.hstack((points, pred_labels)) labeled_pc_torch = torch.from_numpy(labeled_pc).to(device=device, non_blocking=True) map_object.update_map(labeled_pc_torch) total_t += time.time() - start_t current_scene = scene_id current_frame_id = frame_id if VISUALIZE: if rospy.is_shutdown(): exit("Closing Python") try: if MAP_METHOD == "global" or MAP_METHOD == "local": map = publish_voxels(map_object, grid_params['min_bound'], grid_params['max_bound'], grid_params['grid_size'], colors, next_map) map_pub.publish(map) elif MAP_METHOD == "local": map = publish_local_map(map_object.local_map, map_object.centroids, grid_params, colors, next_map) map_pub.publish(map) except: exit("Publishing broke") if MEAS_RESULT: if dataset == "semantic_kitti": # Filter out ignore labels non_ignore_mask = (gt_labels != ignore_labels[0])[:, 0] points = points[non_ignore_mask, :] gt_labels = gt_labels[non_ignore_mask, :] pred_labels = pred_labels[non_ignore_mask, :] # Make predictions and measure predictions, local_mask = map_object.label_points(points) pred_labels = torch.from_numpy(pred_labels).to(device, non_blocking=True) if pred_labels.shape[1] > 1: pred_labels = torch.argmax(pred_labels, dim=1) else: pred_labels = pred_labels.view(-1) gt_labels = torch.from_numpy(gt_labels).to(device, non_blocking=True).view(-1) # TODO: Change this line if needed. Maps outside local mask to segmentation labels. predictions_temp = pred_labels.detach().clone().to(predictions.dtype) predictions_temp[local_mask] = predictions[local_mask] predictions = predictions_temp for i in range(1, map_object.num_classes): gt_i = gt_labels == i pred_bki_i = predictions == i pred_seg_i = pred_labels == i total_class[i] += torch.sum(gt_i) total_int_bki[i] += torch.sum(gt_i & pred_bki_i) total_int_seg[i] += torch.sum(gt_i & pred_seg_i) total_un_bki[i] += torch.sum(gt_i | pred_bki_i) total_un_seg[i] += torch.sum(gt_i | pred_seg_i) if idx % 100 == 0 and not GEN_PREDS: print(idx, len(test_ds)) print("BKI:", total_int_bki / total_un_bki * 100) print("Seg:", total_int_seg / total_un_seg * 100) if dataset == "kitti_odometry": dists = np.linalg.norm(points, axis=1) in_range = dists < 40 points = points[in_range, :] gt_labels = gt_labels[in_range] pred_labels = pred_labels[in_range] predictions, local_mask = map_object.label_points(points) pred_labels = torch.from_numpy(pred_labels).to(device, non_blocking=True) if pred_labels.shape[1] > 1: pred_labels = torch.argmax(pred_labels, dim=1) else: pred_labels = pred_labels.view(-1) gt_labels = torch.from_numpy(gt_labels).to(device, non_blocking=True).view(-1) # TODO: Mask here? gt_labels[~local_mask] = ignore_labels[0] pred_labels[~local_mask] = ignore_labels[0] for i in range(map_object.num_classes): gt_i = gt_labels == i pred_bki_i = predictions == i pred_seg_i = pred_labels == i total_class[i] += torch.sum(gt_i) total_int_bki[i] += torch.sum(gt_i & pred_bki_i) total_int_seg[i] += torch.sum(gt_i & pred_seg_i) total_un_bki[i] += torch.sum(gt_i | pred_bki_i) total_un_seg[i] += torch.sum(gt_i | pred_seg_i) if GEN_PREDS: frame_file = os.path.join(seq_dir, str(frame_num).zfill(6) + ".label") # Make predictions predictions, local_mask = map_object.label_points(points) if MEAS_RESULT: pred_labels = torch.unsqueeze(pred_labels, dim=-1) if pred_labels.shape[1] > 1: pred_labels = torch.argmax(pred_labels, dim=1) else: pred_labels = pred_labels.view(-1) else: pred_labels = torch.from_numpy(pred_labels).to(device) if pred_labels.shape[1] > 1: pred_labels = torch.argmax(pred_labels, dim=1) else: pred_labels = pred_labels.view(-1) # Maps outside local mask to segmentation labels. predictions_temp = pred_labels.detach().clone().to(predictions.dtype) predictions_temp[local_mask] = predictions[local_mask] predictions = predictions_temp.view(-1).detach().cpu().numpy().astype(np.uint32) # Save predictions.tofile(frame_file) frame_num += 1 if MEAS_RESULT: print("Final results:") if dataset == "kitti_odometry": bki_result = (total_int_bki / total_un_bki * 100).detach().cpu().numpy() seg_result = (total_int_seg / total_un_seg * 100).detach().cpu().numpy() bki_result_t = copy.deepcopy(bki_result) seg_result_t = copy.deepcopy(seg_result) Shift = [0, 1, 2, 3, 4, 7, 5, 8, 9, 6, 10] for i, label in enumerate(Shift): bki_result[label] = bki_result_t[i] seg_result[label] = seg_result_t[i] print("BKI:") for i in range(bki_result.shape[0]-3): print(bki_result[i]) print("Seg:") for i in range(seg_result.shape[0]-3): print(seg_result[i]) else: print("Seg:") for i in range(NUM_CLASSES): print((total_int_seg[i] / total_un_seg[i] * 100).item()) print("BKI:") for i in range(NUM_CLASSES): print((total_int_bki[i] / total_un_bki[i] * 100).item())
13,528
41.410658
150
py
NeuralBKI
NeuralBKI-main/train.py
import os import pdb import time import json import yaml os.environ["CUDA_LAUNCH_BLOCKING"] = "1" import numpy as np from tqdm import tqdm # Torch imports import torch from torch import nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader from torch.utils.tensorboard import SummaryWriter # Custom Imports from Data.utils import * from Models.model_utils import * from Models.ConvBKI import * from Data.Rellis3D import Rellis3dDataset from Data.SemanticKitti import KittiDataset from Data.KittiOdometry import KittiOdomDataset MODEL_NAME = "ConvBKI_Single" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("device is ", device) print("Model is", MODEL_NAME) model_params_file = os.path.join(os.getcwd(), "Config", MODEL_NAME + ".yaml") with open(model_params_file, "r") as stream: try: model_params = yaml.safe_load(stream) dataset = model_params["dataset"] SAVE_NAME = model_params["save_dir"] except yaml.YAMLError as exc: print(exc) # CONSTANTS SEED = model_params["seed"] DEBUG_MODE = model_params["debug_mode"] NUM_FRAMES = model_params["num_frames"] MODEL_RUN_DIR = os.path.join("Models", "Runs", SAVE_NAME) NUM_WORKERS = model_params["num_workers"] FLOAT_TYPE = torch.float32 LABEL_TYPE = torch.uint8 FROM_CONT = model_params["from_continuous"] TO_CONT = model_params["to_continuous"] PRED_PATH = model_params["pred_path"] time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S") if not os.path.exists(MODEL_RUN_DIR): WEIGHTS_DIR = os.path.join("Models", "Weights") if os.path.exists(WEIGHTS_DIR): MODEL_RUN_DIR = MODEL_RUN_DIR + "_" + time_stamp os.makedirs(MODEL_RUN_DIR) # Data Parameters data_params_file = os.path.join(os.getcwd(), "Config", dataset + ".yaml") with open(data_params_file, "r") as stream: try: data_params = yaml.safe_load(stream) NUM_CLASSES = data_params["num_classes"] class_frequencies = np.asarray([data_params["class_counts"][i] for i in range(NUM_CLASSES)]) TRAIN_DIR = data_params["data_dir"] except yaml.YAMLError as exc: print(exc) epsilon_w = 1e-5 # eps to avoid zero division # TODO: Try counting for seq 4, ablation studies on seq 4 weights = np.zeros(class_frequencies.shape) weights[1:] = (1 / np.log(class_frequencies[1:] + epsilon_w) ) weights = torch.from_numpy(weights).to(dtype=FLOAT_TYPE, device=device, non_blocking=True) criterion = nn.NLLLoss(weight=weights, ignore_index=0) scenes = [ s for s in sorted(os.listdir(TRAIN_DIR)) if s.isdigit() ] # Load model lr = model_params["train"]["lr"] BETA1 = model_params["train"]["BETA1"] BETA2 = model_params["train"]["BETA2"] decayRate = model_params["train"]["decayRate"] B = model_params["train"]["B"] EPOCH_NUM = model_params["train"]["num_epochs"] model_params["device"] = device model_params["num_classes"] = NUM_CLASSES model_params["datatype"] = FLOAT_TYPE model = get_model(MODEL_NAME, model_params=model_params) if dataset == "rellis": train_ds = Rellis3dDataset(model_params["train"]["grid_params"], directory=TRAIN_DIR, device=device, num_frames=NUM_FRAMES, remap=True, use_aug=False) val_ds = Rellis3dDataset(model_params["train"]["grid_params"], directory=TRAIN_DIR, device=device, num_frames=NUM_FRAMES, remap=True, use_aug=False, data_split="val") if dataset == "semantic_kitti": # Save splits info train_ds = KittiDataset(model_params["train"]["grid_params"], directory=TRAIN_DIR, device=device, num_frames=NUM_FRAMES, remap=True, use_aug=True, data_split="train", from_continuous=FROM_CONT, to_continuous=TO_CONT, pred_path=PRED_PATH) val_ds = KittiDataset(model_params["train"]["grid_params"], directory=TRAIN_DIR, device=device, num_frames=NUM_FRAMES, remap=True, use_aug=False, data_split="val", from_continuous=FROM_CONT, to_continuous=TO_CONT, pred_path=PRED_PATH) if dataset == "kitti_odometry": train_ds = KittiOdomDataset(model_params["train"]["grid_params"], directory=TRAIN_DIR, device=device, num_frames=NUM_FRAMES, remap=False, use_aug=False, data_split="train", from_continuous=FROM_CONT, to_continuous=TO_CONT, num_classes=model_params["num_classes"]) val_ds = KittiOdomDataset(model_params["train"]["grid_params"], directory=TRAIN_DIR, device=device, num_frames=NUM_FRAMES, remap=False, use_aug=False, data_split="val", from_continuous=FROM_CONT, to_continuous=TO_CONT, num_classes=model_params["num_classes"]) dataloader_train = DataLoader(train_ds, batch_size=B, shuffle=True, collate_fn=train_ds.collate_fn, num_workers=NUM_WORKERS, pin_memory=True) dataloader_val = DataLoader(val_ds, batch_size=B, shuffle=False, collate_fn=val_ds.collate_fn, num_workers=NUM_WORKERS, pin_memory=True) trial_dir = MODEL_RUN_DIR save_dir = os.path.join("Models", "Weights", SAVE_NAME) if not DEBUG_MODE: if os.path.exists(save_dir): save_dir_before = save_dir save_dir = save_dir + "_" + time_stamp print("Pretrained model already exists at: {}, the new trained model will be saved at: {} \n".format(save_dir_before, save_dir)) if not os.path.exists(trial_dir): os.makedirs(trial_dir) if not os.path.exists(save_dir): os.makedirs(save_dir) writer = SummaryWriter(MODEL_RUN_DIR) # Optimizer setup setup_seed(SEED) if model_params["train"]["opt"] == "Adam": optimizer = optim.Adam(model.parameters(), lr=lr, betas=(BETA1, BETA2)) else: optimizer = optim.SGD(model.parameters(), lr=lr) my_lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer=optimizer, gamma=decayRate) torch.optim.lr_scheduler.CosineAnnealingLR(optimizer=optimizer, T_max=100, eta_min=1e-4, verbose=True) train_count = 0 min_bound_torch = torch.from_numpy(train_ds.min_bound).to(device=device) grid_dims_torch = torch.from_numpy(train_ds.grid_dims).to(dtype=torch.int, device=device) voxel_sizes_torch = torch.from_numpy(train_ds.voxel_sizes).to(device=device) if DEBUG_MODE: rospy.init_node('talker', anonymous=True) map_pub = rospy.Publisher('SemMap_global', MarkerArray, queue_size=10) def semantic_loop(dataloader, epoch, train_count=None, training=False): num_correct = 0 num_total = 0 all_intersections = np.zeros(NUM_CLASSES) all_unions = np.zeros(NUM_CLASSES) + 1e-6 # SMOOTHING next_map = MarkerArray() for points, points_labels, gt_labels in tqdm(dataloader): batch_gt = torch.zeros((0, 1), device=device, dtype=LABEL_TYPE) batch_preds = torch.zeros((0, NUM_CLASSES), device=device, dtype=FLOAT_TYPE) optimizer.zero_grad() for b in range(len(points)): current_map = model.initialize_grid() if model_params["train"]["remove_last"]: pc_np = np.vstack(np.array(points[b][:-1])) labels_np = np.vstack(np.array(points_labels[b][:-1])) else: pc_np = np.vstack(np.array(points[b], dtype=object)) labels_np = np.vstack(np.array(points_labels[b], dtype=object)) labeled_pc = np.hstack((pc_np, labels_np)) if labeled_pc.shape[0] == 0: # Zero padded print("Something is very wrong!") exit() labeled_pc_torch = torch.from_numpy(labeled_pc).to(device=device, non_blocking=True) preds = model(current_map, labeled_pc_torch) gt_sem_labels = torch.from_numpy(gt_labels[b]).to(device=device, non_blocking=True) if DEBUG_MODE: grid_params = model_params["test"]["grid_params"] colors = remap_colors(data_params["colors"]) if rospy.is_shutdown(): exit("Closing Python") try: next_map = publish_local_map(preds, model.centroids, grid_params, colors, next_map) map_pub.publish(next_map) except: exit("Publishing broke") last_pc_torch = torch.from_numpy(points[b][-1]).to(device=device, non_blocking=True) sem_preds = points_to_voxels_torch(preds, last_pc_torch, min_bound_torch, grid_dims_torch, voxel_sizes_torch) # Evaluate on last frame in scan (most recent one) sem_preds = sem_preds / torch.sum(sem_preds, dim=-1, keepdim=True) # Remove all that are 0 zero label # TODO change to use ignore list non_void_mask = gt_sem_labels[:, 0] != 0 batch_gt = torch.vstack((batch_gt, gt_sem_labels[non_void_mask, :])) batch_preds = torch.vstack((batch_preds, sem_preds[non_void_mask, :])) batch_gt = batch_gt.reshape(-1) # Remove ignore labels not_ignore_mask = batch_gt != 0 batch_preds = batch_preds[not_ignore_mask, :] batch_gt = batch_gt[not_ignore_mask] loss = criterion(torch.log(batch_preds), batch_gt.long()) if training: if DEBUG_MODE: if model.compound: print("Z:", model.ell_z) print("H:", model.ell_h) else: print(model.ell) loss.backward() optimizer.step() # Accuracy with torch.no_grad(): # Softmax on expectation max_batch_preds = torch.argmax(batch_preds, dim=-1) preds_masked = max_batch_preds.cpu().numpy() voxels_np = batch_gt.detach().cpu().numpy() num_correct += np.sum(preds_masked == voxels_np) num_total += voxels_np.shape[0] accuracy = np.sum(preds_masked == voxels_np) / voxels_np.shape[0] inter, union = iou_one_frame(max_batch_preds, batch_gt, n_classes=NUM_CLASSES) union += 1e-6 all_intersections += inter all_unions += union # Record if training: writer.add_scalar(SAVE_NAME + '/Loss/Train', loss.item(), train_count) writer.add_scalar(SAVE_NAME + '/Accuracy/Train', accuracy, train_count) writer.add_scalar(SAVE_NAME + '/mIoU/Train', np.mean(inter / union), train_count) train_count += len(points) # Save model, decrease learning rate if training: my_lr_scheduler.step() print("Epoch ", epoch, " out of ", EPOCH_NUM, " complete.") if not training: all_intersections = all_intersections[all_unions > 0] all_unions = all_unions[all_unions > 0] print(f'Epoch Num: {epoch} ------ average val accuracy: {num_correct/num_total}') print(f'Epoch Num: {epoch} ------ val miou: {np.mean(all_intersections / all_unions)}') writer.add_scalar(SAVE_NAME + '/Accuracy/Val', num_correct/num_total, epoch) writer.add_scalar(SAVE_NAME + '/mIoU/Val', np.mean(all_intersections / all_unions), epoch) return model, train_count def save_filter(model, save_path): filters = model.get_filters() torch.save(filters, save_path) print("Evaluation on the default kernel:") for epoch in range(EPOCH_NUM): # Save filters before any training if not DEBUG_MODE: save_filter(model, os.path.join(save_dir, "filters" + str(epoch) + ".pt")) # Validation model.eval() with torch.no_grad(): semantic_loop(dataloader_val, epoch, training=False) # Training model.train() idx = 0 model, train_count = semantic_loop(dataloader_train, epoch, train_count=train_count, training=True) # Validation epoch = EPOCH_NUM model.eval() with torch.no_grad(): semantic_loop(dataloader_val, epoch, training=False) save_filter(model, os.path.join(save_dir, "filters" + str(epoch) + ".pt")) writer.close()
11,927
39.989691
141
py
NeuralBKI
NeuralBKI-main/Data/KittiOdometry.py
import os import numpy as np # from utils import laserscan import yaml from torch.utils.data import Dataset import torch # import spconv import math from scipy.spatial.transform import Rotation as R config_file = os.path.join('Config/kitti_odometry.yaml') kitti_config = yaml.safe_load(open(config_file, 'r')) SPLIT_SEQUENCES = kitti_config["SPLIT_SEQUENCES"] def grid_ind(input_pc, labels, min_bound, max_bound, grid_size, voxel_sizes): ''' Input: input_xyz: N * (x, y, z, c) float32 array, point cloud Output: grid_inds: N' * (x, y, z, c) int32 array, point cloud mapped to voxels ''' input_xyz = input_pc[:, :3] valid_input_mask = np.all((input_xyz < max_bound) & (input_xyz >= min_bound), axis=1) valid_xyz = input_xyz[valid_input_mask] labels = labels[valid_input_mask] grid_inds = np.floor((valid_xyz - min_bound) / voxel_sizes) maxes = (grid_size - 1).reshape(1, 3) clipped_inds = np.clip(grid_inds, np.zeros_like(maxes), maxes) return clipped_inds, labels, valid_xyz class KittiOdomDataset(Dataset): """Kitti Dataset for Neural BKI project Access to the processed data, including evaluation labels predictions velodyne poses times """ def __init__(self, grid_params, directory="/home/jason/kitti_odometry", device='cuda', num_frames=1, voxelize_input=True, binary_counts=False, random_flips=False, use_aug=True, apply_transform=True, remap=False, from_continuous=False, to_continuous=False, num_classes = 20, data_split='train' ): self.use_aug = use_aug self.apply_transform = apply_transform self._grid_size = grid_params['grid_size'] self.grid_dims = np.asarray(self._grid_size) self._eval_size = list(np.uint32(self._grid_size)) self.coor_ranges = grid_params['min_bound'] + grid_params['max_bound'] self.voxel_sizes = [abs(self.coor_ranges[3] - self.coor_ranges[0]) / self._grid_size[0], abs(self.coor_ranges[4] - self.coor_ranges[1]) / self._grid_size[1], abs(self.coor_ranges[5] - self.coor_ranges[2]) / self._grid_size[2]] self.min_bound = np.asarray(self.coor_ranges[:3]) self.max_bound = np.asarray(self.coor_ranges[3:]) self.voxel_sizes = np.asarray(self.voxel_sizes) self.voxelize_input = voxelize_input self.binary_counts = binary_counts self._directory = directory self._num_frames = num_frames self.device = device self.random_flips = random_flips self.remap = remap self.from_continuous = from_continuous self.to_continuous = to_continuous self.num_classes = num_classes self.split = data_split self._velodyne_list = [] self._label_list = [] self._pred_list = [] self._frames_list = [] self._poses = np.empty((0,12)) self._num_frames_scene = [] self._frames_list_label = [] self._seqs = SPLIT_SEQUENCES[self.split] self._scene_id = [] for seq in self._seqs: velodyne_dir = os.path.join(self._directory, seq, 'training/pointcloud') label_dir = os.path.join(self._directory, seq, 'training/labels') if self.from_continuous: preds_dir = os.path.join(self._directory, seq, 'training/predictions_continuous') else: preds_dir = os.path.join(self._directory, seq, 'training/predictions') self._num_frames_scene.append(len(os.listdir(label_dir))) self._scene_id += [seq] * len(os.listdir(velodyne_dir)) frames_list = [os.path.splitext(filename)[0] for filename in sorted(os.listdir(velodyne_dir))] frames_list_label = [os.path.splitext(filename)[0] for filename in sorted(os.listdir(label_dir))] self._frames_list_label = frames_list_label pose = np.loadtxt(os.path.join(self._directory, seq, 'training/CameraTrajectory.txt'))[:(len(frames_list))] self._poses = np.vstack((self._poses, pose)) self._frames_list.extend(frames_list) self._velodyne_list.extend([os.path.join(velodyne_dir, str(frame).zfill(6)+'.bin') for frame in frames_list]) self._label_list.extend([os.path.join(label_dir, str(frame).zfill(6)+'.label') for frame in frames_list_label]) if self.from_continuous: self._pred_list.extend([os.path.join(preds_dir, str(frame).zfill(6)+'.bin') for frame in frames_list]) else: self._pred_list.extend([os.path.join(preds_dir, str(frame).zfill(6)+'.label') for frame in frames_list]) self._poses = self._poses.reshape(len(frames_list), 12) def collate_fn(self, data): points_batch = [bi[0] for bi in data] label_batch = [bi[1] for bi in data] gt_label_batch = [bi[2] for bi in data] return points_batch, label_batch, gt_label_batch def get_aug_matrix(self, trans): """ trans - 1 or 2 specifies reflection about XZ or YZ plane any other value gives rotation matrix Double checked with rotation matrix calculator """ if trans==1: trans = np.eye(3) trans[1][1] = -1 elif trans==2: trans = np.eye(3) trans[0][0] = -1 else: if trans==0: angle = 0 else: angle = (trans-2)*90 trans = R.from_euler('z', angle, degrees=True).as_matrix() return trans def get_pose(self, frame_id): pose = np.zeros((4, 4)) pose[3, 3] = 1 pose[:3, :4] = self._poses[frame_id,:].reshape(3, 4) R = np.array(([0, -1, 0], [0, 0, -1], [1, 0, 0])) #kitti odometry to rviz coords R_4 = np.zeros((4,4)) R_4[:3,:3] = R R_4[3,3] = 1 pose = np.matmul(np.linalg.inv(R_4), np.matmul(pose, R_4)) global_pose = pose.astype(np.float32) return global_pose # Use all frames, if there is no data then zero pad def __len__(self): return sum(self._num_frames_scene) def __getitem__(self, idx): # -1 indicates no data # the final index is the output idx_2 = int(self._frames_list_label[idx]) idx_range = self.find_horizon(idx_2) current_points = [] current_labels = [] ego_pose = self.get_pose(idx_range[-1]) to_ego = np.linalg.inv(ego_pose) aug_index = np.random.randint(0,3) # Set end idx to 6 to do rotations aug_mat = self.get_aug_matrix(aug_index) gt_labels = None temp_gt_labels = np.fromfile(self._label_list[idx], dtype=np.uint8).reshape((-1)) for i in idx_range: if i == -1: # Zero pad points = np.zeros((1, 3), dtype=np.float32) if self.to_continuous: labels = np.zeros((1,self.num_classes), dtype=np.float32) else: labels = np.zeros((1, 1), dtype=np.uint8) else: points = np.fromfile(self._velodyne_list[i],dtype=np.float32).reshape(-1,3) if self.apply_transform: global_pose = self.get_pose(i) relative_pose = np.matmul(to_ego, global_pose) points = np.dot(relative_pose[:3, :3], points.T).T + relative_pose[:3, 3] if self.from_continuous: labels = np.fromfile(self._pred_list[i], dtype=np.uint8).reshape((-1, self.num_classes)) labels = (labels / 255).astype(np.float32) if not self.to_continuous: labels = np.argmax(labels, axis=1).reshape((-1, 1)).astype(np.uint8) else: labels = np.fromfile(self._pred_list[i], dtype=np.uint8).reshape((-1, 1)) # Perform data augmentation on points if self.use_aug: points = (aug_mat @ points.T).T # Filter points outside of voxel grid if i == idx_range[-1]: grid_point_mask = np.all( (points < self.max_bound) & (points >= self.min_bound), axis=1) points = points[grid_point_mask, :] temp_gt_labels = temp_gt_labels[grid_point_mask] labels = labels[grid_point_mask,:] # Remove ignored classes (sky, person, bicycle) ignored_classes = np.all((temp_gt_labels != 7, temp_gt_labels != 8, temp_gt_labels != 10), axis=0) points = points[ignored_classes, :] temp_gt_labels = temp_gt_labels[ignored_classes] labels = labels[ignored_classes,:] gt_labels = temp_gt_labels else: grid_point_mask = np.all( (points < self.max_bound) & (points >= self.min_bound), axis=1) points = points[grid_point_mask, :] labels = labels[grid_point_mask, :] # Remove zero labels if self.from_continuous: labels_t = np.argmax(labels, axis=1).reshape((-1, 1)).astype(np.uint8) else: labels_t = labels # Remove ignored classes (sky, person, bicycle) ignored_classes = np.all((labels_t != 7,labels_t != 8,labels_t != 10), axis=0).squeeze() points = points[ignored_classes, :] labels = labels[ignored_classes, :] points = points.astype(np.float32) current_points.append(points) current_labels.append(labels) return current_points, current_labels, gt_labels.astype(np.uint8).reshape(-1, 1) def find_horizon(self, idx): end_idx = idx idx_range = np.arange(idx-self._num_frames, idx)+1 diffs = np.asarray([int(self._frames_list[end_idx]) - int(self._frames_list[i]) for i in idx_range]) good_difs = -1 * (np.arange(-self._num_frames, 0) + 1) idx_range[good_difs != diffs] = -1 return idx_range def points_to_voxels(self, voxel_grid, points, t_i): # Valid voxels (make sure to clip) valid_point_mask= np.all( (points < self.max_bound) & (points >= self.min_bound), axis=1) valid_points = points[valid_point_mask, :] voxels = np.floor((valid_points - self.min_bound) / self.voxel_sizes).astype(int) # Clamp to account for any floating point errors maxes = np.reshape(self.grid_dims - 1, (1, 3)) mins = np.zeros_like(maxes) voxels = np.clip(voxels, mins, maxes).astype(int) # This line is needed to create a mask with number of points, not just binary occupied if self.binary_counts: voxel_grid[t_i, voxels[:, 0], voxels[:, 1], voxels[:, 2]] += 1 else: unique_voxels, counts = np.unique(voxels, return_counts=True, axis=0) unique_voxels = unique_voxels.astype(int) voxel_grid[t_i, unique_voxels[:, 0], unique_voxels[:, 1], unique_voxels[:, 2]] += counts return voxel_grid def get_test_item(self, idx, get_gt=False): frame_id = idx # Frame ID in current scene ID idx_2 = int(self._frames_list_label[idx]) frame_id_2 = idx_2 global_pose = self.get_pose(frame_id_2) if frame_id > 0: prior_pose = self.get_pose(frame_id_2 - 1) else: prior_pose = global_pose points = np.fromfile(self._velodyne_list[frame_id_2], dtype=np.float32).reshape(-1, 3)[:, :3] if get_gt: gt_labels = np.fromfile(self._label_list[frame_id], dtype=np.uint8).reshape((-1)) if self.from_continuous: pred_labels = np.fromfile(self._pred_list[frame_id_2], dtype=np.uint8).reshape((-1, self.num_classes)) pred_labels = (pred_labels / 255).astype(np.float32) if not self.to_continuous: pred_labels = np.argmax(pred_labels, axis=1).reshape((-1, 1)) else: pred_labels = np.fromfile(self._pred_list[frame_id_2], dtype=np.uint8).reshape((-1, 1)) # Filter points outside of voxel grid grid_point_mask = np.all( (points < self.max_bound) & (points >= self.min_bound), axis=1) points = points[grid_point_mask, :] if get_gt: gt_labels = gt_labels[grid_point_mask] pred_labels = pred_labels[grid_point_mask, :] # Remove ignored classes (sky, person, bicycle) if get_gt: ignored_classes = np.all((gt_labels != 7,gt_labels != 8,gt_labels != 10), axis=0).squeeze() points = points[ignored_classes, :] pred_labels = pred_labels[ignored_classes, :] gt_labels = gt_labels[ignored_classes] else: ignored_classes = np.all((pred_labels != 7,pred_labels != 8,pred_labels != 10), axis=0).squeeze() points = points[ignored_classes, :] pred_labels = pred_labels[ignored_classes, :] scene_id = self._scene_id[idx] if get_gt: return global_pose, points, pred_labels, gt_labels.astype(np.uint8).reshape(-1, 1), scene_id, frame_id else: return global_pose, points, pred_labels, None, scene_id, frame_id
14,054
40.217009
123
py
NeuralBKI
NeuralBKI-main/Data/utils.py
import os import pdb from matplotlib import markers import rospy import numpy as np import time import os import pdb import torch from visualization_msgs.msg import * from geometry_msgs.msg import Point32 from std_msgs.msg import ColorRGBA # Intersection, union for one frame def iou_one_frame(pred, target, n_classes=21): pred = pred.reshape(-1) target = target.reshape(-1) intersection = np.zeros(n_classes) union = np.zeros(n_classes) for cls in range(n_classes): pred_inds = pred == cls target_inds = target == cls intersection[cls] = (pred_inds[target_inds]).long().sum().item() # Cast to long to prevent overflows union[cls] = pred_inds.long().sum().item() + target_inds.long().sum().item() - intersection[cls] return intersection, union def points_to_voxels_torch(voxel_grid, points, min_bound, grid_dims, voxel_sizes): voxels = torch.floor((points - min_bound) / voxel_sizes).to(dtype=torch.int) # Clamp to account for any floating point errors maxes = (grid_dims - 1).reshape(1, 3) mins = torch.zeros_like(maxes) voxels = torch.clip(voxels, mins, maxes).to(dtype=torch.long) voxel_grid = voxel_grid[voxels[:, 0], voxels[:, 1], voxels[:, 2]] return voxel_grid # Remap colors to np array 0 to 1 def remap_colors(colors): # color colors_temp = np.zeros((len(colors), 3)) for i in range(len(colors)): colors_temp[i, :] = colors[i] colors = colors_temp.astype("int") colors = colors / 255.0 return colors def publish_voxels(map_object, min_dim, max_dim, grid_dims, colors, next_map): next_map.markers.clear() marker = Marker() marker.id = 0 marker.ns = "Global_Semantic_Map" marker.header.frame_id = "map" # change this to match model + scene name LMSC_000001 marker.type = marker.CUBE_LIST marker.action = marker.ADD marker.lifetime.secs = 0 marker.header.stamp = rospy.Time.now() marker.pose.orientation.x = 0.0 marker.pose.orientation.y = 0.0 marker.pose.orientation.z = 0.0 marker.pose.orientation.w = 1 marker.scale.x = (max_dim[0] - min_dim[0]) / grid_dims[0] marker.scale.y = (max_dim[1] - min_dim[1]) / grid_dims[1] marker.scale.z = (max_dim[2] - min_dim[2]) / grid_dims[2] semantic_labels = map_object.global_map[:,3:] centroids = map_object.global_map[:, :3] # Threshold here total_probs = np.sum(semantic_labels, axis=-1, keepdims=False) not_prior = total_probs > 1 semantic_labels = semantic_labels[not_prior, :] centroids = centroids[not_prior, :] semantic_labels = np.argmax(semantic_labels, axis=-1) semantic_labels = semantic_labels.reshape(-1, 1) for i in range(semantic_labels.shape[0]): pred = semantic_labels[i] point = Point32() color = ColorRGBA() point.x = centroids[i, 0] point.y = centroids[i, 1] point.z = centroids[i, 2] color.r, color.g, color.b = colors[pred].squeeze() color.a = 1.0 marker.points.append(point) marker.colors.append(color) next_map.markers.append(marker) return next_map def publish_local_map(labeled_grid, centroids, grid_params, colors, next_map): max_dim = grid_params["max_bound"] min_dim = grid_params["min_bound"] grid_dims = grid_params["grid_size"] next_map.markers.clear() marker = Marker() marker.id = 0 marker.ns = "Local Semantic Map" marker.header.frame_id = "map" marker.type = marker.CUBE_LIST marker.action = marker.ADD marker.lifetime.secs = 0 marker.header.stamp = rospy.Time.now() marker.pose.orientation.x = 0.0 marker.pose.orientation.y = 0.0 marker.pose.orientation.z = 0.0 marker.pose.orientation.w = 1 marker.scale.x = (max_dim[0] - min_dim[0]) / grid_dims[0] marker.scale.y = (max_dim[1] - min_dim[1]) / grid_dims[1] marker.scale.z = (max_dim[2] - min_dim[2]) / grid_dims[2] X, Y, Z, C = labeled_grid.shape semantic_labels = labeled_grid.view(-1, C).detach().cpu().numpy() centroids = centroids.detach().cpu().numpy() semantic_sums = np.sum(semantic_labels, axis=-1, keepdims=False) valid_mask = semantic_sums >= 1 semantic_labels = semantic_labels[valid_mask, :] centroids = centroids[valid_mask, :] semantic_labels = np.argmax(semantic_labels / np.sum(semantic_labels, axis=-1, keepdims=True), axis=-1) semantic_labels = semantic_labels.reshape(-1, 1) for i in range(semantic_labels.shape[0]): pred = semantic_labels[i] point = Point32() color = ColorRGBA() point.x = centroids[i, 0] point.y = centroids[i, 1] point.z = centroids[i, 2] color.r, color.g, color.b = colors[pred].squeeze() color.a = 1.0 marker.points.append(point) marker.colors.append(color) next_map.markers.append(marker) return next_map
4,931
31.662252
109
py
NeuralBKI
NeuralBKI-main/Data/SemanticKitti.py
import os import numpy as np # from utils import laserscan import yaml from torch.utils.data import Dataset import torch # import spconv import math from scipy.spatial.transform import Rotation as R config_file = os.path.join('Config/semantic_kitti.yaml') kitti_config = yaml.safe_load(open(config_file, 'r')) remapdict = kitti_config["learning_map"] LABELS_REMAP = kitti_config["learning_map"] LABEL_INV_REMAP = kitti_config["learning_map_inv"] SPLIT_SEQUENCES = kitti_config["SPLIT_SEQUENCES"] def grid_ind(input_pc, labels, min_bound, max_bound, grid_size, voxel_sizes): ''' Input: input_xyz: N * (x, y, z, c) float32 array, point cloud Output: grid_inds: N' * (x, y, z, c) int32 array, point cloud mapped to voxels ''' input_xyz = input_pc[:, :3] valid_input_mask = np.all((input_xyz < max_bound) & (input_xyz >= min_bound), axis=1) valid_xyz = input_xyz[valid_input_mask] labels = labels[valid_input_mask] grid_inds = np.floor((valid_xyz - min_bound) / voxel_sizes) maxes = (grid_size - 1).reshape(1, 3) clipped_inds = np.clip(grid_inds, np.zeros_like(maxes), maxes) return clipped_inds, labels, valid_xyz def unpack(compressed): ''' given a bit encoded voxel grid, make a normal voxel grid out of it. ''' uncompressed = np.zeros(compressed.shape[0] * 8, dtype=np.uint8) uncompressed[::8] = compressed[:] >> 7 & 1 uncompressed[1::8] = compressed[:] >> 6 & 1 uncompressed[2::8] = compressed[:] >> 5 & 1 uncompressed[3::8] = compressed[:] >> 4 & 1 uncompressed[4::8] = compressed[:] >> 3 & 1 uncompressed[5::8] = compressed[:] >> 2 & 1 uncompressed[6::8] = compressed[:] >> 1 & 1 uncompressed[7::8] = compressed[:] & 1 return uncompressed class KittiDataset(Dataset): """Kitti Dataset for Neural BKI project Access to the processed data, including evaluation labels predictions velodyne poses times """ def __init__(self, grid_params, directory="/home/jason/Data/kitti", device='cuda', num_frames=4, voxelize_input=True, binary_counts=False, random_flips=False, use_aug=True, apply_transform=True, remap=True, data_split='train', from_continuous=False, to_continuous=False, pred_path="predictions_darknet", num_classes=20, remove_zero=False ): self.remove_zero = remove_zero self.from_continuous = from_continuous self.to_continuous = to_continuous self.use_aug = use_aug self.apply_transform = apply_transform self.num_classes = num_classes self._grid_size = grid_params['grid_size'] self.grid_dims = np.asarray(self._grid_size) self._eval_size = list(np.uint32(self._grid_size)) self.coor_ranges = grid_params['min_bound'] + grid_params['max_bound'] self.voxel_sizes = [abs(self.coor_ranges[3] - self.coor_ranges[0]) / self._grid_size[0], abs(self.coor_ranges[4] - self.coor_ranges[1]) / self._grid_size[1], abs(self.coor_ranges[5] - self.coor_ranges[2]) / self._grid_size[2]] self.min_bound = np.asarray(self.coor_ranges[:3]) self.max_bound = np.asarray(self.coor_ranges[3:]) self.voxel_sizes = np.asarray(self.voxel_sizes) self.voxelize_input = voxelize_input self.binary_counts = binary_counts self._directory = os.path.join(directory, 'sequences') self._num_frames = num_frames self.device = device self.random_flips = random_flips self.remap = remap self.split = data_split self._remap_lut = self.get_remap_lut() self._velodyne_list = [] self._label_list = [] self._pred_list = [] self._eval_labels = [] self._eval_valid = [] self._frames_list = [] self._timestamps = [] self._poses = np.empty((0,12)) self._Tr = np.empty((0,12)) self._num_frames_scene = [] self._seqs = SPLIT_SEQUENCES[self.split] self._scene_id = [] for seq in self._seqs: velodyne_dir = os.path.join(self._directory, seq, 'velodyne') label_dir = os.path.join(self._directory, seq, 'labels') preds_dir = os.path.join(self._directory, seq, pred_path) self._num_frames_scene.append(len(os.listdir(velodyne_dir))) self._scene_id += [seq] * len(os.listdir(velodyne_dir)) frames_list = [os.path.splitext(filename)[0] for filename in sorted(os.listdir(velodyne_dir))] pose = np.loadtxt(os.path.join(self._directory, seq, 'poses.txt')) Tr = np.genfromtxt(os.path.join(self._directory, seq, 'calib.txt'))[-1,1:] Tr = np.repeat(np.expand_dims(Tr, axis=1).T,pose.shape[0],axis=0) self._Tr = np.vstack((self._Tr, Tr)) self._poses = np.vstack((self._poses, pose)) self._frames_list.extend(frames_list) self._velodyne_list.extend([os.path.join(velodyne_dir, str(frame).zfill(6)+'.bin') for frame in frames_list]) self._label_list.extend([os.path.join(label_dir, str(frame).zfill(6)+'.label') for frame in frames_list]) self._pred_list.extend([os.path.join(preds_dir, str(frame).zfill(6)+'.label') for frame in frames_list]) assert len(self._velodyne_list) == np.sum(self._num_frames_scene), f"inconsitent number of frames detected, check the dataset" # self._poses = np.concatenate(self._poses) self._poses = self._poses.reshape(sum(self._num_frames_scene), 12) self._Tr = self._Tr.reshape(sum(self._num_frames_scene), 12) def collate_fn(self, data): points_batch = [bi[0] for bi in data] label_batch = [bi[1] for bi in data] gt_label_batch = [bi[2] for bi in data] return points_batch, label_batch, gt_label_batch def get_aug_matrix(self, trans): """ trans - 1 or 2 specifies reflection about XZ or YZ plane any other value gives rotation matrix Double checked with rotation matrix calculator """ if trans==1: trans = np.eye(3) trans[1][1] = -1 elif trans==2: trans = np.eye(3) trans[0][0] = -1 else: if trans==0: angle = 0 else: angle = (trans-2)*90 trans = R.from_euler('z', angle, degrees=True).as_matrix() return trans def get_pose(self, frame_id): pose = np.zeros((4, 4)) pose[3, 3] = 1 pose[:3, :4] = self._poses[frame_id,:].reshape(3, 4) Tr = np.zeros((4, 4)) Tr[3, 3] = 1 Tr[:3, :4] = self._Tr[frame_id,:].reshape(3,4) Tr = Tr.astype(np.float32) pose = pose.astype(np.float32) global_pose = np.matmul(np.linalg.inv(Tr), np.matmul(pose, Tr)) return global_pose # Use all frames, if there is no data then zero pad def __len__(self): return sum(self._num_frames_scene) def get_inv_remap_lut(self): ''' remap_lut to remap classes of semantic kitti for training... :return: ''' # make lookup table for mapping maxkey = max(LABEL_INV_REMAP.keys()) # +100 hack making lut bigger just in case there are unknown labels remap_lut = np.zeros((maxkey + 1), dtype=np.int32) remap_lut[list(LABEL_INV_REMAP.keys())] = list(LABEL_INV_REMAP.values()) return remap_lut def get_remap_lut(self): ''' remap_lut to remap classes of semantic kitti for training... :return: ''' # make lookup table for mapping maxkey = max(LABELS_REMAP.keys()) # +100 hack making lut bigger just in case there are unknown labels remap_lut = np.zeros((maxkey + 100), dtype=np.int32) remap_lut[list(LABELS_REMAP.keys())] = list(LABELS_REMAP.values()) # in completion we have to distinguish empty and invalid voxels. # Important: For voxels 0 corresponds to "empty" and not "unlabeled". remap_lut[remap_lut == 0] = 0 # keep 0 as ignore remap_lut[0] = 0 # only 'empty' stays 'empty'. return remap_lut def __getitem__(self, idx): # -1 indicates no data # the final index is the output idx_range = self.find_horizon(idx) current_points = [] current_labels = [] ego_pose = self.get_pose(idx_range[-1]) to_ego = np.linalg.inv(ego_pose) aug_index = np.random.randint(0,3) # Set end idx to 6 to do rotations aug_mat = self.get_aug_matrix(aug_index) gt_labels = None for i in idx_range: if i == -1: # Zero pad points = np.zeros((1, 3), dtype=np.float32) if self.to_continuous: labels = np.zeros((1,self.num_classes), dtype=np.float32) else: labels = np.zeros((1, 1), dtype=np.uint8) else: points = np.fromfile(self._velodyne_list[i],dtype=np.float32).reshape(-1,4)[:, :3] if self.apply_transform: global_pose = self.get_pose(i) relative_pose = np.matmul(to_ego, global_pose) points = np.dot(relative_pose[:3, :3], points.T).T + relative_pose[:3, 3] temp_gt_labels = np.fromfile(self._label_list[i], dtype=np.uint32) & 0xFFFF temp_gt_labels = temp_gt_labels.reshape((-1)).astype(np.uint8) if not self.from_continuous: labels = np.fromfile(self._pred_list[i], dtype=np.uint32).reshape((-1, 1)).astype(np.uint8) if self.from_continuous: labels = np.fromfile(self._pred_list[i], dtype=np.float32).reshape((-1, self.num_classes)) if not self.to_continuous: labels = np.argmax(labels, axis=1).reshape((-1, 1)).astype(np.uint8) # Perform data augmentation on points if self.use_aug: points = (aug_mat @ points.T).T # Filter points outside of voxel grid grid_point_mask = np.all( (points < self.max_bound) & (points >= self.min_bound), axis=1) points = points[grid_point_mask, :] temp_gt_labels = temp_gt_labels[grid_point_mask] labels = labels[grid_point_mask, :] # Remove zero labels if self.remove_zero: void_mask = temp_gt_labels != 0 points = points[void_mask, :] temp_gt_labels = temp_gt_labels[void_mask] labels = labels[void_mask, :] if self.remap: temp_gt_labels = self._remap_lut[temp_gt_labels].astype(np.uint8) if not self.from_continuous: labels = self._remap_lut[labels].astype(np.uint8) if i == idx_range[-1]: gt_labels = temp_gt_labels points = points.astype(np.float32) #[:, [1, 0, 2]] current_points.append(points) current_labels.append(labels) return current_points, current_labels, gt_labels.astype(np.uint8).reshape(-1, 1) def find_horizon(self, idx): end_idx = idx idx_range = np.arange(idx-self._num_frames, idx)+1 diffs = np.asarray([int(self._frames_list[end_idx]) - int(self._frames_list[i]) for i in idx_range]) good_difs = -1 * (np.arange(-self._num_frames, 0) + 1) idx_range[good_difs != diffs] = -1 return idx_range def points_to_voxels(self, voxel_grid, points, t_i): # Valid voxels (make sure to clip) valid_point_mask= np.all( (points < self.max_bound) & (points >= self.min_bound), axis=1) valid_points = points[valid_point_mask, :] voxels = np.floor((valid_points - self.min_bound) / self.voxel_sizes).astype(int) # Clamp to account for any floating point errors maxes = np.reshape(self.grid_dims - 1, (1, 3)) mins = np.zeros_like(maxes) voxels = np.clip(voxels, mins, maxes).astype(int) # This line is needed to create a mask with number of points, not just binary occupied if self.binary_counts: voxel_grid[t_i, voxels[:, 0], voxels[:, 1], voxels[:, 2]] += 1 else: unique_voxels, counts = np.unique(voxels, return_counts=True, axis=0) unique_voxels = unique_voxels.astype(int) voxel_grid[t_i, unique_voxels[:, 0], unique_voxels[:, 1], unique_voxels[:, 2]] += counts return voxel_grid def get_test_item(self, idx, get_gt=False): frame_id = idx # Frame ID in current scene ID global_pose = self.get_pose(frame_id) if frame_id > 0: prior_pose = self.get_pose(frame_id - 1) else: prior_pose = global_pose points = np.fromfile(self._velodyne_list[frame_id], dtype=np.float32).reshape(-1, 4)[:, :3] if get_gt: gt_labels = np.fromfile(self._label_list[frame_id], dtype=np.uint32) & 0xFFFF gt_labels = gt_labels.reshape((-1)).astype(np.uint8) if not self.from_continuous: pred_labels = np.fromfile(self._pred_list[frame_id], dtype=np.uint32).reshape((-1, 1)).astype(np.uint8) if self.from_continuous: pred_labels = np.fromfile(self._pred_list[frame_id], dtype=np.float32).reshape((-1, self.num_classes)) if not self.to_continuous: pred_labels = np.argmax(pred_labels, axis=1).reshape((-1, 1)) # Remove zero labels if get_gt and self.remove_zero: grid_point_mask = np.all((points < self.max_bound) & (points >= self.min_bound), axis=1) points = points[grid_point_mask, :] gt_labels = gt_labels[grid_point_mask] pred_labels = pred_labels[grid_point_mask, :] void_mask = gt_labels != 0 points = points[void_mask, :] gt_labels = gt_labels[void_mask] pred_labels = pred_labels[void_mask, :] if self.remap: if get_gt: gt_labels = self._remap_lut[gt_labels].astype(np.uint8) if not self.from_continuous: pred_labels = self._remap_lut[pred_labels].astype(np.uint8) scene_id = self._scene_id[idx] if get_gt: return global_pose, points, pred_labels, gt_labels.astype(np.uint8).reshape(-1, 1), scene_id, frame_id else: return global_pose, points, pred_labels, None, scene_id, frame_id
15,165
39.878706
134
py
NeuralBKI
NeuralBKI-main/Data/Rellis3D.py
## Maintainer: Arthur Zhang ##### ## Contact: arthurzh@umich.edu ##### import os import pdb import math import numpy as np import random import json import yaml from sklearn.metrics import homogeneity_completeness_v_measure import torch from torch import gt import torch.nn.functional as F from torch.utils.data import Dataset from scipy.spatial.transform import Rotation as R from Data.utils import * def unpack(compressed): ''' given a bit encoded voxel grid, make a normal voxel grid out of it. ''' uncompressed = np.zeros(compressed.shape[0] * 8, dtype=np.uint8) uncompressed[::8] = compressed[:] >> 7 & 1 uncompressed[1::8] = compressed[:] >> 6 & 1 uncompressed[2::8] = compressed[:] >> 5 & 1 uncompressed[3::8] = compressed[:] >> 4 & 1 uncompressed[4::8] = compressed[:] >> 3 & 1 uncompressed[5::8] = compressed[:] >> 2 & 1 uncompressed[6::8] = compressed[:] >> 1 & 1 uncompressed[7::8] = compressed[:] & 1 return uncompressed class Rellis3dDataset(Dataset): """Rellis3D Dataset for Neural BKI project Access to the processed data, including evaluation labels predictions velodyne poses times """ def __init__(self, grid_params, directory, device='cuda', num_frames=20, remap=True, use_aug=True, apply_transform=True, model_name="salsa", data_split="train" ): '''Constructor. Parameters: directory: directory to the dataset ''' self._directory = directory self._num_frames = num_frames self.device = device self.remap = remap self.use_aug = use_aug self.apply_transform = apply_transform self._scenes = [ s for s in sorted(os.listdir(self._directory)) if s.isdigit() ] self._num_scenes = len(self._scenes) self._num_frames_scene = 0 self._velodyne_list = [] self._label_list = [] self._pred_list = [] self._voxel_label_list = [] self._occupied_list = [] self._invalid_list = [] self._frames_list = [] self._timestamps = [] self._poses = [] self._num_frames_by_scene = [] split_dir = os.path.join(self._directory, "pt_"+data_split+".lst") data_params_file = os.path.join(os.getcwd(), "Config", "rellis.yaml") with open(data_params_file, "r") as stream: try: data_params = yaml.safe_load(stream) self._num_labels = data_params["num_classes"] max_label = max([i for i in data_params["LABELS_REMAP"].keys()]) self.LABELS_REMAP = np.zeros(max_label + 1, dtype=np.long) for v,k in data_params["LABELS_REMAP"].items(): self.LABELS_REMAP[v] = k except yaml.YAMLError as exc: print(exc) self._grid_size = grid_params['grid_size'] self.grid_dims = np.asarray(self._grid_size) self.coor_ranges = grid_params['min_bound'] + grid_params['max_bound'] self.voxel_sizes = np.asarray([abs(self.coor_ranges[3] - self.coor_ranges[0]) / self._grid_size[0], abs(self.coor_ranges[4] - self.coor_ranges[1]) / self._grid_size[1], abs(self.coor_ranges[5] - self.coor_ranges[2]) / self._grid_size[2]]) self.min_bound = np.asarray(self.coor_ranges[:3]) self.max_bound = np.asarray(self.coor_ranges[3:]) # Generate list of scenes and indices to iterate over self._scenes_list = [] self._index_list = [] with open(split_dir, 'r') as split_file: for line in split_file: image_path = line.split(' ') image_path_lst = image_path[0].split('/') scene_num = image_path_lst[0] frame_index = int(image_path_lst[2][0:6]) self._scenes_list.append(scene_num) self._index_list.append(frame_index) for scene_id in range(self._num_scenes): scene_name = self._scenes[scene_id] velodyne_dir = os.path.join(self._directory, scene_name, 'os1_cloud_node_kitti_bin') label_dir = os.path.join(self._directory, scene_name, 'os1_cloud_node_semantickitti_label_id') pred_dir = os.path.join(self._directory, scene_name, model_name, 'os1_cloud_node_semantickitti_label_id') # Load all poses and frame indices regardless of mode self._poses.append(np.loadtxt(os.path.join(self._directory, scene_name, 'poses.txt')).reshape(-1, 12) ) self._frames_list.append([os.path.splitext(filename)[0] for filename in sorted(os.listdir(velodyne_dir))]) self._num_frames_by_scene.append(len(self._frames_list[scene_id])) # PC inputs self._velodyne_list.append( [os.path.join(velodyne_dir, str(frame).zfill(6)+'.bin') for frame in self._frames_list[scene_id]] ) self._label_list.append( [os.path.join(label_dir, str(frame).zfill(6)+'.label') for frame in self._frames_list[scene_id]] ) self._pred_list.append( [os.path.join(pred_dir, str(frame).zfill(6)+'.label') for frame in self._frames_list[scene_id]] ) # Get number of frames to iterate over self._num_frames_scene = len(self._index_list) # Use all frames, if there is no data then zero pad def __len__(self): return self._num_frames_scene def collate_fn(self, data): points_batch = [bi[0] for bi in data] label_batch = [bi[1] for bi in data] gt_label_batch = [bi[2] for bi in data] return points_batch, label_batch, gt_label_batch def get_file_path(self, idx): print(self._frames_list[idx]) def get_aug_matrix(self, trans): """ trans - 1 or 2 specifies reflection about XZ or YZ plane any other value gives rotation matrix Double checked with rotation matrix calculator """ if trans==1: trans = np.eye(3) trans[1][1] = -1 elif trans==2: trans = np.eye(3) trans[0][0] = -1 else: if trans==0: angle = 0 else: angle = (trans-2)*90 trans = R.from_euler('z', angle, degrees=True).as_matrix() return trans def get_pose(self, scene_id, frame_id): pose = np.zeros((4, 4)) pose[3, 3] = 1 pose[:3, :4] = self._poses[scene_id][frame_id].reshape(3, 4) return pose def __getitem__(self, idx): scene_name = self._scenes_list[idx] scene_id = int(scene_name) # Scene ID frame_id = self._index_list[idx] # Frame ID in current scene ID idx_range = self.find_horizon(scene_id, frame_id) current_points = [] current_labels = [] ego_pose = self.get_pose(scene_id, idx_range[-1]) to_ego = np.linalg.inv(ego_pose) aug_index = np.random.randint(0,3) # Set end idx to 6 to do rotations aug_mat = self.get_aug_matrix(aug_index) gt_labels = None for i in idx_range: if i == -1: # Zero pad points = np.zeros((1, 3), dtype=np.float16) labels = np.zeros((1,), dtype=np.uint8) else: points = np.fromfile(self._velodyne_list[scene_id][i], dtype=np.float32).reshape(-1,4)[:, :3] if self.apply_transform: to_world = self.get_pose(scene_id, i) to_world = to_world relative_pose = np.matmul(to_ego, to_world) points = np.dot(relative_pose[:3, :3], points.T).T + relative_pose[:3, 3] temp_gt_labels = np.fromfile(self._label_list[scene_id][i], dtype=np.uint32).reshape((-1)).astype(np.uint8) labels = np.fromfile(self._pred_list[scene_id][i], dtype=np.uint32).reshape((-1)).astype(np.uint8) # Perform data augmentation on points if self.use_aug: points = (aug_mat @ points.T).T # Filter points outside of voxel grid grid_point_mask = np.all( (points < self.max_bound) & (points >= self.min_bound), axis=1) points = points[grid_point_mask, :] temp_gt_labels = temp_gt_labels[grid_point_mask] labels = labels[grid_point_mask] # Remove zero labels void_mask = temp_gt_labels != 0 points = points[void_mask, :] temp_gt_labels = temp_gt_labels[void_mask] labels = labels[void_mask] if self.remap: temp_gt_labels = self.LABELS_REMAP[temp_gt_labels].astype(np.uint8) labels = self.LABELS_REMAP[labels].astype(np.uint8) if i == idx_range[-1]: gt_labels = temp_gt_labels labels = labels.reshape(-1, 1) points = points.astype(np.float32) #[:, [1, 0, 2]] labels = labels.astype(np.uint8) current_points.append(points) current_labels.append(labels) return current_points, current_labels, gt_labels.astype(np.uint8).reshape(-1, 1) def find_horizon(self, scene_id, idx): end_idx = idx idx_range = np.arange(idx- self._num_frames, idx)+1 diffs = np.asarray([int(self._frames_list[scene_id][end_idx]) - int(self._frames_list[scene_id][i]) for i in idx_range]) good_diffs = -1 * (np.arange(- self._num_frames, 0) + 1) idx_range[good_diffs != diffs] = -1 return idx_range def get_test_item(self, idx): scene_name = self._scenes_list[idx] scene_id = int(scene_name) # Scene ID frame_id = self._index_list[idx] # Frame ID in current scene ID pose = self.get_pose(scene_id, frame_id) points = np.fromfile(self._velodyne_list[scene_id][frame_id], dtype=np.float32).reshape(-1, 4)[:, :3] gt_labels = np.fromfile(self._label_list[scene_id][frame_id], dtype=np.uint32).reshape((-1)).astype(np.uint8) pred_labels = np.fromfile(self._pred_list[scene_id][frame_id], dtype=np.uint32).reshape((-1)).astype(np.uint8) # Filter points outside of voxel grid grid_point_mask = np.all( (points < self.max_bound) & (points >= self.min_bound), axis=1) points = points[grid_point_mask, :] gt_labels = gt_labels[grid_point_mask] pred_labels = pred_labels[grid_point_mask] # Remove zero labels void_mask = gt_labels != 0 points = points[void_mask, :] gt_labels = gt_labels[void_mask] pred_labels = pred_labels[void_mask] if self.remap: gt_labels = self.LABELS_REMAP[gt_labels].astype(np.uint8) pred_labels = self.LABELS_REMAP[pred_labels].astype(np.uint8) return pose.astype(np.float32), points, pred_labels.astype(np.uint8).reshape(-1, 1), gt_labels.astype(np.uint8).reshape(-1, 1), scene_id, frame_id
11,319
38.719298
154
py
NeuralBKI
NeuralBKI-main/Models/model_utils.py
import pdb import torch import random import numpy as np from torch import empty from torch import long from Models.ConvBKI import ConvBKI def setup_seed(seed=42): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) def measure_inf_time(model, inputs, reps=300): print(inputs.shape) starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) timings = np.zeros((reps, 1)) model.eval() with torch.no_grad(): current_map = model.initialize_grid() for rep in range(reps): starter.record() _ = model(current_map, inputs) ender.record() # WAIT FOR GPU SYNC torch.cuda.synchronize() curr_time = starter.elapsed_time(ender) timings[rep] = curr_time mean_syn = np.sum(timings) / reps std_syn = np.std(timings) print(mean_syn) def get_model(model_name, model_params): # Model parameters grid_params = model_params["train"]["grid_params"] device = model_params["device"] try: model = ConvBKI( torch.tensor([int(p) for p in grid_params['grid_size']], dtype=torch.long).to(device), # Grid size torch.tensor(grid_params['min_bound']).to(device), # Lower bound torch.tensor(grid_params['max_bound']).to(device), # Upper bound num_classes=model_params["num_classes"], filter_size=model_params["filter_size"], device=device, datatype=model_params["datatype"], kernel=model_params["kernel"], max_dist=model_params["ell"], per_class=model_params["per_class"], compound=model_params["compound"] ) except: exit("Invalid config file.") return model
1,843
30.254237
111
py
NeuralBKI
NeuralBKI-main/Models/ConvBKI.py
import pdb import os import torch torch.backends.cudnn.deterministic = True import torch.nn.functional as F class ConvBKI(torch.nn.Module): def __init__(self, grid_size, min_bound, max_bound, filter_size=3, num_classes=21, prior=0.001, device="cpu", datatype=torch.float32, max_dist=0.5, kernel="sparse", per_class=False, compound=False): ''' Input: grid_size: (x, y, z) int32 array, number of voxels min_bound: (x, y, z) float32 array, lower bound on local map max_bound: (x, y, z) float32 array, upper bound on local map filter_size: int, dimension of the kernel on each axis (must be odd) num_classes: int, number of classes prior: float32, value of prior in map device: cpu or gpu max_dist: size of the kernel ell parameter kernel: kernel to choose per_class: whether to learn a different kernel for each class ''' super().__init__() self.min_bound = min_bound.view(-1, 3).to(device) self.max_bound = max_bound.view(-1, 3).to(device) self.grid_size = grid_size self.dtype = datatype self.prior = prior self.kernel = kernel self.device = device self.num_classes = num_classes self.per_class = per_class self.compound = compound self.voxel_sizes = (self.max_bound.view(-1) - self.min_bound.view(-1)) / self.grid_size.to(self.device) self.pi = torch.acos(torch.zeros(1)).item() * 2 self.max_dist = max_dist self.filter_size = torch.tensor(filter_size, dtype=torch.long, requires_grad=False, device=self.device) self.initialize_kernel() [xs, ys, zs] = [(max_bound[i]-min_bound[i])/(2*grid_size[i]) + torch.linspace(min_bound[i], max_bound[i], device=device, steps=grid_size[i]+1)[:-1] for i in range(3)] self.centroids = torch.cartesian_prod(xs, ys, zs).to(device) def initialize_kernel(self): # Initialize with sparse kernel assert(self.filter_size % 2 == 1) self.sigma = torch.tensor(1.0, device=self.device) # Kernel must map to 0 to 1 # Parameters if self.kernel == "sparse": if self.compound: if self.per_class: self.ell_h = torch.nn.Parameter(torch.tensor([self.max_dist] * self.num_classes, device=self.device)) self.ell_z = torch.nn.Parameter(torch.tensor([self.max_dist] * self.num_classes, device=self.device)) # self.ell_h = torch.nn.Parameter(0.2 + self.max_dist*torch.rand(self.num_classes, device=self.device)) # self.ell_z = torch.nn.Parameter(0.2 + self.max_dist*torch.rand(self.num_classes, device=self.device)) else: self.ell_h = torch.nn.Parameter(torch.tensor(self.max_dist, device=self.device, dtype=self.dtype)) self.ell_z = torch.nn.Parameter(torch.tensor(self.max_dist, device=self.device, dtype=self.dtype)) else: if self.per_class: self.ell = torch.nn.Parameter(torch.tensor([self.max_dist] * self.num_classes, device=self.device)) # self.ell = torch.nn.Parameter(2*self.max_dist*torch.rand(self.num_classes, device=self.device)) else: self.ell = torch.nn.Parameter(torch.tensor(self.max_dist, device=self.device, dtype=self.dtype)) # Distances middle_ind = torch.floor(self.filter_size / 2) if self.compound: self.kernel_dists_h = torch.zeros([1, 1, self.filter_size, self.filter_size, self.filter_size], device=self.device) self.kernel_dists_z = torch.zeros([1, 1, self.filter_size, self.filter_size, self.filter_size], device=self.device) else: self.kernel_dists = torch.zeros([1, 1, self.filter_size, self.filter_size, self.filter_size], device=self.device) for x_ind in range(self.filter_size): for y_ind in range(self.filter_size): for z_ind in range(self.filter_size): x_dist = torch.abs(x_ind - middle_ind) * self.voxel_sizes[0] y_dist = torch.abs(y_ind - middle_ind) * self.voxel_sizes[1] z_dist = torch.abs(z_ind - middle_ind) * self.voxel_sizes[2] if self.compound: horiz_dist = torch.sqrt(x_dist ** 2 + y_dist ** 2) vert_dist = torch.sqrt(z_dist ** 2) self.kernel_dists_h[0, 0, x_ind, y_ind, z_ind] = horiz_dist self.kernel_dists_z[0, 0, x_ind, y_ind, z_ind] = vert_dist else: total_dist = torch.sqrt(x_dist ** 2 + y_dist ** 2 + z_dist ** 2) self.kernel_dists[0, 0, x_ind, y_ind, z_ind] = total_dist def sparse_kernel(self, d, ell, sigma): kernel_val = sigma * ((1.0/3)*(2 + torch.cos(2 * self.pi * d/ell))*(1 - d/ell) + 1.0/(2*self.pi) * torch.sin(2 * self.pi * d / ell)) kernel_val[d >= ell] = 0 return torch.clamp(kernel_val, min=0.0, max=1.0) def calculate_kernel(self, i=0): kernel_val = None if self.kernel == "sparse": if self.per_class: if self.compound: kernel_val = self.sparse_kernel(self.kernel_dists_z, self.ell_z[i], self.sigma) * \ self.sparse_kernel(self.kernel_dists_h, self.ell_h[i], self.sigma) else: kernel_val = self.sparse_kernel(self.kernel_dists, self.ell[i], self.sigma) else: kernel_val = self.sparse_kernel(self.kernel_dists, self.ell, self.sigma) return kernel_val def initialize_grid(self): return torch.zeros(self.grid_size[0], self.grid_size[1], self.grid_size[2], self.num_classes, device=self.device, requires_grad=True, dtype=self.dtype) + self.prior def grid_ind(self, input_pc, min_bound=None, max_bound=None): ''' Input: input_xyz: N * (x, y, z, c) float32 array, point cloud Output: grid_inds: N' * (x, y, z, c) int32 array, point cloud mapped to voxels ''' if min_bound is None: min_bound = self.min_bound if max_bound is None: max_bound = self.max_bound input_xyz = input_pc[:, :3] labels = input_pc[:, 3:] valid_input_mask = torch.all((input_xyz < max_bound) & (input_xyz >= min_bound), axis=1) valid_xyz = input_xyz[valid_input_mask] valid_labels = labels[valid_input_mask] grid_inds = torch.floor((valid_xyz - min_bound) / self.voxel_sizes) maxes = (self.grid_size - 1).view(1, 3) clipped_inds = torch.clamp(grid_inds, torch.zeros_like(maxes), maxes) return torch.hstack( (clipped_inds, valid_labels) ) def get_filters(self): filters = torch.zeros([self.num_classes, 1, self.filter_size, self.filter_size, self.filter_size], device=self.device, dtype=self.dtype) for temp_class in range(self.num_classes): if self.per_class: filters[temp_class, 0, :, :, :] = self.calculate_kernel(i=temp_class) else: filters[temp_class, 0, :, :, :] = self.calculate_kernel() return filters def add_to_update(self, update, grid_pc, continuous=False): if continuous: # Solution inspired by https://github.com/facebookresearch/SparseConvNet/blob/main/sparseconvnet/utils.py xyz = grid_pc[:, :3] feat = grid_pc[:, 3:] xyz, inv, counts = torch.unique(xyz, dim=0, return_inverse=True, return_counts=True) feat_out = torch.zeros(xyz.size(0), feat.size(1), dtype=torch.float32, device=self.device) feat_out.index_add_(0, inv, feat) grid_ind = xyz.to(torch.long) update[grid_ind[:, 0], grid_ind[:, 1], grid_ind[:, 2]] = feat_out else: unique_inds, counts = torch.unique(grid_pc.to(torch.long), return_counts=True, dim=0) counts = counts.type(torch.long) grid_indices = [unique_inds[:, i] for i in range(grid_pc.shape[1])] update[grid_indices] = update[grid_indices] + counts return update def forward(self, current_map, point_cloud): ''' Input: current_map: (x, y, z, c) float32 array, prior dirichlet distribution over map point_cloud: N * (x, y, z, c) float32 array, semantically labeled points Output: updated_map: (x, y, z, c) float32 array, posterior dirichlet distribution over map ''' # Assume map and point cloud are already aligned X, Y, Z, C = current_map.shape update = torch.zeros_like(current_map, requires_grad=False) N, C = point_cloud.shape continuous = False if C == self.num_classes + 3: continuous = True # 1: Discretize grid_pc = self.grid_ind(point_cloud) update = self.add_to_update(update, grid_pc, continuous) # 2: Apply BKI filters filters = self.get_filters() update = torch.unsqueeze(update.permute(3, 0, 1, 2), 0) update = F.conv3d(update, filters, padding="same", groups=self.num_classes) new_update = torch.squeeze(update).permute(1, 2, 3, 0) return current_map + new_update
9,899
47.292683
123
py
NeuralBKI
NeuralBKI-main/Models/mapping_utils.py
# This file contains classes for local and global offline mapping (not running semantic prediction) import torch import torch.nn.functional as F import numpy as np import time from Models.ConvBKI import ConvBKI # TODO: Trilinear interpolation # Save grid in CPU memory, load to GPU when needed for update step # Voxels are stored in a matrix [X | Y | Z | C_0 | ... C_N] where C is semantic class class GlobalMap(ConvBKI): def __init__(self, grid_size, min_bound, max_bound, weights, filter_size, num_classes=21, ignore_labels = None, prior=0.001, device="cpu", datatype=torch.float32, sparse=True, delete_time=10): super().__init__(grid_size, min_bound, max_bound, filter_size=filter_size, num_classes=num_classes, prior=prior, device=device, datatype=datatype) self.ignore_labels = ignore_labels self.weights = weights self.reset_grid() self.ConvLayer = torch.nn.Conv3d(num_classes, num_classes, filter_size, padding="same", groups=num_classes, device=device, dtype=datatype, bias=False) self.ConvLayer.weight.requires_grad = False self.ConvLayer.weight[:, :, :, :, :] = weights.detach()[:, :, :, :, :] self.ConvLayer.eval() self.delete_time = delete_time def reset_grid(self): self.global_map = None self.map_times = None self.initial_pose = None self.translation_discretized = np.zeros(3) self.points_rotation = torch.eye(3, dtype=self.dtype, device=self.device) self.points_translation = torch.zeros(3, dtype=self.dtype, device=self.device) def inside_mask(self, min_bounds, max_bounds): inside = np.all((self.global_map[:, :3] >= min_bounds) & (self.global_map[:, :3] < max_bounds), axis=1) return inside def get_local_map(self, min_bound=None, max_bound=None): # Fetch local map from CPU (anything not seen is prior) local_map = self.initialize_grid() inside_mask = None if min_bound is None: min_bound = self.min_bound if max_bound is None: max_bound = self.max_bound local_min_bound = min_bound + torch.from_numpy(self.voxel_translation).to(self.device) local_max_bound = max_bound + torch.from_numpy(self.voxel_translation).to(self.device) if self.global_map is not None: inside_mask = self.inside_mask(local_min_bound.detach().cpu().numpy(), local_max_bound.detach().cpu().numpy()) allocated_map = torch.tensor(self.global_map[inside_mask], device=self.device, dtype=self.dtype) grid_map = self.grid_ind(allocated_map, min_bound=local_min_bound, max_bound=local_max_bound) grid_indices = grid_map[:, :3].to(torch.long) local_map[grid_indices[:, 0], grid_indices[:, 1], grid_indices[:, 2], :] = allocated_map[:, 3:] return local_map, local_min_bound, local_max_bound, inside_mask # Uses saved weights instead of generating a filter def update_map(self, semantic_preds): semantic_preds = semantic_preds.to(self.dtype) local_map, local_min_bound, local_max_bound, inside_mask = self.get_local_map() # Rotate the point cloud and translate to global frame global_pose = torch.from_numpy(self.global_pose).to(self.device) semantic_preds[:, :3] = torch.matmul(global_pose[:3, :3], semantic_preds[:, :3].T).T + global_pose[:3, 3] # Change to indices using our global frame bounds grid_pc = self.grid_ind(semantic_preds, min_bound=local_min_bound, max_bound=local_max_bound) # Update local map update = torch.zeros_like(local_map, requires_grad=False) continuous = False N, C = semantic_preds.shape if C == self.num_classes + 3: continuous = True update = self.add_to_update(update, grid_pc, continuous) # Apply BKI filters update = torch.unsqueeze(update.permute(3, 0, 1, 2), 0) update = self.ConvLayer(update) new_update = torch.squeeze(update).permute(1, 2, 3, 0) # Find updated cells local_map = local_map + new_update updated_cells = (torch.mean(local_map, dim=3) > self.prior).view(-1) updated_centroids = self.centroids[updated_cells, :] + torch.from_numpy(self.voxel_translation).to(self.device) local_values = local_map.view(-1, self.num_classes)[updated_cells] new_cells = torch.cat((updated_centroids, local_values), dim=1) # Visited Times = 0 visited_times = torch.zeros(new_cells.shape[0], 1).detach().cpu().numpy() # If empty if self.global_map is None: self.global_map = new_cells.detach().cpu().numpy() self.map_times = visited_times else: # Replace local cells outside_mask = ~ inside_mask # Add new cells self.global_map = np.vstack((self.global_map[outside_mask, :], new_cells.detach().cpu().numpy())) self.map_times = np.vstack((self.map_times[outside_mask, :], visited_times)) # Garbage Collection self.garbage_collection() return self.global_map def garbage_collection(self): self.map_times += 1 # Remove cells with T > self.delete_time recent_mask = self.map_times < self.delete_time recent_mask = np.squeeze(recent_mask) self.map_times = self.map_times[recent_mask, :] self.global_map = self.global_map[recent_mask, :] # Propagate map given a transformation matrix def propagate(self, pose): self.global_pose = pose # Was just initialized if self.initial_pose is None: self.initial_pose = pose # Relative transformation between origin and current point relative_translation = pose[:3, 3] - self.initial_pose[:3, 3] # To select voxels from memory, find the nearest voxel voxel_sizes = self.voxel_sizes.detach().cpu().numpy() self.voxel_translation = np.round(relative_translation / voxel_sizes) * voxel_sizes self.nearest_voxel = self.initial_pose[:3, 3] + self.voxel_translation # Predict labels for points after propagating pose def label_points(self, points): points = torch.from_numpy(points).to(self.device) global_pose = torch.from_numpy(self.global_pose).to(self.device) points = torch.matmul(global_pose[:3, :3], points.T).T + global_pose[:3, 3] labels = torch.zeros((points.shape[0], self.num_classes), dtype=torch.float32, device=self.device) local_map, local_min_bound, local_max_bound, __ = self.get_local_map() local_mask = torch.all((points < local_max_bound) & (points >= local_min_bound), dim=1) local_points = points[local_mask] grid_inds = torch.floor((local_points - local_min_bound) / self.voxel_sizes) maxes = (self.grid_size - 1).view(1, 3) clipped_inds = torch.clamp(grid_inds, torch.zeros_like(maxes), maxes).to(torch.long) labels[local_mask, :] = local_map[clipped_inds[:, 0], clipped_inds[:, 1], clipped_inds[:, 2], :] labels[~local_mask, :] = self.prior # TODO: Add some sort of thresholding based on variance # TODO: Add calculation of expectation, variance predictions = torch.argmax(labels, dim=1) predictions[~local_mask] = self.ignore_labels[0] return predictions, local_mask
7,482
46.66242
142
py
NeuralBKI
NeuralBKI-main/Models/BKINet.py
import torch # BKINet consists of two components: # 1) A pre-trained semantic segmentation model # 2) A pre-trained ConvBKI layer # This module is intended for ROS integration class BKINet(torch.nn.Module): def __init__(self, grid_size, min_bound, max_bound, weights, filter_size, segmentation_net, num_classes=21, prior=0.001, device="cpu", datatype=torch.float32): super().__init__() self.segmentation_net = segmentation_net self.min_bound = min_bound.view(-1, 3).to(device) self.max_bound = max_bound.view(-1, 3).to(device) self.grid_size = grid_size self.dtype = datatype def grid_ind(self, input_pc): ''' Input: input_xyz: N * (x, y, z, c) float32 array, point cloud Output: grid_inds: N' * (x, y, z, c) int32 array, point cloud mapped to voxels ''' input_xyz = input_pc[:, :3] labels = input_pc[:, 3].view(-1, 1) valid_input_mask = torch.all((input_xyz < self.max_bound) & (input_xyz >= self.min_bound), axis=1) valid_xyz = input_xyz[valid_input_mask] valid_labels = labels[valid_input_mask] grid_inds = torch.floor((valid_xyz - self.min_bound) / self.voxel_sizes) maxes = (self.grid_size - 1).view(1, 3) clipped_inds = torch.clamp(grid_inds, torch.zeros_like(maxes), maxes) return torch.hstack((clipped_inds, valid_labels))
1,442
34.195122
106
py
pivnet
pivnet-main/pivnet.py
from typing import List import pickle, itertools from numba import jit, i4, i8, f4, typeof from numba.typed import List from numba.experimental import jitclass import numpy as np from sklearn.preprocessing import StandardScaler from collections import OrderedDict from scipy.spatial import KDTree import multiprocessing as mp import torch from torch.utils import data from torch.utils.data import Dataset, DataLoader import torch.nn as nn import torch.nn.functional as F from torch import optim class SimpleDataset(Dataset): def __init__(self, x, y): self.x = x self.y = y def __len__(self): return len(self.y) def __getitem__(self, idx): return self.x[idx], self.y[idx] def get_state_dict(path): state_dict = torch.load(path)['state_dict'] # remove prefix 'net.' and remake state dict return OrderedDict( {key[4:]: val for key, val in state_dict.items()}) def read_pickle(path): with open(path, mode='rb') as f: instance = pickle.load(f) return instance def to_pickle(path, instance): with open(path, mode='wb') as f: pickle.dump(instance, f) def generate_pivots( database: np.array, grid: int, k: int, margin=0., n_threads=1): """ generate pivots database: np.array database bins: int #grid of each dimension k: int calculate knn distance of pivots knnd_scaler: StandardScaler standard scaler fitted to knn distance margin: float margin of data space boundary n_threads: int number of threads to calculate kNN of pivots set s.t. grid ** dim % n_threads == 0 returns: Pivots """ dim = len(database[0]) # calculate ranges min_values = database.min(axis=0) - margin max_values = database.max(axis=0) + margin # make grid hist, edges = np.histogramdd( database, bins=grid, range=list(zip(min_values, max_values)), density=True) # make pivots edges_wo_max = np.array(edges)[:, :-1] pivots = np.array(list( itertools.product(*edges_wo_max))) # add half of bin width into edges for i in range(dim): bin_width = (max_values[i] - min_values[i]) / grid pivots[:, i] += bin_width / 2 # search knn of pivots index = KDTree(database) # knnd, _ = index.query(proxy_queries, k=k) batch_size = len(pivots) // n_threads with mp.Pool(n_threads) as pool: async_results = [] for i in range(0, len(pivots), batch_size): proxy_query_batch = pivots[i:i+batch_size] async_results.append(pool.apply_async( index.query, (proxy_query_batch, k))) results = np.array( [async_res.get()[0] for async_res in async_results]) \ .reshape(-1, k) pivots = pivots.astype('float32') knnd = results.astype('float32') return Pivots( dim, grid, min_values, max_values, pivots, knnd) @jitclass class Pivots: dim: i4 # dimension grid: i4 # #grid of each dimension min_values: f4[:] # min values for each dimension max_values: f4[:] # max values for each dimension bin_width: f4[:] # bin width of histogram cell_diag: f4 # diagonal length of each cell pivots: f4[:, :] # pivots knnd: f4[:, :] # knn distance of pivots def __init__(self, dim: i4, grid: i4, min_values: f4[:], max_values: f4[:], pivots: f4[:, :], knnd: f4[:, :]) -> None: """ dim: int32 dimension of data grid: int32 #grid of each dimension min_values: np.array[float32] min values for each dimension max_values: np.array[float32] max values for each dimension pivots: np.array[np.array[float32]] pivots knnd: np.array[np.array[float32]] knn distance of pivots """ self.dim = dim self.grid = grid self.min_values = min_values self.max_values = max_values self.bin_width = (max_values - min_values) / grid self.cell_diag = np.sqrt((self.bin_width ** 2).sum()) self.pivots = pivots self.knnd = knnd def calc_index(self, query: f4[:]) -> i4: """ returns: int32 pivot index of a given query in pivots array """ index = 0 for i in range(self.dim): index = index * self.grid + int( (query[i] - self.min_values[i]) \ / (self.max_values[i] - self.min_values[i]) \ * self.grid) return index def calc_indices(self, queries: f4[:, :]) -> i4[:]: """ returns: np.array[int32] pivot indices of given queries in pivots array """ indices = [] for data in queries: index = self.calc_index(data) indices.append(index) return np.array(indices) def get_feature(self, query: f4[:]) -> f4[:]: """ returns: np.array[float32] 0:dim query coordinates dim normalized distance between query and nearest pivot dim+1: pivot's knn distances """ index = self.calc_index(query) pivot = self.pivots[index] dist_from_pivot = np.linalg.norm(query - pivot) return np.concatenate(( query, np.array([dist_from_pivot]) / self.cell_diag, self.knnd[index] )) def get_kth_feature(self, query: f4[:], k: i4) -> f4[:]: """ returns: np.array[float32] 0:dim query coordinates dim normalized distance between query and nearest pivot dim+1 pivot's k-th nn distance """ index = self.calc_index(query) pivot = self.pivots[index] dist_from_pivot = np.linalg.norm(query - pivot) return np.concatenate(( query, np.array([dist_from_pivot]) / self.cell_diag, np.array([self.knnd[index, k-1]]) )) def get_features(self, queries: f4[:, :]) -> f4[:, :]: """ returns: np.array[np.array[float32]] features of given queries """ features = np.empty(( len(queries), len(self.knnd[0])+self.dim+1)) for i, query in enumerate(queries): features[i] = self.get_feature(query) return features def get_kth_features(self, queries: f4[:, :], ks: i4[:]) -> f4[:, :]: """ returns: np.array[np.array[float32]] features of given queries """ features = np.zeros((len(queries), self.dim+2)) for i, (query, k) in enumerate(zip(queries, ks)): features[i] = self.get_kth_feature(query, k) return features def calc_knnd_upper_bound(self, query: f4[:]) -> f4[:]: """ returns: float32 upper bound of knn distances of query """ index = self.calc_index(query) pivot = self.pivots[index] pivot_knnd = self.knnd[index] dist_from_pivot = np.linalg.norm(query - pivot) upper_bound = pivot_knnd + dist_from_pivot return upper_bound def calc_knnd_upper_bounds(self, queries: f4[:, :]) -> f4[:, :]: """ returns: float32 upper bounds of knn distances of queries """ results = np.empty((len(queries), len(self.knnd[0]))) for i, query in enumerate(queries): results[i] = self.calc_knn_upper_bound(query) return results class PivNet(nn.Module): def __init__(self, n_units: List[int], pivots: Pivots, query_scaler: StandardScaler, knnd_scaler: StandardScaler): super().__init__() self.dim = pivots.dim self.k_max = n_units[-1] self.pivots = pivots self.query_scaler = query_scaler self.knnd_mean = knnd_scaler.mean_[:self.k_max] self.knnd_std = knnd_scaler.scale_[:self.k_max] self.fc = nn.Sequential( nn.Linear(n_units[0], n_units[1]), nn.ReLU(), nn.Linear(n_units[1], n_units[2]), nn.ReLU(), nn.Linear(n_units[2], n_units[3]), nn.ReLU(), nn.Linear(n_units[3], n_units[4]), ) def forward(self, x: torch.tensor) -> torch.tensor: feature = torch.from_numpy( self.pivots.get_features(x.numpy())).float() # scale query feature feature[:, :self.dim] = torch.from_numpy( self.query_scaler.transform(feature[:, :self.dim])) # scale pivot's knnd feature[:, self.dim+1:] = \ (feature[:, self.dim+1:] - self.knnd_mean) / self.knnd_std pred = self.fc(feature) return pred def estimate(self, x: torch.tensor) -> torch.tensor: # returns: unscaled knn distances pred = self.forward(x) pred = pred * self.knnd_std + self.knnd_mean return pred class PivNetItr(nn.Module): def __init__(self, dim: int, k_max: int, n_units: List[int], pivots: Pivots, query_scaler: StandardScaler, dist_mean: float, dist_std: float): super().__init__() self.dim = dim self.k_max = k_max self.k_mean = np.arange(1, k_max+1).mean() self.k_std = np.arange(1, k_max+1).std() self.pivots = pivots self.query_scaler = query_scaler self.dist_mean = dist_mean self.dist_std = dist_std self.fc = nn.Sequential( nn.Linear(n_units[0], n_units[1]), nn.ReLU(), nn.Linear(n_units[1], n_units[2]), nn.ReLU(), nn.Linear(n_units[2], n_units[3]), nn.ReLU(), nn.Linear(n_units[3], n_units[4]), ) def forward(self, x: torch.tensor) -> torch.tensor: """ x: torch.tensor each element consists of k and query """ # scale k k = x[:, 0].numpy().astype('int32') k_scaled = (x[:, :1] - self.k_mean) / self.k_std queries = x[:, 1:] feature = torch.from_numpy( self.pivots.get_kth_features(queries.numpy(), k)).float() # scale query feature feature[:, :self.dim] = torch.from_numpy( self.query_scaler.transform(feature[:, :self.dim])) # scale pivot's k-th nnd feature[:, self.dim+1] = \ (feature[:, self.dim+1] - self.dist_mean) / self.dist_std feature = torch.cat([k_scaled, feature], dim=1) pred = self.fc(feature) return pred def estimate(self, x): # returns: unscaled knn distance pred = self.forward(x) pred = pred * self.dist_std + self.dist_mean return pred
10,860
30.120344
73
py
absynthe
absynthe-main/scripts/run_sygus_benchmarks.py
from plumbum import local, FG, TF from plumbum.cmd import bundle import json import numpy as np from scipy.stats import iqr import os import argparse import sys import csv parser = argparse.ArgumentParser(description='Run Absynthe SyGuS benchmarks') parser.add_argument('--times', '-t', dest='times', action='store', default=11, help='number of times to run the benchmark') parser.add_argument('--smallbench', dest='benchtype', action='store_const', const='smallbench', default='bench', help='use the small benchmark suite for data collection') args = parser.parse_args() # if str(args.benchtype) == 'smallbench': # print("Small bench not supported yet!") # sys.exit(0) ABSYNTHE_PATH = '..' MY_CWD = os.getcwd() JSON_LOG_FILE = 'test_log.json' def benchmark(**opts): local.cwd.chdir(ABSYNTHE_PATH) bundle.with_env(**opts)['exec', 'rake', str(args.benchtype)] & TF(FG=True) local.cwd.chdir(MY_CWD) def collect(output_file, times, **opts): merged = None for i in range(times): benchmark(**opts) with open(ABSYNTHE_PATH + '/' + JSON_LOG_FILE) as f: data = json.load(f) if merged is None: merged = data for name, info in data.items(): merged[name]['time'] = [merged[name]['time']] else: for name, info in data.items(): merged[name]['time'].append(data[name]['time']) for name, info in merged.items(): if '-' in merged[name]['time']: merged[name]['median_time'] = '-' merged[name]['time_siqr'] = '-' merged[name]['tested_progs'] = '-' merged[name]['size'] = '-' else: merged[name]['median_time'] = np.median(merged[name]['time']) merged[name]['time_siqr'] = iqr(merged[name]['time']) / 2 with open(output_file, 'w') as out: json.dump(merged, out) def combine_results(base, no_template, no_cache): for k, v in no_template.items(): if k not in base: base[k] = {} base[k]['no_template'] = v['time'][0] for k, v in no_cache.items(): if k not in base: base[k] = {} base[k]['no_cache'] = v['time'][0] return base def to_table(data, filename): with open(filename, 'w', newline='') as csvfile: tablewriter = csv.writer(csvfile) tablewriter.writerow(['Name', 'Time Median (s)', 'Time SIQR (s)', 'Size', '# Ex', 'Tested Progs', 'Domains', 'No cache', 'No template']) for k, v in data.items(): tablewriter.writerow([k, v['median_time'], v['time_siqr'], v['size'], v['specs'], v['tested_progs'], v['domain'], v['no_cache'], v['no_template']]) collect('sygus_data.json', int(args.times)) collect('sygus_template_infer.json', 1, TEMPLATE_INFER='1') collect('sygus_no_cache.json', 1, NO_CACHE='1') with open('sygus_data.json', 'r') as f: base = json.load(f) with open('sygus_template_infer.json', 'r') as f: no_template = json.load(f) with open('sygus_no_cache.json', 'r') as f: no_cache = json.load(f) data = combine_results(base, no_template, no_cache) to_table(data, 'table1.csv')
3,229
34.494505
159
py
absynthe
absynthe-main/scripts/run_autopandas_benchmarks.py
import json import numpy as np from scipy.stats import iqr import os import argparse import sys import csv sys.path.insert(1, os.path.abspath('../autopandas/')) from harness import run_benchmarks, benches, smallbenches parser = argparse.ArgumentParser(description='Run Absynthe AutoPandas benchmarks') parser.add_argument('--times', '-t', dest='times', action='store', default=11, help='number of times to run the benchmark') parser.add_argument('--smallbench', dest='benchtype', action='store_const', const='smallbench', default='bench', help='use the small benchmark suite for data collection') args = parser.parse_args() # if str(args.benchtype) == 'smallbench': # print("Small bench not supported yet!") # sys.exit(0) ABSYNTHE_PATH = '..' MY_CWD = os.getcwd() IGNORE_LIST = [] BENCH_ORDER = [ 'SO_11881165_depth1', 'SO_11941492_depth1', 'SO_13647222_depth1', 'SO_18172851_depth1', 'SO_49583055_depth1', 'SO_49583055_depth1', 'SO_49592930_depth1', 'SO_49572546_depth1', 'SO_12860421_depth1', 'SO_13261175_depth1', 'SO_13793321_depth1', 'SO_14085517_depth1', 'SO_11418192_depth2', 'SO_49567723_depth2', 'SO_49987108_depth2', 'SO_13261691_depth2', 'SO_13659881_depth2', 'SO_13807758_depth2', 'SO_34365578_depth2', 'SO_10982266_depth3', 'SO_11811392_depth3', 'SO_49581206_depth3', 'SO_12065885_depth3', 'SO_13576164_depth3', 'SO_14023037_depth3', 'SO_53762029_depth3', 'SO_21982987_depth3', 'SO_39656670_depth3', 'SO_23321300_depth3' ] def collect(output_file, times, **opts): merged = None for i in range(times): if str(args.benchtype) == 'smallbench': data, skips = run_benchmarks(smallbenches, IGNORE_LIST) else: data, skips = run_benchmarks(benches, IGNORE_LIST) IGNORE_LIST.extend(skips) if merged is None: merged = data for name, info in data.items(): merged[name]['time'] = [merged[name]['time']] else: for name, info in data.items(): merged[name]['time'].append(data[name]['time']) for name, info in merged.items(): if '-' in merged[name]['time']: merged[name]['median_time'] = '-' merged[name]['time_siqr'] = '-' merged[name]['size'] = '-' merged[name]['tested_progs'] = '-' else: merged[name]['median_time'] = np.median(merged[name]['time']) merged[name]['time_siqr'] = iqr(merged[name]['time']) / 2 with open(output_file, 'w') as out: json.dump(merged, out) def to_table(data, filename): with open(filename, 'w', newline='') as csvfile: tablewriter = csv.writer(csvfile) tablewriter.writerow(['Name', 'Depth', 'Time Median (s)', 'Time SIQR (s)', 'Size', 'Tested Progs']) for k in BENCH_ORDER: if k in data: v = data[k] tablewriter.writerow([k, v['depth'], v['median_time'], v['time_siqr'], v['size'], v['tested_progs']]) collect('autopandas_data.json', int(args.times)) with open('autopandas_data.json', 'r') as f: data = json.load(f) to_table(data, 'table2.csv')
3,202
30.401961
117
py
absynthe
absynthe-main/autopandas/benchmarks.py
# The following benchmarks are sourced from the AutoPandas benchmarks # Source: https://github.com/rbavishi/autopandas/blob/master/autopandas_v2/evaluation/benchmarks/stackoverflow.py from io import StringIO import pandas as pd import numpy as np from runner import Benchmark # https://stackoverflow.com/questions/11881165 class SO_11881165_depth1(Benchmark): def __init__(self): super().__init__() self.inputs = [pd.DataFrame({"a": [5, 6, 7, 8, 9], "b": [10, 11, 12, 13, 14]})] self.output = self.inputs[0].loc[[0, 2, 4]] self.funcs = ['df.loc_getitem'] self.seqs = [[0]] # https://stackoverflow.com/questions/11941492/ # same thing class SO_11941492_depth1(Benchmark): def __init__(self): super().__init__() df = pd.DataFrame({'group1': ['a', 'a', 'a', 'b', 'b', 'b'], 'group2': ['c', 'c', 'd', 'd', 'd', 'e'], 'value1': [1.1, 2, 3, 4, 5, 6], 'value2': [7.1, 8, 9, 10, 11, 12] }) df = df.set_index(['group1', 'group2']) self.inputs = [df] self.output = df.xs('a', level=0) self.funcs = ['df.xs'] self.seqs = [[0]] # https://stackoverflow.com/questions/13647222 class SO_13647222_depth1(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame({'series': {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'B', 5: 'C', 6: 'A', 7: 'B', 8: 'C', 9: 'A', 10: 'B', 11: 'C', 12: 'A', 13: 'B', 14: 'C'}, 'step': {0: '100', 1: '100', 2: '100', 3: '101', 4: '101', 5: '101', 6: '102', 7: '102', 8: '102', 9: '103', 10: '103', 11: '103', 12: '104', 13: '104', 14: '104'}, 'value': {0: '1000', 1: '1001', 2: '1002', 3: '1003', 4: '1004', 5: '1005', 6: '1006', 7: '1007', 8: '1008', 9: '1009', 10: '1010', 11: '1011', 12: '1012', 13: '1013', 14: '1014'}}) ] self.output = self.inputs[0].pivot(columns='series', values='value', index='step') self.funcs = ['df.pivot'] self.seqs = [[0]] # https://stackoverflow.com/questions/18172851/ class SO_18172851_depth1(Benchmark): def __init__(self): super().__init__() df = pd.DataFrame({'daysago': {'2007-03-31': 62, '2007-03-10': 83, '2007-02-10': 111, '2007-01-13': 139, '2006-12-23': 160, '2006-11-09': 204, '2006-10-22': 222, '2006-09-29': 245, '2006-09-16': 258, '2006-08-30': 275, '2006-02-11': 475, '2006-01-13': 504, '2006-01-02': 515, '2005-12-06': 542, '2005-11-29': 549, '2005-11-22': 556, '2005-11-01': 577, '2005-10-20': 589, '2005-09-27': 612, '2005-09-07': 632, '2005-06-12': 719, '2005-05-29': 733, '2005-05-02': 760, '2005-04-02': 790, '2005-03-13': 810, '2004-11-09': 934}, 'line_race': {'2007-03-31': 111, '2007-03-10': 211, '2007-02-10': 29, '2007-01-13': 110, '2006-12-23': 210, '2006-11-09': 39, '2006-10-22': 28, '2006-09-29': 49, '2006-09-16': 311, '2006-08-30': 48, '2006-02-11': 45, '2006-01-13': 0, '2006-01-02': 0, '2005-12-06': 0, '2005-11-29': 0, '2005-11-22': 0, '2005-11-01': 0, '2005-10-20': 0, '2005-09-27': 0, '2005-09-07': 0, '2005-06-12': 0, '2005-05-29': 0, '2005-05-02': 0, '2005-04-02': 0, '2005-03-13': 0, '2004-11-09': 0}, 'rw': {'2007-03-31': 0.99999, '2007-03-10': 0.97, '2007-02-10': 0.9, '2007-01-13': 0.8806780000000001, '2006-12-23': 0.793033, '2006-11-09': 0.636655, '2006-10-22': 0.581946, '2006-09-29': 0.518825, '2006-09-16': 0.48622600000000005, '2006-08-30': 0.446667, '2006-02-11': 0.16459100000000002, '2006-01-13': 0.14240899999999998, '2006-01-02': 0.1348, '2005-12-06': 0.11780299999999999, '2005-11-29': 0.113758, '2005-11-22': 0.10985199999999999, '2005-11-01': 0.098919, '2005-10-20': 0.093168, '2005-09-27': 0.083063, '2005-09-07': 0.075171, '2005-06-12': 0.04869, '2005-05-29': 0.045404, '2005-05-02': 0.039679, '2005-04-02': 0.03416, '2005-03-13': 0.030914999999999998, '2004-11-09': 0.016647}}) df['rating'] = range(2, 28) df['wrating'] = df['rw'] * df['rating'] df = df[['daysago', 'line_race', 'rating', 'rw', 'wrating']] self.inputs = [df, lambda a: a.line_race != 0] self.output = self.inputs[0].loc[lambda a: a.line_race != 0] self.funcs = ['df.loc_getitem'] self.seqs = [[0]] # https://stackoverflow.com/questions/49583055 class SO_49583055_depth1(Benchmark): def __init__(self): super().__init__() self.inputs = [pd.DataFrame({'ID': {0: 20, 1: 21, 2: 22, 3: 32, 4: 31, 5: 33}, 'admit': {0: pd.Timestamp('2018-03-04 00:00:00'), 1: pd.Timestamp('2018-02-02 00:00:00'), 2: pd.Timestamp('2018-02-05 00:00:00'), 3: pd.Timestamp('2018-01-02 00:00:00'), 4: pd.Timestamp('2018-01-15 00:00:00'), 5: pd.Timestamp('2018-01-20 00:00:00')}, 'discharge': {0: pd.Timestamp('2018-03-06 00:00:00'), 1: pd.Timestamp('2018-02-06 00:00:00'), 2: pd.Timestamp('2018-02-23 00:00:00'), 3: pd.Timestamp('2018-02-03 00:00:00'), 4: pd.Timestamp('2018-01-18 00:00:00'), 5: pd.Timestamp('2018-01-24 00:00:00')}, 'discharge_location': {0: 'Home1', 1: 'Home2', 2: 'Home3', 3: 'Home4', 4: 'Home5', 5: 'Home6'}, 'first': {0: 11, 1: 10, 2: 9, 3: 8, 4: 12, 5: 7}})] self.output = self.inputs[0].sort_values(by=['ID', 'first', 'admit'], ascending=[True, False, True]) self.funcs = ['df.sort_values'] self.seqs = [[0]] # https://stackoverflow.com/questions/49592930 # ok I didn't uniqify the timestamps because that would change the actual output class SO_49592930_depth1(Benchmark): def __init__(self): super().__init__() self.inputs = [pd.DataFrame({'value': {pd.Timestamp('2014-05-21 09:30:00'): 0.0, pd.Timestamp('2014-05-21 10:00:00'): 10.0, pd.Timestamp('2014-05-21 10:30:00'): 3.0, pd.Timestamp('2017-07-10 22:30:00'): 18.3, pd.Timestamp('2017-07-10 23:00:00'): 7.6, pd.Timestamp('2017-07-10 23:30:00'): 2.0}}), pd.DataFrame({'value': {pd.Timestamp('2014-05-21 09:00:00'): 1.0, pd.Timestamp('2014-05-21 10:00:00'): 13.0, pd.Timestamp('2017-07-10 21:00:00'): 1.6, pd.Timestamp('2017-07-10 22:00:00'): 32.1, pd.Timestamp('2017-07-10 23:00:00'): 7.7}}) ] self.output = self.inputs[0].combine_first(self.inputs[1]) self.funcs = ['df.combine_first'] self.seqs = [[0]] # https://stackoverflow.com/questions/49572546 class SO_49572546_depth1(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame( {'C1': {1: 100, 2: 102, 3: 103, 4: 104, 5: 105, 6: 106, 7: 107}, 'C2': {1: 201, 2: 202, 3: 203, 4: 204, 5: 205, 6: 206, 7: 207}, 'C3': {1: 301, 2: 302, 3: 303, 4: 304, 5: 305, 6: 306, 7: 307}}), pd.DataFrame( {'C1': {2: '1002', 3: 'v1', 4: 'v4', 7: '1007'}, 'C2': {2: '2002', 3: 'v2', 4: 'v5', 7: '2007'}, 'C3': {2: '3002', 3: 'v3', 4: 'v6', 7: '3007'}}) ] self.output = self.inputs[1].combine_first(self.inputs[0]) self.funcs = ['df.combine_first'] self.seqs = [[0]] class SO_12860421_depth1(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame(columns=['X', 'Y', 'Z'], index=[4, 5, 6, 7], data=[['X1', 'Y2', 'Z3'], ['X1', 'Y1', 'Z1'], ['X1', 'Y1', 'Z1'], ['X1', 'Y1', 'Z2']] ), pd.Series.nunique ] self.output = self.inputs[0].pivot_table(values='X', index='Y', columns='Z', aggfunc=pd.Series.nunique) self.funcs = ['df.pivot_table'] self.seqs = [[0]] # https://stackoverflow.com/questions/13261175 class SO_13261175_depth1(Benchmark): def __init__(self): super().__init__() df = pd.DataFrame({'name': ['A', 'B', 'A', 'B'], 'type': [11, 11, 12, 12], 'date': ['2012-01-01', '2012-01-01', '2012-02-01', '2012-02-01'], 'value': [4, 5, 6, 7]}) pt = df.pivot_table(values='value', index='name', columns=['type', 'date']) self.inputs = [df] self.output = pt self.funcs = ['df.pivot_table'] self.seqs = [[0]] # https://stackoverflow.com/questions/13793321 class SO_13793321_depth1(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame([[11, 12, 13]], columns=[10, 1, 2]), pd.DataFrame([[11, 37, 38], [34, 19, 39]], columns=[10, 3, 4]) ] self.output = self.inputs[0].merge(self.inputs[1], on=10) self.funcs = ['df.merge'] self.seqs = [[0]] class SO_14085517_depth1(Benchmark): def __init__(self): super().__init__() text = '''\ SEGM1\tDESC\tDistribuzione Ponderata\tRotazioni a volume AD2\tACCADINAROLO\t74.040\t140249.693409 AD1\tZYMIL AMALAT Z\t90.085\t321529.053570 FUN\tSPECIALMALAT S\t88.650\t120711.182177 NORM5\tSTD INNAROLO\t49.790\t162259.216710 NORM4\tSTD P.NAROLO\t52.125\t1252174.695695 NORM3\tSTD PLNAROLO\t54.230\t213257.829615 NORM1\tBONTA' MALAT B\t79.280\t520454.366419 NORM6\tDA STD RILGARD\t35.290\t554927.497875 NORM7\tOVANE VT.MANTO\t15.040\t466232.639628 NORM2\tWEIGHT MALAT W\t79.170\t118628.572692 ''' from io import StringIO a = pd.read_csv(StringIO(text), delimiter='\t', index_col=(0, 1), ) self.inputs = [a] self.output = a.sort_values(['SEGM1', 'Distribuzione Ponderata'], ascending=[True, False]) self.seqs = [[0]] self.funcs = ['df.sort_values'] class SO_11418192_depth2(Benchmark): def __init__(self): super().__init__() self.inputs = [pd.DataFrame(data=[[5, 7], [6, 8], [-1, 9], [-2, 10]], columns=['a', 'b']), lambda x: x['a'] > 1, 'a > 1'] t = self.inputs[0] self.output = t[t.apply(lambda x: x['a'] > 1, axis=1)] self.funcs = ['df.apply', 'df.__getitem__'] self.seqs = [[0, 1]] class SO_49567723_depth2(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame({'id': {0: 255, 1: 91, 2: 347, 3: 30, 4: 68, 5: 159, 6: 32, 7: 110, 8: 225, 9: 257}, 'valueA': {0: 1141, 1: 1130, 2: 830, 3: 757, 4: 736, 5: 715, 6: 713, 7: 683, 8: 638, 9: 616}}), pd.DataFrame({'id': {0: 255, 1: 91, 2: 5247, 3: 347, 4: 30, 5: 68, 6: 159, 7: 32, 8: 110, 9: 225, 10: 257, 11: 917, 12: 211, 13: 25}, 'valueB': {0: 1231, 1: 1170, 2: 954, 3: 870, 4: 757, 5: 736, 6: 734, 7: 713, 8: 683, 9: 644, 10: 616, 11: 585, 12: 575, 13: 530}}), 'valueA != valueB' ] self.output = self.inputs[0].merge(self.inputs[1], on=['id']).query('valueA != valueB') self.funcs = ['df.merge', 'df.query'] self.seqs = [[0, 1]] # https://stackoverflow.com/questions/49987108 class SO_49987108_depth2(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame({'ID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 'COL': [23, np.nan, np.nan, np.nan, np.nan, 21, np.nan, np.nan, np.nan, 25, np.nan, np.nan]}).set_index('ID'), int ] self.output = self.inputs[0].fillna(method='ffill').astype(int) self.seqs = [[0, 1]] self.funcs = ['df.fillna', 'df.astype'] # https://stackoverflow.com/questions/13261691 # (there's also another potential q/a pair in this question) # or this could just be done with a sort???? class SO_13261691_depth2(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame( {'date': ['3/9/12', '3/10/12', '4/9/12', '9/9/12', '11/9/12', '30/9/12', '31/10/12', '1/11/12'], 'score': [100, 99, 102, 103, 111, 98, 103, 104]}, index=pd.MultiIndex.from_tuples( [('A', 'John1'), ('B', 'John2'), ('B', 'Jane'), ('A', 'Peter'), ('C', 'Josie'), ('A', 'Rachel'), ('B', 'Kate'), ('C', 'David')], names=['team', 'name'])) ] self.output = self.inputs[0].stack().unstack() self.funcs = ['df.stack', 'df.unstack'] self.seqs = [[0, 1]] class SO_13659881_depth2(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame( columns=['ip', 'useragent'], index=[0, 1, 2, 3], data=[['192.168.0.1', 'a'], ['192.168.0.1', 'a'], ['192.168.0.1', 'b'], ['192.168.0.2', 'b']] ) ] self.output = self.inputs[0].groupby(['ip', 'useragent']).size() self.funcs = ['df.groupby', 'dfgroupby.size'] self.seqs = [[0, 1]] # https://stackoverflow.com/questions/13807758 class SO_13807758_depth2(Benchmark): def __init__(self): super().__init__() df1 = pd.DataFrame([[10], [11], [12], [14], [16], [18]]) df1[::3] = np.nan self.inputs = [ df1 ] self.output = self.inputs[0].dropna().reset_index(drop=True) self.funcs = ['df.dropna', 'df.reset_index'] self.seqs = [[0, 1]] # http://stackoverflow.com/questions/34365578/dplyr-filtering-based-on-two-variables class SO_34365578_depth2(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame({'Group': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B', 5: 'B'}, 'Id': {0: 11, 1: 12, 2: 13, 3: 14, 4: 15, 5: 16}, 'Var1': {0: 'good', 1: 'good', 2: 'bad', 3: 'good', 4: 'good', 5: 'bad'}, 'Var2': {0: 20, 1: 26, 2: 29, 3: 23, 4: 23, 5: 28}}), "Group == \"A\"", 'sum', ] self.output = self.inputs[0].query('Group == "A"').pivot_table(index='Group', columns='Var1', values='Var2', aggfunc='sum') self.funcs = ['df.query', 'df.pivot_table'] self.seqs = [[0, 1]] # https://stackoverflow.com/questions/10982266 class SO_10982266_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [pd.DataFrame( [['08:01:08', 'C', 'PXA', 20100101, 4000, 'A', 57.8, 60], ['08:01:11', 'C', 'PXA', 20100101, 4000, 'A', 58.4, 60], ['08:01:12', 'C', 'PXA', 20100101, 4000, 'A', 58.0, 60], ['08:01:16', 'C', 'PXA', 20100101, 4000, 'A', 58.4, 60], ['08:01:16', 'C', 'PXA', 20100101, 4000, 'A', 58.0, 60], ['08:01:21', 'C', 'PXA', 20100101, 4000, 'A', 58.4, 60], ['08:01:21', 'C', 'PXA', 20100101, 4000, 'A', 58.0, 60]], columns=['time', 'contract', 'ticker', 'expiry', 'strike', 'quote', 'price', 'volume'], index=[0, 1, 2, 3, 4, 5, 6] )] self.output = pd.DataFrame( [['08:01:08', 57.8, 60], ['08:01:11', 58.4, 60], ['08:01:12', 58.0, 60], ['08:01:16', 58.2, 60], ['08:01:21', 58.2, 60]], columns=['time', 'price', 'volume'], index=[0, 1, 2, 3, 4] ) self.funcs = ['df.groupby', 'dfgroupby.mean', 'df.__getitem__'] self.seqs = [[0, 1, 2]] # original answer for input a: # pd.DataFrame([{'time': k, # 'price': (v.price * v.volume).sum() / v.volume.sum(), # 'volume': v.volume.mean()} # for k, v in a.groupby(['time'])], # columns=['time', 'price', 'volume']) # https://stackoverflow.com/questions/11811392 class SO_11811392_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [pd.DataFrame( columns=['one', 'two', 'three', 'four', 'five'], index=[0, 1], data=[[1, 2, 3, 4, 5], [1, 1, 1, 1, 1]] )] # original has a tolist at the end, but we don't support that self.output = self.inputs[0].T.reset_index().values self.funcs = ['df.T', 'dfgroupby.reset_index', 'df.values'] self.seqs = [[0, 1, 2]] # https://stackoverflow.com/questions/49581206 class SO_49581206_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame({'A': {('col1', 'no'): 2, ('col1', 'yes'): 8, ('col2', 'no'): 2, ('col2', 'yes'): 6}, 'B': {('col1', 'no'): 0, ('col1', 'yes'): 2, ('col2', 'no'): 1, ('col2', 'yes'): 1}}).T ] self.output = self.inputs[0].div(self.inputs[0].sum(1, level=0), 1, 0).xs('yes', 1, 1) self.funcs = ['df.sum', 'df.div', 'df.xs'] self.seqs = [[0, 1, 2]] # https://stackoverflow.com/questions/12065885 class SO_12065885_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame({'RPT_Date': {0: '1980-01-01', 1: '1980-01-02', 2: '1980-01-03', 3: '1980-01-04', 4: '1980-01-05', 5: '1980-01-06', 6: '1980-01-07', 7: '1980-01-08', 8: '1980-01-09', 9: '1980-01-10'}, 'STK_ID': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}, 'STK_Name': {0: 'Arthur', 1: 'Beate', 2: 'Cecil', 3: 'Dana', 4: 'Eric', 5: 'Fidel', 6: 'George', 7: 'Hans', 8: 'Ingrid', 9: 'Jones'}, 'sales': {0: 0, 1: 4, 2: 2, 3: 8, 4: 4, 5: 5, 6: 4, 7: 7, 8: 7, 9: 4}}), [[4, 2, 6]] ] self.output = self.inputs[0][self.inputs[0].STK_ID.isin([4, 2, 6])] self.funcs = ['df.isin', 'df.getitem', 'df.loc_getitem'] self.seqs = [[2, 0, 1]] # https://stackoverflow.com/questions/13576164 class SO_13576164_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame(columns=['col1', 'to_merge_on'], index=pd.MultiIndex.from_arrays([[1, 1, 2, 2], ['a', 'b', 'a', 'b']], names=['id1', 'id2']), data=[[1, 2], [3, 4], [1, 2], [3, 4]]), pd.DataFrame(columns=['col2', 'to_merge_on'], index=[0, 1, 2], data=[[1, 1], [2, 3], [3, 5]]) ] self.output = self.inputs[0].reset_index().merge(self.inputs[1], how='left').set_index( ['id1', 'id2']) self.funcs = ['df.reset_index', 'df.merge', 'df.set_index'] self.seqs = [[0, 1, 2]] # https://stackoverflow.com/questions/14023037 class SO_14023037_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame( {'id': [1, 2, 3, 4, 5, 6], 'col1': ['A1', 'A1', 'A1', 'A1', 'A2', 'A2'], 'col2': ['B1', 'B1', 'B2', 'B2', 'B1', 'B2'], 'col3': ['before', 'after', 'before', 'after', 'before', 'after'], 'value': [20, 13, 11, 21, 18, 22]}, columns=['id', 'col1', 'col2', 'col3', 'value']) ] self.output = self.inputs[0].pivot_table(values='value', index=['col1', 'col2'], columns=['col3']).fillna(method='bfill').dropna() self.funcs = ['df.pivot_table', 'df.fillna', 'df.dropna'] self.seqs = [[0, 1, 2]] # https://stackoverflow.com/questions/53762029/pandas-groupby-and-cumsum-on-a-column class SO_53762029_depth3(Benchmark): def __init__(self): super().__init__() data = """ doc_created_month doc_created_year speciality doc_id_count 8 2016 Acupuncturist 1 2 2017 Acupuncturist 1 4 2017 Acupuncturist 1 4 2017 Allergist 1 5 2018 Allergist 1 10 2018 Allergist 2 """ df = pd.read_csv(StringIO(data), sep='\s+') self.inputs = [df] self.output = df.groupby(['doc_created_month', 'doc_created_year', 'speciality']).sum().cumsum() self.funcs = ['df.groupby', 'dfgroupby.sum', 'df.cumsum'] self.seqs = [[0, 1, 2]] # http://stackoverflow.com/questions/21982987/mean-per-group-in-a-data-frame class SO_21982987_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame({"Name": ["Aira", "Aira", "Ben", "Ben", "Cat", "Cat"], "Month": [1, 2, 1, 2, 1, 2], "Rate1": [12, 18, 53, 22, 22, 27], "Rate2": [23, 73, 19, 87, 87, 43]}), ] self.output = pd.DataFrame({'Name': {0: 'Aira', 1: 'Ben', 2: 'Cat'}, 'Rate1': {0: 15.0, 1: 37.5, 2: 24.5}, 'Rate2': {0: 48.0, 1: 53.0, 2: 65.0}}) self.seqs = [[0, 1, 2]] self.funcs = ['df.groupby', 'dfgroupby.mean', 'df.drop'] # http://stackoverflow.com/questions/39656670/pivot-table-on-r-using-dplyr-or-tidyr class SO_39656670_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame( {"Player": ["Abdoun", "Abe", "Abidal", "Abreu"], "Team": ["Algeria", "Japan", "France", "Uruguay"], "Shots": [0, 3, 0, 5], "Passes": [6, 101, 91, 15], "Tackles": [0, 14, 6, 0]}), ] self.output = self.inputs[0].melt(value_vars=["Passes", "Tackles"], var_name="Var", value_name="Mean").groupby( "Var", as_index=False).mean() self.seqs = [[0, 1, 2]] self.funcs = ['df.melt', 'df.groupby', 'dfgroupby.mean'] # http://stackoverflow.com/questions/23321300/efficient-method-to-filter-and-add-based-on-certain-conditions-3-conditions-in class SO_23321300_depth3(Benchmark): def __init__(self): super().__init__() self.inputs = [ pd.DataFrame({"a": [1, 1, 1, 1, 1, 1, 1, 1, 1], "b": [1, 1, 1, 1, 1, 2, 2, 2, 3], "d": [0, 200, 300, 0, 600, 0, 100, 200, 0]}), 'd > 0' ] self.output = self.inputs[0].query('d > 0').groupby(['a', 'b']).mean() self.funcs = ['df.query', 'df.groupby', 'dfgroupby.mean'] self.seqs = [[0, 1, 2]]
25,083
49.777328
124
py
absynthe
absynthe-main/autopandas/harness.py
import io import subprocess import benchmarks import unittest import warnings import time import random import sys import os from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import TerminalFormatter from protocol import Protocol, handle_action # List of benchmarks to run in standard mode benches = [ benchmarks.SO_11881165_depth1(), benchmarks.SO_11941492_depth1(), benchmarks.SO_13647222_depth1(), benchmarks.SO_18172851_depth1(), benchmarks.SO_49583055_depth1(), benchmarks.SO_49583055_depth1(), benchmarks.SO_49592930_depth1(), benchmarks.SO_49572546_depth1(), benchmarks.SO_12860421_depth1(), # slow; not in AutoPandas paper benchmarks.SO_13261175_depth1(), benchmarks.SO_13793321_depth1(), benchmarks.SO_14085517_depth1(), benchmarks.SO_11418192_depth2(), benchmarks.SO_49567723_depth2(), benchmarks.SO_49987108_depth2(), # not in AutoPandas paper benchmarks.SO_13261691_depth2(), benchmarks.SO_13659881_depth2(), benchmarks.SO_13807758_depth2(), benchmarks.SO_34365578_depth2(), # slow benchmarks.SO_10982266_depth3(), # fail benchmarks.SO_11811392_depth3(), benchmarks.SO_49581206_depth3(), # slow benchmarks.SO_12065885_depth3(), # slow benchmarks.SO_13576164_depth3(), benchmarks.SO_14023037_depth3(), benchmarks.SO_53762029_depth3(), benchmarks.SO_21982987_depth3(), # not tried benchmarks.SO_39656670_depth3(), benchmarks.SO_23321300_depth3() ] random.shuffle(benches) # List of benchmarks to run in --smallbench mode smallbenches = [ benchmarks.SO_11881165_depth1(), benchmarks.SO_11418192_depth2(), benchmarks.SO_13659881_depth2() ] random.shuffle(smallbenches) def pprint_color(obj): print(highlight(obj, PythonLexer(), TerminalFormatter())) def run_benchmarks(benches, ignore_list): skips = [] results = {} for bench in benches: print(type(bench).__name__) if bench in ignore_list: print('SKIPPED!') continue try: with warnings.catch_warnings(): warnings.simplefilter("ignore") # infer abstract spec from the input output example data = bench.absynthe_input() data['action'] = 'start' env = os.environ env['RUBYOPT'] = '-W0' # run Absynthe as a child process proc = subprocess.Popen(['bundle', 'exec', 'bin/autopandas'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, # stderr=subprocess.PIPE, cwd=r'..', env=env) # use the I/O protcol to communicate with Absynthe p = Protocol(proc, log=True) p.write(data) final_out = handle_action(p, bench) if final_out is None: # timeout happened # results are logged with a `-` for the time taken skips.append(bench) final_out = {} final_out['depth'] = len(bench.seqs[0]) final_out['time'] = '-' results[type(bench).__name__] = final_out else: # benchmark completed to success # synthesized program and the time is logged prog = final_out['prog'] final_out['depth'] = len(bench.seqs[0]) pprint_color(prog) print(final_out['time']) results[type(bench).__name__] = final_out proc.wait() proc.stdin.close() proc.stdout.close() # proc.stderr.close() except: print("ERROR!") print(sys.exc_info()) return (results, skips) if __name__ == '__main__': run_benchmarks(benches, [])
3,650
29.940678
69
py
absynthe
absynthe-main/autopandas/runner.py
import pandas as pd import numpy as np import itertools def flatten(xs): try: return list(itertools.chain(*xs)) except: return xs # Defines and infers the domains required by AutoPandas in Python # Note that all the methods required by each domain is still defined in Ruby. # The code here just reads a Python value, infers necessary abstractions, # serializes it and then hands it as a JSON to the Absynthe core. # This allows us to leverage native Python methods and libraries to infer # abstractions from Python values. class Abstraction: # Infers the type from a Python value def _infer_type(arg): if isinstance(arg, pd.DataFrame): return 'DataFrame' elif isinstance(arg, pd.Series): return 'Series' elif isinstance(arg, np.ndarray): return 'NdArray' elif isinstance(arg, str): return 'String' elif isinstance(arg, int): return 'Integer' elif isinstance(arg, list): return 'Array<{}>'.format(Abstraction._infer_type(arg[0])) elif callable(arg): # NOTE: all functions a -> b are typed as Lambda return 'Lambda' else: raise Exception("Unexpected input argument {}".format(arg)) # Infers row labels as a set def _infer_rownum(df): # return list(df.index) return list(set(flatten(list(df.index)))) # Gets the types for input and output examples def types(b): inp = list(map(Abstraction._infer_type, b.inputs)) out = Abstraction._infer_type(b.output) return [inp, out] # Infers row labels as a set for input and output examples def rownums(b): inp = list(map(Abstraction._infer_rownum, b.inputs)) out = Abstraction._infer_rownum(b.output) return [inp, out] # Infer constants from Pandas indexes def index2const(index): consts = [] if type(index) in [pd.Index, pd.Int64Index, pd.DatetimeIndex] : consts.extend(list(index)) elif type(index) == pd.RangeIndex: consts.extend(range(index.start, index.stop, index.step)) elif type(index) == pd.MultiIndex: consts.extend(flatten(list(index))) else: print(index) raise RuntimeError("Unhandled index: " + str(type(index))) if index.name is not None: consts.append(index.name) if index.names is not None: consts.extend(list(index.names)) return filter(lambda v: v is not None, consts) # Set of constants in rows and columns def consts(b): filtered_vals = list(filter(lambda v: isinstance(v, pd.DataFrame), b.inputs + [b.output])) val_indexes = map(Abstraction.index2const, map(lambda v: v.index, filtered_vals)) val_columns = map(Abstraction.index2const, map(lambda v: v.columns, filtered_vals)) consts = flatten(list(val_indexes) + list(val_columns)) consts.append(0) # NOTE: only support int and strings in JSON serialization supported_consts = filter(lambda v: type(v) in [int, str], consts) return set(supported_consts) # Set of column labels as inputs def cols_inp(b): idx = 0 colmap = {} for i in b.inputs: if type(i) == pd.DataFrame: colmap["arg{}".format(idx)] = i.columns else: colmap["arg{}".format(idx)] = 'bot' idx += 1 if type(b.output) == pd.DataFrame: outcol = "outcol" for i in range(idx): if type(colmap["arg{}".format(i)]) is not str and colmap["arg{}".format(i)].equals(b.output.columns): outcol = "df{}".format(i) else: outcol = 'bot' for i in range(idx): if type(colmap["arg{}".format(i)]) == str: continue replaced = False for j in range(i): if type(colmap["arg{}".format(j)]) == type(colmap["arg{}".format(i)]) == pd.DataFrame: if colmap["arg{}".format(i)].equals(colmap["arg{}".format(j)]): colmap["arg{}".format(i)] = colmap["arg{}".format(j)] replaced = True if not replaced: colmap["arg{}".format(i)] = "df{}".format(i) args = [] for i in range(idx): args.append(colmap["arg{}".format(i)]) return (args, outcol) # Combine all these individual abstractions into the composite object def all(b): tyin, tyout = Abstraction.types(b) # rownumin, rownumout = Abstraction.rownums(b) colin, colout = Abstraction.cols_inp(b) return { 'argsty': tyin, 'outputty': tyout, # 'rownumin': rownumin, # 'rownumout': rownumout, 'colin': colin, 'colout': colout, 'consts': list(Abstraction.consts(b)), 'seqs': len(b.seqs[0]) } # Base class for each benchmark. We define a `test_candidate` method that # allows one to run a candidate against a benchmark's input/output example class Benchmark: def __init__(self): pass def absynthe_input(self): return Abstraction.all(self) def test_candidate(self, prog): env = {} for i in range(len(self.inputs)): env['arg' + str(i)] = self.inputs[i] try: ret = eval(prog, globals(), env) if isinstance(ret, np.ndarray): return np.array_equal(ret, self.output) elif isinstance(ret, list): return ret == self.output else: return ret.equals(self.output) except: # print("Eval error: {}".format(prog)) return False
5,867
34.137725
117
py
absynthe
absynthe-main/autopandas/protocol.py
# This file defines the IPC protocol used by the AutoPandas Python test harness # process to communicate with the Absynthe core process in Ruby. This is a JSON # line protocol with each action decribing steps happening with every message. import json class Action: pass class Protocol: def __init__(self, proc, log=True): self.proc = proc self.log = log def read(self): while True: line = self.proc.stdout.readline() if not line: # TODO: process ended return try: # read messages returned by Absynthe core data = json.loads(line) # TODO: additional parsing return data except ValueError: if self.log: print("ABSYNTHE LOG: {}".format(line.decode("UTF-8").strip())) def write(self, data): txt = json.dumps(data) self.proc.stdin.write((txt + "\n").encode("UTF-8")) self.proc.stdin.flush() # TODO: convert to `Action` objects for better handling of the return value def handle_action(protocol, bench): while True: data = protocol.read() # The cases below describe all the messages handled by the Absynthe if data['action'] == 'test': # Absynthe core asking to test a candidate in Python res = bench.test_candidate(data['prog']) protocol.write({'action': 'test_res', 'res': res}) elif data['action'] == 'done': # Absynthe core finished synthesizing a function data.pop('action', None) return data elif data['action'] == 'timeout': # Absynthe core had a timeout during synthesis return None else: # Unexpected message raise Exception("Unexpected RPC message")
1,669
29.925926
79
py
tdqn
tdqn-master/tdqn/tdqn.py
import time import math, random import numpy as np from os.path import join as pjoin import torch import torch.nn as nn import torch.optim as optim import torch.autograd as autograd import torch.nn.functional as F import logger import copy from replay import * from schedule import * from models import TDQN from env import * import jericho from jericho.template_action_generator import TemplateActionGenerator import sentencepiece as spm def configure_logger(log_dir): logger.configure(log_dir, format_strs=['log']) global tb tb = logger.Logger(log_dir, [logger.make_output_format('tensorboard', log_dir), logger.make_output_format('csv', log_dir), logger.make_output_format('stdout', log_dir)]) global log log = logger.log class TDQN_Trainer(object): def __init__(self, args): configure_logger(args.output_dir) log(args) self.args = args self.log_freq = args.log_freq self.update_freq = args.update_freq_td self.update_freq_tar = args.update_freq_tar self.filename = 'tdqn' self.sp = spm.SentencePieceProcessor() self.sp.Load(args.spm_path) self.binding = jericho.load_bindings(args.rom_path) self.vocab_act, self.vocab_act_rev = self.load_vocab_act(args.rom_path) vocab_size = len(self.sp) vocab_size_act = len(self.vocab_act.keys()) self.template_generator = TemplateActionGenerator(self.binding) self.template_size = len(self.template_generator.templates) if args.replay_buffer_type == 'priority': self.replay_buffer = PriorityReplayBuffer(int(args.replay_buffer_size)) elif args.replay_buffer_type == 'standard': self.replay_buffer = ReplayBuffer(int(args.replay_buffer_size)) self.model = TDQN(args, self.template_size, vocab_size, vocab_size_act).cuda() self.target_model = TDQN(args, self.template_size, vocab_size, vocab_size_act).cuda() self.optimizer = optim.Adam(self.model.parameters(), lr=args.lr) self.num_steps = args.steps self.batch_size = args.batch_size self.gamma = args.gamma self.rho = args.rho self.bce_loss = nn.BCELoss() def load_vocab_act(self, rom_path): #loading vocab directly from Jericho env = FrotzEnv(rom_path) vocab = {i+2: str(v) for i, v in enumerate(env.get_dictionary())} vocab[0] = ' ' vocab[1] = '<s>' vocab_rev = {v: idx for idx, v in vocab.items()} env.close() return vocab, vocab_rev def state_rep_generator(self, state_description): remove = ['=', '-', '\'', ':', '[', ']', 'eos', 'EOS', 'SOS', 'UNK', 'unk', 'sos', '<', '>'] for rm in remove: state_description = state_description.replace(rm, '') state_description = state_description.split('|') ret = [self.sp.encode_as_ids('<s>' + s_desc + '</s>') for s_desc in state_description] return pad_sequences(ret, maxlen=self.args.max_seq_len) def plot(self, frame_idx, rewards, losses, completion_steps): fig = plt.figure(figsize=(20, 5)) plt.subplot(131) plt.title('frame %s. reward: %s' % (frame_idx, np.mean(rewards[-10:]))) plt.plot(rewards) plt.subplot(132) plt.title('frame %s. steps: %s' % (frame_idx, np.mean(completion_steps[-10:]))) plt.plot(completion_steps) plt.subplot(133) plt.title('loss-lstm-dqn') plt.plot(losses) # txt = "Gamma:" + str(self.gamma) + ", Num Frames:" + str(self.num_frames) + ", E Decay:" + str(epsilon_decay) plt.figtext(0.5, 0.01, self.filename, wrap=True, horizontalalignment='center', fontsize=12) # plt.show() fig.savefig('plots/' + self.filename + '_' + str(frame_idx) + '.png') def compute_td_loss(self): state, action, reward, next_state, done, valid = self.replay_buffer.sample(self.batch_size, self.rho) action = torch.LongTensor(action).cuda() state = torch.LongTensor(state).permute(1, 0, 2).cuda() next_state = torch.LongTensor(next_state).permute(1, 0, 2).detach().cuda() template_targets = torch.stack([v[0] for v in valid]).cuda() obj_targets = torch.stack([v[1] for v in valid]).cuda() decode_steps = [] for t in action[:, 0]: decode_steps.append(self.template_generator.templates[t.item()].count('OBJ')) template = action[:, 0] object1 = action[:, 1] object2 = action[:, 2] reward = torch.FloatTensor(reward).cuda() done = torch.FloatTensor(1 * done).cuda() o1_mask, o2_mask = [0] * self.batch_size, [0] * self.batch_size for d, st in enumerate(decode_steps): if st > 1: o1_mask[d] = 1 o2_mask[d] = 1 elif st == 1: o1_mask[d] = 1 o1_mask, o2_mask = torch.FloatTensor(o1_mask).cuda(), torch.FloatTensor(o2_mask).cuda() self.model.flatten_parameters() q_t, q_o1, q_o2 = self.model(state) supervised_loss = self.bce_loss(F.softmax(q_t, dim=1), template_targets)+\ self.bce_loss(F.softmax(q_o1, dim=1), obj_targets)+\ self.bce_loss(F.softmax(q_o2, dim=1), obj_targets) tb.logkv_mean('SupervisedLoss', supervised_loss.item()) self.target_model.flatten_parameters() next_q_t, next_q_o1, next_q_o2 = self.target_model(next_state) q_t = q_t.gather(1, template.unsqueeze(1)).squeeze(1) q_o1 = q_o1.gather(1, object1.unsqueeze(1)).squeeze(1) q_o2 = q_o2.gather(1, object2.unsqueeze(1)).squeeze(1) next_q_t = next_q_t.max(1)[0] next_q_o1 = next_q_o1.max(1)[0] next_q_o2 = next_q_o2.max(1)[0] td_loss = F.smooth_l1_loss(q_t, (reward + self.gamma * next_q_t).detach()) +\ F.smooth_l1_loss(q_o1 * o1_mask, o1_mask * (reward + self.gamma * next_q_o1).detach()) +\ F.smooth_l1_loss(q_o2 * o2_mask, o2_mask * (reward + self.gamma * next_q_o2).detach()) tb.logkv_mean('TDLoss', td_loss.item()) loss = td_loss + supervised_loss self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.model.parameters(), self.args.clip) self.optimizer.step() return loss def tmpl_to_str(self, template_idx, o1_id, o2_id): template_str = self.template_generator.templates[template_idx] holes = template_str.count('OBJ') assert holes <= 2 if holes <= 0: return template_str elif holes == 1: return template_str.replace('OBJ', self.vocab_act[o1_id]) else: return template_str.replace('OBJ', self.vocab_act[o1_id], 1)\ .replace('OBJ', self.vocab_act[o2_id], 1) def generate_targets_multilabel(self, valid_acts): template_targets = torch.zeros([self.template_size]) obj_targets = torch.zeros([len(self.vocab_act.keys())]) for act in valid_acts: template_targets[act.template_id] = 1 for obj_id in act.obj_ids: obj_targets[obj_id] = 1 return template_targets, obj_targets def train(self): start = time.time() env = JerichoEnv(self.args.rom_path, 0, self.vocab_act_rev, self.args.env_step_limit) env.create() episode = 1 state_text, info = env.reset() state_rep = self.state_rep_generator(state_text) for frame_idx in range(1, self.num_steps + 1): found_valid_action = False while not found_valid_action: templates, o1s, o2s, q_ts, q_o1s, q_o2s = self.model.poly_act(state_rep) for template, o1, o2, q_t, q_o1, q_o2 in zip(templates, o1s, o2s, q_ts, q_o1s, q_o2s): action = [template, o1, o2] action_str = self.tmpl_to_str(template, o1, o2) next_state_text, reward, done, info = env.step(action_str) if info['action_valid'] == True: found_valid_action = True break if episode % 100 == 0: log('Action: {} Q_t: {:.2f} Q_o1: {:.2f} Q_o2: {:.2f}'.format(action_str, q_t, q_o1, q_o2)) log('Obs: {}'.format(clean(next_state_text.split('|')[2]))) log('Reward {}: {}'.format(env.steps, reward)) valid_acts = info['valid'] template_targets, obj_targets = self.generate_targets_multilabel(valid_acts) next_state_rep = self.state_rep_generator(next_state_text) self.replay_buffer.push(state_rep, action, reward, next_state_rep, done, (template_targets, obj_targets)) state_text = next_state_text state_rep = next_state_rep if done: score = info['score'] if episode % 100 == 0: log('Episode {} Score {}\n'.format(episode, score)) tb.logkv_mean('EpisodeScore', score) state_text, info = env.reset() state_rep = self.state_rep_generator(state_text) episode += 1 if len(self.replay_buffer) > self.batch_size: if frame_idx % self.update_freq == 0: loss = self.compute_td_loss() tb.logkv_mean('Loss', loss.item()) if frame_idx % self.update_freq_tar == 0: self.target_model = copy.deepcopy(self.model) if frame_idx % self.log_freq == 0: tb.logkv('Step', frame_idx) tb.logkv('FPS', int(frame_idx/(time.time()-start))) tb.dumpkvs() env.close() parameters = { 'model': self.model, 'target': self.target_model, 'replay_buffer': self.replay_buffer } torch.save(parameters, pjoin(self.args.output_dir, self.filename + '_final.pt')) def pad_sequences(sequences, maxlen=None, dtype='int32', value=0.): ''' Partially borrowed from Keras # Arguments sequences: list of lists where each element is a sequence maxlen: int, maximum length dtype: type to cast the resulting sequence. value: float, value to pad the sequences to the desired value. # Returns x: numpy array with dimensions (number_of_sequences, maxlen) ''' lengths = [len(s) for s in sequences] nb_samples = len(sequences) if maxlen is None: maxlen = np.max(lengths) # take the sample shape from the first non empty sequence # checking for consistency in the main loop below. sample_shape = tuple() for s in sequences: if len(s) > 0: sample_shape = np.asarray(s).shape[1:] break x = (np.ones((nb_samples, maxlen) + sample_shape) * value).astype(dtype) for idx, s in enumerate(sequences): if len(s) == 0: continue # empty list was found # pre truncating trunc = s[-maxlen:] # check `trunc` has expected shape trunc = np.asarray(trunc, dtype=dtype) if trunc.shape[1:] != sample_shape: raise ValueError('Shape of sample %s of sequence at position %s is different from expected shape %s' % (trunc.shape[1:], idx, sample_shape)) # post padding x[idx, :len(trunc)] = trunc return x
11,644
37.816667
119
py
tdqn
tdqn-master/tdqn/logger.py
import os import sys import shutil import os.path as osp import json import time import datetime import tempfile from collections import defaultdict DEBUG = 10 INFO = 20 WARN = 30 ERROR = 40 DISABLED = 50 class KVWriter(object): def writekvs(self, kvs): raise NotImplementedError class SeqWriter(object): def writeseq(self, seq): raise NotImplementedError class HumanOutputFormat(KVWriter, SeqWriter): def __init__(self, filename_or_file): if isinstance(filename_or_file, str): self.file = open(filename_or_file, 'wt') self.own_file = True else: assert hasattr(filename_or_file, 'read'), 'expected file or str, got %s'%filename_or_file self.file = filename_or_file self.own_file = False def writekvs(self, kvs): # Create strings for printing key2str = {} for (key, val) in sorted(kvs.items()): if isinstance(val, float): valstr = '%-8.3g' % (val,) else: valstr = str(val) key2str[self._truncate(key)] = self._truncate(valstr) # Find max widths if len(key2str) == 0: print('WARNING: tried to write empty key-value dict') return else: keywidth = max(map(len, key2str.keys())) valwidth = max(map(len, key2str.values())) # Write out the data dashes = '-' * (keywidth + valwidth + 7) lines = [dashes] for (key, val) in sorted(key2str.items()): lines.append('| %s%s | %s%s |' % ( key, ' ' * (keywidth - len(key)), val, ' ' * (valwidth - len(val)), )) lines.append(dashes) self.file.write('\n'.join(lines) + '\n') # Flush the output to the file self.file.flush() def _truncate(self, s): return s[:20] + '...' if len(s) > 23 else s def writeseq(self, seq): seq = list(seq) for (i, elem) in enumerate(seq): self.file.write(elem) if i < len(seq) - 1: # add space unless this is the last one self.file.write(' ') self.file.write('\n') self.file.flush() def close(self): if self.own_file: self.file.close() class JSONOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'wt') def writekvs(self, kvs): for k, v in sorted(kvs.items()): if hasattr(v, 'dtype'): v = v.tolist() kvs[k] = float(v) self.file.write(json.dumps(kvs) + '\n') self.file.flush() def close(self): self.file.close() class CSVOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'w+t') self.keys = [] self.sep = ',' def writekvs(self, kvs): # Add our current row to the history extra_keys = kvs.keys() - self.keys if extra_keys: self.keys.extend(extra_keys) self.file.seek(0) lines = self.file.readlines() self.file.seek(0) for (i, k) in enumerate(self.keys): if i > 0: self.file.write(',') self.file.write(k) self.file.write('\n') for line in lines[1:]: self.file.write(line[:-1]) self.file.write(self.sep * len(extra_keys)) self.file.write('\n') for (i, k) in enumerate(self.keys): if i > 0: self.file.write(',') v = kvs.get(k) if v is not None: self.file.write(str(v)) self.file.write('\n') self.file.flush() def close(self): self.file.close() class TensorBoardOutputFormat(KVWriter): """ Dumps key/value pairs into TensorBoard's numeric format. """ def __init__(self, dir): os.makedirs(dir, exist_ok=True) self.dir = dir self.step = 1 prefix = 'events' path = osp.join(osp.abspath(dir), prefix) import tensorflow as tf from tensorflow.python import pywrap_tensorflow from tensorflow.core.util import event_pb2 from tensorflow.python.util import compat self.tf = tf self.event_pb2 = event_pb2 self.pywrap_tensorflow = pywrap_tensorflow self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path)) def writekvs(self, kvs): def summary_val(k, v): kwargs = {'tag': k, 'simple_value': float(v)} return self.tf.Summary.Value(**kwargs) summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()]) event = self.event_pb2.Event(wall_time=time.time(), summary=summary) event.step = self.step # is there any reason why you'd want to specify the step? self.writer.WriteEvent(event) self.writer.Flush() self.step += 1 def close(self): if self.writer: self.writer.Close() self.writer = None def make_output_format(format, ev_dir, log_suffix=''): os.makedirs(ev_dir, exist_ok=True) if format == 'stdout': return HumanOutputFormat(sys.stdout) elif format == 'log': return HumanOutputFormat(osp.join(ev_dir, 'log%s.txt' % log_suffix)) elif format == 'json': return JSONOutputFormat(osp.join(ev_dir, 'progress%s.json' % log_suffix)) elif format == 'csv': return CSVOutputFormat(osp.join(ev_dir, 'progress%s.csv' % log_suffix)) elif format == 'tensorboard': return TensorBoardOutputFormat(osp.join(ev_dir, 'tb%s' % log_suffix)) else: raise ValueError('Unknown format specified: %s' % (format,)) # ================================================================ # API # ================================================================ def logkv(key, val): """ Log a value of some diagnostic Call this once for each diagnostic quantity, each iteration If called many times, last value will be used. """ Logger.CURRENT.logkv(key, val) def logkv_mean(key, val): """ The same as logkv(), but if called many times, values averaged. """ Logger.CURRENT.logkv_mean(key, val) def logkvs(d): """ Log a dictionary of key-value pairs """ for (k, v) in d.items(): logkv(k, v) def dumpkvs(): """ Write all of the diagnostics from the current iteration level: int. (see logger.py docs) If the global logger level is higher than the level argument here, don't print to stdout. """ Logger.CURRENT.dumpkvs() def getkvs(): return Logger.CURRENT.name2val def log(*args, level=INFO): """ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file). """ Logger.CURRENT.log(*args, level=level) def debug(*args): log(*args, level=DEBUG) def info(*args): log(*args, level=INFO) def warn(*args): log(*args, level=WARN) def error(*args): log(*args, level=ERROR) def set_level(level): """ Set logging threshold on current logger. """ Logger.CURRENT.set_level(level) def get_dir(): """ Get directory that log files are being written to. will be None if there is no output directory (i.e., if you didn't call start) """ return Logger.CURRENT.get_dir() record_tabular = logkv dump_tabular = dumpkvs class ProfileKV: """ Usage: with logger.ProfileKV("interesting_scope"): code """ def __init__(self, n): self.n = "wait_" + n def __enter__(self): self.t1 = time.time() def __exit__(self ,type, value, traceback): Logger.CURRENT.name2val[self.n] += time.time() - self.t1 def profile(n): """ Usage: @profile("my_func") def my_func(): code """ def decorator_with_name(func): def func_wrapper(*args, **kwargs): with ProfileKV(n): return func(*args, **kwargs) return func_wrapper return decorator_with_name # ================================================================ # Backend # ================================================================ class Logger(object): DEFAULT = None # A logger with no output files. (See right below class definition) # So that you can still log to the terminal without setting up any output files CURRENT = None # Current logger being used by the free functions above def __init__(self, dir, output_formats): self.name2val = defaultdict(float) # values this iteration self.name2cnt = defaultdict(int) self.level = INFO self.dir = dir self.output_formats = output_formats # Logging API, forwarded # ---------------------------------------- def logkv(self, key, val): self.name2val[key] = val def logkv_mean(self, key, val): if val is None: self.name2val[key] = None return oldval, cnt = self.name2val[key], self.name2cnt[key] self.name2val[key] = oldval*cnt/(cnt+1) + val/(cnt+1) self.name2cnt[key] = cnt + 1 def dumpkvs(self): if self.level == DISABLED: return for fmt in self.output_formats: if isinstance(fmt, KVWriter): fmt.writekvs(self.name2val) self.name2val.clear() self.name2cnt.clear() def log(self, *args, level=INFO): if self.level <= level: self._do_log(args) # Configuration # ---------------------------------------- def set_level(self, level): self.level = level def get_dir(self): return self.dir def close(self): for fmt in self.output_formats: fmt.close() # Misc # ---------------------------------------- def _do_log(self, args): for fmt in self.output_formats: if isinstance(fmt, SeqWriter): fmt.writeseq(map(str, args)) def configure(dir=None, format_strs=None): if dir is None: dir = os.getenv('OPENAI_LOGDIR') if dir is None: dir = osp.join(tempfile.gettempdir(), datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f")) assert isinstance(dir, str) os.makedirs(dir, exist_ok=True) log_suffix = '' rank = 0 # check environment variables here instead of importing mpi4py # to avoid calling MPI_Init() when this module is imported for varname in ['PMI_RANK', 'OMPI_COMM_WORLD_RANK']: if varname in os.environ: rank = int(os.environ[varname]) if rank > 0: log_suffix = "-rank%03i" % rank if format_strs is None: if rank == 0: format_strs = os.getenv('OPENAI_LOG_FORMAT', 'stdout,log,csv').split(',') else: format_strs = os.getenv('OPENAI_LOG_FORMAT_MPI', 'log').split(',') format_strs = filter(None, format_strs) output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs] Logger.CURRENT = Logger(dir=dir, output_formats=output_formats) log('Logging to %s'%dir) def _configure_default_logger(): format_strs = None # keep the old default of only writing to stdout if 'OPENAI_LOG_FORMAT' not in os.environ: format_strs = ['stdout'] configure(format_strs=format_strs) Logger.DEFAULT = Logger.CURRENT def reset(): if Logger.CURRENT is not Logger.DEFAULT: Logger.CURRENT.close() Logger.CURRENT = Logger.DEFAULT log('Reset logger') class scoped_configure(object): def __init__(self, dir=None, format_strs=None): self.dir = dir self.format_strs = format_strs self.prevlogger = None def __enter__(self): self.prevlogger = Logger.CURRENT configure(dir=self.dir, format_strs=self.format_strs) def __exit__(self, *args): Logger.CURRENT.close() Logger.CURRENT = self.prevlogger # ================================================================ def _demo(): info("hi") debug("shouldn't appear") set_level(DEBUG) debug("should appear") dir = "/tmp/testlogging" if os.path.exists(dir): shutil.rmtree(dir) configure(dir=dir) logkv("a", 3) logkv("b", 2.5) dumpkvs() logkv("b", -2.5) logkv("a", 5.5) dumpkvs() info("^^^ should see a = 5.5") logkv_mean("b", -22.5) logkv_mean("b", -44.4) logkv("a", 5.5) dumpkvs() info("^^^ should see b = 33.3") logkv("b", -2.5) dumpkvs() logkv("a", "longasslongasslongasslongasslongasslongassvalue") dumpkvs() # ================================================================ # Readers # ================================================================ def read_json(fname): import pandas ds = [] with open(fname, 'rt') as fh: for line in fh: ds.append(json.loads(line)) return pandas.DataFrame(ds) def read_csv(fname): import pandas return pandas.read_csv(fname, index_col=None, comment='#') def read_tb(path): """ path : a tensorboard file OR a directory, where we will find all TB files of the form events.* """ import pandas import numpy as np from glob import glob from collections import defaultdict import tensorflow as tf if osp.isdir(path): fnames = glob(osp.join(path, "events.*")) elif osp.basename(path).startswith("events."): fnames = [path] else: raise NotImplementedError("Expected tensorboard file or directory containing them. Got %s"%path) tag2pairs = defaultdict(list) maxstep = 0 for fname in fnames: for summary in tf.train.summary_iterator(fname): if summary.step > 0: for v in summary.summary.value: pair = (summary.step, v.simple_value) tag2pairs[v.tag].append(pair) maxstep = max(summary.step, maxstep) data = np.empty((maxstep, len(tag2pairs))) data[:] = np.nan tags = sorted(tag2pairs.keys()) for (colidx,tag) in enumerate(tags): pairs = tag2pairs[tag] for (step, value) in pairs: data[step-1, colidx] = value return pandas.DataFrame(data, columns=tags) # configure the default logger on import # _configure_default_logger() if __name__ == "__main__": _demo()
14,503
28.660532
122
py
tdqn
tdqn-master/tdqn/replay.py
from collections import deque import numpy as np import random class ReplayBuffer(object): def __init__(self, capacity): self.buffer = deque(maxlen=capacity) def push(self, state, action, reward, next_state, done): self.buffer.append((state, action, reward, next_state, done)) def sample(self, batch_size): state, action, reward, next_state, done = zip(*random.sample(self.buffer, batch_size)) return state, action, reward, next_state, done def __len__(self): return len(self.buffer) class PriorityReplayBuffer(object): def __init__(self, capacity): self.buffer = deque(maxlen=capacity) self.priority_buffer = deque(maxlen=capacity) def push(self, state, action, reward, next_state, done, valid_acts): if reward > 0: self.priority_buffer.append((state, action, reward, next_state, done, valid_acts)) else: self.buffer.append((state, action, reward, next_state, done, valid_acts)) def sample(self, batch_size, rho): pbatch = int(batch_size * rho) batch = int(batch_size * (1 - rho)) if pbatch > len(self.priority_buffer): pbatch = len(self.priority_buffer) batch = batch_size - len(self.priority_buffer) elif batch > len(self.buffer): batch = len(self.buffer) pbatch = batch_size - len(self.buffer) if pbatch == 0: state, action, reward, next_state, done, valid = zip(*random.sample(self.buffer, batch)) return list(state), action, reward, list(next_state), done, valid if batch == 0: pstate, paction, preward, pnext_state, pdone, pvalid = zip(*random.sample(self.priority_buffer, pbatch)) return list(pstate), paction, preward, list(pnext_state), pdone, pvalid state, action, reward, next_state, done, valid = zip(*random.sample(self.buffer, batch)) pstate, paction, preward, pnext_state, pdone, pvalid = zip(*random.sample(self.priority_buffer, pbatch)) return pstate + state, paction + action, preward + reward, pnext_state + next_state, pdone + done, pvalid + valid def __len__(self): return len(self.buffer)
2,230
38.140351
121
py
tdqn
tdqn-master/tdqn/models.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import random class TDQN(nn.Module): def __init__(self, args, template_size, vocab_size, vocab_size_act): super(TDQN, self).__init__() self.embeddings = nn.Embedding(vocab_size_act, args.embedding_size) self.state_network = StateNetwork(args, vocab_size) self.t_scorer = nn.Linear(args.hidden_size, template_size) self.o1_scorer = nn.Linear(args.hidden_size, vocab_size_act) self.o2_scorer = nn.Linear(args.hidden_size, vocab_size_act) self.args = args self.template_size = template_size self.vocab_size_act = vocab_size_act def forward(self, state): x, h = self.state_network(state) q_t = self.t_scorer(x) q_o1 = self.o1_scorer(x) q_o2 = self.o2_scorer(x) return q_t, q_o1, q_o2 def act(self, state, epsilon): with torch.no_grad(): state = torch.LongTensor(state).unsqueeze(0).permute(1, 0, 2).cuda() q_t, q_o1, q_o2 = self.forward(state) t, o1, o2 = F.softmax(q_t, dim=1).multinomial(num_samples=1).item(),\ F.softmax(q_o1, dim=1).multinomial(num_samples=1).item(),\ F.softmax(q_o2, dim=1).multinomial(num_samples=1).item() q_t = q_t[0,t].item() q_o1 = q_o1[0,o1].item() q_o2 = q_o2[0,o2].item() return t, o1, o2, q_t, q_o1, q_o2 def poly_act(self, state, n_samples=512, replacement=True): ''' Samples many times from the model, optionally with replacement. ''' with torch.no_grad(): state = torch.LongTensor(state).unsqueeze(0).permute(1, 0, 2).cuda() q_t, q_o1, q_o2 = self.forward(state) t, o1, o2 = F.softmax(q_t, dim=1).multinomial(n_samples, replacement)[0],\ F.softmax(q_o1, dim=1).multinomial(n_samples, replacement)[0],\ F.softmax(q_o2, dim=1).multinomial(n_samples, replacement)[0] qv_t = torch.index_select(q_t, 1, t).squeeze().cpu().detach().numpy() qv_o1 = torch.index_select(q_o1, 1, o1).squeeze().cpu().detach().numpy() qv_o2 = torch.index_select(q_o2, 1, o2).squeeze().cpu().detach().numpy() return t.cpu().numpy(), o1.cpu().numpy(), o2.cpu().numpy(), qv_t, qv_o1, qv_o2 def flatten_parameters(self): self.state_network.flatten_parameters() class StateNetwork(nn.Module): def __init__(self, args, vocab_size): super(StateNetwork, self).__init__() self.args = args self.enc_look = PackedEncoderRNN(vocab_size, args.hidden_size) self.enc_inv = PackedEncoderRNN(vocab_size, args.hidden_size) self.enc_ob = PackedEncoderRNN(vocab_size, args.hidden_size) self.enc_preva = PackedEncoderRNN(vocab_size, args.hidden_size) self.fcx = nn.Linear(args.hidden_size * 4, args.hidden_size) self.fch = nn.Linear(args.hidden_size * 4, args.hidden_size) def forward(self, obs): x_l, h_l = self.enc_look(obs[0, :, :], self.enc_look.initHidden(self.args.batch_size)) x_i, h_i = self.enc_inv(obs[1, :, :], self.enc_inv.initHidden(self.args.batch_size)) x_o, h_o = self.enc_ob(obs[2, :, :], self.enc_ob.initHidden(self.args.batch_size)) x_p, h_p = self.enc_preva(obs[3, :, :], self.enc_preva.initHidden(self.args.batch_size)) x = F.relu(self.fcx(torch.cat((x_l, x_i, x_o, x_p), dim=1))) h = F.relu(self.fch(torch.cat((h_l, h_i, h_o, h_p), dim=2))) return x, h def flatten_parameters(self): self.enc_look.flatten_parameters() self.enc_inv.flatten_parameters() self.enc_ob.flatten_parameters() self.enc_preva.flatten_parameters() class PackedEncoderRNN(nn.Module): def __init__(self, input_size, hidden_size): super(PackedEncoderRNN, self).__init__() self.hidden_size = hidden_size self.embedding = nn.Embedding(input_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, input, hidden=None): embedded = self.embedding(input).permute(1,0,2) # T x Batch x EmbDim if hidden is None: hidden = self.initHidden(input.size(0)) # Pack the padded batch of sequences lengths = torch.tensor([torch.nonzero(n)[-1] + 1 for n in input], dtype=torch.long).cuda() packed = nn.utils.rnn.pack_padded_sequence(embedded, lengths, enforce_sorted=False) output, hidden = self.gru(packed, hidden) # Unpack the padded sequence output, _ = nn.utils.rnn.pad_packed_sequence(output) # Return only the last timestep of output for each sequence idx = (lengths-1).view(-1, 1).expand(len(lengths), output.size(2)).unsqueeze(0) output = output.gather(0, idx).squeeze(0) return output, hidden def initHidden(self, batch_size): return torch.zeros(1, batch_size, self.hidden_size).cuda() def flatten_parameters(self): self.gru.flatten_parameters()
5,149
40.532258
98
py
tdqn
tdqn-master/tdqn/schedule.py
import math """ Adapted from https://github.com/berkeleydeeprlcourse/homework """ class Schedule(object): def value(self, t): """Value of the schedule at time t""" raise NotImplementedError() class ConstantSchedule(object): def __init__(self, value): """Value remains constant over time. Parameters ---------- value: float Constant value of the schedule """ self._v = value def value(self, t): """See Schedule.value""" return self._v def linear_interpolation(l, r, alpha): return l + alpha * (r - l) class PiecewiseSchedule(object): def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None): """Piecewise schedule. endpoints: [(int, int)] list of pairs `(time, value)` meanining that schedule should output `value` when `t==time`. All the values for time must be sorted in an increasing order. When t is between two times, e.g. `(time_a, value_a)` and `(time_b, value_b)`, such that `time_a <= t < time_b` then value outputs `interpolation(value_a, value_b, alpha)` where alpha is a fraction of time passed between `time_a` and `time_b` for time `t`. interpolation: lambda float, float, float: float a function that takes value to the left and to the right of t according to the `endpoints`. Alpha is the fraction of distance from left endpoint to right endpoint that t has covered. See linear_interpolation for example. outside_value: float if the value is requested outside of all the intervals sepecified in `endpoints` this value is returned. If None then AssertionError is raised when outside value is requested. """ idxes = [e[0] for e in endpoints] assert idxes == sorted(idxes) self._interpolation = interpolation self._outside_value = outside_value self._endpoints = endpoints def value(self, t): """See Schedule.value""" for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]): if l_t <= t and t < r_t: alpha = float(t - l_t) / (r_t - l_t) return self._interpolation(l, r, alpha) # t does not belong to any of the pieces, so doom. assert self._outside_value is not None return self._outside_value class LinearSchedule(object): def __init__(self, schedule_timesteps, final_e, initial_e=1.0): """Linear interpolation between initial_p and final_p over schedule_timesteps. After this many timesteps pass final_p is returned. Parameters ---------- schedule_timesteps: int Number of timesteps for which to linearly anneal initial_p to final_p initial_p: float initial output value final_p: float final output value """ self.schedule_timesteps = schedule_timesteps self.final_e = final_e self.initial_e = initial_e def value(self, t): """See Schedule.value""" fraction = min(float(t) / self.schedule_timesteps, 1.0) return self.initial_e + fraction * (self.final_e - self.initial_e) class ExponentialSchedule(object): def __init__(self, schedule_timesteps, decay, final_e, initial_e=1.0): self.decay = decay self.initial_e = initial_e self.final_e = final_e self.schedule_timesteps = schedule_timesteps def value(self, t): return self.final_e + (self.initial_e - self.final_e) * math.exp(-1. * t / self.decay)
3,725
34.826923
94
py
tdqn
tdqn-master/tdqn/train.py
import os import argparse import jericho from tdqn import TDQN_Trainer def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--rom_path', default='zork1.z5') parser.add_argument('--output_dir', default='logs') parser.add_argument('--spm_path', default='../spm_models/unigram_8k.model') parser.add_argument('--batch_size', default=64, type=int) parser.add_argument('--env_step_limit', default=100, type=int) parser.add_argument('--lr', default=0.0003, type=float) parser.add_argument('--gamma', default=.95, type=float) parser.add_argument('--rho', default=.5, type=float) parser.add_argument('--embedding_size', default=64, type=int) parser.add_argument('--hidden_size', default=128, type=int) parser.add_argument('--steps', default=1000000, type=int) parser.add_argument('--log_freq', default=100, type=int) parser.add_argument('--update_freq_td', default=4, type=int) parser.add_argument('--update_freq_tar', default=1000, type=int) parser.add_argument('--replay_buffer_size', default=100000, type=int) parser.add_argument('--replay_buffer_type', default='priority') parser.add_argument('--clip', default=40, type=float) parser.add_argument('--max_seq_len', default=300, type=int) return parser.parse_args() if __name__ == "__main__": assert jericho.__version__ == '2.1.0', "This code is designed to be run with Jericho version 2.1.0." args = parse_args() print(args) trainer = TDQN_Trainer(args) trainer.train()
1,538
42.971429
104
py
tdqn
tdqn-master/tdqn/env.py
import subprocess import time import redis from os.path import basename, dirname from jericho import * from jericho.template_action_generator import TemplateActionGenerator from jericho.util import * from jericho.defines import * def start_redis(): print('Starting Redis') subprocess.Popen(['redis-server', '--save', '\"\"', '--appendonly', 'no']) time.sleep(1) class JerichoEnv: def __init__(self, rom_path, seed, vocab_rev, step_limit=None): self.rom_path = rom_path self.bindings = load_bindings(rom_path) self.act_gen = TemplateActionGenerator(self.bindings) self.seed = seed self.steps = 0 self.step_limit = step_limit self.vocab_rev = vocab_rev self.env = None self.conn = None def create(self): self.env = FrotzEnv(self.rom_path, self.seed) start_redis() self.conn = redis.Redis(host='localhost', port=6379, db=0) self.conn.flushdb() def step(self, action): ob, reward, done, info = self.env.step(action) action_valid = done or self.env.world_changed() info['action_valid'] = action_valid if not action_valid: # Exit early for invalid actions return None, None, None, info if action_valid: self.steps += 1 # Initialize with default values look = 'unknown' inv = 'unknown' info['valid'] = [] if not done: try: save = self.env.save_str() look, _, _, _ = self.env.step('look') self.env.load_str(save) inv, _, _, _ = self.env.step('inventory') self.env.load_str(save) # Find Valid actions world_state_hash = self.env.get_world_state_hash() valid = self.conn.get(world_state_hash) if valid is None: objs = [o[0] for o in self.env.identify_interactive_objects(ob)] obj_ids = [self.vocab_rev[o[:self.bindings['max_word_length']]] for o in objs] acts = self.act_gen.generate_template_actions(objs, obj_ids) valid = self.env.find_valid_actions(acts) redis_valid_value = '/'.join([str(a) for a in valid]) self.conn.set(world_state_hash, redis_valid_value) else: valid = valid.decode('cp1252') if valid: valid = [eval(a) for a in valid.split('/')] info['valid'] = valid except RuntimeError: print('RuntimeError: {}, Done: {}, Info: {}'.format(clean(ob), done, info)) if self.step_limit and self.steps >= self.step_limit: done = True ob = look + '|' + inv + '|' + ob + '|' + action return ob, reward, done, info def reset(self): initial_ob, info = self.env.reset() try: save = self.env.save_str() look, _, _, _ = self.env.step('look') self.env.load_str(save) inv, _, _, _ = self.env.step('inventory') self.env.load_str(save) except RuntimeError: print('RuntimeError: {}, Info: {}'.format(initial_ob, info)) look, inv = '' self.steps = 0 initial_ob = look + '|' + inv + '|' + initial_ob + '|' + 'look' return initial_ob, info def get_dictionary(self): if not self.env: self.create() return self.env.get_dictionary() def get_action_set(self): return None def close(self): self.env.close() self.conn.shutdown(save=True)
3,689
35.534653
98
py
tdqn
tdqn-master/drrn/drrn.py
import pickle import torch import torch.nn as nn import torch.nn.functional as F from os.path import join as pjoin from memory import ReplayMemory, Transition, State from model import DRRN from util import * import logger import sentencepiece as spm device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class DRRN_Agent: def __init__(self, args): self.gamma = args.gamma self.batch_size = args.batch_size self.sp = spm.SentencePieceProcessor() self.sp.Load(args.spm_path) self.network = DRRN(len(self.sp), args.embedding_dim, args.hidden_dim).to(device) self.memory = ReplayMemory(args.memory_size) self.save_path = args.output_dir self.clip = args.clip self.optimizer = torch.optim.Adam(self.network.parameters(), lr=args.learning_rate) def observe(self, state, act, rew, next_state, next_acts, done): self.memory.push(state, act, rew, next_state, next_acts, done) def build_state(self, obs, infos): """ Returns a state representation built from various info sources. """ obs_ids = [self.sp.EncodeAsIds(o) for o in obs] look_ids = [self.sp.EncodeAsIds(info['look']) for info in infos] inv_ids = [self.sp.EncodeAsIds(info['inv']) for info in infos] return [State(ob, lk, inv) for ob, lk, inv in zip(obs_ids, look_ids, inv_ids)] def encode(self, obs_list): """ Encode a list of observations """ return [self.sp.EncodeAsIds(o) for o in obs_list] def act(self, states, poss_acts, sample=True): """ Returns a string action from poss_acts. """ idxs, values = self.network.act(states, poss_acts, sample) act_ids = [poss_acts[batch][idx] for batch, idx in enumerate(idxs)] return act_ids, idxs, values def update(self): if len(self.memory) < self.batch_size: return transitions = self.memory.sample(self.batch_size) batch = Transition(*zip(*transitions)) # Compute Q(s', a') for all a' # TODO: Use a target network??? next_qvals = self.network(batch.next_state, batch.next_acts) # Take the max over next q-values next_qvals = torch.tensor([vals.max() for vals in next_qvals], device=device) # Zero all the next_qvals that are done next_qvals = next_qvals * (1-torch.tensor(batch.done, dtype=torch.float, device=device)) targets = torch.tensor(batch.reward, dtype=torch.float, device=device) + self.gamma * next_qvals # Next compute Q(s, a) # Nest each action in a list - so that it becomes the only admissible cmd nested_acts = tuple([[a] for a in batch.act]) qvals = self.network(batch.state, nested_acts) # Combine the qvals: Maybe just do a greedy max for generality qvals = torch.cat(qvals) # Compute Huber loss loss = F.smooth_l1_loss(qvals, targets.detach()) self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.network.parameters(), self.clip) self.optimizer.step() return loss.item() def load(self): try: self.memory = pickle.load(open(pjoin(self.save_path, 'memory.pkl'), 'rb')) self.network = torch.load(pjoin(self.save_path, 'model.pt')) except Exception as e: print("Error saving model.") logging.error(traceback.format_exc()) def save(self): try: pickle.dump(self.memory, open(pjoin(self.save_path, 'memory.pkl'), 'wb')) torch.save(self.network, pjoin(self.save_path, 'model.pt')) except Exception as e: print("Error saving model.") logging.error(traceback.format_exc())
3,809
36.722772
104
py
tdqn
tdqn-master/drrn/memory.py
from collections import namedtuple import random State = namedtuple('State', ('obs', 'description', 'inventory')) Transition = namedtuple('Transition', ('state', 'act', 'reward', 'next_state', 'next_acts', 'done')) class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0 def push(self, *args): if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position + 1) % self.capacity def sample(self, batch_size): return random.sample(self.memory, batch_size) def __len__(self): return len(self.memory) class PrioritizedReplayMemory(object): def __init__(self, capacity=100000, priority_fraction=0.0): self.priority_fraction = priority_fraction self.alpha_capacity = int(capacity * priority_fraction) self.beta_capacity = capacity - self.alpha_capacity self.alpha_memory, self.beta_memory = [], [] self.alpha_position, self.beta_position = 0, 0 def push(self, is_prior=False, *args): """Saves a transition.""" if self.priority_fraction == 0.0: is_prior = False if is_prior: if len(self.alpha_memory) < self.alpha_capacity: self.alpha_memory.append(None) self.alpha_memory[self.alpha_position] = Transition(*args) self.alpha_position = (self.alpha_position + 1) % self.alpha_capacity else: if len(self.beta_memory) < self.beta_capacity: self.beta_memory.append(None) self.beta_memory[self.beta_position] = Transition(*args) self.beta_position = (self.beta_position + 1) % self.beta_capacity def sample(self, batch_size): if self.priority_fraction == 0.0: from_beta = min(batch_size, len(self.beta_memory)) res = random.sample(self.beta_memory, from_beta) else: from_alpha = min(int(self.priority_fraction * batch_size), len(self.alpha_memory)) from_beta = min(batch_size - int(self.priority_fraction * batch_size), len(self.beta_memory)) res = random.sample(self.alpha_memory, from_alpha) + random.sample(self.beta_memory, from_beta) random.shuffle(res) return res def __len__(self): return len(self.alpha_memory) + len(self.beta_memory)
2,479
37.153846
107
py
tdqn
tdqn-master/drrn/model.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import random import itertools from util import pad_sequences from memory import State device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class DRRN(torch.nn.Module): """ Deep Reinforcement Relevance Network - He et al. '16 """ def __init__(self, vocab_size, embedding_dim, hidden_dim): super(DRRN, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.obs_encoder = nn.GRU(embedding_dim, hidden_dim) self.look_encoder = nn.GRU(embedding_dim, hidden_dim) self.inv_encoder = nn.GRU(embedding_dim, hidden_dim) self.act_encoder = nn.GRU(embedding_dim, hidden_dim) self.hidden = nn.Linear(4*hidden_dim, hidden_dim) self.act_scorer = nn.Linear(hidden_dim, 1) def packed_rnn(self, x, rnn): """ Runs the provided rnn on the input x. Takes care of packing/unpacking. x: list of unpadded input sequences Returns a tensor of size: len(x) x hidden_dim """ lengths = torch.tensor([len(n) for n in x], dtype=torch.long, device=device) # Sort this batch in descending order by seq length lengths, idx_sort = torch.sort(lengths, dim=0, descending=True) _, idx_unsort = torch.sort(idx_sort, dim=0) idx_sort = torch.autograd.Variable(idx_sort) idx_unsort = torch.autograd.Variable(idx_unsort) padded_x = pad_sequences(x) x_tt = torch.from_numpy(padded_x).type(torch.long).to(device) x_tt = x_tt.index_select(0, idx_sort) # Run the embedding layer embed = self.embedding(x_tt).permute(1,0,2) # Time x Batch x EncDim # Pack padded batch of sequences for RNN module packed = nn.utils.rnn.pack_padded_sequence(embed, lengths) # Run the RNN out, _ = rnn(packed) # Unpack out, _ = nn.utils.rnn.pad_packed_sequence(out) # Get the last step of each sequence idx = (lengths-1).view(-1,1).expand(len(lengths), out.size(2)).unsqueeze(0) out = out.gather(0, idx).squeeze(0) # Unsort out = out.index_select(0, idx_unsort) return out def forward(self, state_batch, act_batch): """ Batched forward pass. obs_id_batch: iterable of unpadded sequence ids act_batch: iterable of lists of unpadded admissible command ids Returns a tuple of tensors containing q-values for each item in the batch """ # Zip the state_batch into an easy access format state = State(*zip(*state_batch)) # This is number of admissible commands in each element of the batch act_sizes = [len(a) for a in act_batch] # Combine next actions into one long list act_batch = list(itertools.chain.from_iterable(act_batch)) act_out = self.packed_rnn(act_batch, self.act_encoder) # Encode the various aspects of the state obs_out = self.packed_rnn(state.obs, self.obs_encoder) look_out = self.packed_rnn(state.description, self.look_encoder) inv_out = self.packed_rnn(state.inventory, self.inv_encoder) state_out = torch.cat((obs_out, look_out, inv_out), dim=1) # Expand the state to match the batches of actions state_out = torch.cat([state_out[i].repeat(j,1) for i,j in enumerate(act_sizes)], dim=0) z = torch.cat((state_out, act_out), dim=1) # Concat along hidden_dim z = F.relu(self.hidden(z)) act_values = self.act_scorer(z).squeeze(-1) # Split up the q-values by batch return act_values.split(act_sizes) def act(self, states, act_ids, sample=True): """ Returns an action-string, optionally sampling from the distribution of Q-Values. """ act_values = self.forward(states, act_ids) if sample: act_probs = [F.softmax(vals, dim=0) for vals in act_values] act_idxs = [torch.multinomial(probs, num_samples=1).item() \ for probs in act_probs] else: act_idxs = [vals.argmax(dim=0).item() for vals in act_values] return act_idxs, act_values
4,282
40.990196
96
py
tdqn
tdqn-master/drrn/logger.py
import os import sys import shutil import os.path as osp import json import time import datetime import tempfile from collections import defaultdict DEBUG = 10 INFO = 20 WARN = 30 ERROR = 40 DISABLED = 50 class KVWriter(object): def writekvs(self, kvs): raise NotImplementedError class SeqWriter(object): def writeseq(self, seq): raise NotImplementedError class HumanOutputFormat(KVWriter, SeqWriter): def __init__(self, filename_or_file): if isinstance(filename_or_file, str): self.file = open(filename_or_file, 'wt') self.own_file = True else: assert hasattr(filename_or_file, 'read'), 'expected file or str, got %s'%filename_or_file self.file = filename_or_file self.own_file = False def writekvs(self, kvs): # Create strings for printing key2str = {} for (key, val) in sorted(kvs.items()): if isinstance(val, float): valstr = '%-8.3g' % (val,) else: valstr = str(val) key2str[self._truncate(key)] = self._truncate(valstr) # Find max widths if len(key2str) == 0: print('WARNING: tried to write empty key-value dict') return else: keywidth = max(map(len, key2str.keys())) valwidth = max(map(len, key2str.values())) # Write out the data dashes = '-' * (keywidth + valwidth + 7) lines = [dashes] for (key, val) in sorted(key2str.items()): lines.append('| %s%s | %s%s |' % ( key, ' ' * (keywidth - len(key)), val, ' ' * (valwidth - len(val)), )) lines.append(dashes) self.file.write('\n'.join(lines) + '\n') # Flush the output to the file self.file.flush() def _truncate(self, s): return s[:20] + '...' if len(s) > 23 else s def writeseq(self, seq): seq = list(seq) for (i, elem) in enumerate(seq): self.file.write(elem) if i < len(seq) - 1: # add space unless this is the last one self.file.write(' ') self.file.write('\n') self.file.flush() def close(self): if self.own_file: self.file.close() class JSONOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'wt') def writekvs(self, kvs): for k, v in sorted(kvs.items()): if hasattr(v, 'dtype'): v = v.tolist() kvs[k] = float(v) self.file.write(json.dumps(kvs) + '\n') self.file.flush() def close(self): self.file.close() class CSVOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'w+t') self.keys = [] self.sep = ',' def writekvs(self, kvs): # Add our current row to the history extra_keys = kvs.keys() - self.keys if extra_keys: self.keys.extend(extra_keys) self.file.seek(0) lines = self.file.readlines() self.file.seek(0) for (i, k) in enumerate(self.keys): if i > 0: self.file.write(',') self.file.write(k) self.file.write('\n') for line in lines[1:]: self.file.write(line[:-1]) self.file.write(self.sep * len(extra_keys)) self.file.write('\n') for (i, k) in enumerate(self.keys): if i > 0: self.file.write(',') v = kvs.get(k) if v is not None: self.file.write(str(v)) self.file.write('\n') self.file.flush() def close(self): self.file.close() class TensorBoardOutputFormat(KVWriter): """ Dumps key/value pairs into TensorBoard's numeric format. """ def __init__(self, dir): os.makedirs(dir, exist_ok=True) self.dir = dir self.step = 1 prefix = 'events' path = osp.join(osp.abspath(dir), prefix) import tensorflow as tf from tensorflow.python import pywrap_tensorflow from tensorflow.core.util import event_pb2 from tensorflow.python.util import compat self.tf = tf self.event_pb2 = event_pb2 self.pywrap_tensorflow = pywrap_tensorflow self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path)) def writekvs(self, kvs): def summary_val(k, v): kwargs = {'tag': k, 'simple_value': float(v)} return self.tf.Summary.Value(**kwargs) summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()]) event = self.event_pb2.Event(wall_time=time.time(), summary=summary) event.step = self.step # is there any reason why you'd want to specify the step? self.writer.WriteEvent(event) self.writer.Flush() self.step += 1 def close(self): if self.writer: self.writer.Close() self.writer = None def make_output_format(format, ev_dir, log_suffix=''): os.makedirs(ev_dir, exist_ok=True) if format == 'stdout': return HumanOutputFormat(sys.stdout) elif format == 'log': return HumanOutputFormat(osp.join(ev_dir, 'log%s.txt' % log_suffix)) elif format == 'json': return JSONOutputFormat(osp.join(ev_dir, 'progress%s.json' % log_suffix)) elif format == 'csv': return CSVOutputFormat(osp.join(ev_dir, 'progress%s.csv' % log_suffix)) elif format == 'tensorboard': return TensorBoardOutputFormat(osp.join(ev_dir, 'tb%s' % log_suffix)) else: raise ValueError('Unknown format specified: %s' % (format,)) # ================================================================ # API # ================================================================ def logkv(key, val): """ Log a value of some diagnostic Call this once for each diagnostic quantity, each iteration If called many times, last value will be used. """ Logger.CURRENT.logkv(key, val) def logkv_mean(key, val): """ The same as logkv(), but if called many times, values averaged. """ Logger.CURRENT.logkv_mean(key, val) def logkvs(d): """ Log a dictionary of key-value pairs """ for (k, v) in d.items(): logkv(k, v) def dumpkvs(): """ Write all of the diagnostics from the current iteration level: int. (see logger.py docs) If the global logger level is higher than the level argument here, don't print to stdout. """ Logger.CURRENT.dumpkvs() def getkvs(): return Logger.CURRENT.name2val def log(*args, level=INFO): """ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file). """ Logger.CURRENT.log(*args, level=level) def debug(*args): log(*args, level=DEBUG) def info(*args): log(*args, level=INFO) def warn(*args): log(*args, level=WARN) def error(*args): log(*args, level=ERROR) def set_level(level): """ Set logging threshold on current logger. """ Logger.CURRENT.set_level(level) def get_dir(): """ Get directory that log files are being written to. will be None if there is no output directory (i.e., if you didn't call start) """ return Logger.CURRENT.get_dir() record_tabular = logkv dump_tabular = dumpkvs class ProfileKV: """ Usage: with logger.ProfileKV("interesting_scope"): code """ def __init__(self, n): self.n = "wait_" + n def __enter__(self): self.t1 = time.time() def __exit__(self ,type, value, traceback): Logger.CURRENT.name2val[self.n] += time.time() - self.t1 def profile(n): """ Usage: @profile("my_func") def my_func(): code """ def decorator_with_name(func): def func_wrapper(*args, **kwargs): with ProfileKV(n): return func(*args, **kwargs) return func_wrapper return decorator_with_name # ================================================================ # Backend # ================================================================ class Logger(object): DEFAULT = None # A logger with no output files. (See right below class definition) # So that you can still log to the terminal without setting up any output files CURRENT = None # Current logger being used by the free functions above def __init__(self, dir, output_formats): self.name2val = defaultdict(float) # values this iteration self.name2cnt = defaultdict(int) self.level = INFO self.dir = dir self.output_formats = output_formats # Logging API, forwarded # ---------------------------------------- def logkv(self, key, val): self.name2val[key] = val def logkv_mean(self, key, val): if val is None: self.name2val[key] = None return oldval, cnt = self.name2val[key], self.name2cnt[key] self.name2val[key] = oldval*cnt/(cnt+1) + val/(cnt+1) self.name2cnt[key] = cnt + 1 def dumpkvs(self): if self.level == DISABLED: return for fmt in self.output_formats: if isinstance(fmt, KVWriter): fmt.writekvs(self.name2val) self.name2val.clear() self.name2cnt.clear() def log(self, *args, level=INFO): if self.level <= level: self._do_log(args) # Configuration # ---------------------------------------- def set_level(self, level): self.level = level def get_dir(self): return self.dir def close(self): for fmt in self.output_formats: fmt.close() # Misc # ---------------------------------------- def _do_log(self, args): for fmt in self.output_formats: if isinstance(fmt, SeqWriter): fmt.writeseq(map(str, args)) def configure(dir=None, format_strs=None): if dir is None: dir = os.getenv('OPENAI_LOGDIR') if dir is None: dir = osp.join(tempfile.gettempdir(), datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f")) assert isinstance(dir, str) os.makedirs(dir, exist_ok=True) log_suffix = '' rank = 0 # check environment variables here instead of importing mpi4py # to avoid calling MPI_Init() when this module is imported for varname in ['PMI_RANK', 'OMPI_COMM_WORLD_RANK']: if varname in os.environ: rank = int(os.environ[varname]) if rank > 0: log_suffix = "-rank%03i" % rank if format_strs is None: if rank == 0: format_strs = os.getenv('OPENAI_LOG_FORMAT', 'stdout,log,csv').split(',') else: format_strs = os.getenv('OPENAI_LOG_FORMAT_MPI', 'log').split(',') format_strs = filter(None, format_strs) output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs] Logger.CURRENT = Logger(dir=dir, output_formats=output_formats) log('Logging to %s'%dir) def _configure_default_logger(): format_strs = None # keep the old default of only writing to stdout if 'OPENAI_LOG_FORMAT' not in os.environ: format_strs = ['stdout'] configure(format_strs=format_strs) Logger.DEFAULT = Logger.CURRENT def reset(): if Logger.CURRENT is not Logger.DEFAULT: Logger.CURRENT.close() Logger.CURRENT = Logger.DEFAULT log('Reset logger') class scoped_configure(object): def __init__(self, dir=None, format_strs=None): self.dir = dir self.format_strs = format_strs self.prevlogger = None def __enter__(self): self.prevlogger = Logger.CURRENT configure(dir=self.dir, format_strs=self.format_strs) def __exit__(self, *args): Logger.CURRENT.close() Logger.CURRENT = self.prevlogger # ================================================================ def _demo(): info("hi") debug("shouldn't appear") set_level(DEBUG) debug("should appear") dir = "/tmp/testlogging" if os.path.exists(dir): shutil.rmtree(dir) configure(dir=dir) logkv("a", 3) logkv("b", 2.5) dumpkvs() logkv("b", -2.5) logkv("a", 5.5) dumpkvs() info("^^^ should see a = 5.5") logkv_mean("b", -22.5) logkv_mean("b", -44.4) logkv("a", 5.5) dumpkvs() info("^^^ should see b = 33.3") logkv("b", -2.5) dumpkvs() logkv("a", "longasslongasslongasslongasslongasslongassvalue") dumpkvs() # ================================================================ # Readers # ================================================================ def read_json(fname): import pandas ds = [] with open(fname, 'rt') as fh: for line in fh: ds.append(json.loads(line)) return pandas.DataFrame(ds) def read_csv(fname): import pandas return pandas.read_csv(fname, index_col=None, comment='#') def read_tb(path): """ path : a tensorboard file OR a directory, where we will find all TB files of the form events.* """ import pandas import numpy as np from glob import glob from collections import defaultdict import tensorflow as tf if osp.isdir(path): fnames = glob(osp.join(path, "events.*")) elif osp.basename(path).startswith("events."): fnames = [path] else: raise NotImplementedError("Expected tensorboard file or directory containing them. Got %s"%path) tag2pairs = defaultdict(list) maxstep = 0 for fname in fnames: for summary in tf.train.summary_iterator(fname): if summary.step > 0: for v in summary.summary.value: pair = (summary.step, v.simple_value) tag2pairs[v.tag].append(pair) maxstep = max(summary.step, maxstep) data = np.empty((maxstep, len(tag2pairs))) data[:] = np.nan tags = sorted(tag2pairs.keys()) for (colidx,tag) in enumerate(tags): pairs = tag2pairs[tag] for (step, value) in pairs: data[step-1, colidx] = value return pandas.DataFrame(data, columns=tags) # configure the default logger on import # _configure_default_logger() if __name__ == "__main__": _demo()
14,503
28.660532
122
py
tdqn
tdqn-master/drrn/vec_env.py
import numpy as np from multiprocessing import Process, Pipe def worker(remote, parent_remote, env): parent_remote.close() env.create() try: done = False while True: cmd, data = remote.recv() if cmd == 'step': if done: ob, info = env.reset() reward = 0 done = False else: ob, reward, done, info = env.step(data) remote.send((ob, reward, done, info)) elif cmd == 'reset': ob, info = env.reset() remote.send((ob, info)) elif cmd == 'close': env.close() break else: raise NotImplementedError except KeyboardInterrupt: print('SubprocVecEnv worker: got KeyboardInterrupt') finally: env.close() class VecEnv: def __init__(self, num_envs, env): self.closed = False self.num_envs = num_envs self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(num_envs)]) self.ps = [Process(target=worker, args=(work_remote, remote, env)) for (work_remote, remote) in zip(self.work_remotes, self.remotes)] for p in self.ps: p.daemon = True # if the main process crashes, we should not cause things to hang p.start() for remote in self.work_remotes: remote.close() def step(self, actions): self._assert_not_closed() assert len(actions) == self.num_envs, "Error: incorrect number of actions." for remote, action in zip(self.remotes, actions): remote.send(('step', action)) results = [remote.recv() for remote in self.remotes] self.waiting = False obs, rewards, dones, infos = zip(*results) return np.stack(obs), np.stack(rewards), np.stack(dones), infos def reset(self): self._assert_not_closed() for remote in self.remotes: remote.send(('reset', None)) results = [remote.recv() for remote in self.remotes] obs, infos = zip(*results) return np.stack(obs), infos def close_extras(self): self.closed = True for remote in self.remotes: remote.send(('close', None)) for p in self.ps: p.join() def _assert_not_closed(self): assert not self.closed, "Trying to operate on a SubprocVecEnv after calling close()"
2,514
33.452055
94
py
tdqn
tdqn-master/drrn/util.py
import numpy as np def pad_sequences(sequences, maxlen=None, dtype='int32', value=0.): ''' Partially borrowed from Keras # Arguments sequences: list of lists where each element is a sequence maxlen: int, maximum length dtype: type to cast the resulting sequence. value: float, value to pad the sequences to the desired value. # Returns x: numpy array with dimensions (number_of_sequences, maxlen) ''' lengths = [len(s) for s in sequences] nb_samples = len(sequences) if maxlen is None: maxlen = np.max(lengths) # take the sample shape from the first non empty sequence # checking for consistency in the main loop below. sample_shape = tuple() for s in sequences: if len(s) > 0: sample_shape = np.asarray(s).shape[1:] break x = (np.ones((nb_samples, maxlen) + sample_shape) * value).astype(dtype) for idx, s in enumerate(sequences): if len(s) == 0: continue # empty list was found # pre truncating trunc = s[-maxlen:] # check `trunc` has expected shape trunc = np.asarray(trunc, dtype=dtype) if trunc.shape[1:] != sample_shape: raise ValueError('Shape of sample %s of sequence at position %s is different from expected shape %s' % (trunc.shape[1:], idx, sample_shape)) # post padding x[idx, :len(trunc)] = trunc return x
1,480
36.025
114
py
tdqn
tdqn-master/drrn/train.py
import subprocess import time import os import torch import logger import argparse import yaml import jericho from os.path import basename, dirname from drrn import DRRN_Agent from vec_env import VecEnv from env import JerichoEnv from jericho.util import clean def configure_logger(log_dir): logger.configure(log_dir, format_strs=['log']) global tb tb = logger.Logger(log_dir, [logger.make_output_format('tensorboard', log_dir), logger.make_output_format('csv', log_dir), logger.make_output_format('stdout', log_dir)]) global log log = logger.log def evaluate(agent, env, nb_episodes=1): with torch.no_grad(): total_score = 0 for ep in range(nb_episodes): log("Starting evaluation episode {}".format(ep)) score = evaluate_episode(agent, env) log("Evaluation episode {} ended with score {}\n\n".format(ep, score)) total_score += score avg_score = total_score / nb_episodes return avg_score def evaluate_episode(agent, env): step = 0 done = False ob, info = env.reset() state = agent.build_state([ob], [info])[0] log('Obs{}: {} Inv: {} Desc: {}'.format(step, clean(ob), clean(info['inv']), clean(info['look']))) while not done: valid_acts = info['valid'] valid_ids = agent.encode(valid_acts) _, action_idx, action_values = agent.act([state], [valid_ids], sample=False) action_idx = action_idx[0] action_values = action_values[0] action_str = valid_acts[action_idx] log('Action{}: {}, Q-Value {:.2f}'.format(step, action_str, action_values[action_idx].item())) s = '' for idx, (act, val) in enumerate(sorted(zip(valid_acts, action_values), key=lambda x: x[1], reverse=True), 1): s += "{}){:.2f} {} ".format(idx, val.item(), act) log('Q-Values: {}'.format(s)) ob, rew, done, info = env.step(action_str) log("Reward{}: {}, Score {}, Done {}".format(step, rew, info['score'], done)) step += 1 log('Obs{}: {} Inv: {} Desc: {}'.format(step, clean(ob), clean(info['inv']), clean(info['look']))) state = agent.build_state([ob], [info])[0] return info['score'] def train(agent, eval_env, envs, max_steps, update_freq, eval_freq, checkpoint_freq, log_freq): start = time.time() obs, infos = envs.reset() states = agent.build_state(obs, infos) valid_ids = [agent.encode(info['valid']) for info in infos] for step in range(1, max_steps+1): action_ids, action_idxs, _ = agent.act(states, valid_ids) action_strs = [info['valid'][idx] for info, idx in zip(infos, action_idxs)] obs, rewards, dones, infos = envs.step(action_strs) for done, info in zip(dones, infos): if done: tb.logkv_mean('EpisodeScore', info['score']) next_states = agent.build_state(obs, infos) next_valids = [agent.encode(info['valid']) for info in infos] for state, act, rew, next_state, valids, done in \ zip(states, action_ids, rewards, next_states, next_valids, dones): agent.observe(state, act, rew, next_state, valids, done) states = next_states valid_ids = next_valids if step % log_freq == 0: tb.logkv('Step', step) tb.logkv("FPS", int((step*envs.num_envs)/(time.time()-start))) tb.dumpkvs() if step % update_freq == 0: loss = agent.update() if loss is not None: tb.logkv_mean('Loss', loss) if step % checkpoint_freq == 0: agent.save() if step % eval_freq == 0: eval_score = evaluate(agent, eval_env) tb.logkv('EvalScore', eval_score) tb.dumpkvs() def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--output_dir', default='logs') parser.add_argument('--spm_path', default='../spm_models/unigram_8k.model') parser.add_argument('--rom_path', default='zork1.z5') parser.add_argument('--env_step_limit', default=100, type=int) parser.add_argument('--seed', default=0, type=int) parser.add_argument('--num_envs', default=8, type=int) parser.add_argument('--max_steps', default=100000, type=int) parser.add_argument('--update_freq', default=1, type=int) parser.add_argument('--checkpoint_freq', default=5000, type=int) parser.add_argument('--eval_freq', default=5000, type=int) parser.add_argument('--log_freq', default=100, type=int) parser.add_argument('--memory_size', default=500000, type=int) parser.add_argument('--batch_size', default=64, type=int) parser.add_argument('--gamma', default=.9, type=float) parser.add_argument('--learning_rate', default=0.0001, type=float) parser.add_argument('--clip', default=5, type=float) parser.add_argument('--embedding_dim', default=128, type=int) parser.add_argument('--hidden_dim', default=128, type=int) return parser.parse_args() def start_redis(): print('Starting Redis') subprocess.Popen(['redis-server', '--save', '\"\"', '--appendonly', 'no']) time.sleep(1) def main(): assert jericho.__version__ == '2.1.0', "This code is designed to be run with Jericho version 2.1.0." args = parse_args() print(args) configure_logger(args.output_dir) start_redis() agent = DRRN_Agent(args) env = JerichoEnv(args.rom_path, args.seed, args.env_step_limit) envs = VecEnv(args.num_envs, env) env.create() # Create the environment for evaluation train(agent, env, envs, args.max_steps, args.update_freq, args.eval_freq, args.checkpoint_freq, args.log_freq) def interactive_run(env): ob, info = env.reset() while True: print(clean(ob), 'Reward', reward, 'Done', done, 'Valid', info) ob, reward, done, info = env.step(input()) if __name__ == "__main__": main()
5,988
38.926667
118
py