code
stringlengths
17
6.64M
def logmeanexp(x, dim=0): return (x.logsumexp(dim) - math.log(x.shape[dim]))
def stack(x, num_samples=None, dim=0): return (x if (num_samples is None) else torch.stack(([x] * num_samples), dim=dim))
class Logger(): ' Writes results of training/testing ' @classmethod def initialize(cls, args, training): logtime = datetime.datetime.now().__format__('_%m%d_%H%M%S') logpath = (args.logpath if training else (('_TEST_' + args.load.split('/')[(- 1)].split('.')[0]) + logtime)) if (lo...
class AverageMeter(): ' Stores loss, evaluation results, selected layers ' def __init__(self, benchamrk): ' Constructor of AverageMeter ' self.buffer_keys = ['pck'] self.buffer = {} for key in self.buffer_keys: self.buffer[key] = [] self.loss_buffer = [] ...
class CorrespondenceDataset(Dataset): ' Parent class of PFPascal, PFWillow, and SPair ' def __init__(self, benchmark, datapath, thres, split): ' CorrespondenceDataset constructor ' super(CorrespondenceDataset, self).__init__() self.metadata = {'pfwillow': ('PF-WILLOW', 'test_pairs.csv...
def load_dataset(benchmark, datapath, thres, split='test'): ' Instantiate a correspondence dataset ' correspondence_benchmark = {'spair': spair.SPairDataset, 'pfpascal': pfpascal.PFPascalDataset, 'pfwillow': pfwillow.PFWillowDataset} dataset = correspondence_benchmark.get(benchmark) if (dataset is Non...
def download_from_google(token_id, filename): ' Download desired filename from Google drive ' print(('Downloading %s ...' % os.path.basename(filename))) url = 'https://docs.google.com/uc?export=download' destination = (filename + '.tar.gz') session = requests.Session() response = session.get(u...
def get_confirm_token(response): 'Retrieves confirm token' for (key, value) in response.cookies.items(): if key.startswith('download_warning'): return value return None
def save_response_content(response, destination): 'Saves the response to the destination' chunk_size = 32768 with open(destination, 'wb') as file: for chunk in response.iter_content(chunk_size): if chunk: file.write(chunk)
def download_dataset(datapath, benchmark): 'Downloads semantic correspondence benchmark dataset from Google drive' if (not os.path.isdir(datapath)): os.mkdir(datapath) file_data = {'spair': ('1KSvB0k2zXA06ojWNvFjBv0Ake426Y76k', 'SPair-71k'), 'pfpascal': ('1OOwpGzJnTsFXYh-YffMQ9XKM_Kl_zdzg', 'PF-PA...
class SPairDataset(CorrespondenceDataset): def __init__(self, benchmark, datapath, thres, split): ' SPair-71k dataset constructor ' super(SPairDataset, self).__init__(benchmark, datapath, thres, split) self.train_data = open(self.spt_path).read().split('\n') self.train_data = self...
def conv3x3(in_planes, out_planes, stride=1): ' 3x3 convolution with padding ' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, groups=2, bias=False)
def conv1x1(in_planes, out_planes, stride=1): ' 1x1 convolution ' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, groups=2, bias=False)
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = conv1x1(inplanes, planes) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes, stride) self.bn2...
class Backbone(nn.Module): def __init__(self, block, layers, zero_init_residual=False): super(Backbone, self).__init__() self.inplanes = 128 self.conv1 = nn.Conv2d(6, 128, kernel_size=7, stride=2, padding=3, groups=2, bias=False) self.bn1 = nn.BatchNorm2d(128) self.relu = ...
def resnet101(pretrained=False, **kwargs): 'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = Backbone(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: weights = model_zoo.load_url(model_urls['resnet101']) ...
class KernelGenerator(): def __init__(self, ksz, ktype): self.ksz = ksz self.idx4d = Geometry.init_idx4d(ksz) self.kernel = torch.zeros((ksz, ksz, ksz, ksz)).cuda() self.center = ((ksz // 2), (ksz // 2)) self.ktype = ktype def quadrant(self, crd): if (crd[0] <...
class Correlation(): @classmethod def mutual_nn_filter(cls, correlation_matrix, eps=1e-30): " Mutual nearest neighbor filtering (Rocco et al. NeurIPS'18 )" corr_src_max = torch.max(correlation_matrix, dim=2, keepdim=True)[0] corr_trg_max = torch.max(correlation_matrix, dim=1, keepdim=...
class CHMLearner(nn.Module): def __init__(self, ktype, feat_dim): super(CHMLearner, self).__init__() self.scales = [0.5, 1, 2] self.conv2ds = nn.ModuleList([nn.Conv2d(feat_dim, (feat_dim // 4), kernel_size=3, padding=1, bias=False) for _ in self.scales]) ksz_translation = 5 ...
class CHMNet(nn.Module): def __init__(self, ktype): super(CHMNet, self).__init__() self.backbone = backbone.resnet101(pretrained=True) self.learner = chmlearner.CHMLearner(ktype, feat_dim=1024) def forward(self, src_img, trg_img): (src_feat, trg_feat) = self.extract_features(...
def test(model, dataloader): average_meter = AverageMeter(dataloader.dataset.benchmark) model.eval() for (idx, batch) in enumerate(dataloader): corr_matrix = model(batch['src_img'].cuda(), batch['trg_img'].cuda()) prd_kps = Geometry.transfer_kps(corr_matrix, batch['src_kps'].cuda(), batch[...
def train(epoch, model, dataloader, optimizer, training): (model.train() if training else model.eval()) average_meter = AverageMeter(dataloader.dataset.benchmark) for (idx, batch) in enumerate(dataloader): corr_matrix = model(batch['src_img'].cuda(), batch['trg_img'].cuda()) prd_trg_kps = ...
def getSeries(df, value): df2 = df[(df.Name == value)] return np.asarray(df2['close'])
def Jitter(X, sigma=0.5): myNoise = np.random.normal(loc=0, scale=sigma, size=X.shape) return (X + myNoise)
def augment(df, n): res = [] for i in range(0, n): x = df.apply(Jitter, axis=1) res.append(np.asarray(x)) return np.hstack(res)
def scale(path): df = pd.read_csv(path, index_col=0) scaled_feats = StandardScaler().fit_transform(df.values) scaled_features_df = pd.DataFrame(scaled_feats, columns=df.columns) return scaled_features_df
class UmapKmeans(): def __init__(self, n_clusters, umap_dim=2, umap_neighbors=10, umap_min_distance=float(0), umap_metric='euclidean', random_state=0): self.n_clusters = n_clusters self.manifold_in_embedding = umap.UMAP(random_state=random_state, metric=umap_metric, n_components=umap_dim, n_neigh...
def add_noise(x, noise_factor): x_clean = x x_noisy = (x_clean + (noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_clean.shape))) x_noisy = np.clip(x_noisy, 0.0, 1.0) return x_noisy
class AutoEncoder(): "AutoeEncoder: standard feed forward autoencoder\n\n Parameters:\n -----------\n input_dim: int\n The number of dimensions of your input\n\n\n latent_dim: int\n The number of dimensions which you wish to represent the data as.\n\n architecture: list\n The s...
class UmapGMM(): '\n UmapGMM: UMAP gaussian mixing\n\n Parameters:\n ------------\n n_clusters: int\n the number of clusters\n\n umap_dim: int\n number of dimensions to find with umap. Defaults to 2\n\n umap_neighbors: int...
def best_cluster_fit(y_true, y_pred): y_true = y_true.astype(np.int64) D = (max(y_pred.max(), y_true.max()) + 1) w = np.zeros((D, D), dtype=np.int64) for i in range(y_pred.size): w[(y_pred[i], y_true[i])] += 1 ind = la.linear_assignment((w.max() - w)) best_fit = [] for i in range(y...
def cluster_acc(y_true, y_pred): (_, ind, w) = best_cluster_fit(y_true, y_pred) return ((sum([w[(i, j)] for (i, j) in ind]) * 1.0) / y_pred.size)
def plot(x, y, plot_id, names=None, n_clusters=10): viz_df = pd.DataFrame(data=x[:5000]) viz_df['Label'] = y[:5000] if (names is not None): viz_df['Label'] = viz_df['Label'].map(names) plt.subplots(figsize=(8, 5)) sns.scatterplot(x=0, y=1, hue='Label', legend='full', hue_order=sorted(viz_d...
class n2d(): '\n n2d: Class for n2d\n\n Parameters:\n ------------\n\n input_dim: int\n dimensions of input\n\n manifold_learner: initialized class, such as UmapGMM\n the manifold learner and clustering algorithm. Class should have at\n least fi...
def save_n2d(obj, encoder_id, manifold_id): '\n save_n2d: save n2d objects\n --------------------------\n\n description: Saves the encoder to an h5 file and the manifold learner/clusterer\n to a pickle.\n\n parameters:\n\n - obj: the fitted n2d object\n - encoder_id: what to save the ...
def load_n2d(encoder_id, manifold_id): '\n load_n2d: load n2d objects\n --------------------------\n\n description: loads fitted n2d objects from files. Note you CANNOT train\n these objects further, the only method which will perform correctly is `.predict`\n\n parameters:\n\n - encoder_id:...
class manifold_cluster_generator(N2D.UmapGMM): def __init__(self, manifold_class, manifold_args, cluster_class, cluster_args): self.manifold_in_embedding = manifold_class(**manifold_args) self.cluster_manifold = cluster_class(**cluster_args) proba = getattr(self.cluster_manifold, 'predict...
class autoencoder_generator(N2D.AutoEncoder): def __init__(self, model_levels=(), x_lambda=(lambda x: x)): self.Model = Model(model_levels[0], model_levels[2]) self.encoder = Model(model_levels[0], model_levels[1]) self.x_lambda = x_lambda def fit(self, x, batch_size, epochs, loss, o...
class SetTransformer(nn.Module): def __init__(self, dim_input=3, num_outputs=1, dim_output=40, num_inds=32, dim_hidden=128, num_heads=4, ln=False): super(SetTransformer, self).__init__() self.enc = nn.Sequential(ISAB(dim_input, dim_hidden, num_heads, num_inds, ln=ln), ISAB(dim_hidden, dim_hidden,...
def gen_data(batch_size, max_length=10, test=False): length = np.random.randint(1, (max_length + 1)) x = np.random.randint(1, 100, (batch_size, length)) y = np.max(x, axis=1) (x, y) = (np.expand_dims(x, axis=2), np.expand_dims(y, axis=1)) return (x, y)
class SmallDeepSet(nn.Module): def __init__(self, pool='max'): super().__init__() self.enc = nn.Sequential(nn.Linear(in_features=1, out_features=64), nn.ReLU(), nn.Linear(in_features=64, out_features=64), nn.ReLU(), nn.Linear(in_features=64, out_features=64), nn.ReLU(), nn.Linear(in_features=64, ...
class SmallSetTransformer(nn.Module): def __init__(self): super().__init__() self.enc = nn.Sequential(SAB(dim_in=1, dim_out=64, num_heads=4), SAB(dim_in=64, dim_out=64, num_heads=4)) self.dec = nn.Sequential(PMA(dim=64, num_heads=4, num_seeds=1), nn.Linear(in_features=64, out_features=1))...
def train(model): model = model.cuda() optimizer = torch.optim.Adam(model.parameters(), lr=0.0001) criterion = nn.L1Loss().cuda() losses = [] for _ in range(500): (x, y) = gen_data(batch_size=(2 ** 10), max_length=10) (x, y) = (torch.from_numpy(x).float().cuda(), torch.from_numpy(y...
class MultivariateNormal(object): def __init__(self, dim): self.dim = dim def sample(self, B, K, labels): raise NotImplementedError def log_prob(self, X, params): raise NotImplementedError def stats(self): raise NotImplementedError def parse(self, raw): ...
class MixtureOfMVNs(object): def __init__(self, mvn): self.mvn = mvn def sample(self, B, N, K, return_gt=False): device = ('cpu' if (not torch.cuda.is_available()) else torch.cuda.current_device()) pi = Dirichlet(torch.ones(K)).sample(torch.Size([B])).to(device) labels = Cate...
class DeepSet(nn.Module): def __init__(self, dim_input, num_outputs, dim_output, dim_hidden=128): super(DeepSet, self).__init__() self.num_outputs = num_outputs self.dim_output = dim_output self.enc = nn.Sequential(nn.Linear(dim_input, dim_hidden), nn.ReLU(), nn.Linear(dim_hidden,...
class SetTransformer(nn.Module): def __init__(self, dim_input, num_outputs, dim_output, num_inds=32, dim_hidden=128, num_heads=4, ln=False): super(SetTransformer, self).__init__() self.enc = nn.Sequential(ISAB(dim_input, dim_hidden, num_heads, num_inds, ln=ln), ISAB(dim_hidden, dim_hidden, num_he...
class MAB(nn.Module): def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False): super(MAB, self).__init__() self.dim_V = dim_V self.num_heads = num_heads self.fc_q = nn.Linear(dim_Q, dim_V) self.fc_k = nn.Linear(dim_K, dim_V) self.fc_v = nn.Linear(dim_K, dim_V)...
class SAB(nn.Module): def __init__(self, dim_in, dim_out, num_heads, ln=False): super(SAB, self).__init__() self.mab = MAB(dim_in, dim_in, dim_out, num_heads, ln=ln) def forward(self, X): return self.mab(X, X)
class ISAB(nn.Module): def __init__(self, dim_in, dim_out, num_heads, num_inds, ln=False): super(ISAB, self).__init__() self.I = nn.Parameter(torch.Tensor(1, num_inds, dim_out)) nn.init.xavier_uniform_(self.I) self.mab0 = MAB(dim_out, dim_in, dim_out, num_heads, ln=ln) sel...
class PMA(nn.Module): def __init__(self, dim, num_heads, num_seeds, ln=False): super(PMA, self).__init__() self.S = nn.Parameter(torch.Tensor(1, num_seeds, dim)) nn.init.xavier_uniform_(self.S) self.mab = MAB(dim, dim, dim, num_heads, ln=ln) def forward(self, X): retu...
def generate_benchmark(): if (not os.path.isdir('benchmark')): os.makedirs('benchmark') N_list = np.random.randint(N_min, N_max, args.num_bench) data = [] ll = 0.0 for N in tqdm(N_list): (X, labels, pi, params) = mog.sample(B, N, K, return_gt=True) ll += mog.log_prob(X, pi,...
def train(): if (not os.path.isdir(save_dir)): os.makedirs(save_dir) if (not os.path.isfile(benchfile)): generate_benchmark() bench = torch.load(benchfile) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(args.run_name) logger.addHandler(logging.FileHandler(os...
def test(bench, verbose=True): net.eval() (data, oracle_ll) = bench avg_ll = 0.0 for X in data: X = X.cuda() avg_ll += mog.log_prob(X, *mvn.parse(net(X))).item() avg_ll /= len(data) line = 'test ll {:.4f} (oracle {:.4f})'.format(avg_ll, oracle_ll) if verbose: loggin...
def plot(): net.eval() X = mog.sample(B, np.random.randint(N_min, N_max), K) (pi, params) = mvn.parse(net(X)) (ll, labels) = mog.log_prob(X, pi, params, return_labels=True) (fig, axes) = plt.subplots(2, (B // 2), figsize=(((7 * B) // 5), 5)) mog.plot(X, labels, params, axes) plt.show()
class Logger(): 'Writes results of training/testing' @classmethod def initialize(cls, args): logtime = datetime.datetime.now().__format__('_%m%d_%H%M%S') logpath = args.logpath cls.logpath = os.path.join('logs', ((logpath + logtime) + '.log')) cls.benchmark = args.benchmar...
class AverageMeter(): 'Stores loss, evaluation results, selected layers' def __init__(self, benchamrk): 'Constructor of AverageMeter' if (benchamrk == 'caltech'): self.buffer_keys = ['ltacc', 'iou'] else: self.buffer_keys = ['pck'] self.buffer = {} ...
class SupervisionStrategy(ABC): 'Different strategies for methods:' @abstractmethod def get_image_pair(self, batch, *args): pass @abstractmethod def get_correlation(self, correlation_matrix): pass @abstractmethod def compute_loss(self, correlation_matrix, *args): ...
class StrongSupStrategy(SupervisionStrategy): def get_image_pair(self, batch, *args): 'Returns (semantically related) pairs for strongly-supervised training' return (batch['src_img'], batch['trg_img']) def get_correlation(self, correlation_matrix): "Returns correlation matrices of 'A...
class WeakSupStrategy(SupervisionStrategy): def get_image_pair(self, batch, *args): 'Forms positive/negative image paris for weakly-supervised training' training = args[0] self.bsz = len(batch['src_img']) if training: shifted_idx = np.roll(np.arange(self.bsz), (- 1)) ...
def fix_randseed(seed): 'Fixes random seed for reproducibility' random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True
def mean(x): 'Computes average of a list' return ((sum(x) / len(x)) if (len(x) > 0) else 0.0)
def where(predicate): 'Predicate must be a condition on nd-tensor' matching_indices = predicate.nonzero() if (len(matching_indices) != 0): matching_indices = matching_indices.t().squeeze(0) return matching_indices
class CorrespondenceDataset(Dataset): 'Parent class of PFPascal, PFWillow, Caltech, and SPair' def __init__(self, benchmark, datapath, thres, device, split): 'CorrespondenceDataset constructor' super(CorrespondenceDataset, self).__init__() self.metadata = {'pfwillow': ('PF-WILLOW', 't...
def find_knn(db_vectors, qr_vectors): 'Finds K-nearest neighbors (Euclidean distance)' db = db_vectors.unsqueeze(1).repeat(1, qr_vectors.size(0), 1) qr = qr_vectors.unsqueeze(0).repeat(db_vectors.size(0), 1, 1) dist = (db - qr).pow(2).sum(2).pow(0.5).t() (_, nearest_idx) = dist.min(dim=1) retu...
def load_dataset(benchmark, datapath, thres, device, split='test'): 'Instantiates desired correspondence dataset' correspondence_benchmark = {'pfpascal': pfpascal.PFPascalDataset, 'pfwillow': pfwillow.PFWillowDataset, 'caltech': caltech.CaltechDataset, 'spair': spair.SPairDataset} dataset = correspondence...
def download_from_google(token_id, filename): 'Downloads desired filename from Google drive' print(('Downloading %s ...' % os.path.basename(filename))) url = 'https://docs.google.com/uc?export=download' destination = (filename + '.tar.gz') session = requests.Session() response = session.get(ur...
def get_confirm_token(response): 'Retrieves confirm token' for (key, value) in response.cookies.items(): if key.startswith('download_warning'): return value return None
def save_response_content(response, destination): 'Saves the response to the destination' chunk_size = 32768 with open(destination, 'wb') as file: for chunk in response.iter_content(chunk_size): if chunk: file.write(chunk)
def download_dataset(datapath, benchmark): 'Downloads semantic correspondence benchmark dataset from Google drive' if (not os.path.isdir(datapath)): os.mkdir(datapath) file_data = {'pfwillow': ('1tDP0y8RO5s45L-vqnortRaieiWENQco_', 'PF-WILLOW'), 'pfpascal': ('1OOwpGzJnTsFXYh-YffMQ9XKM_Kl_zdzg', 'PF...
class SPairDataset(CorrespondenceDataset): 'Inherits CorrespondenceDataset' def __init__(self, benchmark, datapath, thres, device, split): 'SPair-71k dataset constructor' super(SPairDataset, self).__init__(benchmark, datapath, thres, device, split) self.train_data = open(self.spt_path...
class Correlation(): @classmethod def bmm_interp(cls, src_feat, trg_feat, interp_size): 'Performs batch-wise matrix-multiplication after interpolation' src_feat = F.interpolate(src_feat, interp_size, mode='bilinear', align_corners=True) trg_feat = F.interpolate(trg_feat, interp_size, ...
class Norm(): 'Vector normalization' @classmethod def feat_normalize(cls, x, interp_size): 'L2-normalizes given 2D feature map after interpolation' x = F.interpolate(x, interp_size, mode='bilinear', align_corners=True) return x.pow(2).sum(1).view(x.size(0), (- 1)) @classmetho...
def conv3x3(in_planes, out_planes, stride=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, groups=2, bias=False)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, groups=2, bias=False)
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = conv1x1(inplanes, planes) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes, stride) self.bn2...
class Backbone(nn.Module): def __init__(self, block, layers, zero_init_residual=False): super(Backbone, self).__init__() self.inplanes = 128 self.conv1 = nn.Conv2d(6, 128, kernel_size=7, stride=2, padding=3, groups=2, bias=False) self.bn1 = nn.BatchNorm2d(128) self.relu = ...
def resnet50(pretrained=False, **kwargs): 'Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = Backbone(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: weights = model_zoo.load_url(model_urls['resnet50']) ...
def resnet101(pretrained=False, **kwargs): 'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = Backbone(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: weights = model_zoo.load_url(model_urls['resnet101']) ...
class DynamicHPF(): 'Dynamic Hyperpixel Flow (DHPF)' def __init__(self, backbone, device, img_side=240): 'Constructor for DHPF' super(DynamicHPF, self).__init__() if (backbone == 'resnet50'): self.backbone = resnet.resnet50(pretrained=True).to(device) self.in_c...
class Objective(): 'Provides training objectives of DHPF' @classmethod def initialize(cls, target_rate, alpha): cls.softmax = torch.nn.Softmax(dim=1) cls.target_rate = target_rate cls.alpha = alpha cls.eps = 1e-30 @classmethod def weighted_cross_entropy(cls, corre...
def test(model, dataloader): 'Code for testing DHPF' average_meter = AverageMeter(dataloader.dataset.benchmark) for (idx, batch) in enumerate(dataloader): (correlation_matrix, layer_sel) = model(batch['src_img'], batch['trg_img']) prd_kps = Geometry.transfer_kps(correlation_matrix, batch['...
def train(epoch, model, dataloader, strategy, optimizer, training): 'Code for training DHPF' (model.train() if training else model.eval()) average_meter = AverageMeter(dataloader.dataset.benchmark) for (idx, batch) in enumerate(dataloader): (src_img, trg_img) = strategy.get_image_pair(batch, t...
def align_and_split(files): for f in tqdm(files): get_ipython().system('/notebooks/MotionCor2_1.3.0-Cuda101 -InMrc {f} -OutMrc tmp/aligned.mrc -Patch 5 5 5 -OutStack 1 >> motioncor2.log') aligned_stack = mrcfile.open(glob('tmp/*_Stk.mrc')[0], permissive=True) save_mrc(join(data_path, 'even...
def copy_etomo_files(src, name, target): if exists(join(src, (name + 'local.xf'))): cp(join(src, (name + 'local.xf')), target) cp(join(src, (name + '.xf')), target) cp(join(src, 'eraser.com'), target) cp(join(src, 'ctfcorrection.com'), target) cp(join(src, 'tilt.com'), target) cp(join(...
def augment(x, y): rot_k = np.random.randint(0, 4, x.shape[0]) X = x.copy() Y = y.copy() for i in range(X.shape[0]): if (np.random.rand() < 0.5): X[i] = np.rot90(x[i], k=rot_k[i], axes=(0, 2)) Y[i] = np.rot90(y[i], k=rot_k[i], axes=(0, 2)) else: X[i]...
class CryoDataWrapper(Sequence): def __init__(self, X, Y, batch_size): (self.X, self.Y) = (X, Y) self.batch_size = batch_size self.perm = np.random.permutation(len(self.X)) def __len__(self): return int(np.ceil((len(self.X) / float(self.batch_size)))) def on_epoch_end(se...
class CryoCARE(CARE): def train(self, X, Y, validation_data, epochs=None, steps_per_epoch=None): 'Train the neural network with the given data.\n Parameters\n ----------\n X : :class:`numpy.ndarray`\n Array of source images.\n Y : :class:`numpy.ndarray`\n ...
@contextmanager def cd(newdir): 'Context manager to temporarily change the working directory' prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: (yield) finally: os.chdir(prevdir)
def save_mrc(path, data, pixel_spacing): '\n Save data in a mrc-file and set the pixel spacing with the `alterheader` command from IMOD.\n\n Parameters\n ----------\n path : str\n Path of the new file.\n data : array(float)\n The data to save.\n pixel_spacing : float\n The p...
def remove_files(dir, extension='.mrc'): "\n Removes all files in a directory with the given extension.\n\n Parameters\n ----------\n dir : str\n The directory to clean.\n extension : str\n The file extension. Default: ``'.mrc'``\n " files = glob(join(dir, ('*' + extension))) ...
def modify_newst(path, bin_factor): '\n Modifies the bin-factor of a given newst.com file.\n\n Note: This will overwrite the file!\n\n Parameters\n ----------\n path : str\n Path to the newst.com file.\n bin_factor : int\n The new bin-factor.\n ' f = open(path, 'r') cont...
def modify_ctfcorrection(path, bin_factor, pixel_spacing): '\n Modifies the bin-factor of a given ctfcorrection.com file.\n\n Note: This will overwrite the file!\n\n Parameters\n ----------\n path : str\n Path to the ctfcorrection.com file.\n bin_factor : int\n The new bin-factor.\...
def modify_tilt(path, bin_factor, exclude_angles=[]): '\n Modifies the bin-factor and exclude-angles of a given tilt.com file.\n\n Note: This will overwrite the file!\n\n Parameters\n ----------\n path : str\n Path to the tilt.com file.\n bin_factor : int\n The new bin-factor.\n ...
def modify_com_scripts(path, bin_factor, pixel_spacing, exclude_angles=[]): '\n Modifies the bin-factor and exclude-angles of the newst.com, ctfcorrection.com and tilt.com scripts.\n\n Note: This will overwrite the files!\n\n Parameters\n ----------\n path : str\n Path to the parent director...
def reconstruct_tomo(path, name, dfix, init, volt=300, rotate_X=True): '\n Reconstruct a tomogram with IMOD-com scripts. This also applies mtffilter after ctfcorrection.\n\n A reconstruction log will be placed in the reconstruction-directory.\n\n Parameters\n ----------\n path : str\n Path t...
def parse_layers(layer_ids): 'Parse list of layer ids (int) into string format' layer_str = ''.join(list(map((lambda x: ('%d,' % x)), layer_ids)))[:(- 1)] layer_str = (('(' + layer_str) + ')') return layer_str
def find_topk(membuf, kval): 'Return top-k performance along with layer combinations' membuf.sort(key=(lambda x: x[0]), reverse=True) return membuf[:kval]
def log_evaluation(layers, score, elapsed): 'Log a single evaluation result' logging.info(('%20s: %4.2f %% %5.1f sec' % (layers, score, elapsed)))
def log_selected(depth, membuf_topk): 'Log selected layers at each depth' logging.info((' ===================== Depth %d =====================' % depth)) for (score, layers) in membuf_topk: logging.info(('%20s: %4.2f %%' % (layers, score))) logging.info(' ======================================...