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
CoordFill
CoordFill-master/models/ffc.py
# Fast Fourier Convolution NeurIPS 2020 # original implementation https://github.com/pkumivision/FFC/blob/main/model_zoo/ffc.py # paper https://proceedings.neurips.cc/paper/2020/file/2fd5d41ec6cfab47e32164d5624269b1-Paper.pdf import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.fft # from saicinpainting.training.modules.base import get_activation, BaseDiscriminator # from saicinpainting.training.modules.spatial_transform import LearnableSpatialTransformWrapper # from saicinpainting.training.modules.squeeze_excitation import SELayer # from saicinpainting.utils import get_shape class FFCSE_block(nn.Module): def __init__(self, channels, ratio_g): super(FFCSE_block, self).__init__() in_cg = int(channels * ratio_g) in_cl = channels - in_cg r = 16 self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.conv1 = nn.Conv2d(channels, channels // r, kernel_size=1, bias=True) self.relu1 = nn.ReLU() self.conv_a2l = None if in_cl == 0 else nn.Conv2d( channels // r, in_cl, kernel_size=1, bias=True) self.conv_a2g = None if in_cg == 0 else nn.Conv2d( channels // r, in_cg, kernel_size=1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, x): x = x if type(x) is tuple else (x, 0) id_l, id_g = x x = id_l if type(id_g) is int else torch.cat([id_l, id_g], dim=1) x = self.avgpool(x) x = self.relu1(self.conv1(x)) x_l = 0 if self.conv_a2l is None else id_l * \ self.sigmoid(self.conv_a2l(x)) x_g = 0 if self.conv_a2g is None else id_g * \ self.sigmoid(self.conv_a2g(x)) return x_l, x_g class FourierUnit(nn.Module): def __init__(self, in_channels, out_channels, groups=1, spatial_scale_factor=None, spatial_scale_mode='bilinear', spectral_pos_encoding=False, use_se=False, se_kwargs=None, ffc3d=False, fft_norm='ortho'): # bn_layer not used super(FourierUnit, self).__init__() self.groups = groups self.conv_layer = torch.nn.Conv2d(in_channels=in_channels * 2 + (2 if spectral_pos_encoding else 0), out_channels=out_channels * 2, kernel_size=1, stride=1, padding=0, groups=self.groups, bias=False) self.bn = torch.nn.BatchNorm2d(out_channels * 2) self.relu = torch.nn.ReLU() # squeeze and excitation block self.use_se = use_se if use_se: if se_kwargs is None: se_kwargs = {} self.se = SELayer(self.conv_layer.in_channels, **se_kwargs) self.spatial_scale_factor = spatial_scale_factor self.spatial_scale_mode = spatial_scale_mode self.spectral_pos_encoding = spectral_pos_encoding self.ffc3d = ffc3d self.fft_norm = fft_norm def forward(self, x): batch = x.shape[0] if self.spatial_scale_factor is not None: orig_size = x.shape[-2:] x = F.interpolate(x, scale_factor=self.spatial_scale_factor, mode=self.spatial_scale_mode, align_corners=False) r_size = x.size() # (batch, c, h, w/2+1, 2) fft_dim = (-3, -2, -1) if self.ffc3d else (-2, -1) ffted = torch.fft.rfftn(x, dim=fft_dim, norm=self.fft_norm) ffted = torch.stack((ffted.real, ffted.imag), dim=-1) ffted = ffted.permute(0, 1, 4, 2, 3).contiguous() # (batch, c, 2, h, w/2+1) ffted = ffted.view((batch, -1,) + ffted.size()[3:]) if self.spectral_pos_encoding: height, width = ffted.shape[-2:] coords_vert = torch.linspace(0, 1, height)[None, None, :, None].expand(batch, 1, height, width).to(ffted) coords_hor = torch.linspace(0, 1, width)[None, None, None, :].expand(batch, 1, height, width).to(ffted) ffted = torch.cat((coords_vert, coords_hor, ffted), dim=1) if self.use_se: ffted = self.se(ffted) ffted = self.conv_layer(ffted) # (batch, c*2, h, w/2+1) # ffted = self.relu(self.bn(ffted)) ffted = self.relu(ffted) ffted = ffted.view((batch, -1, 2,) + ffted.size()[2:]).permute( 0, 1, 3, 4, 2).contiguous() # (batch,c, t, h, w/2+1, 2) ffted = torch.complex(ffted[..., 0], ffted[..., 1]) ifft_shape_slice = x.shape[-3:] if self.ffc3d else x.shape[-2:] output = torch.fft.irfftn(ffted, s=ifft_shape_slice, dim=fft_dim, norm=self.fft_norm) if self.spatial_scale_factor is not None: output = F.interpolate(output, size=orig_size, mode=self.spatial_scale_mode, align_corners=False) return output class SpectralTransform(nn.Module): def __init__(self, in_channels, out_channels, stride=1, groups=1, enable_lfu=True, **fu_kwargs): # bn_layer not used super(SpectralTransform, self).__init__() self.enable_lfu = enable_lfu if stride == 2: self.downsample = nn.AvgPool2d(kernel_size=(2, 2), stride=2) else: self.downsample = nn.Identity() self.stride = stride self.conv1 = nn.Sequential( nn.Conv2d(in_channels, out_channels // 2, kernel_size=1, groups=groups, bias=False), # nn.BatchNorm2d(out_channels // 2), nn.ReLU() ) self.fu = FourierUnit( out_channels // 2, out_channels // 2, groups, **fu_kwargs) if self.enable_lfu: self.lfu = FourierUnit( out_channels // 2, out_channels // 2, groups) self.conv2 = torch.nn.Conv2d( out_channels // 2, out_channels, kernel_size=1, groups=groups, bias=False) def forward(self, x): x = self.downsample(x) x = self.conv1(x) output = self.fu(x) if self.enable_lfu: n, c, h, w = x.shape split_no = 2 split_s = h // split_no xs = torch.cat(torch.split( x[:, :c // 4], split_s, dim=-2), dim=1).contiguous() xs = torch.cat(torch.split(xs, split_s, dim=-1), dim=1).contiguous() xs = self.lfu(xs) xs = xs.repeat(1, 1, split_no, split_no).contiguous() else: xs = 0 output = self.conv2(x + output + xs) return output class FFC(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, ratio_gin, ratio_gout, stride=1, padding=0, dilation=1, groups=1, bias=False, enable_lfu=True, padding_type='reflect', gated=False, **spectral_kwargs): super(FFC, self).__init__() assert stride == 1 or stride == 2, "Stride should be 1 or 2." self.stride = stride in_cg = int(in_channels * ratio_gin) in_cl = in_channels - in_cg out_cg = int(out_channels * ratio_gout) out_cl = out_channels - out_cg #groups_g = 1 if groups == 1 else int(groups * ratio_gout) #groups_l = 1 if groups == 1 else groups - groups_g self.ratio_gin = ratio_gin self.ratio_gout = ratio_gout self.global_in_num = in_cg module = nn.Identity if in_cl == 0 or out_cl == 0 else nn.Conv2d self.convl2l = module(in_cl, out_cl, kernel_size, stride, padding, dilation, groups, bias, padding_mode=padding_type) module = nn.Identity if in_cl == 0 or out_cg == 0 else nn.Conv2d self.convl2g = module(in_cl, out_cg, kernel_size, stride, padding, dilation, groups, bias, padding_mode=padding_type) module = nn.Identity if in_cg == 0 or out_cl == 0 else nn.Conv2d self.convg2l = module(in_cg, out_cl, kernel_size, stride, padding, dilation, groups, bias, padding_mode=padding_type) module = nn.Identity if in_cg == 0 or out_cg == 0 else SpectralTransform self.convg2g = module( in_cg, out_cg, stride, 1 if groups == 1 else groups // 2, enable_lfu, **spectral_kwargs) self.gated = gated module = nn.Identity if in_cg == 0 or out_cl == 0 or not self.gated else nn.Conv2d self.gate = module(in_channels, 2, 1) def forward(self, x): x_l, x_g = x if type(x) is tuple else (x, 0) out_xl, out_xg = 0, 0 if self.gated: total_input_parts = [x_l] if torch.is_tensor(x_g): total_input_parts.append(x_g) total_input = torch.cat(total_input_parts, dim=1) gates = torch.sigmoid(self.gate(total_input)) g2l_gate, l2g_gate = gates.chunk(2, dim=1) else: g2l_gate, l2g_gate = 1, 1 if self.ratio_gout != 1: out_xl = self.convl2l(x_l) + self.convg2l(x_g) * g2l_gate if self.ratio_gout != 0: out_xg = self.convl2g(x_l) * l2g_gate + self.convg2g(x_g) return out_xl, out_xg class FFC_BN_ACT(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, ratio_gin, ratio_gout, stride=1, padding=0, dilation=1, groups=1, bias=False, norm_layer=nn.BatchNorm2d, activation_layer=nn.Identity, padding_type='reflect', enable_lfu=True, **kwargs): super(FFC_BN_ACT, self).__init__() self.ffc = FFC(in_channels, out_channels, kernel_size, ratio_gin, ratio_gout, stride, padding, dilation, groups, bias, enable_lfu, padding_type=padding_type, **kwargs) lnorm = nn.Identity if ratio_gout == 1 else norm_layer gnorm = nn.Identity if ratio_gout == 0 else norm_layer global_channels = int(out_channels * ratio_gout) self.bn_l = lnorm(out_channels - global_channels) self.bn_g = gnorm(global_channels) lact = nn.Identity if ratio_gout == 1 else activation_layer gact = nn.Identity if ratio_gout == 0 else activation_layer self.act_l = lact() self.act_g = gact() def forward(self, x): x_l, x_g = self.ffc(x) # x_l = self.act_l(self.bn_l(x_l)) # x_g = self.act_g(self.bn_g(x_g)) x_l = self.act_l(x_l) x_g = self.act_g(x_g) return x_l, x_g class FFCResnetBlock(nn.Module): def __init__(self, dim, padding_type, norm_layer, activation_layer=nn.ReLU, dilation=1, spatial_transform_kwargs=None, inline=False, **conv_kwargs): super().__init__() self.conv1 = FFC_BN_ACT(dim, dim, kernel_size=3, padding=dilation, dilation=dilation, norm_layer=norm_layer, activation_layer=activation_layer, padding_type=padding_type, **conv_kwargs) self.conv2 = FFC_BN_ACT(dim, dim, kernel_size=3, padding=1, dilation=1, norm_layer=norm_layer, activation_layer=nn.Identity, padding_type=padding_type, **conv_kwargs) if spatial_transform_kwargs is not None: self.conv1 = LearnableSpatialTransformWrapper(self.conv1, **spatial_transform_kwargs) self.conv2 = LearnableSpatialTransformWrapper(self.conv2, **spatial_transform_kwargs) self.inline = inline def forward(self, x): if self.inline: x_l, x_g = x[:, :-self.conv1.ffc.global_in_num], x[:, -self.conv1.ffc.global_in_num:] else: x_l, x_g = x if type(x) is tuple else (x, 0) id_l, id_g = x_l, x_g x_l, x_g = self.conv1((x_l, x_g)) x_l, x_g = self.conv2((x_l, x_g)) x_l, x_g = id_l + x_l, id_g + x_g out = x_l, x_g if self.inline: out = torch.cat(out, dim=1) return out class ConcatTupleLayer(nn.Module): def forward(self, x): assert isinstance(x, tuple) x_l, x_g = x assert torch.is_tensor(x_l) or torch.is_tensor(x_g) if not torch.is_tensor(x_g): return x_l return torch.cat(x, dim=1) class FFCResNetGenerator(nn.Module): def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, n_blocks=9, res_dilation=2, norm_layer=nn.BatchNorm2d, padding_type='reflect', activation_layer=nn.ReLU, up_norm_layer=nn.BatchNorm2d, up_activation=nn.ReLU(True), # init_conv_kwargs={}, downsample_conv_kwargs={}, resnet_conv_kwargs={}, init_conv_kwargs={"ratio_gin": 0, "ratio_gout": 0, "enable_lfu": False}, downsample_conv_kwargs={"ratio_gin": 0, "ratio_gout": 0, "enable_lfu": False}, resnet_conv_kwargs={"ratio_gin": 0.75, "ratio_gout": 0.75, "enable_lfu": False}, spatial_transform_layers=None, spatial_transform_kwargs={}, add_out_act=True, max_features=1024, out_ffc=False, out_ffc_kwargs={}, decode=True): assert (n_blocks >= 0) super().__init__() model = [nn.ReflectionPad2d(3), FFC_BN_ACT(input_nc, ngf, kernel_size=7, padding=0, norm_layer=norm_layer, activation_layer=activation_layer, **init_conv_kwargs)] kw = 4 ### downsample for i in range(n_downsampling): mult = 2 ** i if i == n_downsampling - 1: cur_conv_kwargs = dict(downsample_conv_kwargs) cur_conv_kwargs['ratio_gout'] = resnet_conv_kwargs.get('ratio_gin', 0) else: cur_conv_kwargs = downsample_conv_kwargs model = model + [FFC_BN_ACT(min(max_features, ngf * mult), min(max_features, ngf * mult * 2), kernel_size=kw, stride=2, padding=1, norm_layer=norm_layer, activation_layer=activation_layer, **cur_conv_kwargs)] mult = 2 ** n_downsampling feats_num_bottleneck = min(max_features, ngf * mult) ### resnet blocks for i in range(n_blocks): cur_resblock = FFCResnetBlock(feats_num_bottleneck, padding_type=padding_type, activation_layer=activation_layer, norm_layer=norm_layer, dilation=res_dilation, **resnet_conv_kwargs) if spatial_transform_layers is not None and i in spatial_transform_layers: cur_resblock = LearnableSpatialTransformWrapper(cur_resblock, **spatial_transform_kwargs) model = model + [cur_resblock] model = model + [ConcatTupleLayer()] self.model = nn.Sequential(*model) self.encoder = self.model self.decode = decode model = [] ### upsample for i in range(n_downsampling): mult = 2 ** (n_downsampling - i) model = model + [ # nn.ConvTranspose2d(min(max_features, ngf * mult), # min(max_features, int(ngf * mult / 2)), # kernel_size=3, stride=2, padding=1, output_padding=1), # up_norm_layer(min(max_features, int(ngf * mult / 2))), nn.ConvTranspose2d(min(max_features, ngf * mult), min(max_features, int(ngf * mult / 2)), kernel_size=kw, stride=2, padding=1), up_activation] if out_ffc: model = model + [FFCResnetBlock(ngf, padding_type=padding_type, activation_layer=activation_layer, norm_layer=norm_layer, inline=True, **out_ffc_kwargs)] model = model + [nn.ReflectionPad2d(3), nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] if add_out_act: model.append(get_activation('tanh' if add_out_act is True else add_out_act)) self.model = nn.Sequential(*model) self.decoder = self.model def forward(self, input): output = self.encoder(input) if self.decode: output = self.decoder(output) return output import abc from typing import Tuple, List class BaseDiscriminator(nn.Module): @abc.abstractmethod def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: """ Predict scores and get intermediate activations. Useful for feature matching loss :return tuple (scores, list of intermediate activations) """ raise NotImplemented() class FFCNLayerDiscriminator(BaseDiscriminator): def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, max_features=512, use_sigmoid=True, # init_conv_kwargs={}, conv_kwargs={} init_conv_kwargs = {"ratio_gin": 0, "ratio_gout": 0, "enable_lfu": False}, conv_kwargs={"ratio_gin": 0, "ratio_gout": 0, "enable_lfu": False}): super().__init__() self.n_layers = n_layers self.use_sigmoid = use_sigmoid def _act_ctor(): return nn.LeakyReLU(negative_slope=0.2) kw = 4 padw = int(np.ceil((kw-1.0)/2)) sequence = [[FFC_BN_ACT(input_nc, ndf, kernel_size=kw, stride=2, padding=padw, norm_layer=norm_layer, activation_layer=_act_ctor, **init_conv_kwargs)]] nf = ndf for n in range(1, n_layers): nf_prev = nf nf = min(nf * 2, max_features) cur_model = [ FFC_BN_ACT(nf_prev, nf, kernel_size=kw, stride=2, padding=padw, norm_layer=norm_layer, activation_layer=_act_ctor, **conv_kwargs) ] sequence.append(cur_model) nf_prev = nf nf = min(nf * 2, 512) cur_model = [ FFC_BN_ACT(nf_prev, nf, kernel_size=kw, stride=1, padding=padw, norm_layer=norm_layer, activation_layer=lambda *args, **kwargs: nn.LeakyReLU(*args, negative_slope=0.2, **kwargs), **conv_kwargs), ConcatTupleLayer() ] sequence.append(cur_model) sequence = sequence + [[nn.Conv2d(nf, 1, kernel_size=kw, stride=1, padding=padw)]] for n in range(len(sequence)): setattr(self, 'model'+str(n), nn.Sequential(*sequence[n])) def get_all_activations(self, x): res = [x] for n in range(self.n_layers + 2): model = getattr(self, 'model' + str(n)) res.append(model(res[-1])) return res[1:] def forward(self, x): act = self.get_all_activations(x) feats = [] for out in act[:-1]: if isinstance(out, tuple): if torch.is_tensor(out[1]): out = torch.cat(out, dim=1) else: out = out[0] feats.append(out) outputs = act[-1] if self.use_sigmoid: outputs = torch.sigmoid(act[-1]) # return outputs return outputs, feats from kornia.geometry.transform import rotate class LearnableSpatialTransformWrapper(nn.Module): def __init__(self, impl, pad_coef=0.5, angle_init_range=80, train_angle=True): super().__init__() self.impl = impl self.angle = torch.rand(1) * angle_init_range if train_angle: self.angle = nn.Parameter(self.angle, requires_grad=True) self.pad_coef = pad_coef def forward(self, x): if torch.is_tensor(x): return self.inverse_transform(self.impl(self.transform(x)), x) elif isinstance(x, tuple): x_trans = tuple(self.transform(elem) for elem in x) y_trans = self.impl(x_trans) return tuple(self.inverse_transform(elem, orig_x) for elem, orig_x in zip(y_trans, x)) else: raise ValueError(f'Unexpected input type {type(x)}') def transform(self, x): height, width = x.shape[2:] pad_h, pad_w = int(height * self.pad_coef), int(width * self.pad_coef) x_padded = F.pad(x, [pad_w, pad_w, pad_h, pad_h], mode='reflect') x_padded_rotated = rotate(x_padded, angle=self.angle.to(x_padded)) return x_padded_rotated def inverse_transform(self, y_padded_rotated, orig_x): height, width = orig_x.shape[2:] pad_h, pad_w = int(height * self.pad_coef), int(width * self.pad_coef) y_padded = rotate(y_padded_rotated, angle=-self.angle.to(y_padded_rotated)) y_height, y_width = y_padded.shape[2:] y = y_padded[:, :, pad_h : y_height - pad_h, pad_w : y_width - pad_w] return y class SELayer(nn.Module): def __init__(self, channel, reduction=16): super(SELayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, channel // reduction, bias=False), nn.ReLU(), nn.Linear(channel // reduction, channel, bias=False), nn.Sigmoid() ) def forward(self, x): b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) res = x * y.expand_as(x) return res def get_activation(kind='tanh'): if kind == 'tanh': return nn.Tanh() if kind == 'sigmoid': return nn.Sigmoid() if kind is False: return nn.Identity() raise ValueError(f'Unknown activation kind {kind}') import numbers def get_shape(t): if torch.is_tensor(t): return tuple(t.shape) elif isinstance(t, dict): return {n: get_shape(q) for n, q in t.items()} elif isinstance(t, (list, tuple)): return [get_shape(q) for q in t] elif isinstance(t, numbers.Number): return type(t) else: raise ValueError('unexpected type {}'.format(type(t)))
22,247
39.014388
125
py
CoordFill
CoordFill-master/models/models.py
import copy models = {} def register(name): def decorator(cls): models[name] = cls return cls return decorator def make(model_spec, args=None, load_sd=False): if args is not None: model_args = copy.deepcopy(model_spec['args']) model_args.update(args) else: model_args = model_spec['args'] model = models[model_spec['name']](**model_args) if load_sd: model.load_state_dict(model_spec['sd']) return model
485
19.25
54
py
CoordFill
CoordFill-master/models/__init__.py
from .models import register, make from . import gan, modules, coordfill, ffc_baseline from . import misc
106
25.75
51
py
CoordFill
CoordFill-master/models/sync_batchnorm.py
# -*- coding: utf-8 -*- # File : batchnorm.py # Author : Jiayuan Mao # Email : [email protected] # Date : 27/01/2018 # # This file is part of Synchronized-BatchNorm-PyTorch. # https://github.com/vacancy/Synchronized-BatchNorm-PyTorch # Distributed under MIT License. import collections import contextlib import torch import torch.nn.functional as F from torch.nn.modules.batchnorm import _BatchNorm try: from torch.nn.parallel._functions import ReduceAddCoalesced, Broadcast except ImportError: ReduceAddCoalesced = Broadcast = None try: from jactorch.parallel.comm import SyncMaster from jactorch.parallel.data_parallel import JacDataParallel as DataParallelWithCallback except ImportError: from .comm import SyncMaster from .replicate import DataParallelWithCallback __all__ = [ 'set_sbn_eps_mode', 'SynchronizedBatchNorm1d', 'SynchronizedBatchNorm2d', 'SynchronizedBatchNorm3d', 'patch_sync_batchnorm', 'convert_model' ] SBN_EPS_MODE = 'clamp' def set_sbn_eps_mode(mode): global SBN_EPS_MODE assert mode in ('clamp', 'plus') SBN_EPS_MODE = mode def _sum_ft(tensor): """sum over the first and last dimention""" return tensor.sum(dim=0).sum(dim=-1) def _unsqueeze_ft(tensor): """add new dimensions at the front and the tail""" return tensor.unsqueeze(0).unsqueeze(-1) _ChildMessage = collections.namedtuple('_ChildMessage', ['sum', 'ssum', 'sum_size']) _MasterMessage = collections.namedtuple('_MasterMessage', ['sum', 'inv_std']) class _SynchronizedBatchNorm(_BatchNorm): def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True): assert ReduceAddCoalesced is not None, 'Can not use Synchronized Batch Normalization without CUDA support.' super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine, track_running_stats=track_running_stats) if not self.track_running_stats: import warnings warnings.warn('track_running_stats=False is not supported by the SynchronizedBatchNorm.') self._sync_master = SyncMaster(self._data_parallel_master) self._is_parallel = False self._parallel_id = None self._slave_pipe = None def forward(self, input): # If it is not parallel computation or is in evaluation mode, use PyTorch's implementation. if not (self._is_parallel and self.training): return F.batch_norm( input, self.running_mean, self.running_var, self.weight, self.bias, self.training, self.momentum, self.eps) # Resize the input to (B, C, -1). input_shape = input.size() assert input.size(1) == self.num_features, 'Channel size mismatch: got {}, expect {}.'.format(input.size(1), self.num_features) input = input.view(input.size(0), self.num_features, -1) # Compute the sum and square-sum. sum_size = input.size(0) * input.size(2) input_sum = _sum_ft(input) input_ssum = _sum_ft(input ** 2) # Reduce-and-broadcast the statistics. if self._parallel_id == 0: mean, inv_std = self._sync_master.run_master(_ChildMessage(input_sum, input_ssum, sum_size)) else: mean, inv_std = self._slave_pipe.run_slave(_ChildMessage(input_sum, input_ssum, sum_size)) # Compute the output. if self.affine: # MJY:: Fuse the multiplication for speed. output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std * self.weight) + _unsqueeze_ft(self.bias) else: output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std) # Reshape it. return output.view(input_shape) def __data_parallel_replicate__(self, ctx, copy_id): self._is_parallel = True self._parallel_id = copy_id # parallel_id == 0 means master device. if self._parallel_id == 0: ctx.sync_master = self._sync_master else: self._slave_pipe = ctx.sync_master.register_slave(copy_id) def _data_parallel_master(self, intermediates): """Reduce the sum and square-sum, compute the statistics, and broadcast it.""" # Always using same "device order" makes the ReduceAdd operation faster. # Thanks to:: Tete Xiao (http://tetexiao.com/) intermediates = sorted(intermediates, key=lambda i: i[1].sum.get_device()) to_reduce = [i[1][:2] for i in intermediates] to_reduce = [j for i in to_reduce for j in i] # flatten target_gpus = [i[1].sum.get_device() for i in intermediates] sum_size = sum([i[1].sum_size for i in intermediates]) sum_, ssum = ReduceAddCoalesced.apply(target_gpus[0], 2, *to_reduce) mean, inv_std = self._compute_mean_std(sum_, ssum, sum_size) broadcasted = Broadcast.apply(target_gpus, mean, inv_std) outputs = [] for i, rec in enumerate(intermediates): outputs.append((rec[0], _MasterMessage(*broadcasted[i*2:i*2+2]))) return outputs def _compute_mean_std(self, sum_, ssum, size): """Compute the mean and standard-deviation with sum and square-sum. This method also maintains the moving average on the master device.""" assert size > 1, 'BatchNorm computes unbiased standard-deviation, which requires size > 1.' mean = sum_ / size sumvar = ssum - sum_ * mean unbias_var = sumvar / (size - 1) bias_var = sumvar / size if hasattr(torch, 'no_grad'): with torch.no_grad(): self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean.data self.running_var = (1 - self.momentum) * self.running_var + self.momentum * unbias_var.data else: self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean.data self.running_var = (1 - self.momentum) * self.running_var + self.momentum * unbias_var.data if SBN_EPS_MODE == 'clamp': return mean, bias_var.clamp(self.eps) ** -0.5 elif SBN_EPS_MODE == 'plus': return mean, (bias_var + self.eps) ** -0.5 else: raise ValueError('Unknown EPS mode: {}.'.format(SBN_EPS_MODE)) class SynchronizedBatchNorm1d(_SynchronizedBatchNorm): r"""Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a mini-batch. .. math:: y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta This module differs from the built-in PyTorch BatchNorm1d as the mean and standard-deviation are reduced across all devices during training. For example, when one uses `nn.DataParallel` to wrap the network during training, PyTorch's implementation normalize the tensor on each device using the statistics only on that device, which accelerated the computation and is also easy to implement, but the statistics might be inaccurate. Instead, in this synchronized version, the statistics will be computed over all training samples distributed on multiple devices. Note that, for one-GPU or CPU-only case, this module behaves exactly same as the built-in PyTorch implementation. The mean and standard-deviation are calculated per-dimension over the mini-batches and gamma and beta are learnable parameter vectors of size C (where C is the input size). During training, this layer keeps a running estimate of its computed mean and variance. The running sum is kept with a default momentum of 0.1. During evaluation, this running mean/variance is used for normalization. Because the BatchNorm is done over the `C` dimension, computing statistics on `(N, L)` slices, it's common terminology to call this Temporal BatchNorm Args: num_features: num_features from an expected input of size `batch_size x num_features [x width]` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Default: 0.1 affine: a boolean value that when set to ``True``, gives the layer learnable affine parameters. Default: ``True`` Shape:: - Input: :math:`(N, C)` or :math:`(N, C, L)` - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input) Examples: # >>> # With Learnable Parameters # >>> m = SynchronizedBatchNorm1d(100) # >>> # Without Learnable Parameters # >>> m = SynchronizedBatchNorm1d(100, affine=False) # >>> input = torch.autograd.Variable(torch.randn(20, 100)) # >>> output = m(input) """ def _check_input_dim(self, input): if input.dim() != 2 and input.dim() != 3: raise ValueError('expected 2D or 3D input (got {}D input)' .format(input.dim())) class SynchronizedBatchNorm2d(_SynchronizedBatchNorm): r"""Applies Batch Normalization over a 4d input that is seen as a mini-batch of 3d inputs .. math:: y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta This module differs from the built-in PyTorch BatchNorm2d as the mean and standard-deviation are reduced across all devices during training. For example, when one uses `nn.DataParallel` to wrap the network during training, PyTorch's implementation normalize the tensor on each device using the statistics only on that device, which accelerated the computation and is also easy to implement, but the statistics might be inaccurate. Instead, in this synchronized version, the statistics will be computed over all training samples distributed on multiple devices. Note that, for one-GPU or CPU-only case, this module behaves exactly same as the built-in PyTorch implementation. The mean and standard-deviation are calculated per-dimension over the mini-batches and gamma and beta are learnable parameter vectors of size C (where C is the input size). During training, this layer keeps a running estimate of its computed mean and variance. The running sum is kept with a default momentum of 0.1. During evaluation, this running mean/variance is used for normalization. Because the BatchNorm is done over the `C` dimension, computing statistics on `(N, H, W)` slices, it's common terminology to call this Spatial BatchNorm Args: num_features: num_features from an expected input of size batch_size x num_features x height x width eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Default: 0.1 affine: a boolean value that when set to ``True``, gives the layer learnable affine parameters. Default: ``True`` Shape:: - Input: :math:`(N, C, H, W)` - Output: :math:`(N, C, H, W)` (same shape as input) Examples: # >>> # With Learnable Parameters # >>> m = SynchronizedBatchNorm2d(100) # >>> # Without Learnable Parameters # >>> m = SynchronizedBatchNorm2d(100, affine=False) # >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45)) # >>> output = m(input) """ def _check_input_dim(self, input): if input.dim() != 4: raise ValueError('expected 4D input (got {}D input)' .format(input.dim())) class SynchronizedBatchNorm3d(_SynchronizedBatchNorm): r"""Applies Batch Normalization over a 5d input that is seen as a mini-batch of 4d inputs .. math:: y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta This module differs from the built-in PyTorch BatchNorm3d as the mean and standard-deviation are reduced across all devices during training. For example, when one uses `nn.DataParallel` to wrap the network during training, PyTorch's implementation normalize the tensor on each device using the statistics only on that device, which accelerated the computation and is also easy to implement, but the statistics might be inaccurate. Instead, in this synchronized version, the statistics will be computed over all training samples distributed on multiple devices. Note that, for one-GPU or CPU-only case, this module behaves exactly same as the built-in PyTorch implementation. The mean and standard-deviation are calculated per-dimension over the mini-batches and gamma and beta are learnable parameter vectors of size C (where C is the input size). During training, this layer keeps a running estimate of its computed mean and variance. The running sum is kept with a default momentum of 0.1. During evaluation, this running mean/variance is used for normalization. Because the BatchNorm is done over the `C` dimension, computing statistics on `(N, D, H, W)` slices, it's common terminology to call this Volumetric BatchNorm or Spatio-temporal BatchNorm Args: num_features: num_features from an expected input of size batch_size x num_features x depth x height x width eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Default: 0.1 affine: a boolean value that when set to ``True``, gives the layer learnable affine parameters. Default: ``True`` Shape:: - Input: :math:`(N, C, D, H, W)` - Output: :math:`(N, C, D, H, W)` (same shape as input) Examples: # >>> # With Learnable Parameters # >>> m = SynchronizedBatchNorm3d(100) # >>> # Without Learnable Parameters # >>> m = SynchronizedBatchNorm3d(100, affine=False) # >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45, 10)) # >>> output = m(input) """ def _check_input_dim(self, input): if input.dim() != 5: raise ValueError('expected 5D input (got {}D input)' .format(input.dim())) @contextlib.contextmanager def patch_sync_batchnorm(): import torch.nn as nn backup = nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d nn.BatchNorm1d = SynchronizedBatchNorm1d nn.BatchNorm2d = SynchronizedBatchNorm2d nn.BatchNorm3d = SynchronizedBatchNorm3d yield nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d = backup def convert_model(module): """Traverse the input module and its child recursively and replace all instance of torch.nn.modules.batchnorm.BatchNorm*N*d to SynchronizedBatchNorm*N*d Args: module: the input module needs to be convert to SyncBN model Examples: # >>> import torch.nn as nn # >>> import torchvision # >>> # m is a standard pytorch model # >>> m = torchvision.models.resnet18(True) # >>> m = nn.DataParallel(m) # >>> # after convert, m is using SyncBN # >>> m = convert_model(m) """ if isinstance(module, torch.nn.DataParallel): mod = module.module mod = convert_model(mod) mod = DataParallelWithCallback(mod, device_ids=module.device_ids) return mod mod = module for pth_module, sync_module in zip([torch.nn.modules.batchnorm.BatchNorm1d, torch.nn.modules.batchnorm.BatchNorm2d, torch.nn.modules.batchnorm.BatchNorm3d], [SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d]): if isinstance(module, pth_module): mod = sync_module(module.num_features, module.eps, module.momentum, module.affine) mod.running_mean = module.running_mean mod.running_var = module.running_var if module.affine: mod.weight.data = module.weight.data.clone().detach() mod.bias.data = module.bias.data.clone().detach() for name, child in module.named_children(): mod.add_module(name, convert_model(child)) return mod
16,476
43.05615
135
py
CoordFill
CoordFill-master/models/adv_loss.py
import os import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch import autograd import torchvision.models as models device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class AdversarialLoss(nn.Module): """ Adversarial loss https://arxiv.org/abs/1711.10337 """ def __init__(self, type='nsgan', target_real_label=1.0, target_fake_label=0.0): """ type = nsgan | lsgan | hinge """ super(AdversarialLoss, self).__init__() self.type = type self.register_buffer('real_label', torch.tensor(target_real_label)) self.register_buffer('fake_label', torch.tensor(target_fake_label)) if type == 'nsgan': self.criterion = nn.BCELoss() if type == 'relativegan': self.criterion = nn.BCEWithLogitsLoss() elif type == 'lsgan': self.criterion = nn.MSELoss() elif type == 'hinge': self.criterion = nn.ReLU() def __call__(self, outputs, is_real, is_disc=None): if self.type == 'hinge': if is_disc: if is_real: outputs = -outputs return self.criterion(1 + outputs).mean() else: return (-outputs).mean() else: labels = (self.real_label if is_real else self.fake_label).expand_as(outputs) loss = self.criterion(outputs, labels) return loss
1,484
28.7
89
py
CoordFill
CoordFill-master/models/coordfill.py
import torch.nn as nn import torch.nn.functional as F import torch from scipy import ndimage import numpy as np from .ffc import FFCResNetGenerator from .modules import CoordFillGenerator from .ffc import FFCResNetGenerator, FFCResnetBlock, ConcatTupleLayer, FFC_BN_ACT class AttFFC(nn.Module): """Convolutional LR stream to estimate the pixel-wise MLPs parameters""" def __init__(self, ngf): super(AttFFC, self).__init__() self.add = FFC_BN_ACT(ngf, ngf, kernel_size=3, stride=1, padding=1, norm_layer=nn.BatchNorm2d, activation_layer=nn.ReLU, **{"ratio_gin": 0.75, "ratio_gout": 0.75, "enable_lfu": False}) self.minus = FFC_BN_ACT(ngf+1, ngf, kernel_size=3, stride=1, padding=1, norm_layer=nn.BatchNorm2d, activation_layer=nn.ReLU, **{"ratio_gin": 0, "ratio_gout": 0.75, "enable_lfu": False}) self.mask = FFC_BN_ACT(ngf, 1, kernel_size=3, stride=1, padding=1, norm_layer=nn.BatchNorm2d, activation_layer=nn.Sigmoid, **{"ratio_gin": 0.75, "ratio_gout": 0, "enable_lfu": False}) def forward(self, x): x_l, x_g = x if type(x) is tuple else (x, 0) mask, _ = self.mask((x_l, x_g)) minus_l, minus_g = self.minus(torch.cat([x_l, x_g, mask], 1)) add_l, add_g = self.add((x_l - minus_l, x_g - minus_g)) x_l, x_g = x_l - minus_l + add_l, x_g - minus_g + add_g return x_l, x_g class AttFFCResNetGenerator(nn.Module): """Convolutional LR stream to estimate the pixel-wise MLPs parameters""" def __init__(self, ngf): super(AttFFCResNetGenerator, self).__init__() self.dowm = nn.Sequential( nn.ReflectionPad2d(3), FFC_BN_ACT(4, 64, kernel_size=7, padding=0, norm_layer=nn.BatchNorm2d, activation_layer=nn.ReLU, **{"ratio_gin": 0, "ratio_gout": 0, "enable_lfu": False}), FFC_BN_ACT(64, 128, kernel_size=4, stride=2, padding=1, norm_layer=nn.BatchNorm2d, activation_layer=nn.ReLU, **{"ratio_gin": 0, "ratio_gout": 0, "enable_lfu": False}), FFC_BN_ACT(128, 256, kernel_size=4, stride=2, padding=1, norm_layer=nn.BatchNorm2d, activation_layer=nn.ReLU, **{"ratio_gin": 0, "ratio_gout": 0, "enable_lfu": False}), FFC_BN_ACT(256, 512, kernel_size=4, stride=2, padding=1, norm_layer=nn.BatchNorm2d, activation_layer=nn.ReLU, **{"ratio_gin": 0, "ratio_gout": 0.75, "enable_lfu": False}), ) self.block1 = AttFFC(ngf) self.block2 = AttFFC(ngf) self.block3 = AttFFC(ngf) self.block4 = AttFFC(ngf) self.block5 = AttFFC(ngf) self.block6 = AttFFC(ngf) self.c = ConcatTupleLayer() def forward(self, x): x = self.dowm(x) x = self.block1(x) x = self.block2(x) x = self.block3(x) x = self.block4(x) x = self.block5(x) x = self.block6(x) x = self.c(x) return x from .ffc_baseline import MLPModel class CoordFill(nn.Module): def __init__(self, args, name, mask_prediction=False, attffc=False, scale_injection=False): super(CoordFill, self).__init__() self.args = args self.n_channels = args.n_channels self.n_classes = args.n_classes self.out_dim = args.n_classes self.in_size = 256 self.name = name self.mask_prediction = mask_prediction self.attffc = attffc self.scale_injection = scale_injection self.opt = self.get_opt() self.asap = CoordFillGenerator(self.opt) if self.name == 'ffc': self.refine = FFCResNetGenerator(4, 3, ngf=64, n_downsampling=3, n_blocks=6, res_dilation=1, decode=True) elif self.name == 'mlp': self.refine = MLPModel() elif self.name == 'coordfill': if self.attffc: self.refine = AttFFCResNetGenerator(512) else: self.refine = FFCResNetGenerator(4, 3, ngf=64, n_downsampling=3, n_blocks=6, res_dilation=1, decode=False) def get_opt(self): from yacs.config import CfgNode as CN opt = CN() opt.label_nc = 0 # opt.label_nc = 1 opt.lr_instance = False opt.crop_size = 512 opt.ds_scale = 32 opt.aspect_ratio = 1.0 opt.contain_dontcare_label = False opt.no_instance_edge = True opt.no_instance_dist = True opt.gpu_ids = 0 opt.output_nc = 3 opt.hr_width = 64 opt.hr_depth = 5 opt.scale_injection = self.scale_injection opt.no_one_hot = False opt.lr_instance = False opt.norm_G = 'batch' opt.lr_width = 256 opt.lr_max_width = 256 opt.lr_depth = 5 opt.learned_ds_factor = 1 opt.reflection_pad = False return opt def forward(self, inp): img, mask = inp hr_hole = img * mask lr_img = F.interpolate(img, size=(self.in_size, self.in_size), mode='bilinear') lr_mask = F.interpolate(mask, size=(self.in_size, self.in_size), mode='nearest') lr_hole = lr_img * lr_mask lr_features = self.asap.lowres_stream(self.refine, torch.cat([lr_hole, lr_mask], dim=1), hr_hole) output = self.asap.highres_stream(hr_hole, lr_features) if self.mask_prediction: output = output * (1 - mask) + hr_hole return output def mask_predict(self, inp): img, mask = inp hr_hole = img * mask lr_img = F.interpolate(img, size=(self.in_size, self.in_size), mode='bilinear') lr_mask = F.interpolate(mask, size=(self.in_size, self.in_size), mode='nearest') lr_hole = lr_img * lr_mask lr_features, temp_mask = self.asap.lowres_stream.mask_predict(self.refine, torch.cat([lr_hole, lr_mask], dim=1), hr_hole, mask) output = self.asap.highres_stream.mask_predict(hr_hole, lr_features, mask, temp_mask) output = output * (1 - mask) + hr_hole return output def load_state_dict(self, state_dict, strict=True): own_state = self.state_dict() for name, param in state_dict.items(): if name in own_state: if isinstance(param, nn.Parameter): param = param.data try: own_state[name].copy_(param) except Exception: if name.find('tail') == -1: raise RuntimeError('While copying the parameter named {}, ' 'whose dimensions in the model are {} and ' 'whose dimensions in the checkpoint are {}.' .format(name, own_state[name].size(), param.size())) elif strict: if name.find('tail') == -1: raise KeyError('unexpected key "{}" in state_dict' .format(name)) device=torch.device('cuda') # device=torch.device('cpu') from models import register from argparse import Namespace @register('asap') def make_unet(n_channels=3, n_classes=3, no_upsampling=False): args = Namespace() args.n_channels = n_channels args.n_classes = n_classes args.no_upsampling = no_upsampling return LPTN(args)
7,669
36.598039
135
py
CoordFill
CoordFill-master/models/bn_helper.py
import torch import functools if torch.__version__.startswith('0'): from .sync_bn.inplace_abn.bn import InPlaceABNSync BatchNorm2d = functools.partial(InPlaceABNSync, activation='none') BatchNorm2d_class = InPlaceABNSync relu_inplace = False else: BatchNorm2d_class = BatchNorm2d = torch.nn.SyncBatchNorm relu_inplace = True import torch BatchNorm2d = torch.nn.BatchNorm2d BatchNorm2d_class = BatchNorm2d relu_inplace = False
451
27.25
70
py
CoordFill
CoordFill-master/models/ffc_baseline.py
import torch.nn as nn import torch.nn.functional as F import torch from scipy import ndimage import numpy as np class ResnetBlock_remove_IN(nn.Module): def __init__(self, dim, dilation=1, use_spectral_norm=True): super(ResnetBlock_remove_IN, self).__init__() self.conv_block = nn.Sequential( nn.ReflectionPad2d(dilation), spectral_norm(nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=3, padding=0, dilation=dilation, bias=not use_spectral_norm), use_spectral_norm), nn.ReLU(), nn.ReflectionPad2d(1), spectral_norm(nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=3, padding=0, dilation=1, bias=not use_spectral_norm), use_spectral_norm), ) def forward(self, x): out = x + self.conv_block(x) # Remove ReLU at the end of the residual block # http://torch.ch/blog/2016/02/04/resnets.html return out def spectral_norm(module, mode=True): if mode: return nn.utils.spectral_norm(module) return module class MLPModel(nn.Module): """Convolutional LR stream to estimate the pixel-wise MLPs parameters""" def __init__(self): super(MLPModel, self).__init__() self.refine = FFCResNetGenerator(4, 3, ngf=64, n_downsampling=3, n_blocks=6, res_dilation=1, decode=False) self.mapping = nn.Conv2d(64 * 8, 64, 1) self.mlp = nn.Sequential( nn.Conv2d(64, 64, 1), nn.ReLU(), nn.Conv2d(64, 64, 1), nn.ReLU(), nn.Conv2d(64, 64, 1), nn.ReLU(), nn.Conv2d(64, 64, 1), nn.ReLU(), nn.Conv2d(64, 3, 1), ) def forward(self, x): bs, _, h, w = x.size() x = self.refine(x) x = self.mapping(x) x = F.interpolate(x, size=(h, w), mode='nearest') x = self.mlp(x) x = torch.tanh(x) return x from .ffc import FFCResNetGenerator, FFCResnetBlock, ConcatTupleLayer, FFC_BN_ACT class FFC(nn.Module): def __init__(self, args, name, mask_prediction=False): super(FFC, self).__init__() self.args = args self.n_channels = args.n_channels self.n_classes = args.n_classes self.out_dim = args.n_classes self.name = name self.mask_prediction = mask_prediction if self.name == 'ffc': self.refine = FFCResNetGenerator(4, 3, ngf=64, n_downsampling=3, n_blocks=6, res_dilation=1, decode=True) elif self.name == 'mlp': self.refine = MLPModel() def forward(self, inp): img, mask = inp hole = img * mask output = self.refine(torch.cat([hole, mask], dim=1)) if self.mask_prediction: output = output * (1 - mask) + hole return output, output def load_state_dict(self, state_dict, strict=True): own_state = self.state_dict() for name, param in state_dict.items(): if name in own_state: if isinstance(param, nn.Parameter): param = param.data try: own_state[name].copy_(param) except Exception: if name.find('tail') == -1: raise RuntimeError('While copying the parameter named {}, ' 'whose dimensions in the model are {} and ' 'whose dimensions in the checkpoint are {}.' .format(name, own_state[name].size(), param.size())) elif strict: if name.find('tail') == -1: raise KeyError('unexpected key "{}" in state_dict' .format(name)) device=torch.device('cuda') # device=torch.device('cpu') from models import register from argparse import Namespace @register('ffc') def make_unet(n_channels=3, n_classes=3, no_upsampling=False): args = Namespace() args.n_channels = n_channels args.n_classes = n_classes args.no_upsampling = no_upsampling return FFC(args)
4,182
32.464
164
py
CoordFill
CoordFill-master/models/LPIPS/models/base_model.py
import os import torch import sys sys.path.insert(1, './LPIPS/') # import util.util as util from torch.autograd import Variable from pdb import set_trace as st from IPython import embed class BaseModel(): def __init__(self): pass; def name(self): return 'BaseModel' def initialize(self, use_gpu=True): self.use_gpu = use_gpu self.Tensor = torch.cuda.FloatTensor if self.use_gpu else torch.Tensor # self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) def forward(self): pass def get_image_paths(self): pass def optimize_parameters(self): pass def get_current_visuals(self): return self.input def get_current_errors(self): return {} def save(self, label): pass # helper saving function that can be used by subclasses def save_network(self, network, path, network_label, epoch_label): save_filename = '%s_net_%s.pth' % (epoch_label, network_label) save_path = os.path.join(path, save_filename) torch.save(network.state_dict(), save_path) # helper loading function that can be used by subclasses def load_network(self, network, network_label, epoch_label): # embed() save_filename = '%s_net_%s.pth' % (epoch_label, network_label) save_path = os.path.join(self.save_dir, save_filename) print('Loading network from %s'%save_path) network.load_state_dict(torch.load(save_path)) def update_learning_rate(): pass def get_image_paths(self): return self.image_paths def save_done(self, flag=False): np.save(os.path.join(self.save_dir, 'done_flag'),flag) np.savetxt(os.path.join(self.save_dir, 'done_flag'),[flag,],fmt='%i')
1,794
26.19697
78
py
CoordFill
CoordFill-master/models/LPIPS/models/pretrained_networks.py
from collections import namedtuple import torch from torchvision import models from IPython import embed class squeezenet(torch.nn.Module): def __init__(self, requires_grad=False, pretrained=True): super(squeezenet, self).__init__() pretrained_features = models.squeezenet1_1(pretrained=pretrained).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() self.slice5 = torch.nn.Sequential() self.slice6 = torch.nn.Sequential() self.slice7 = torch.nn.Sequential() self.N_slices = 7 for x in range(2): self.slice1.add_module(str(x), pretrained_features[x]) for x in range(2,5): self.slice2.add_module(str(x), pretrained_features[x]) for x in range(5, 8): self.slice3.add_module(str(x), pretrained_features[x]) for x in range(8, 10): self.slice4.add_module(str(x), pretrained_features[x]) for x in range(10, 11): self.slice5.add_module(str(x), pretrained_features[x]) for x in range(11, 12): self.slice6.add_module(str(x), pretrained_features[x]) for x in range(12, 13): self.slice7.add_module(str(x), pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False def forward(self, X): h = self.slice1(X) h_relu1 = h h = self.slice2(h) h_relu2 = h h = self.slice3(h) h_relu3 = h h = self.slice4(h) h_relu4 = h h = self.slice5(h) h_relu5 = h h = self.slice6(h) h_relu6 = h h = self.slice7(h) h_relu7 = h vgg_outputs = namedtuple("SqueezeOutputs", ['relu1','relu2','relu3','relu4','relu5','relu6','relu7']) out = vgg_outputs(h_relu1,h_relu2,h_relu3,h_relu4,h_relu5,h_relu6,h_relu7) return out class alexnet(torch.nn.Module): def __init__(self, requires_grad=False, pretrained=True): super(alexnet, self).__init__() alexnet_pretrained_features = models.alexnet(pretrained=pretrained).features # model = models.alexnet(pretrained=False) # model.load_state_dict(torch.load('/apdcephfs/private_weihuangliu/pretrained_weights/alexnet-owt-7be5be79.pth')) # alexnet_pretrained_features = model.features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() self.slice5 = torch.nn.Sequential() self.N_slices = 5 for x in range(2): self.slice1.add_module(str(x), alexnet_pretrained_features[x]) for x in range(2, 5): self.slice2.add_module(str(x), alexnet_pretrained_features[x]) for x in range(5, 8): self.slice3.add_module(str(x), alexnet_pretrained_features[x]) for x in range(8, 10): self.slice4.add_module(str(x), alexnet_pretrained_features[x]) for x in range(10, 12): self.slice5.add_module(str(x), alexnet_pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False def forward(self, X): h = self.slice1(X) h_relu1 = h h = self.slice2(h) h_relu2 = h h = self.slice3(h) h_relu3 = h h = self.slice4(h) h_relu4 = h h = self.slice5(h) h_relu5 = h alexnet_outputs = namedtuple("AlexnetOutputs", ['relu1', 'relu2', 'relu3', 'relu4', 'relu5']) out = alexnet_outputs(h_relu1, h_relu2, h_relu3, h_relu4, h_relu5) return out class vgg16(torch.nn.Module): def __init__(self, requires_grad=False, pretrained=True): super(vgg16, self).__init__() vgg_pretrained_features = models.vgg16(pretrained=pretrained).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() self.slice5 = torch.nn.Sequential() self.N_slices = 5 for x in range(4): self.slice1.add_module(str(x), vgg_pretrained_features[x]) for x in range(4, 9): self.slice2.add_module(str(x), vgg_pretrained_features[x]) for x in range(9, 16): self.slice3.add_module(str(x), vgg_pretrained_features[x]) for x in range(16, 23): self.slice4.add_module(str(x), vgg_pretrained_features[x]) for x in range(23, 30): self.slice5.add_module(str(x), vgg_pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False def forward(self, X): h = self.slice1(X) h_relu1_2 = h h = self.slice2(h) h_relu2_2 = h h = self.slice3(h) h_relu3_3 = h h = self.slice4(h) h_relu4_3 = h h = self.slice5(h) h_relu5_3 = h vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3']) out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3) return out class resnet(torch.nn.Module): def __init__(self, requires_grad=False, pretrained=True, num=18): super(resnet, self).__init__() if(num==18): self.net = models.resnet18(pretrained=pretrained) elif(num==34): self.net = models.resnet34(pretrained=pretrained) elif(num==50): self.net = models.resnet50(pretrained=pretrained) elif(num==101): self.net = models.resnet101(pretrained=pretrained) elif(num==152): self.net = models.resnet152(pretrained=pretrained) self.N_slices = 5 self.conv1 = self.net.conv1 self.bn1 = self.net.bn1 self.relu = self.net.relu self.maxpool = self.net.maxpool self.layer1 = self.net.layer1 self.layer2 = self.net.layer2 self.layer3 = self.net.layer3 self.layer4 = self.net.layer4 def forward(self, X): h = self.conv1(X) h = self.bn1(h) h = self.relu(h) h_relu1 = h h = self.maxpool(h) h = self.layer1(h) h_conv2 = h h = self.layer2(h) h_conv3 = h h = self.layer3(h) h_conv4 = h h = self.layer4(h) h_conv5 = h outputs = namedtuple("Outputs", ['relu1','conv2','conv3','conv4','conv5']) out = outputs(h_relu1, h_conv2, h_conv3, h_conv4, h_conv5) return out
6,788
35.5
121
py
CoordFill
CoordFill-master/models/LPIPS/models/networks_basic.py
from __future__ import absolute_import import sys sys.path.append('..') sys.path.append('.') import torch import torch.nn as nn import torch.nn.init as init from torch.autograd import Variable import numpy as np from pdb import set_trace as st from skimage import color from IPython import embed from . import pretrained_networks as pn # from PerceptualSimilarity.util import util from ..util import util # Off-the-shelf deep network class PNet(nn.Module): '''Pre-trained network with all channels equally weighted by default''' def __init__(self, pnet_type='vgg', pnet_rand=False, use_gpu=True): super(PNet, self).__init__() self.use_gpu = use_gpu self.pnet_type = pnet_type self.pnet_rand = pnet_rand self.shift = torch.autograd.Variable(torch.Tensor([-.030, -.088, -.188]).view(1,3,1,1)) self.scale = torch.autograd.Variable(torch.Tensor([.458, .448, .450]).view(1,3,1,1)) if(self.pnet_type in ['vgg','vgg16']): self.net = pn.vgg16(pretrained=not self.pnet_rand,requires_grad=False) elif(self.pnet_type=='alex'): self.net = pn.alexnet(pretrained=not self.pnet_rand,requires_grad=False) elif(self.pnet_type[:-2]=='resnet'): self.net = pn.resnet(pretrained=not self.pnet_rand,requires_grad=False, num=int(self.pnet_type[-2:])) elif(self.pnet_type=='squeeze'): self.net = pn.squeezenet(pretrained=not self.pnet_rand,requires_grad=False) self.L = self.net.N_slices if(use_gpu): self.net.cuda() self.shift = self.shift.cuda() self.scale = self.scale.cuda() def forward(self, in0, in1, retPerLayer=False): in0_sc = (in0 - self.shift.expand_as(in0))/self.scale.expand_as(in0) in1_sc = (in1 - self.shift.expand_as(in0))/self.scale.expand_as(in0) outs0 = self.net.forward(in0_sc) outs1 = self.net.forward(in1_sc) if(retPerLayer): all_scores = [] for (kk,out0) in enumerate(outs0): cur_score = (1.-util.cos_sim(outs0[kk],outs1[kk])) if(kk==0): val = 1.*cur_score else: # val = val + self.lambda_feat_layers[kk]*cur_score val = val + cur_score if(retPerLayer): all_scores+=[cur_score] if(retPerLayer): return (val, all_scores) else: return val # Learned perceptual metric class PNetLin(nn.Module): def __init__(self, pnet_type='vgg', pnet_rand=False, pnet_tune=False, use_dropout=True, use_gpu=True, spatial=False, version='0.1'): super(PNetLin, self).__init__() self.use_gpu = use_gpu self.pnet_type = pnet_type self.pnet_tune = pnet_tune self.pnet_rand = pnet_rand self.spatial = spatial self.version = version if(self.pnet_type in ['vgg','vgg16']): net_type = pn.vgg16 self.chns = [64,128,256,512,512] elif(self.pnet_type=='alex'): net_type = pn.alexnet self.chns = [64,192,384,256,256] elif(self.pnet_type=='squeeze'): net_type = pn.squeezenet self.chns = [64,128,256,384,384,512,512] if(self.pnet_tune): self.net = net_type(pretrained=not self.pnet_rand,requires_grad=True) else: self.net = [net_type(pretrained=not self.pnet_rand,requires_grad=True),] self.lin0 = NetLinLayer(self.chns[0],use_dropout=use_dropout) self.lin1 = NetLinLayer(self.chns[1],use_dropout=use_dropout) self.lin2 = NetLinLayer(self.chns[2],use_dropout=use_dropout) self.lin3 = NetLinLayer(self.chns[3],use_dropout=use_dropout) self.lin4 = NetLinLayer(self.chns[4],use_dropout=use_dropout) self.lins = [self.lin0,self.lin1,self.lin2,self.lin3,self.lin4] if(self.pnet_type=='squeeze'): # 7 layers for squeezenet self.lin5 = NetLinLayer(self.chns[5],use_dropout=use_dropout) self.lin6 = NetLinLayer(self.chns[6],use_dropout=use_dropout) self.lins+=[self.lin5,self.lin6] self.shift = torch.autograd.Variable(torch.Tensor([-.030, -.088, -.188]).view(1,3,1,1)) self.scale = torch.autograd.Variable(torch.Tensor([.458, .448, .450]).view(1,3,1,1)) if(use_gpu): if(self.pnet_tune): self.net.cuda() else: self.net[0].cuda() self.shift = self.shift.cuda() self.scale = self.scale.cuda() self.lin0.cuda() self.lin1.cuda() self.lin2.cuda() self.lin3.cuda() self.lin4.cuda() if(self.pnet_type=='squeeze'): self.lin5.cuda() self.lin6.cuda() def forward(self, in0, in1): in0_sc = (in0 - self.shift.expand_as(in0))/self.scale.expand_as(in0) in1_sc = (in1 - self.shift.expand_as(in0))/self.scale.expand_as(in0) if(self.version=='0.0'): # v0.0 - original release had a bug, where input was not scaled in0_input = in0 in1_input = in1 else: # v0.1 in0_input = in0_sc in1_input = in1_sc if(self.pnet_tune): outs0 = self.net.forward(in0_input) outs1 = self.net.forward(in1_input) else: outs0 = self.net[0].forward(in0_input) outs1 = self.net[0].forward(in1_input) feats0 = {} feats1 = {} diffs = [0]*len(outs0) for (kk,out0) in enumerate(outs0): feats0[kk] = util.normalize_tensor(outs0[kk]) feats1[kk] = util.normalize_tensor(outs1[kk]) diffs[kk] = (feats0[kk]-feats1[kk])**2 # diffs[kk] = (outs0[kk]-outs1[kk])**2 if self.spatial: lin_models = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4] if(self.pnet_type=='squeeze'): lin_models.extend([self.lin5, self.lin6]) res = [lin_models[kk].model(diffs[kk]) for kk in range(len(diffs))] return res val1 = torch.mean(torch.mean(self.lin0.model(diffs[0]),dim=3),dim=2) val2 = torch.mean(torch.mean(self.lin1.model(diffs[1]),dim=3),dim=2) val3 = torch.mean(torch.mean(self.lin2.model(diffs[2]),dim=3),dim=2) val4 = torch.mean(torch.mean(self.lin3.model(diffs[3]),dim=3),dim=2) val5 = torch.mean(torch.mean(self.lin4.model(diffs[4]),dim=3),dim=2) val = val1 + val2 + val3 + val4 + val5 val_out = val.view(val.size()[0],val.size()[1],1,1) val_out2 = [val1, val2, val3, val4, val5] if(self.pnet_type=='squeeze'): val6 = val + torch.mean(torch.mean(self.lin5.model(diffs[5]),dim=3),dim=2) val7 = val6 + torch.mean(torch.mean(self.lin6.model(diffs[6]),dim=3),dim=2) val7 = val7.view(val7.size()[0],val7.size()[1],1,1) return val7 return val_out, val_out2 # return [val1, val2, val3, val4, val5] class Dist2LogitLayer(nn.Module): ''' takes 2 distances, puts through fc layers, spits out value between [0,1] (if use_sigmoid is True) ''' def __init__(self, chn_mid=32,use_sigmoid=True): super(Dist2LogitLayer, self).__init__() layers = [nn.Conv2d(5, chn_mid, 1, stride=1, padding=0, bias=True),] layers += [nn.LeakyReLU(0.2,True),] layers += [nn.Conv2d(chn_mid, chn_mid, 1, stride=1, padding=0, bias=True),] layers += [nn.LeakyReLU(0.2,True),] layers += [nn.Conv2d(chn_mid, 1, 1, stride=1, padding=0, bias=True),] if(use_sigmoid): layers += [nn.Sigmoid(),] self.model = nn.Sequential(*layers) def forward(self,d0,d1,eps=0.1): return self.model.forward(torch.cat((d0,d1,d0-d1,d0/(d1+eps),d1/(d0+eps)),dim=1)) class BCERankingLoss(nn.Module): def __init__(self, use_gpu=True, chn_mid=32): super(BCERankingLoss, self).__init__() self.use_gpu = use_gpu self.net = Dist2LogitLayer(chn_mid=chn_mid) self.parameters = list(self.net.parameters()) self.loss = torch.nn.BCELoss() self.model = nn.Sequential(*[self.net]) if(self.use_gpu): self.net.cuda() def forward(self, d0, d1, judge): per = (judge+1.)/2. if(self.use_gpu): per = per.cuda() self.logit = self.net.forward(d0,d1) return self.loss(self.logit, per) class NetLinLayer(nn.Module): ''' A single linear layer which does a 1x1 conv ''' def __init__(self, chn_in, chn_out=1, use_dropout=False): super(NetLinLayer, self).__init__() layers = [nn.Dropout(),] if(use_dropout) else [] layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False),] self.model = nn.Sequential(*layers) # L2, DSSIM metrics class FakeNet(nn.Module): def __init__(self, use_gpu=True, colorspace='Lab'): super(FakeNet, self).__init__() self.use_gpu = use_gpu self.colorspace=colorspace class L2(FakeNet): def forward(self, in0, in1): assert(in0.size()[0]==1) # currently only supports batchSize 1 if(self.colorspace=='RGB'): (N,C,X,Y) = in0.size() value = torch.mean(torch.mean(torch.mean((in0-in1)**2,dim=1).view(N,1,X,Y),dim=2).view(N,1,1,Y),dim=3).view(N) return value elif(self.colorspace=='Lab'): value = util.l2(util.tensor2np(util.tensor2tensorlab(in0.data,to_norm=False)), util.tensor2np(util.tensor2tensorlab(in1.data,to_norm=False)), range=100.).astype('float') ret_var = Variable( torch.Tensor((value,) ) ) if(self.use_gpu): ret_var = ret_var.cuda() return ret_var class DSSIM(FakeNet): def forward(self, in0, in1): assert(in0.size()[0]==1) # currently only supports batchSize 1 if(self.colorspace=='RGB'): value = util.dssim(1.*util.tensor2im(in0.data), 1.*util.tensor2im(in1.data), range=255.).astype('float') elif(self.colorspace=='Lab'): value = util.dssim(util.tensor2np(util.tensor2tensorlab(in0.data,to_norm=False)), util.tensor2np(util.tensor2tensorlab(in1.data,to_norm=False)), range=100.).astype('float') ret_var = Variable( torch.Tensor((value,) ) ) if(self.use_gpu): ret_var = ret_var.cuda() return ret_var def print_network(net): num_params = 0 for param in net.parameters(): num_params += param.numel() print('Network',net) print('Total number of parameters: %d' % num_params)
10,730
37.188612
136
py
CoordFill
CoordFill-master/models/LPIPS/models/models.py
from __future__ import absolute_import def create_model(opt): model = None print(opt.model) from .siam_model import * model = DistModel() model.initialize(opt, opt.batchSize, ) print("model [%s] was created" % (model.name())) return model
269
21.5
52
py
CoordFill
CoordFill-master/models/LPIPS/models/__init__.py
0
0
0
py
CoordFill
CoordFill-master/models/LPIPS/models/dist_model.py
from __future__ import absolute_import import sys sys.path.append('..') sys.path.append('.') import numpy as np import torch from torch import nn import os from collections import OrderedDict from torch.autograd import Variable import itertools from .base_model import BaseModel from scipy.ndimage import zoom import fractions import functools import skimage.transform from IPython import embed from . import networks_basic as networks # from PerceptualSimilarity.util import util import sys sys.path.insert(1, './LPIPS/') from ..util import util class DistModel(BaseModel): def name(self): return self.model_name def initialize(self, model='net-lin', net='alex', pnet_rand=False, pnet_tune=False, model_path=None, colorspace='Lab', use_gpu=True, printNet=False, spatial=False, spatial_shape=None, spatial_order=1, spatial_factor=None, is_train=False, lr=.0001, beta1=0.5, version='0.1'): ''' INPUTS model - ['net-lin'] for linearly calibrated network ['net'] for off-the-shelf network ['L2'] for L2 distance in Lab colorspace ['SSIM'] for ssim in RGB colorspace net - ['squeeze','alex','vgg'] model_path - if None, will look in weights/[NET_NAME].pth colorspace - ['Lab','RGB'] colorspace to use for L2 and SSIM use_gpu - bool - whether or not to use a GPU printNet - bool - whether or not to print network architecture out spatial - bool - whether to output an array containing varying distances across spatial dimensions spatial_shape - if given, output spatial shape. if None then spatial shape is determined automatically via spatial_factor (see below). spatial_factor - if given, specifies upsampling factor relative to the largest spatial extent of a convolutional layer. if None then resized to size of input images. spatial_order - spline order of filter for upsampling in spatial mode, by default 1 (bilinear). is_train - bool - [True] for training mode lr - float - initial learning rate beta1 - float - initial momentum term for adam version - 0.1 for latest, 0.0 was original ''' BaseModel.initialize(self, use_gpu=use_gpu) self.model = model self.net = net self.use_gpu = use_gpu self.is_train = is_train self.spatial = spatial self.spatial_shape = spatial_shape self.spatial_order = spatial_order self.spatial_factor = spatial_factor self.model_name = '%s [%s]'%(model,net) if(self.model == 'net-lin'): # pretrained net + linear layer self.net = networks.PNetLin(use_gpu=use_gpu,pnet_rand=pnet_rand, pnet_tune=pnet_tune, pnet_type=net,use_dropout=True,spatial=spatial,version=version) kw = {} if not use_gpu: kw['map_location'] = 'cpu' if(model_path is None): import inspect # model_path = './PerceptualSimilarity/weights/v%s/%s.pth'%(version,net) model_path = os.path.abspath(os.path.join(inspect.getfile(self.initialize), '..', '..', 'weights/v%s/%s.pth'%(version,net))) if(not is_train): print('Loading model from: %s'%model_path) self.net.load_state_dict(torch.load(model_path, **kw)) elif(self.model=='net'): # pretrained network assert not self.spatial, 'spatial argument not supported yet for uncalibrated networks' self.net = networks.PNet(use_gpu=use_gpu,pnet_type=net) self.is_fake_net = True elif(self.model in ['L2','l2']): self.net = networks.L2(use_gpu=use_gpu,colorspace=colorspace) # not really a network, only for testing self.model_name = 'L2' elif(self.model in ['DSSIM','dssim','SSIM','ssim']): self.net = networks.DSSIM(use_gpu=use_gpu,colorspace=colorspace) self.model_name = 'SSIM' else: raise ValueError("Model [%s] not recognized." % self.model) self.parameters = list(self.net.parameters()) if self.is_train: # training mode # extra network on top to go from distances (d0,d1) => predicted human judgment (h*) self.rankLoss = networks.BCERankingLoss(use_gpu=use_gpu) self.parameters+=self.rankLoss.parameters self.lr = lr self.old_lr = lr self.optimizer_net = torch.optim.Adam(self.parameters, lr=lr, betas=(beta1, 0.999)) else: # test mode self.net.eval() if(printNet): print('---------- Networks initialized -------------') networks.print_network(self.net) print('-----------------------------------------------') def forward_pair(self,in1,in2,retPerLayer=False): if(retPerLayer): return self.net.forward(in1,in2, retPerLayer=True) else: return self.net.forward(in1,in2) def forward(self, in0, in1, retNumpy=True): ''' Function computes the distance between image patches in0 and in1 INPUTS in0, in1 - torch.Tensor object of shape Nx3xXxY - image patch scaled to [-1,1] retNumpy - [False] to return as torch.Tensor, [True] to return as numpy array OUTPUT computed distances between in0 and in1 ''' self.input_ref = in0 self.input_p0 = in1 if(self.use_gpu): self.input_ref = self.input_ref.cuda() self.input_p0 = self.input_p0.cuda() self.var_ref = Variable(self.input_ref,requires_grad=True) self.var_p0 = Variable(self.input_p0,requires_grad=True) self.d0, _ = self.forward_pair(self.var_ref, self.var_p0) self.loss_total = self.d0 def convert_output(d0): if(retNumpy): ans = d0.cpu().data.numpy() if not self.spatial: ans = ans.flatten() else: assert(ans.shape[0] == 1 and len(ans.shape) == 4) return ans[0,...].transpose([1, 2, 0]) # Reshape to usual numpy image format: (height, width, channels) return ans else: return d0 if self.spatial: L = [convert_output(x) for x in self.d0] spatial_shape = self.spatial_shape if spatial_shape is None: if(self.spatial_factor is None): spatial_shape = (in0.size()[2],in0.size()[3]) else: spatial_shape = (max([x.shape[0] for x in L])*self.spatial_factor, max([x.shape[1] for x in L])*self.spatial_factor) L = [skimage.transform.resize(x, spatial_shape, order=self.spatial_order, mode='edge') for x in L] L = np.mean(np.concatenate(L, 2) * len(L), 2) return L else: return convert_output(self.d0) # ***** TRAINING FUNCTIONS ***** def optimize_parameters(self): self.forward_train() self.optimizer_net.zero_grad() self.backward_train() self.optimizer_net.step() self.clamp_weights() def clamp_weights(self): for module in self.net.modules(): if(hasattr(module, 'weight') and module.kernel_size==(1,1)): module.weight.data = torch.clamp(module.weight.data,min=0) def set_input(self, data): self.input_ref = data['ref'] self.input_p0 = data['p0'] self.input_p1 = data['p1'] self.input_judge = data['judge'] if(self.use_gpu): self.input_ref = self.input_ref.cuda() self.input_p0 = self.input_p0.cuda() self.input_p1 = self.input_p1.cuda() self.input_judge = self.input_judge.cuda() self.var_ref = Variable(self.input_ref,requires_grad=True) self.var_p0 = Variable(self.input_p0,requires_grad=True) self.var_p1 = Variable(self.input_p1,requires_grad=True) def forward_train(self): # run forward pass self.d0 = self.forward_pair(self.var_ref, self.var_p0) self.d1 = self.forward_pair(self.var_ref, self.var_p1) self.acc_r = self.compute_accuracy(self.d0,self.d1,self.input_judge) # var_judge self.var_judge = Variable(1.*self.input_judge).view(self.d0.size()) self.loss_total = self.rankLoss.forward(self.d0, self.d1, self.var_judge*2.-1.) return self.loss_total def backward_train(self): torch.mean(self.loss_total).backward() def compute_accuracy(self,d0,d1,judge): ''' d0, d1 are Variables, judge is a Tensor ''' d1_lt_d0 = (d1<d0).cpu().data.numpy().flatten() judge_per = judge.cpu().numpy().flatten() return d1_lt_d0*judge_per + (1-d1_lt_d0)*(1-judge_per) def get_current_errors(self): retDict = OrderedDict([('loss_total', self.loss_total.data.cpu().numpy()), ('acc_r', self.acc_r)]) for key in retDict.keys(): retDict[key] = np.mean(retDict[key]) return retDict def get_current_visuals(self): zoom_factor = 256/self.var_ref.data.size()[2] ref_img = util.tensor2im(self.var_ref.data) p0_img = util.tensor2im(self.var_p0.data) p1_img = util.tensor2im(self.var_p1.data) ref_img_vis = zoom(ref_img,[zoom_factor, zoom_factor, 1],order=0) p0_img_vis = zoom(p0_img,[zoom_factor, zoom_factor, 1],order=0) p1_img_vis = zoom(p1_img,[zoom_factor, zoom_factor, 1],order=0) return OrderedDict([('ref', ref_img_vis), ('p0', p0_img_vis), ('p1', p1_img_vis)]) def save(self, path, label): self.save_network(self.net, path, '', label) self.save_network(self.rankLoss.net, path, 'rank', label) def update_learning_rate(self,nepoch_decay): lrd = self.lr / nepoch_decay lr = self.old_lr - lrd for param_group in self.optimizer_net.param_groups: param_group['lr'] = lr print('update lr [%s] decay: %f -> %f' % (type,self.old_lr, lr)) self.old_lr = lr def score_2afc_dataset(data_loader,func): ''' Function computes Two Alternative Forced Choice (2AFC) score using distance function 'func' in dataset 'data_loader' INPUTS data_loader - CustomDatasetDataLoader object - contains a TwoAFCDataset inside func - callable distance function - calling d=func(in0,in1) should take 2 pytorch tensors with shape Nx3xXxY, and return numpy array of length N OUTPUTS [0] - 2AFC score in [0,1], fraction of time func agrees with human evaluators [1] - dictionary with following elements d0s,d1s - N arrays containing distances between reference patch to perturbed patches gts - N array in [0,1], preferred patch selected by human evaluators (closer to "0" for left patch p0, "1" for right patch p1, "0.6" means 60pct people preferred right patch, 40pct preferred left) scores - N array in [0,1], corresponding to what percentage function agreed with humans CONSTS N - number of test triplets in data_loader ''' d0s = [] d1s = [] gts = [] # bar = pb.ProgressBar(max_value=data_loader.load_data().__len__()) for (i,data) in enumerate(data_loader.load_data()): d0s+=func(data['ref'],data['p0']).tolist() d1s+=func(data['ref'],data['p1']).tolist() gts+=data['judge'].cpu().numpy().flatten().tolist() # bar.update(i) d0s = np.array(d0s) d1s = np.array(d1s) gts = np.array(gts) scores = (d0s<d1s)*(1.-gts) + (d1s<d0s)*gts + (d1s==d0s)*.5 return(np.mean(scores), dict(d0s=d0s,d1s=d1s,gts=gts,scores=scores)) def score_jnd_dataset(data_loader,func): ''' Function computes JND score using distance function 'func' in dataset 'data_loader' INPUTS data_loader - CustomDatasetDataLoader object - contains a JNDDataset inside func - callable distance function - calling d=func(in0,in1) should take 2 pytorch tensors with shape Nx3xXxY, and return numpy array of length N OUTPUTS [0] - JND score in [0,1], mAP score (area under precision-recall curve) [1] - dictionary with following elements ds - N array containing distances between two patches shown to human evaluator sames - N array containing fraction of people who thought the two patches were identical CONSTS N - number of test triplets in data_loader ''' ds = [] gts = [] # bar = pb.ProgressBar(max_value=data_loader.load_data().__len__()) for (i,data) in enumerate(data_loader.load_data()): ds+=func(data['p0'],data['p1']).tolist() gts+=data['same'].cpu().numpy().flatten().tolist() # bar.update(i) sames = np.array(gts) ds = np.array(ds) sorted_inds = np.argsort(ds) ds_sorted = ds[sorted_inds] sames_sorted = sames[sorted_inds] TPs = np.cumsum(sames_sorted) FPs = np.cumsum(1-sames_sorted) FNs = np.sum(sames_sorted)-TPs precs = TPs/(TPs+FPs) recs = TPs/(TPs+FNs) score = util.voc_ap(recs,precs) return(score, dict(ds=ds,sames=sames))
13,452
39.521084
278
py
CoordFill
CoordFill-master/models/LPIPS/util/html.py
import dominate from dominate.tags import * import os class HTML: def __init__(self, web_dir, title, image_subdir='', reflesh=0): self.title = title self.web_dir = web_dir # self.img_dir = os.path.join(self.web_dir, ) self.img_subdir = image_subdir self.img_dir = os.path.join(self.web_dir, image_subdir) if not os.path.exists(self.web_dir): os.makedirs(self.web_dir) if not os.path.exists(self.img_dir): os.makedirs(self.img_dir) # print(self.img_dir) self.doc = dominate.document(title=title) if reflesh > 0: with self.doc.head: meta(http_equiv="reflesh", content=str(reflesh)) def get_image_dir(self): return self.img_dir def add_header(self, str): with self.doc: h3(str) def add_table(self, border=1): self.t = table(border=border, style="table-layout: fixed;") self.doc.add(self.t) def add_images(self, ims, txts, links, width=400): self.add_table() with self.t: with tr(): for im, txt, link in zip(ims, txts, links): with td(style="word-wrap: break-word;", halign="center", valign="top"): with p(): with a(href=os.path.join(link)): img(style="width:%dpx" % width, src=os.path.join(im)) br() p(txt) def save(self,file='index'): html_file = '%s/%s.html' % (self.web_dir,file) f = open(html_file, 'wt') f.write(self.doc.render()) f.close() if __name__ == '__main__': html = HTML('web/', 'test_html') html.add_header('hello world') ims = [] txts = [] links = [] for n in range(4): ims.append('image_%d.png' % n) txts.append('text_%d' % n) links.append('image_%d.png' % n) html.add_images(ims, txts, links) html.save()
2,023
29.208955
91
py
CoordFill
CoordFill-master/models/LPIPS/util/visualizer.py
import numpy as np import os import time from . import util from . import html # from pdb import set_trace as st import matplotlib.pyplot as plt import math # from IPython import embed def zoom_to_res(img,res=256,order=0,axis=0): # img 3xXxX from scipy.ndimage import zoom zoom_factor = res/img.shape[1] if(axis==0): return zoom(img,[1,zoom_factor,zoom_factor],order=order) elif(axis==2): return zoom(img,[zoom_factor,zoom_factor,1],order=order) class Visualizer(): def __init__(self, opt): # self.opt = opt self.display_id = opt.display_id # self.use_html = opt.is_train and not opt.no_html self.win_size = opt.display_winsize self.name = opt.name self.display_cnt = 0 # display_current_results counter self.display_cnt_high = 0 self.use_html = opt.use_html if self.display_id > 0: import visdom self.vis = visdom.Visdom(port = opt.display_port) self.web_dir = os.path.join(opt.checkpoints_dir, opt.name, 'web') util.mkdirs([self.web_dir,]) if self.use_html: self.img_dir = os.path.join(self.web_dir, 'images') print('create web directory %s...' % self.web_dir) util.mkdirs([self.img_dir,]) # |visuals|: dictionary of images to display or save def display_current_results(self, visuals, epoch, nrows=None, res=256): if self.display_id > 0: # show images in the browser title = self.name if(nrows is None): nrows = int(math.ceil(len(visuals.items()) / 2.0)) images = [] idx = 0 for label, image_numpy in visuals.items(): title += " | " if idx % nrows == 0 else ", " title += label img = image_numpy.transpose([2, 0, 1]) img = zoom_to_res(img,res=res,order=0) images.append(img) idx += 1 if len(visuals.items()) % 2 != 0: white_image = np.ones_like(image_numpy.transpose([2, 0, 1]))*255 white_image = zoom_to_res(white_image,res=res,order=0) images.append(white_image) self.vis.images(images, nrow=nrows, win=self.display_id + 1, opts=dict(title=title)) if self.use_html: # save images to a html file for label, image_numpy in visuals.items(): img_path = os.path.join(self.img_dir, 'epoch%.3d_cnt%.6d_%s.png' % (epoch, self.display_cnt, label)) util.save_image(zoom_to_res(image_numpy, res=res, axis=2), img_path) self.display_cnt += 1 self.display_cnt_high = np.maximum(self.display_cnt_high, self.display_cnt) # update website webpage = html.HTML(self.web_dir, 'Experiment name = %s' % self.name, reflesh=1) for n in range(epoch, 0, -1): webpage.add_header('epoch [%d]' % n) if(n==epoch): high = self.display_cnt else: high = self.display_cnt_high for c in range(high-1,-1,-1): ims = [] txts = [] links = [] for label, image_numpy in visuals.items(): img_path = 'epoch%.3d_cnt%.6d_%s.png' % (n, c, label) ims.append(os.path.join('images',img_path)) txts.append(label) links.append(os.path.join('images',img_path)) webpage.add_images(ims, txts, links, width=self.win_size) webpage.save() # save errors into a directory def plot_current_errors_save(self, epoch, counter_ratio, opt, errors,keys='+ALL',name='loss', to_plot=False): if not hasattr(self, 'plot_data'): self.plot_data = {'X':[],'Y':[], 'legend':list(errors.keys())} self.plot_data['X'].append(epoch + counter_ratio) self.plot_data['Y'].append([errors[k] for k in self.plot_data['legend']]) # embed() if(keys=='+ALL'): plot_keys = self.plot_data['legend'] else: plot_keys = keys if(to_plot): (f,ax) = plt.subplots(1,1) for (k,kname) in enumerate(plot_keys): kk = np.where(np.array(self.plot_data['legend'])==kname)[0][0] x = self.plot_data['X'] y = np.array(self.plot_data['Y'])[:,kk] if(to_plot): ax.plot(x, y, 'o-', label=kname) np.save(os.path.join(self.web_dir,'%s_x')%kname,x) np.save(os.path.join(self.web_dir,'%s_y')%kname,y) if(to_plot): plt.legend(loc=0,fontsize='small') plt.xlabel('epoch') plt.ylabel('Value') f.savefig(os.path.join(self.web_dir,'%s.png'%name)) f.clf() plt.close() # errors: dictionary of error labels and values def plot_current_errors(self, epoch, counter_ratio, opt, errors): if not hasattr(self, 'plot_data'): self.plot_data = {'X':[],'Y':[], 'legend':list(errors.keys())} self.plot_data['X'].append(epoch + counter_ratio) self.plot_data['Y'].append([errors[k] for k in self.plot_data['legend']]) self.vis.line( X=np.stack([np.array(self.plot_data['X'])]*len(self.plot_data['legend']),1), Y=np.array(self.plot_data['Y']), opts={ 'title': self.name + ' loss over time', 'legend': self.plot_data['legend'], 'xlabel': 'epoch', 'ylabel': 'loss'}, win=self.display_id) # errors: same format as |errors| of plotCurrentErrors def print_current_errors(self, epoch, i, errors, t, t2=-1, t2o=-1, fid=None): message = '(ep: %d, it: %d, t: %.3f[s], ept: %.2f/%.2f[h]) ' % (epoch, i, t, t2o, t2) message += (', ').join(['%s: %.3f' % (k, v) for k, v in errors.items()]) print(message) if(fid is not None): fid.write('%s\n'%message) # save image to the disk def save_images_simple(self, webpage, images, names, in_txts, prefix='', res=256): image_dir = webpage.get_image_dir() ims = [] txts = [] links = [] for name, image_numpy, txt in zip(names, images, in_txts): image_name = '%s_%s.png' % (prefix, name) save_path = os.path.join(image_dir, image_name) if(res is not None): util.save_image(zoom_to_res(image_numpy,res=res,axis=2), save_path) else: util.save_image(image_numpy, save_path) ims.append(os.path.join(webpage.img_subdir,image_name)) # txts.append(name) txts.append(txt) links.append(os.path.join(webpage.img_subdir,image_name)) # embed() webpage.add_images(ims, txts, links, width=self.win_size) # save image to the disk def save_images(self, webpage, images, names, image_path, title=''): image_dir = webpage.get_image_dir() # short_path = ntpath.basename(image_path) # name = os.path.splitext(short_path)[0] # name = short_path # webpage.add_header('%s, %s' % (name, title)) ims = [] txts = [] links = [] for label, image_numpy in zip(names, images): image_name = '%s.jpg' % (label,) save_path = os.path.join(image_dir, image_name) util.save_image(image_numpy, save_path) ims.append(image_name) txts.append(label) links.append(image_name) webpage.add_images(ims, txts, links, width=self.win_size) # save image to the disk # def save_images(self, webpage, visuals, image_path, short=False): # image_dir = webpage.get_image_dir() # if short: # short_path = ntpath.basename(image_path) # name = os.path.splitext(short_path)[0] # else: # name = image_path # webpage.add_header(name) # ims = [] # txts = [] # links = [] # for label, image_numpy in visuals.items(): # image_name = '%s_%s.png' % (name, label) # save_path = os.path.join(image_dir, image_name) # util.save_image(image_numpy, save_path) # ims.append(image_name) # txts.append(label) # links.append(image_name) # webpage.add_images(ims, txts, links, width=self.win_size)
8,602
38.645161
116
py
CoordFill
CoordFill-master/models/LPIPS/util/util.py
from __future__ import print_function import numpy as np from PIL import Image import inspect import re import numpy as np import os import collections import matplotlib.pyplot as plt from scipy.ndimage.interpolation import zoom from skimage.measure import compare_ssim # from skimage.metrics import from skimage import measure import torch from IPython import embed import cv2 from datetime import datetime def datetime_str(): now = datetime.now() return '%04d-%02d-%02d-%02d-%02d-%02d'%(now.year,now.month,now.day,now.hour,now.minute,now.second) def read_text_file(in_path): fid = open(in_path,'r') vals = [] cur_line = fid.readline() while(cur_line!=''): vals.append(float(cur_line)) cur_line = fid.readline() fid.close() return np.array(vals) def bootstrap(in_vec,num_samples=100,bootfunc=np.mean): from astropy import stats return stats.bootstrap(np.array(in_vec),bootnum=num_samples,bootfunc=bootfunc) def rand_flip(input1,input2): if(np.random.binomial(1,.5)==1): return (input1,input2) else: return (input2,input1) def l2(p0, p1, range=255.): return .5*np.mean((p0 / range - p1 / range)**2) def psnr(p0, p1, peak=255.): return 10*np.log10(peak**2/np.mean((1.*p0-1.*p1)**2)) def dssim(p0, p1, range=255.): # embed() return (1 - compare_ssim(p0, p1, data_range=range, multichannel=True)) / 2. def rgb2lab(in_img,mean_cent=False): from skimage import color img_lab = color.rgb2lab(in_img) if(mean_cent): img_lab[:,:,0] = img_lab[:,:,0]-50 return img_lab def normalize_blob(in_feat,eps=1e-10): norm_factor = np.sqrt(np.sum(in_feat**2,axis=1,keepdims=True)) return in_feat/(norm_factor+eps) def cos_sim_blob(in0,in1): in0_norm = normalize_blob(in0) in1_norm = normalize_blob(in1) (N,C,X,Y) = in0_norm.shape return np.mean(np.mean(np.sum(in0_norm*in1_norm,axis=1),axis=1),axis=1) def normalize_tensor(in_feat,eps=1e-10): # norm_factor = torch.sqrt(torch.sum(in_feat**2,dim=1)).view(in_feat.size()[0],1,in_feat.size()[2],in_feat.size()[3]).repeat(1,in_feat.size()[1],1,1) norm_factor = torch.sqrt(torch.sum(in_feat**2,dim=1)).view(in_feat.size()[0],1,in_feat.size()[2],in_feat.size()[3]) return in_feat/(norm_factor.expand_as(in_feat)+eps) def cos_sim(in0,in1): in0_norm = normalize_tensor(in0) in1_norm = normalize_tensor(in1) N = in0.size()[0] X = in0.size()[2] Y = in0.size()[3] return torch.mean(torch.mean(torch.sum(in0_norm*in1_norm,dim=1).view(N,1,X,Y),dim=2).view(N,1,1,Y),dim=3).view(N) # Converts a Tensor into a Numpy array # |imtype|: the desired type of the conve def tensor2np(tensor_obj): # change dimension of a tensor object into a numpy array return tensor_obj[0].cpu().float().numpy().transpose((1,2,0)) def np2tensor(np_obj): # change dimenion of np array into tensor array return torch.Tensor(np_obj[:, :, :, np.newaxis].transpose((3, 2, 0, 1))) def tensor2tensorlab(image_tensor,to_norm=True,mc_only=False): # image tensor to lab tensor from skimage import color img = tensor2im(image_tensor) # print('img_rgb',img.flatten()) img_lab = color.rgb2lab(img) # print('img_lab',img_lab.flatten()) if(mc_only): img_lab[:,:,0] = img_lab[:,:,0]-50 if(to_norm and not mc_only): img_lab[:,:,0] = img_lab[:,:,0]-50 img_lab = img_lab/100. return np2tensor(img_lab) def tensorlab2tensor(lab_tensor,return_inbnd=False): from skimage import color import warnings warnings.filterwarnings("ignore") lab = tensor2np(lab_tensor)*100. lab[:,:,0] = lab[:,:,0]+50 # print('lab',lab) rgb_back = 255.*np.clip(color.lab2rgb(lab.astype('float')),0,1) # print('rgb',rgb_back) if(return_inbnd): # convert back to lab, see if we match lab_back = color.rgb2lab(rgb_back.astype('uint8')) # print('lab_back',lab_back) # print('lab==lab_back',np.isclose(lab_back,lab,atol=1.)) # print('lab-lab_back',np.abs(lab-lab_back)) mask = 1.*np.isclose(lab_back,lab,atol=2.) mask = np2tensor(np.prod(mask,axis=2)[:,:,np.newaxis]) return (im2tensor(rgb_back),mask) else: return im2tensor(rgb_back) def tensor2im(image_tensor, imtype=np.uint8, cent=1., factor=255./2.): # def tensor2im(image_tensor, imtype=np.uint8, cent=1., factor=1.): image_numpy = image_tensor[0].cpu().float().numpy() image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + cent) * factor return image_numpy.astype(imtype) def im2tensor(image, imtype=np.uint8, cent=1., factor=255./2.): # def im2tensor(image, imtype=np.uint8, cent=1., factor=1.): return torch.Tensor((image / factor - cent) [:, :, :, np.newaxis].transpose((3, 2, 0, 1))) def tensor2vec(vector_tensor): return vector_tensor.data.cpu().numpy()[:, :, 0, 0] def diagnose_network(net, name='network'): mean = 0.0 count = 0 for param in net.parameters(): if param.grad is not None: mean += torch.mean(torch.abs(param.grad.data)) count += 1 if count > 0: mean = mean / count print(name) print(mean) def grab_patch(img_in, P, yy, xx): return img_in[yy:yy+P,xx:xx+P,:] def load_image(path): if(path[-3:] == 'dng'): import rawpy with rawpy.imread(path) as raw: img = raw.postprocess() # img = plt.imread(path) elif(path[-3:]=='bmp' or path[-3:]=='jpg' or path[-3:]=='png'): import cv2 return cv2.imread(path)[:,:,::-1] else: img = (255*plt.imread(path)[:,:,:3]).astype('uint8') return img def resize_image(img, max_size=256): [Y, X] = img.shape[:2] # resize max_dim = max([Y, X]) zoom_factor = 1. * max_size / max_dim img = zoom(img, [zoom_factor, zoom_factor, 1]) return img def resize_image_zoom(img, zoom_factor=1., order=3): if(zoom_factor==1): return img else: return zoom(img, [zoom_factor, zoom_factor, 1], order=order) def save_image(image_numpy, image_path, ): image_pil = Image.fromarray(image_numpy) image_pil.save(image_path) def prep_display_image(img, dtype='uint8'): if(dtype == 'uint8'): return np.clip(img, 0, 255).astype('uint8') else: return np.clip(img, 0, 1.) def info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [ e for e in dir(object) if isinstance( getattr( object, e), collections.Callable)] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print("\n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList])) def varname(p): for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]: m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) if m: return m.group(1) def print_numpy(x, val=True, shp=False): x = x.astype(np.float64) if shp: print('shape,', x.shape) if val: x = x.flatten() print( 'mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % (np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x))) def mkdirs(paths): if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths) def mkdir(path): if not os.path.exists(path): os.makedirs(path) def rgb2lab(input): from skimage import color return color.rgb2lab(input / 255.) def montage( imgs, PAD=5, RATIO=16 / 9., EXTRA_PAD=( False, False), MM=-1, NN=-1, primeDir=0, verbose=False, returnGridPos=False, backClr=np.array( (0, 0, 0))): # INPUTS # imgs YxXxMxN or YxXxN # PAD scalar number of pixels in between # RATIO scalar target ratio of cols/rows # MM scalar # rows, if specified, overrides RATIO # NN scalar # columns, if specified, overrides RATIO # primeDir scalar 0 for top-to-bottom, 1 for left-to-right # OUTPUTS # mont_imgs MM*Y x NN*X x M big image with everything montaged # def montage(imgs, PAD=5, RATIO=16/9., MM=-1, NN=-1, primeDir=0, # verbose=False, forceFloat=False): if(imgs.ndim == 3): toExp = True imgs = imgs[:, :, np.newaxis, :] else: toExp = False Y = imgs.shape[0] X = imgs.shape[1] M = imgs.shape[2] N = imgs.shape[3] PADS = np.array((PAD)) if(PADS.flatten().size == 1): PADY = PADS PADX = PADS else: PADY = PADS[0] PADX = PADS[1] if(MM == -1 and NN == -1): NN = np.ceil(np.sqrt(1.0 * N * RATIO)) MM = np.ceil(1.0 * N / NN) NN = np.ceil(1.0 * N / MM) elif(MM == -1): MM = np.ceil(1.0 * N / NN) elif(NN == -1): NN = np.ceil(1.0 * N / MM) if(primeDir == 0): # write top-to-bottom [grid_mm, grid_nn] = np.meshgrid( np.arange(MM, dtype='uint'), np.arange(NN, dtype='uint')) elif(primeDir == 1): # write left-to-right [grid_nn, grid_mm] = np.meshgrid( np.arange(NN, dtype='uint'), np.arange(MM, dtype='uint')) grid_mm = np.uint(grid_mm.flatten()[0:N]) grid_nn = np.uint(grid_nn.flatten()[0:N]) EXTRA_PADY = EXTRA_PAD[0] * PADY EXTRA_PADX = EXTRA_PAD[0] * PADX # mont_imgs = np.zeros(((Y+PAD)*MM-PAD, (X+PAD)*NN-PAD, M), dtype=use_dtype) mont_imgs = np.zeros( (np.uint( (Y + PADY) * MM - PADY + EXTRA_PADY), np.uint( (X + PADX) * NN - PADX + EXTRA_PADX), M), dtype=imgs.dtype) mont_imgs = mont_imgs + \ backClr.flatten()[np.newaxis, np.newaxis, :].astype(mont_imgs.dtype) for ii in np.random.permutation(N): # print imgs[:,:,:,ii].shape # mont_imgs[grid_mm[ii]*(Y+PAD):(grid_mm[ii]*(Y+PAD)+Y), grid_nn[ii]*(X+PAD):(grid_nn[ii]*(X+PAD)+X),:] mont_imgs[np.uint(grid_mm[ii] * (Y + PADY)):np.uint((grid_mm[ii] * (Y + PADY) + Y)), np.uint(grid_nn[ii] * (X + PADX)):np.uint((grid_nn[ii] * (X + PADX) + X)), :] = imgs[:, :, :, ii] if(M == 1): imgs = imgs.reshape(imgs.shape[0], imgs.shape[1], imgs.shape[3]) if(toExp): mont_imgs = mont_imgs[:, :, 0] if(returnGridPos): # return (mont_imgs,np.concatenate((grid_mm[:,:,np.newaxis]*(Y+PAD), # grid_nn[:,:,np.newaxis]*(X+PAD)),axis=2)) return (mont_imgs, np.concatenate( (grid_mm[:, np.newaxis] * (Y + PADY), grid_nn[:, np.newaxis] * (X + PADX)), axis=1)) # return (mont_imgs, (grid_mm,grid_nn)) else: return mont_imgs class zeroClipper(object): def __init__(self, frequency=1): self.frequency = frequency def __call__(self, module): embed() if hasattr(module, 'weight'): # module.weight.data = torch.max(module.weight.data, 0) module.weight.data = torch.max(module.weight.data, 0) + 100 def flatten_nested_list(nested_list): # only works for list of list accum = [] for sublist in nested_list: for item in sublist: accum.append(item) return accum def read_file(in_path,list_lines=False): agg_str = '' f = open(in_path,'r') cur_line = f.readline() while(cur_line!=''): agg_str+=cur_line cur_line = f.readline() f.close() if(list_lines==False): return agg_str.replace('\n','') else: line_list = agg_str.split('\n') ret_list = [] for item in line_list: if(item!=''): ret_list.append(item) return ret_list def read_csv_file_as_text(in_path): agg_str = [] f = open(in_path,'r') cur_line = f.readline() while(cur_line!=''): agg_str.append(cur_line) cur_line = f.readline() f.close() return agg_str def random_swap(obj0,obj1): if(np.random.rand() < .5): return (obj0,obj1,0) else: return (obj1,obj0,1) def voc_ap(rec, prec, use_07_metric=False): """ ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False). """ if use_07_metric: # 11 point metric ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap = ap + p / 11. else: # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap
14,095
29.912281
153
py
CoordFill
CoordFill-master/models/LPIPS/util/__init__.py
0
0
0
py
CoordFill
CoordFill-master/datasets/wrappers.py
import functools import random import math from PIL import Image import numpy as np import torch from torch.utils.data import Dataset from torchvision import transforms from datasets import register def to_mask(mask): return transforms.ToTensor()( transforms.Grayscale(num_output_channels=1)( transforms.ToPILImage()(mask))) def resize_fn(img, size): return transforms.ToTensor()( transforms.Resize(size)( transforms.ToPILImage()(img))) def get_coord(shape): ranges = None coord_seqs = [] for i, n in enumerate(shape): if ranges is None: v0, v1 = -1, 1 else: v0, v1 = ranges[i] r = (v1 - v0) / (2 * n) seq = v0 + r + (2 * r) * torch.arange(n).float() coord_seqs.append(seq) ret = torch.stack(torch.meshgrid(*coord_seqs), dim=-1) return ret @register('sr-implicit-paired') class SRImplicitPaired(Dataset): def __init__(self, dataset, inp_size=None, augment=False, sample_q=None): self.dataset = dataset self.inp_size = inp_size self.augment = augment self.sample_q = sample_q def __len__(self): return len(self.dataset) def __getitem__(self, idx): img, mask = self.dataset[[idx, idx]] size = self.inp_size img = resize_fn(img, (size, size)) mask = resize_fn(mask, (size, size)) mask = to_mask(mask) mask[mask > 0] = 1 mask = 1 - mask return { 'inp': img, 'gt_rgb': img, 'mask': mask, } @register('sr-implicit-uniform-varied') class SRImplicitUniformVaried(Dataset): def __init__(self, dataset, size_min, size_max=None, augment=False): self.dataset = dataset self.size_min = size_min if size_max is None: size_max = size_min self.size_max = size_max self.augment = augment self.count = 0 self.scale = 0 def __len__(self): return len(self.dataset) def __getitem__(self, idx): img, mask = self.dataset[[idx, idx]] size = self.size_max img = resize_fn(img, (size, size)) mask = resize_fn(mask, (size, size)) mask = to_mask(mask) mask[mask > 0] = 1 mask = 1 - mask if self.augment: if random.random() < 0.5: img = img.flip(-1) mask = mask.flip(-1) return { 'inp': img, 'gt_rgb': img, 'mask': mask, }
2,575
22.851852
77
py
CoordFill
CoordFill-master/datasets/datasets.py
import copy datasets = {} def register(name): def decorator(cls): datasets[name] = cls return cls return decorator def make(dataset_spec, args=None): if args is not None: dataset_args = copy.deepcopy(dataset_spec['args']) dataset_args.update(args) else: dataset_args = dataset_spec['args'] dataset = datasets[dataset_spec['name']](**dataset_args) return dataset
432
18.681818
60
py
CoordFill
CoordFill-master/datasets/image_folder.py
import os import json from PIL import Image import pickle import imageio import numpy as np import torch from torch.utils.data import Dataset from torchvision import transforms from datasets import register @register('image-folder') class ImageFolder(Dataset): def __init__(self, path, split_file=None, split_key=None, first_k=None, repeat=1, cache=False): self.repeat = repeat self.cache = False if split_file is None: filenames = sorted(os.listdir(path)) else: with open(split_file, 'r') as f: filenames = json.load(f)[split_key] if first_k is not None: filenames = filenames[:first_k] self.files = [] for filepath, dirnames, filenames in os.walk(path): for filename in filenames: if self.cache: self.files.append( transforms.ToTensor()(Image.open(os.path.join(filepath, filename)).convert('RGB'))) else: self.files.append(os.path.join(filepath, filename)) if first_k is not None: self.files = self.files[:first_k] def __len__(self): return len(self.files) * self.repeat def __getitem__(self, idx): x = self.files[idx % len(self.files)] if self.cache: return x else: return transforms.ToTensor()(Image.open(x).convert('RGB')) @register('paired-image-folders') class PairedImageFolders(Dataset): def __init__(self, root_path_1, root_path_2, **kwargs): self.dataset_1 = ImageFolder(root_path_1, **kwargs) self.dataset_2 = ImageFolder(root_path_2, **kwargs) def __len__(self): return len(self.dataset_1) def __getitem__(self, idx): idx1, idx2 = idx return self.dataset_1[idx1], self.dataset_2[idx2]
1,885
27.575758
107
py
CoordFill
CoordFill-master/datasets/__init__.py
from .datasets import register, make from . import image_folder from . import wrappers
87
21
36
py
cycle-transformer
cycle-transformer-main/test.py
# This code is released under the CC BY-SA 4.0 license. import glob import os import numpy as np import pandas as pd import pydicom import torch from skimage.metrics import structural_similarity as ssim from models import create_model from options.train_options import TrainOptions @torch.no_grad() def compute_eval_metrics_gan(root_path, tagA='ARTERIAL', tagB='NATIVE', device='cpu'): # root_path - is the path to the raw Coltea-Lung-CT-100W data set. opt = TrainOptions().parse() opt.load_iter = 40 opt.isTrain = False opt.device = device model = create_model(opt) model.setup(opt) gen = model.netG_A gen.eval() eval_dirs = pd.read_csv(os.path.join(root_path, 'test_data.csv')) eval_dirs = list(eval_dirs.iloc[:, 1]) mae_pre = [] mae_post = [] rmse_pre = [] rmse_post = [] ssim_pre = [] ssim_post = [] for path in glob.glob(os.path.join(root_path, 'Coltea-Lung-CT-100W/*')): if not path.split('/')[-1] in eval_dirs: continue for scan in glob.glob(os.path.join(path, tagA, 'DICOM', '*')): orig_img = pydicom.dcmread(scan).pixel_array native_img = pydicom.dcmread(scan.replace(tagA, tagB)).pixel_array # Scale native image native_img[native_img < 0] = 0 native_img = native_img / 1e3 native_img = native_img - 1 # Scale original image, which is transform orig_img[orig_img < 0] = 0 orig_img = orig_img / 1e3 orig_img = orig_img - 1 orig_img_in = np.expand_dims(orig_img, 0).astype(np.float) orig_img_in = torch.from_numpy(orig_img_in).float().to(device) orig_img_in = orig_img_in.unsqueeze(0) native_fake = gen(orig_img_in)[0, 0].detach().cpu().numpy() mae_pre.append(np.mean(np.abs(orig_img - native_img))) mae_post.append(np.mean(np.abs(native_fake - native_img))) rmse_pre.append(np.sqrt(np.mean((orig_img - native_img)**2))) rmse_post.append(np.sqrt(np.mean((native_fake - native_img)**2))) ssim_pre.append(ssim(orig_img, native_img)) ssim_post.append(ssim(native_fake, native_img)) mae_pre = np.mean(mae_pre) mae_post = np.mean(mae_post) rmse_pre = np.mean(rmse_pre) rmse_post = np.mean(rmse_post) ssim_pre = np.mean(ssim_pre) ssim_post = np.mean(ssim_post) print(f"MAE before {mae_pre}, after {mae_post}") print(f"RMSE before {rmse_pre}, after {rmse_post}") print(f"SSIM before {ssim_pre}, after {ssim_post}") if __name__ == '__main__': compute_eval_metrics_gan( root_path='/path/to/data/set/', device='cuda' )
2,738
29.775281
86
py
cycle-transformer
cycle-transformer-main/train.py
# This code is released under the CC BY-SA 4.0 license. import time from options.train_options import TrainOptions from data import create_dataset from models import create_model from util.visualizer import Visualizer if __name__ == '__main__': opt = TrainOptions().parse() # get training options dataset = create_dataset(opt) # create a dataset given opt.dataset_mode and other options dataset_size = len(dataset) # get the number of images in the dataset. print('The number of training images = %d' % dataset_size) model = create_model(opt) # create a model given opt.model and other options model.setup(opt) # regular setup: load and print networks; create schedulers visualizer = Visualizer(opt) # create a visualizer that display/save images and plots total_iters = 0 # the total number of training iterations for epoch in range(opt.epoch_count, opt.n_epochs + opt.n_epochs_decay + 1): # outer loop for different epochs; we save the model by <epoch_count>, <epoch_count>+<save_latest_freq> epoch_start_time = time.time() # timer for entire epoch iter_data_time = time.time() # timer for data loading per iteration epoch_iter = 0 # the number of training iterations in current epoch, reset to 0 every epoch visualizer.reset() # reset the visualizer: make sure it saves the results to HTML at least once every epoch for i, data in enumerate(dataset): # inner loop within one epoch iter_start_time = time.time() # timer for computation per iteration if total_iters % opt.print_freq == 0: t_data = iter_start_time - iter_data_time total_iters += opt.batch_size epoch_iter += opt.batch_size model.set_input(data) # unpack data from dataset and apply preprocessing model.optimize_parameters() # calculate loss functions, get gradients, update network weights if total_iters % opt.display_freq == 0: # display images on visdom and save images to a HTML file save_result = total_iters % opt.update_html_freq == 0 model.compute_visuals() visualizer.display_current_results(model.get_current_visuals(), epoch, save_result) if total_iters % opt.print_freq == 0: # print training losses and save logging information to the disk losses = model.get_current_losses() t_comp = (time.time() - iter_start_time) / opt.batch_size visualizer.print_current_losses(epoch, epoch_iter, losses, t_comp, t_data) if opt.display_id > 0: visualizer.plot_current_losses(epoch, float(epoch_iter) / dataset_size, losses) if total_iters % opt.save_latest_freq == 0: # cache our latest model every <save_latest_freq> iterations print('saving the latest model (epoch %d, total_iters %d)' % (epoch, total_iters)) save_suffix = 'iter_%d' % total_iters if opt.save_by_iter else 'latest' model.save_networks(save_suffix) iter_data_time = time.time() if epoch % opt.save_epoch_freq == 0: # cache our model every <save_epoch_freq> epochs print('saving the model at the end of epoch %d, iters %d' % (epoch, total_iters)) model.save_networks('latest') model.save_networks(epoch) model.update_learning_rate() # update learning rates in the beginning of every epoch. print('End of epoch %d / %d \t Time Taken: %d sec' % (epoch, opt.n_epochs + opt.n_epochs_decay, time.time() - epoch_start_time))
3,739
57.4375
136
py
cycle-transformer
cycle-transformer-main/options/train_options.py
from .base_options import BaseOptions class TrainOptions(BaseOptions): """This class includes training options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): parser = BaseOptions.initialize(self, parser) # visdom and HTML visualization parameters parser.add_argument('--display_freq', type=int, default=400, help='frequency of showing training results on screen') parser.add_argument('--display_ncols', type=int, default=4, help='if positive, display all images in a single visdom web panel with certain number of images per row.') parser.add_argument('--display_id', type=int, default=1, help='window id of the web display') parser.add_argument('--display_server', type=str, default="http://localhost", help='visdom server of the web display') parser.add_argument('--display_env', type=str, default='main', help='visdom display environment name (default is "main")') parser.add_argument('--display_port', type=int, default=8097, help='visdom port of the web display') parser.add_argument('--update_html_freq', type=int, default=1000, help='frequency of saving training results to html') parser.add_argument('--print_freq', type=int, default=100, help='frequency of showing training results on console') parser.add_argument('--no_html', action='store_true', help='do not save intermediate training results to [opt.checkpoints_dir]/[opt.name]/web/') # network saving and loading parameters parser.add_argument('--save_latest_freq', type=int, default=5000, help='frequency of saving the latest results') parser.add_argument('--save_epoch_freq', type=int, default=2, help='frequency of saving checkpoints at the end of epochs') parser.add_argument('--save_by_iter', action='store_true', help='whether saves model by iteration') parser.add_argument('--continue_train', action='store_true', help='continue training: load the latest model') parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...') parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc') # training parameters parser.add_argument('--n_epochs', type=int, default=50, help='number of epochs with the initial learning rate') parser.add_argument('--n_epochs_decay', type=int, default=40, help='number of epochs to linearly decay learning rate to zero') parser.add_argument('--beta1', type=float, default=0.5, help='momentum term of adam') parser.add_argument('--lr', type=float, default=0.0001, help='initial learning rate for adam') parser.add_argument('--gan_mode', type=str, default='lsgan', help='the type of GAN objective. [vanilla| lsgan | wgangp]. vanilla GAN loss is the cross-entropy objective used in the original GAN paper.') parser.add_argument('--pool_size', type=int, default=50, help='the size of image buffer that stores previously generated images') parser.add_argument('--lr_policy', type=str, default='linear', help='learning rate policy. [linear | step | plateau | cosine]') parser.add_argument('--lr_decay_iters', type=int, default=50, help='multiply by a gamma every lr_decay_iters iterations') # transformer parameters parser.add_argument('--ngf_cytran', type=int, default=16, help='number of down') parser.add_argument('--n_downsampling', type=int, default=3, help='number of down') parser.add_argument('--depth', type=int, default=3, help='number of down') parser.add_argument('--heads', type=int, default=6, help='number of down') parser.add_argument('--dropout', type=float, default=0.05, help='number of down') self.isTrain = True return parser
3,916
80.604167
210
py
cycle-transformer
cycle-transformer-main/options/base_options.py
import argparse import os from util import util import torch import models as models class BaseOptions: """This class defines options used during both training and test time. It also implements several helper functions such as parsing, printing, and saving the options. It also gathers additional options defined in <modify_commandline_options> functions in both dataset class and model class. """ def __init__(self): """Reset the class; indicates the class hasn't been initailized""" self.initialized = False def initialize(self, parser): """Define the common options that are used in both training and test.""" # basic parameters parser.add_argument('--dataroot', default='/path/to/ct/dataset', help='path to images (should have subfolders trainA, trainB, valA, valB, etc)') parser.add_argument('--name', type=str, default='cytran', help='name of the experiment. It decides where to store samples and models') parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU') parser.add_argument('--device', type=str, default='cuda', help='cuda or cpu') parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here') # model parameters parser.add_argument('--model', type=str, default='cytran', help='chooses which model to use. [transformer_cvt | transformer | cycle_gan | pix2pix | test | colorization]') parser.add_argument('--input_nc', type=int, default=1, help='# of input image channels: 3 for RGB and 1 for grayscale') parser.add_argument('--output_nc', type=int, default=1, help='# of output image channels: 3 for RGB and 1 for grayscale') parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in the last conv layer') parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in the first conv layer') parser.add_argument('--netD', type=str, default='basic', help='specify discriminator architecture [basic | n_layers | pixel]. The basic model is a 70x70 PatchGAN. n_layers allows you to specify the layers in the discriminator') parser.add_argument('--netG', type=str, default='unet_256', help='specify generator architecture [resnet_9blocks | resnet_6blocks | unet_256 | unet_128]') parser.add_argument('--n_layers_D', type=int, default=3, help='only used if netD==n_layers') parser.add_argument('--norm', type=str, default='instance', help='instance normalization or batch normalization [instance | batch | none]') parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal | xavier | kaiming | orthogonal]') parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.') parser.add_argument('--no_dropout', action='store_true', help='no dropout for the generator') # dataset parameters parser.add_argument('--dataset_mode', type=str, default='ct', help='chooses how datasets are loaded. [ct, unaligned | aligned | single | colorization]') parser.add_argument('--Aclass', type=str, default='ARTERIAL') parser.add_argument('--Bclass', type=str, default='NATIVE') parser.add_argument('--direction', type=str, default='AtoB', help='AtoB or BtoA') parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly') parser.add_argument('--num_threads', default=4, type=int, help='# threads for loading data') parser.add_argument('--batch_size', type=int, default=2, help='input batch size') parser.add_argument('--img_size', type=int, default=512, help='scale images to this size') parser.add_argument('--load_size', type=int, default=512, help='scale images to this size') parser.add_argument('--crop_size', type=int, default=512, help='then crop to this size') parser.add_argument('--max_dataset_size', type=int, default=float("inf"), help='Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.') parser.add_argument('--preprocess', type=str, default='resize_and_crop', help='scaling and cropping of images at load time [resize_and_crop | crop | scale_width | scale_width_and_crop | none]') parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data augmentation') parser.add_argument('--display_winsize', type=int, default=512, help='display window size for both visdom and HTML') # additional parameters parser.add_argument('--epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model') parser.add_argument('--load_iter', type=int, default='0', help='which iteration to load? if load_iter > 0, the code will load models by iter_[load_iter]; otherwise, the code will load models by [epoch]') parser.add_argument('--verbose', action='store_true', help='if specified, print more debugging information') parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{load_size}') self.initialized = True return parser def gather_options(self): """Initialize our parser with basic options(only once). Add additional model-specific and dataset-specific options. These options are defined in the <modify_commandline_options> function in model and dataset classes. """ if not self.initialized: # check if it has been initialized parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser = self.initialize(parser) # get the basic options opt, _ = parser.parse_known_args() # modify model-related parser options model_name = opt.model model_option_setter = models.get_option_setter(model_name) parser = model_option_setter(parser, self.isTrain) opt, _ = parser.parse_known_args() # parse again with new defaults # modify dataset-related parser options # dataset_name = opt.dataset_mode # dataset_option_setter = data.get_option_setter(dataset_name) # parser = dataset_option_setter(parser, self.isTrain) # save and return the parser self.parser = parser return parser.parse_args() def print_options(self, opt): """Print and save options It will print both current options and default values(if different). It will save options into a text file / [checkpoints_dir] / opt.txt """ message = '' message += '----------------- Options ---------------\n' for k, v in sorted(vars(opt).items()): comment = '' default = self.parser.get_default(k) if v != default: comment = '\t[default: %s]' % str(default) message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment) message += '----------------- End -------------------' print(message) # save to the disk expr_dir = os.path.join(opt.checkpoints_dir, opt.name) util.mkdirs(expr_dir) file_name = os.path.join(expr_dir, '{}_opt.txt'.format(opt.phase)) with open(file_name, 'wt') as opt_file: opt_file.write(message) opt_file.write('\n') def parse(self): """Parse our options, create checkpoints directory suffix, and set up gpu device.""" opt = self.gather_options() opt.isTrain = self.isTrain # train or test # process opt.suffix if opt.suffix: suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else '' opt.name = opt.name + suffix self.print_options(opt) # set gpu ids str_ids = opt.gpu_ids.split(',') opt.gpu_ids = [] for str_id in str_ids: id = int(str_id) if id >= 0: opt.gpu_ids.append(id) if len(opt.gpu_ids) > 0: torch.cuda.set_device(opt.gpu_ids[0]) self.opt = opt return self.opt
8,414
58.680851
235
py
cycle-transformer
cycle-transformer-main/options/__init__.py
"""This package options includes option modules: training options, test options, and basic options (used in both training and test)."""
136
67.5
135
py
cycle-transformer
cycle-transformer-main/options/test_options.py
from .base_options import BaseOptions class TestOptions(BaseOptions): """This class includes test options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): parser = BaseOptions.initialize(self, parser) # define shared options # parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.') # parser.add_argument('--aspect_ratio', type=float, default=1.0, help='aspect ratio of result images') parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc') # Dropout and Batchnorm has different behavioir during training and test. # parser.add_argument('--eval', action='store_true', help='use eval mode during test time.') # parser.add_argument('--num_test', type=int, default=50, help='how many test images to run') # rewrite devalue values parser.set_defaults(model='test') # To avoid cropping, the load_size should be the same as crop_size # parser.set_defaults(load_size=parser.get_default('crop_size')) self.isTrain = False return parser
1,168
47.708333
110
py
cycle-transformer
cycle-transformer-main/models/base_model.py
import os import torch from collections import OrderedDict from abc import ABC, abstractmethod from . import networks class BaseModel(ABC): """This class is an abstract base class (ABC) for models. To create a subclass, you need to implement the following five functions: -- <__init__>: initialize the class; first call BaseModel.__init__(self, opt). -- <set_input>: unpack data from dataset and apply preprocessing. -- <forward>: produce intermediate results. -- <optimize_parameters>: calculate losses, gradients, and update network weights. -- <modify_commandline_options>: (optionally) add model-specific options and set default options. """ def __init__(self, opt): """Initialize the BaseModel class. Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions When creating your custom class, you need to implement your own initialization. In this function, you should first call <BaseModel.__init__(self, opt)> Then, you need to define four lists: -- self.loss_names (str list): specify the training losses that you want to plot and save. -- self.model_names (str list): define networks used in our training. -- self.visual_names (str list): specify the images that you want to display and save. -- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example. """ self.opt = opt self.gpu_ids = opt.gpu_ids self.isTrain = opt.isTrain self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') # get device name: CPU or GPU self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) # save all the checkpoints to save_dir if opt.preprocess != 'scale_width': # with [scale_width], input images might have different sizes, which hurts the performance of cudnn.benchmark. torch.backends.cudnn.benchmark = True self.loss_names = [] self.model_names = [] self.visual_names = [] self.optimizers = [] self.image_paths = [] self.metric = 0 # used for learning rate policy 'plateau' @staticmethod def modify_commandline_options(parser, is_train): """Add new model-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser. """ return parser @abstractmethod def set_input(self, input): """Unpack input data from the dataloader and perform necessary pre-processing steps. Parameters: input (dict): includes the data itself and its metadata information. """ pass @abstractmethod def forward(self): """Run forward pass; called by both functions <optimize_parameters> and <test>.""" pass @abstractmethod def optimize_parameters(self): """Calculate losses, gradients, and update network weights; called in every training iteration""" pass def setup(self, opt): """Load and print networks; create schedulers Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ if self.isTrain: self.schedulers = [networks.get_scheduler(optimizer, opt) for optimizer in self.optimizers] if not self.isTrain or opt.continue_train: load_suffix = '%d' % opt.load_iter if opt.load_iter > 0 else opt.epoch self.load_networks(load_suffix) self.print_networks(opt.verbose) def eval(self): """Make models eval mode during test time""" for name in self.model_names: if isinstance(name, str): net = getattr(self, 'net' + name) net.eval() def test(self): """Forward function used in test time. This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop It also calls <compute_visuals> to produce additional visualization results """ with torch.no_grad(): self.forward() self.compute_visuals() def compute_visuals(self): """Calculate additional output images for visdom and HTML visualization""" pass def get_image_paths(self): """ Return image paths that are used to load current data""" return self.image_paths def update_learning_rate(self): """Update learning rates for all the networks; called at the end of every epoch""" old_lr = self.optimizers[0].param_groups[0]['lr'] for scheduler in self.schedulers: if self.opt.lr_policy == 'plateau': scheduler.step(self.metric) else: scheduler.step() lr = self.optimizers[0].param_groups[0]['lr'] print('learning rate %.7f -> %.7f' % (old_lr, lr)) def get_current_visuals(self): """Return visualization images. train.py will display these images with visdom, and save the images to a HTML""" visual_ret = OrderedDict() for name in self.visual_names: if isinstance(name, str): visual_ret[name] = getattr(self, name) return visual_ret def get_current_losses(self): """Return traning losses / errors. train.py will print out these errors on console, and save them to a file""" errors_ret = OrderedDict() for name in self.loss_names: if isinstance(name, str): errors_ret[name] = float(getattr(self, 'loss_' + name)) # float(...) works for both scalar tensor and float number return errors_ret def save_networks(self, epoch): """Save all the networks to the disk. Parameters: epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name) """ for name in self.model_names: if isinstance(name, str): save_filename = '%s_net_%s.pth' % (epoch, name) save_path = os.path.join(self.save_dir, save_filename) net = getattr(self, 'net' + name) if len(self.gpu_ids) > 0 and torch.cuda.is_available(): try: torch.save(net.module.cpu().state_dict(), save_path) net.cuda(self.gpu_ids[0]) except: torch.save(net.cpu().state_dict(), save_path) net.cuda(self.gpu_ids[0]) else: torch.save(net.cpu().state_dict(), save_path) def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0): """Fix InstanceNorm checkpoints incompatibility (prior to 0.4)""" key = keys[i] if i + 1 == len(keys): # at the end, pointing to a parameter/buffer if module.__class__.__name__.startswith('InstanceNorm') and \ (key == 'running_mean' or key == 'running_var'): if getattr(module, key) is None: state_dict.pop('.'.join(keys)) if module.__class__.__name__.startswith('InstanceNorm') and \ (key == 'num_batches_tracked'): state_dict.pop('.'.join(keys)) else: self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1) def load_networks(self, epoch): """Load all the networks from the disk. Parameters: epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name) """ for name in self.model_names: if isinstance(name, str): load_filename = '%s_net_%s.pth' % (epoch, name) load_path = os.path.join(self.save_dir, load_filename) net = getattr(self, 'net' + name) if isinstance(net, torch.nn.DataParallel): net = net.module print('loading the model from %s' % load_path) # if you are using PyTorch newer than 0.4 (e.g., built from # GitHub source), you can remove str() on self.device state_dict = torch.load(load_path, map_location=str(self.device)) if hasattr(state_dict, '_metadata'): del state_dict._metadata # patch InstanceNorm checkpoints prior to 0.4 for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop self.__patch_instance_norm_state_dict(state_dict, net, key.split('.')) net.load_state_dict(state_dict) def print_networks(self, verbose): """Print the total number of parameters in the network and (if verbose) network architecture Parameters: verbose (bool) -- if verbose: print the network architecture """ print('---------- Networks initialized -------------') for name in self.model_names: if isinstance(name, str): net = getattr(self, 'net' + name) num_params = 0 for param in net.parameters(): num_params += param.numel() if verbose: print(net) print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6)) print('-----------------------------------------------') def set_requires_grad(self, nets, requires_grad=False): """Set requies_grad=Fasle for all the networks to avoid unnecessary computations Parameters: nets (network list) -- a list of networks requires_grad (bool) -- whether the networks require gradients or not """ if not isinstance(nets, list): nets = [nets] for net in nets: if net is not None: for param in net.parameters(): param.requires_grad = requires_grad
10,583
44.038298
260
py
cycle-transformer
cycle-transformer-main/models/cytran_model.py
# This code is released under the CC BY-SA 4.0 license. import torch import itertools from util import ImagePool from models.conv_transformer import ConvTransformer from .base_model import BaseModel from . import networks class CyTranModel(BaseModel): @staticmethod def modify_commandline_options(parser, is_train=True): """Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser. For CycleGAN, in addition to GAN losses, we introduce lambda_A, lambda_B, and lambda_identity for the following losses. A (source domain), B (target domain). Generators: G_A: A -> B; G_B: B -> A. Discriminators: D_A: G_A(A) vs. B; D_B: G_B(B) vs. A. Forward cycle loss: lambda_A * ||G_B(G_A(A)) - A|| (Eqn. (2) in the paper) Backward cycle loss: lambda_B * ||G_A(G_B(B)) - B|| (Eqn. (2) in the paper) Identity loss (optional): lambda_identity * (||G_A(B) - B|| * lambda_B + ||G_B(A) - A|| * lambda_A) (Sec 5.2 "Photo generation from paintings" in the paper) Dropout is not used in the original CycleGAN paper. """ parser.set_defaults(no_dropout=True) # default CycleGAN did not use dropout if is_train: parser.add_argument('--lambda_A', type=float, default=10.0, help='weight for cycle loss (A -> B -> A)') parser.add_argument('--lambda_B', type=float, default=10.0, help='weight for cycle loss (B -> A -> B)') parser.add_argument('--lambda_identity', type=float, default=0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1') return parser def __init__(self, opt): """Initialize the CycleGAN class. Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseModel.__init__(self, opt) # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses> self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B'] # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals> visual_names_A = ['real_A', 'fake_B', 'rec_A'] visual_names_B = ['real_B', 'fake_A', 'rec_B'] if self.isTrain and self.opt.lambda_identity > 0.0: # if identity loss is used, we also visualize idt_B=G_A(B) ad idt_A=G_A(B) visual_names_A.append('idt_B') visual_names_B.append('idt_A') self.visual_names = visual_names_A + visual_names_B # combine visualizations for A and B # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>. if self.isTrain: self.model_names = ['G_A', 'G_B', 'D_A', 'D_B'] else: # during test time, only load Gs self.model_names = ['G_A', 'G_B'] # self.clip_dis = opt.clip_dis # self.clip_gen = opt.clip_gen # define networks (both Generators and discriminators) self.netG_A = ConvTransformer(input_nc=opt.input_nc, n_downsampling=opt.n_downsampling, depth=opt.depth, heads=opt.heads, dropout=opt.dropout, ngf=opt.ngf_cytran).to(opt.device) self.netG_B = ConvTransformer(input_nc=opt.input_nc, n_downsampling=opt.n_downsampling, depth=opt.depth, heads=opt.heads, dropout=opt.dropout, ngf=opt.ngf_cytran).to(opt.device) if self.isTrain: # define discriminators self.netD_A = networks.define_D(opt.output_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids) self.netD_B = networks.define_D(opt.input_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids) if self.isTrain: if opt.lambda_identity > 0.0: # only works when input and output images have the same number of channels assert(opt.input_nc == opt.output_nc) self.fake_A_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images self.fake_B_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images # define loss functions self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device) # define GAN loss. self.criterionCycle = torch.nn.L1Loss() self.criterionIdt = torch.nn.L1Loss() # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>. self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999)) self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(), self.netD_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999)) self.optimizers.append(self.optimizer_G) self.optimizers.append(self.optimizer_D) def set_input(self, input): """Unpack input data from the dataloader and perform necessary pre-processing steps. Parameters: input (dict): include the data itself and its metadata information. The option 'direction' can be used to swap domain A and domain B. """ AtoB = self.opt.direction == 'AtoB' self.real_A = input['A' if AtoB else 'B'].to(self.device).float() self.real_B = input['B' if AtoB else 'A'].to(self.device).float() def forward(self): """Run forward pass; called by both functions <optimize_parameters> and <test>.""" self.fake_B = self.netG_A(self.real_A) # G_A(A) self.rec_A = self.netG_B(self.fake_B) # G_B(G_A(A)) self.fake_A = self.netG_B(self.real_B) # G_B(B) self.rec_B = self.netG_A(self.fake_A) # G_A(G_B(B)) def backward_D_basic(self, netD, real, fake): """Calculate GAN loss for the discriminator Parameters: netD (network) -- the discriminator D real (tensor array) -- real images fake (tensor array) -- images generated by a generator Return the discriminator loss. We also call loss_D.backward() to calculate the gradients. """ # Real pred_real = netD(real) loss_D_real = self.criterionGAN(pred_real, True) # Fake pred_fake = netD(fake.detach()) loss_D_fake = self.criterionGAN(pred_fake, False) # Combined loss and calculate gradients loss_D = (loss_D_real + loss_D_fake) * 0.5 loss_D.backward() return loss_D def backward_D_A(self): """Calculate GAN loss for discriminator D_A""" fake_B = self.fake_B_pool.query(self.fake_B) self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_B, fake_B) def backward_D_B(self): """Calculate GAN loss for discriminator D_B""" fake_A = self.fake_A_pool.query(self.fake_A) self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_A, fake_A) def backward_G(self): """Calculate the loss for generators G_A and G_B""" lambda_idt = self.opt.lambda_identity lambda_A = self.opt.lambda_A lambda_B = self.opt.lambda_B # Identity loss if lambda_idt > 0: # G_A should be identity if real_B is fed: ||G_A(B) - B|| self.idt_A = self.netG_A(self.real_B) self.loss_idt_A = self.criterionIdt(self.idt_A, self.real_B) * lambda_B * lambda_idt # G_B should be identity if real_A is fed: ||G_B(A) - A|| self.idt_B = self.netG_B(self.real_A) self.loss_idt_B = self.criterionIdt(self.idt_B, self.real_A) * lambda_A * lambda_idt else: self.loss_idt_A = 0 self.loss_idt_B = 0 # GAN loss D_A(G_A(A)) self.loss_G_A = self.criterionGAN(self.netD_A(self.fake_B), True) # GAN loss D_B(G_B(B)) self.loss_G_B = self.criterionGAN(self.netD_B(self.fake_A), True) # Forward cycle loss || G_B(G_A(A)) - A|| self.loss_cycle_A = self.criterionCycle(self.rec_A, self.real_A) * lambda_A # Backward cycle loss || G_A(G_B(B)) - B|| self.loss_cycle_B = self.criterionCycle(self.rec_B, self.real_B) * lambda_B # combined loss and calculate gradients self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + self.loss_idt_B self.loss_G.backward() def optimize_parameters(self): """Calculate losses, gradients, and update network weights; called in every training iteration""" # forward self.forward() # compute fake images and reconstruction images. # D_A and D_B self.set_requires_grad([self.netD_A, self.netD_B], True) self.optimizer_D.zero_grad() # set D_A and D_B's gradients to zero self.backward_D_A() # calculate gradients for D_A self.backward_D_B() # calculate graidents for D_B # torch.nn.utils.clip_grad_norm_(self.netD_A.parameters(), self.clip_dis) # torch.nn.utils.clip_grad_norm_(self.netD_B.parameters(), self.clip_dis) self.optimizer_D.step() # update D_A and D_B's weights # G_A and G_B self.set_requires_grad([self.netD_A, self.netD_B], False) # Ds require no gradients when optimizing Gs self.optimizer_G.zero_grad() # set G_A and G_B's gradients to zero self.backward_G() # calculate gradients for G_A and G_B # torch.nn.utils.clip_grad_norm_(self.netG_A.parameters(), self.clip_gen) # torch.nn.utils.clip_grad_norm_(self.netG_B.parameters(), self.clip_gen) self.optimizer_G.step() # update G_A and G_B's weights
10,350
54.352941
362
py
cycle-transformer
cycle-transformer-main/models/conv_transformer.py
# This code is released under the CC BY-SA 4.0 license. from einops import rearrange from torch import nn, einsum import functools class Encoder(nn.Module): def __init__(self, input_nc, ngf=16, norm_layer=nn.BatchNorm2d, n_downsampling=3): super(Encoder, self).__init__() if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True)] for i in range(n_downsampling): # add downsampling layers mult = 2 ** i model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias), norm_layer(ngf * mult * 2), nn.ReLU(True)] self.down_sampling = nn.Sequential(*model) def forward(self, input): input = self.down_sampling(input) return input class Decoder(nn.Module): def __init__(self, output_nc, ngf=16, norm_layer=nn.BatchNorm2d, n_downsampling=3): super(Decoder, self).__init__() if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d model = [] for i in range(n_downsampling): # add upsampling layers mult = 2 ** (n_downsampling - i) model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias), norm_layer(int(ngf * mult / 2)), nn.ReLU(True)] model += [nn.ReflectionPad2d(3)] model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] self.up_sampling = nn.Sequential(*model) def forward(self, input): input = self.up_sampling(input) return input class PreNorm(nn.Module): def __init__(self, dim, fn): super().__init__() self.norm = nn.LayerNorm(dim) self.fn = fn def forward(self, x, **kwargs): x = rearrange(x, 'b c h w -> b h w c') x = self.norm(x) x = rearrange(x, 'b h w c -> b c h w') return self.fn(x, **kwargs) class FeedForward(nn.Module): def __init__(self, dim, mult=4, dropout=0.): super().__init__() self.net = nn.Sequential( nn.Conv2d(dim, dim * mult, 1), nn.GELU(), nn.Dropout(dropout), nn.Conv2d(dim * mult, dim, 1), nn.Dropout(dropout) ) def forward(self, x): return self.net(x) class DepthWiseConv2d(nn.Module): def __init__(self, dim_in, dim_out, kernel_size, padding, stride, bias=True): super().__init__() self.net = nn.Sequential( nn.Conv2d(dim_in, dim_in, kernel_size=kernel_size, padding=padding, groups=dim_in, stride=stride, bias=bias), nn.BatchNorm2d(dim_in), nn.Conv2d(dim_in, dim_out, kernel_size=1, bias=bias) ) def forward(self, x): return self.net(x) class Attention(nn.Module): def __init__(self, dim, proj_kernel, kv_proj_stride, heads=8, dim_head=64, dropout=0.): super().__init__() inner_dim = dim_head * heads padding = proj_kernel // 2 self.heads = heads self.scale = dim_head ** -0.5 self.attend = nn.Softmax(dim=-1) self.to_q = DepthWiseConv2d(dim, inner_dim, 3, padding=padding, stride=1, bias=False) self.to_kv = DepthWiseConv2d(dim, inner_dim * 2, 3, padding=padding, stride=kv_proj_stride, bias=False) self.to_out = nn.Sequential( nn.Conv2d(inner_dim, dim, 1), nn.Dropout(dropout) ) def forward(self, x): shape = x.shape b, n, _, y, h = *shape, self.heads q, k, v = (self.to_q(x), *self.to_kv(x).chunk(2, dim=1)) q, k, v = map(lambda t: rearrange(t, 'b (h d) x y -> (b h) (x y) d', h=h), (q, k, v)) dots = einsum('b i d, b j d -> b i j', q, k) * self.scale attn = self.attend(dots) out = einsum('b i j, b j d -> b i d', attn, v) out = rearrange(out, '(b h) (x y) d -> b (h d) x y', h=h, y=y) return self.to_out(out) class Transformer(nn.Module): def __init__(self, dim, proj_kernel, kv_proj_stride, depth, heads, dim_head=64, mlp_mult=4, dropout=0.): super().__init__() self.layers = nn.ModuleList([]) for _ in range(depth): self.layers.append(nn.ModuleList([ PreNorm(dim, Attention(dim, proj_kernel=proj_kernel, kv_proj_stride=kv_proj_stride, heads=heads, dim_head=dim_head, dropout=dropout)), PreNorm(dim, FeedForward(dim, mlp_mult, dropout=dropout)) ])) def forward(self, x): for attn, ff in self.layers: x = attn(x) + x x = ff(x) + x return x class ConvTransformer(nn.Module): def __init__(self, input_nc, n_downsampling, depth, heads, proj_kernel=3, mlp_mult=4, dropout=0., ngf=16): super().__init__() dim = (2 ** n_downsampling) * ngf self.conv_encoder = Encoder(input_nc=input_nc, ngf=ngf, n_downsampling=n_downsampling) self.conv_decoder = Decoder(output_nc=input_nc, ngf=ngf, n_downsampling=n_downsampling) self.transformer = Transformer(dim=dim, proj_kernel=proj_kernel, kv_proj_stride=2, depth=depth, heads=heads, mlp_mult=mlp_mult, dropout=dropout) def forward(self, img): x = self.conv_encoder(img) x = self.transformer(x) x = self.conv_decoder(x) return x
6,016
34.187135
116
py
cycle-transformer
cycle-transformer-main/models/networks.py
# This code is released under the CC BY-SA 4.0 license. import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler ############################################################################### # Helper Functions ############################################################################### class Identity(nn.Module): def forward(self, x): return x def get_norm_layer(norm_type='instance'): """Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics. """ if norm_type == 'batch': norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True) elif norm_type == 'instance': norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False) elif norm_type == 'none': def norm_layer(x): return Identity() else: raise NotImplementedError('normalization layer [%s] is not found' % norm_type) return norm_layer def get_scheduler(optimizer, opt): """Return a learning rate scheduler Parameters: optimizer -- the optimizer of the network opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.  opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine For 'linear', we keep the same learning rate for the first <opt.n_epochs> epochs and linearly decay the rate to zero over the next <opt.n_epochs_decay> epochs. For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers. See https://pytorch.org/docs/stable/optim.html for more details. """ if opt.lr_policy == 'linear': def lambda_rule(epoch): lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.n_epochs) / float(opt.n_epochs_decay + 1) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif opt.lr_policy == 'step': scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1) elif opt.lr_policy == 'plateau': scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5) elif opt.lr_policy == 'cosine': scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.n_epochs, eta_min=0) else: return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy) return scheduler def init_weights(net, init_type='normal', init_gain=0.02): """Initialize network weights. Parameters: net (network) -- network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal init_gain (float) -- scaling factor for normal, xavier and orthogonal. We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might work better for some applications. Feel free to try yourself. """ def init_func(m): # define the initialization function classname = m.__class__.__name__ if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): if init_type == 'normal': init.normal_(m.weight.data, 0.0, init_gain) elif init_type == 'xavier': init.xavier_normal_(m.weight.data, gain=init_gain) elif init_type == 'kaiming': init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') elif init_type == 'orthogonal': init.orthogonal_(m.weight.data, gain=init_gain) else: raise NotImplementedError('initialization method [%s] is not implemented' % init_type) if hasattr(m, 'bias') and m.bias is not None: init.constant_(m.bias.data, 0.0) elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies. init.normal_(m.weight.data, 1.0, init_gain) init.constant_(m.bias.data, 0.0) print('initialize network with %s' % init_type) net.apply(init_func) # apply the initialization function <init_func> def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Return an initialized network. """ if len(gpu_ids) > 0: assert(torch.cuda.is_available()) net.to(gpu_ids[0]) net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs init_weights(net, init_type, init_gain=init_gain) return net def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]): """Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128 norm (str) -- the name of normalization layers used in the network: batch | instance | none use_dropout (bool) -- if use dropout layers. init_type (str) -- the name of our initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a generator Our current implementation provides two types of generators: U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images) The original U-Net paper: https://arxiv.org/abs/1505.04597 Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks) Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style). The generator has been initialized by <init_net>. It uses RELU for non-linearity. """ net = None norm_layer = get_norm_layer(norm_type=norm) if netG == 'resnet_9blocks': net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9) elif netG == 'resnet_6blocks': net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6) elif netG == 'unet_128': net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout) elif netG == 'unet_256': net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout) else: raise NotImplementedError('Generator model name [%s] is not recognized' % netG) return init_net(net, init_type, init_gain, gpu_ids) def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]): """Create a discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the first conv layer netD (str) -- the architecture's name: basic | n_layers | pixel n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers' norm (str) -- the type of normalization layers used in the network. init_type (str) -- the name of the initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a discriminator Our current implementation provides three types of discriminators: [basic]: 'PatchGAN' classifier described in the original pix2pix paper. It can classify whether 70×70 overlapping patches are real or fake. Such a patch-level discriminator architecture has fewer parameters than a full-image discriminator and can work on arbitrarily-sized images in a fully convolutional fashion. [n_layers]: With this mode, you can specify the number of conv layers in the discriminator with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).) [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not. It encourages greater color diversity but has no effect on spatial statistics. The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity. """ net = None norm_layer = get_norm_layer(norm_type=norm) if netD == 'basic': # default PatchGAN classifier net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer) elif netD == 'n_layers': # more options net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer) elif netD == 'pixel': # classify if each pixel is real or fake net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer) else: raise NotImplementedError('Discriminator model name [%s] is not recognized' % netD) return init_net(net, init_type, init_gain, gpu_ids) ############################################################################## # Classes ############################################################################## class GANLoss(nn.Module): """Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. """ def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0): """ Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp. target_real_label (bool) - - label for a real image target_fake_label (bool) - - label of a fake image Note: Do not use sigmoid as the last layer of Discriminator. LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss. """ super(GANLoss, self).__init__() self.register_buffer('real_label', torch.tensor(target_real_label)) self.register_buffer('fake_label', torch.tensor(target_fake_label)) self.gan_mode = gan_mode if gan_mode == 'lsgan': self.loss = nn.MSELoss() elif gan_mode == 'vanilla': self.loss = nn.BCEWithLogitsLoss() elif gan_mode in ['wgangp']: self.loss = None else: raise NotImplementedError('gan mode %s not implemented' % gan_mode) def get_target_tensor(self, prediction, target_is_real): """Create label tensors with the same size as the input. Parameters: prediction (tensor) - - tpyically the prediction from a discriminator target_is_real (bool) - - if the ground truth label is for real images or fake images Returns: A label tensor filled with ground truth label, and with the size of the input """ if target_is_real: target_tensor = self.real_label else: target_tensor = self.fake_label return target_tensor.expand_as(prediction) def __call__(self, prediction, target_is_real): """Calculate loss given Discriminator's output and grount truth labels. Parameters: prediction (tensor) - - tpyically the prediction output from a discriminator target_is_real (bool) - - if the ground truth label is for real images or fake images Returns: the calculated loss. """ if self.gan_mode in ['lsgan', 'vanilla']: target_tensor = self.get_target_tensor(prediction, target_is_real) loss = self.loss(prediction, target_tensor) elif self.gan_mode == 'wgangp': if target_is_real: loss = -prediction.mean() else: loss = prediction.mean() return loss def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0): """Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028 Arguments: netD (network) -- discriminator network real_data (tensor array) -- real images fake_data (tensor array) -- generated images from the generator device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') type (str) -- if we mix real and fake data or not [real | fake | mixed]. constant (float) -- the constant used in formula ( ||gradient||_2 - constant)^2 lambda_gp (float) -- weight for this loss Returns the gradient penalty loss """ if lambda_gp > 0.0: if type == 'real': # either use real images, fake images, or a linear interpolation of two. interpolatesv = real_data elif type == 'fake': interpolatesv = fake_data elif type == 'mixed': alpha = torch.rand(real_data.shape[0], 1, device=device) alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape) interpolatesv = alpha * real_data + ((1 - alpha) * fake_data) else: raise NotImplementedError('{} not implemented'.format(type)) interpolatesv.requires_grad_(True) disc_interpolates = netD(interpolatesv) gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True) gradients = gradients[0].view(real_data.size(0), -1) # flat the data gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps return gradient_penalty, gradients else: return 0.0, None class ResnetGenerator(nn.Module): """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'): """Construct a Resnet-based generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers n_blocks (int) -- the number of ResNet blocks padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero """ assert(n_blocks >= 0) super(ResnetGenerator, self).__init__() if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True)] n_downsampling = 2 for i in range(n_downsampling): # add downsampling layers mult = 2 ** i model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias), norm_layer(ngf * mult * 2), nn.ReLU(True)] mult = 2 ** n_downsampling for i in range(n_blocks): # add ResNet blocks model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)] for i in range(n_downsampling): # add upsampling layers mult = 2 ** (n_downsampling - i) model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias), norm_layer(int(ngf * mult / 2)), nn.ReLU(True)] model += [nn.ReflectionPad2d(3)] model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] model += [nn.Tanh()] self.model = nn.Sequential(*model) def forward(self, input): """Standard forward""" return self.model(input) class ResnetBlock(nn.Module): """Define a Resnet block""" def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias): """Initialize the Resnet block A resnet block is a conv block with skip connections We construct a conv block with build_conv_block function, and implement skip connections in <forward> function. Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf """ super(ResnetBlock, self).__init__() self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias) def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias): """Construct a convolutional block. Parameters: dim (int) -- the number of channels in the conv layer. padding_type (str) -- the name of padding layer: reflect | replicate | zero norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers. use_bias (bool) -- if the conv layer uses bias or not Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU)) """ conv_block = [] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)] if use_dropout: conv_block += [nn.Dropout(0.5)] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)] return nn.Sequential(*conv_block) def forward(self, x): """Forward function (with skip connections)""" out = x + self.conv_block(x) # add skip connections return out class UnetGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7, image of size 128x128 will become of size 1x1 # at the bottleneck ngf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer We construct the U-Net from the innermost layer to the outermost layer. It is a recursive process. """ super(UnetGenerator, self).__init__() # construct unet structure unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout) # gradually reduce the number of filters from ngf * 8 to ngf unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer def forward(self, input): """Standard forward""" return self.model(input) class UnetSkipConnectionBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet submodule with skip connections. Parameters: outer_nc (int) -- the number of filters in the outer conv layer inner_nc (int) -- the number of filters in the inner conv layer input_nc (int) -- the number of channels in input images/features submodule (UnetSkipConnectionBlock) -- previously defined submodules outermost (bool) -- if this module is the outermost module innermost (bool) -- if this module is the innermost module norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers. """ super(UnetSkipConnectionBlock, self).__init__() self.outermost = outermost if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d if input_nc is None: input_nc = outer_nc downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) downrelu = nn.LeakyReLU(0.2, True) downnorm = norm_layer(inner_nc) uprelu = nn.ReLU(True) upnorm = norm_layer(outer_nc) if outermost: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1) down = [downconv] up = [uprelu, upconv, nn.Tanh()] model = down + [submodule] + up elif innermost: upconv = nn.ConvTranspose2d(inner_nc, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv] up = [uprelu, upconv, upnorm] model = down + up else: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv, downnorm] up = [uprelu, upconv, upnorm] if use_dropout: model = down + [submodule] + up + [nn.Dropout(0.5)] else: model = down + [submodule] + up self.model = nn.Sequential(*model) def forward(self, x): if self.outermost: return self.model(x) else: # add skip connections return torch.cat([x, self.model(x)], 1) class NLayerDiscriminator(nn.Module): """Defines a PatchGAN discriminator""" def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d): """Construct a PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the last conv layer n_layers (int) -- the number of conv layers in the discriminator norm_layer -- normalization layer """ super(NLayerDiscriminator, self).__init__() if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d kw = 4 padw = 1 sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)] nf_mult = 1 nf_mult_prev = 1 for n in range(1, n_layers): # gradually increase the number of filters nf_mult_prev = nf_mult nf_mult = min(2 ** n, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ] nf_mult_prev = nf_mult nf_mult = min(2 ** n_layers, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ] sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map self.model = nn.Sequential(*sequence) def forward(self, input): """Standard forward.""" return self.model(input) class PixelDiscriminator(nn.Module): """Defines a 1x1 PatchGAN discriminator (pixelGAN)""" def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d): """Construct a 1x1 PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer """ super(PixelDiscriminator, self).__init__() if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d self.net = [ nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias), norm_layer(ndf * 2), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)] self.net = nn.Sequential(*self.net) def forward(self, input): """Standard forward.""" return self.net(input)
28,452
45.115073
167
py
cycle-transformer
cycle-transformer-main/models/__init__.py
"""This package contains modules related to objective functions, optimizations, and network architectures. To add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from BaseModel. You need to implement the following five functions: -- <__init__>: initialize the class; first call BaseModel.__init__(self, opt). -- <set_input>: unpack data from dataset and apply preprocessing. -- <forward>: produce intermediate results. -- <optimize_parameters>: calculate loss, gradients, and update network weights. -- <modify_commandline_options>: (optionally) add model-specific options and set default options. In the function <__init__>, you need to define four lists: -- self.loss_names (str list): specify the training losses that you want to plot and save. -- self.model_names (str list): define networks used in our training. -- self.visual_names (str list): specify the images that you want to display and save. -- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an usage. Now you can use the model class by specifying flag '--model dummy'. See our template model class 'template_model.py' for more details. """ import importlib from models.base_model import BaseModel def find_model_using_name(model_name): """Import the module "models/[model_name]_model.py". In the file, the class called DatasetNameModel() will be instantiated. It has to be a subclass of BaseModel, and it is case-insensitive. """ model_filename = "pix2pix.models." + model_name + "_model" modellib = importlib.import_module(model_filename) model = None target_model_name = model_name.replace('_', '') + 'model' for name, cls in modellib.__dict__.items(): if name.lower() == target_model_name.lower() \ and issubclass(cls, BaseModel): model = cls if model is None: print("In %s.py, there should be a subclass of BaseModel with class name that matches %s in lowercase." % (model_filename, target_model_name)) exit(0) return model def get_option_setter(model_name): """Return the static method <modify_commandline_options> of the model class.""" model_class = find_model_using_name(model_name) return model_class.modify_commandline_options def create_model(opt): """Create a model given the option. This function warps the class CustomDatasetDataLoader. This is the main interface between this package and 'train.py'/'test.py' Example: >>> from models import create_model >>> model = create_model(opt) """ model = find_model_using_name(opt.model) instance = model(opt) print("model [%s] was created" % type(instance).__name__) return instance
3,080
44.308824
250
py
cycle-transformer
cycle-transformer-main/models/cycle_gan_model.py
# This code is released under the CC BY-SA 4.0 license. import torch import itertools from util import ImagePool from .base_model import BaseModel from . import networks class CycleGANModel(BaseModel): """ This class implements the CycleGAN model, for learning image-to-image translation without paired data. The model training requires '--dataset_mode unaligned' dataset. By default, it uses a '--netG resnet_9blocks' ResNet generator, a '--netD basic' discriminator (PatchGAN introduced by pix2pix), and a least-square GANs objective ('--gan_mode lsgan'). CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf """ @staticmethod def modify_commandline_options(parser, is_train=True): """Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser. For CycleGAN, in addition to GAN losses, we introduce lambda_A, lambda_B, and lambda_identity for the following losses. A (source domain), B (target domain). Generators: G_A: A -> B; G_B: B -> A. Discriminators: D_A: G_A(A) vs. B; D_B: G_B(B) vs. A. Forward cycle loss: lambda_A * ||G_B(G_A(A)) - A|| (Eqn. (2) in the paper) Backward cycle loss: lambda_B * ||G_A(G_B(B)) - B|| (Eqn. (2) in the paper) Identity loss (optional): lambda_identity * (||G_A(B) - B|| * lambda_B + ||G_B(A) - A|| * lambda_A) (Sec 5.2 "Photo generation from paintings" in the paper) Dropout is not used in the original CycleGAN paper. """ parser.set_defaults(no_dropout=True) # default CycleGAN did not use dropout if is_train: parser.add_argument('--lambda_A', type=float, default=10.0, help='weight for cycle loss (A -> B -> A)') parser.add_argument('--lambda_B', type=float, default=10.0, help='weight for cycle loss (B -> A -> B)') parser.add_argument('--lambda_identity', type=float, default=0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1') return parser def __init__(self, opt): """Initialize the CycleGAN class. Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseModel.__init__(self, opt) # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses> self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B'] # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals> visual_names_A = ['real_A', 'fake_B', 'rec_A'] visual_names_B = ['real_B', 'fake_A', 'rec_B'] if self.isTrain and self.opt.lambda_identity > 0.0: # if identity loss is used, we also visualize idt_B=G_A(B) ad idt_A=G_A(B) visual_names_A.append('idt_B') visual_names_B.append('idt_A') self.visual_names = visual_names_A + visual_names_B # combine visualizations for A and B # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>. if self.isTrain: self.model_names = ['G_A', 'G_B', 'D_A', 'D_B'] else: # during test time, only load Gs self.model_names = ['G_A', 'G_B'] # define networks (both Generators and discriminators) # The naming is different from those used in the paper. # Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X) self.netG_A = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids) self.netG_B = networks.define_G(opt.output_nc, opt.input_nc, opt.ngf, opt.netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids) if self.isTrain: # define discriminators self.netD_A = networks.define_D(opt.output_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids) self.netD_B = networks.define_D(opt.input_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids) if self.isTrain: if opt.lambda_identity > 0.0: # only works when input and output images have the same number of channels assert(opt.input_nc == opt.output_nc) self.fake_A_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images self.fake_B_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images # define loss functions self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device) # define GAN loss. self.criterionCycle = torch.nn.L1Loss() self.criterionIdt = torch.nn.L1Loss() # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>. self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999)) self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(), self.netD_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999)) self.optimizers.append(self.optimizer_G) self.optimizers.append(self.optimizer_D) def set_input(self, input): """Unpack input data from the dataloader and perform necessary pre-processing steps. Parameters: input (dict): include the data itself and its metadata information. The option 'direction' can be used to swap domain A and domain B. """ AtoB = self.opt.direction == 'AtoB' self.real_A = input['A' if AtoB else 'B'].to(self.device).float() self.real_B = input['B' if AtoB else 'A'].to(self.device).float() # self.image_paths = input['A_paths' if AtoB else 'B_paths'] def forward(self): """Run forward pass; called by both functions <optimize_parameters> and <test>.""" self.fake_B = self.netG_A(self.real_A) # G_A(A) self.rec_A = self.netG_B(self.fake_B) # G_B(G_A(A)) self.fake_A = self.netG_B(self.real_B) # G_B(B) self.rec_B = self.netG_A(self.fake_A) # G_A(G_B(B)) def backward_D_basic(self, netD, real, fake): """Calculate GAN loss for the discriminator Parameters: netD (network) -- the discriminator D real (tensor array) -- real images fake (tensor array) -- images generated by a generator Return the discriminator loss. We also call loss_D.backward() to calculate the gradients. """ # Real pred_real = netD(real) loss_D_real = self.criterionGAN(pred_real, True) # Fake pred_fake = netD(fake.detach()) loss_D_fake = self.criterionGAN(pred_fake, False) # Combined loss and calculate gradients loss_D = (loss_D_real + loss_D_fake) * 0.5 loss_D.backward() return loss_D def backward_D_A(self): """Calculate GAN loss for discriminator D_A""" fake_B = self.fake_B_pool.query(self.fake_B) self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_B, fake_B) def backward_D_B(self): """Calculate GAN loss for discriminator D_B""" fake_A = self.fake_A_pool.query(self.fake_A) self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_A, fake_A) def backward_G(self): """Calculate the loss for generators G_A and G_B""" lambda_idt = self.opt.lambda_identity lambda_A = self.opt.lambda_A lambda_B = self.opt.lambda_B # Identity loss if lambda_idt > 0: # G_A should be identity if real_B is fed: ||G_A(B) - B|| self.idt_A = self.netG_A(self.real_B) self.loss_idt_A = self.criterionIdt(self.idt_A, self.real_B) * lambda_B * lambda_idt # G_B should be identity if real_A is fed: ||G_B(A) - A|| self.idt_B = self.netG_B(self.real_A) self.loss_idt_B = self.criterionIdt(self.idt_B, self.real_A) * lambda_A * lambda_idt else: self.loss_idt_A = 0 self.loss_idt_B = 0 # GAN loss D_A(G_A(A)) self.loss_G_A = self.criterionGAN(self.netD_A(self.fake_B), True) # GAN loss D_B(G_B(B)) self.loss_G_B = self.criterionGAN(self.netD_B(self.fake_A), True) # Forward cycle loss || G_B(G_A(A)) - A|| self.loss_cycle_A = self.criterionCycle(self.rec_A, self.real_A) * lambda_A # Backward cycle loss || G_A(G_B(B)) - B|| self.loss_cycle_B = self.criterionCycle(self.rec_B, self.real_B) * lambda_B # combined loss and calculate gradients self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + self.loss_idt_B self.loss_G.backward() def optimize_parameters(self): """Calculate losses, gradients, and update network weights; called in every training iteration""" # forward self.forward() # compute fake images and reconstruction images. # G_A and G_B self.set_requires_grad([self.netD_A, self.netD_B], False) # Ds require no gradients when optimizing Gs self.optimizer_G.zero_grad() # set G_A and G_B's gradients to zero self.backward_G() # calculate gradients for G_A and G_B self.optimizer_G.step() # update G_A and G_B's weights # D_A and D_B self.set_requires_grad([self.netD_A, self.netD_B], True) self.optimizer_D.zero_grad() # set D_A and D_B's gradients to zero self.backward_D_A() # calculate gradients for D_A self.backward_D_B() # calculate graidents for D_B self.optimizer_D.step() # update D_A and D_B's weights
10,621
52.918782
362
py
cycle-transformer
cycle-transformer-main/util/image_pool.py
import random import torch class ImagePool: """This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. """ def __init__(self, pool_size): """Initialize the ImagePool class Parameters: pool_size (int) -- the size of image buffer, if pool_size=0, no buffer will be created """ self.pool_size = pool_size if self.pool_size > 0: # create an empty pool self.num_imgs = 0 self.images = [] def query(self, images): """Return an image from the pool. Parameters: images: the latest generated images from the generator Returns images from the buffer. By 50/100, the buffer will return input images. By 50/100, the buffer will return images previously stored in the buffer, and insert the current images to the buffer. """ if self.pool_size == 0: # if the buffer size is 0, do nothing return images return_images = [] for image in images: image = torch.unsqueeze(image.data, 0) if self.num_imgs < self.pool_size: # if the buffer is not full; keep inserting current images to the buffer self.num_imgs = self.num_imgs + 1 self.images.append(image) return_images.append(image) else: p = random.uniform(0, 1) if p > 0.5: # by 50% chance, the buffer will return a previously stored image, and insert the current image into the buffer random_id = random.randint(0, self.pool_size - 1) # randint is inclusive tmp = self.images[random_id].clone() self.images[random_id] = image return_images.append(tmp) else: # by another 50% chance, the buffer will return the current image return_images.append(image) return_images = torch.cat(return_images, 0) # collect all the images and return return return_images
2,224
39.454545
140
py
cycle-transformer
cycle-transformer-main/util/html.py
import dominate from dominate.tags import meta, h3, table, tr, td, p, a, img, br import os class HTML: """This HTML class allows us to save images and write texts into a single HTML file. It consists of functions such as <add_header> (add a text header to the HTML file), <add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk). It is based on Python library 'dominate', a Python library for creating and manipulating HTML documents using a DOM API. """ def __init__(self, web_dir, title, refresh=0): """Initialize the HTML classes Parameters: web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/ title (str) -- the webpage name refresh (int) -- how often the website refresh itself; if 0; no refreshing """ self.title = title self.web_dir = web_dir self.img_dir = os.path.join(self.web_dir, 'images') if not os.path.exists(self.web_dir): os.makedirs(self.web_dir) if not os.path.exists(self.img_dir): os.makedirs(self.img_dir) self.doc = dominate.document(title=title) if refresh > 0: with self.doc.head: meta(http_equiv="refresh", content=str(refresh)) def get_image_dir(self): """Return the directory that stores images""" return self.img_dir def add_header(self, text): """Insert a header to the HTML file Parameters: text (str) -- the header text """ with self.doc: h3(text) def add_images(self, ims, txts, links, width=400): """add images to the HTML file Parameters: ims (str list) -- a list of image paths txts (str list) -- a list of image names shown on the website links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page """ self.t = table(border=1, style="table-layout: fixed;") # Insert a table self.doc.add(self.t) with self.t: with tr(): for im, txt, link in zip(ims, txts, links): with td(style="word-wrap: break-word;", halign="center", valign="top"): with p(): with a(href=os.path.join('images', link)): img(style="width:%dpx" % width, src=os.path.join('images', im)) br() p(txt) def save(self): """save the current content to the HMTL file""" html_file = '%s/index.html' % self.web_dir f = open(html_file, 'wt') f.write(self.doc.render()) f.close() if __name__ == '__main__': # we show an example usage here. html = HTML('web/', 'test_html') html.add_header('hello world') ims, txts, links = [], [], [] for n in range(4): ims.append('image_%d.png' % n) txts.append('text_%d' % n) links.append('image_%d.png' % n) html.add_images(ims, txts, links) html.save()
3,223
36.057471
157
py
cycle-transformer
cycle-transformer-main/util/visualizer.py
import numpy as np import os import sys import ntpath import time from . import util, html from subprocess import Popen, PIPE if sys.version_info[0] == 2: VisdomExceptionBase = Exception else: VisdomExceptionBase = ConnectionError def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256): """Save images to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs image_path (str) -- the string is used to create image paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save images stored in 'visuals' to the HTML file specified by 'webpage'. """ image_dir = webpage.get_image_dir() short_path = ntpath.basename(image_path[0]) name = os.path.splitext(short_path)[0] webpage.add_header(name) ims, txts, links = [], [], [] for label, im_data in visuals.items(): im = util.tensor2im(im_data) image_name = '%s_%s.png' % (name, label) save_path = os.path.join(image_dir, image_name) util.save_image(im, save_path, aspect_ratio=aspect_ratio) ims.append(image_name) txts.append(label) links.append(image_name) webpage.add_images(ims, txts, links, width=width) class Visualizer(): """This class includes several functions that can display/save images and print/save logging information. It uses a Python library 'visdom' for display, and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images. """ def __init__(self, opt): """Initialize the Visualizer class Parameters: opt -- stores all the experiment flags; needs to be a subclass of BaseOptions Step 1: Cache the training/test options Step 2: connect to a visdom server Step 3: create an HTML object for saveing HTML filters Step 4: create a logging file to store training losses """ self.opt = opt # cache the option self.display_id = opt.display_id self.use_html = opt.isTrain and not opt.no_html self.win_size = opt.display_winsize self.name = opt.name self.port = opt.display_port self.saved = False if self.display_id > 0: # connect to a visdom server given <display_port> and <display_server> import visdom self.ncols = opt.display_ncols self.vis = visdom.Visdom(server=opt.display_server, port=opt.display_port, env=opt.display_env) if not self.vis.check_connection(): self.create_visdom_connections() if self.use_html: # create an HTML object at <checkpoints_dir>/web/; images will be saved under <checkpoints_dir>/web/images/ self.web_dir = os.path.join(opt.checkpoints_dir, opt.name, 'web') self.img_dir = os.path.join(self.web_dir, 'images') print('create web directory %s...' % self.web_dir) util.mkdirs([self.web_dir, self.img_dir]) # create a logging file to store training losses self.log_name = os.path.join(opt.checkpoints_dir, opt.name, 'loss_log.txt') with open(self.log_name, "a") as log_file: now = time.strftime("%c") log_file.write('================ Training Loss (%s) ================\n' % now) def reset(self): """Reset the self.saved status""" self.saved = False def create_visdom_connections(self): """If the program could not connect to Visdom server, this function will start a new server at port < self.port > """ cmd = sys.executable + ' -m visdom.server -p %d &>/dev/null &' % self.port print('\n\nCould not connect to Visdom server. \n Trying to start a server....') print('Command: %s' % cmd) Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) def display_current_results(self, visuals, epoch, save_result): """Display current results on visdom; save current results to an HTML file. Parameters: visuals (OrderedDict) - - dictionary of images to display or save epoch (int) - - the current epoch save_result (bool) - - if save the current results to an HTML file """ if self.display_id > 0: # show images in the browser using visdom ncols = self.ncols if ncols > 0: # show all the images in one visdom panel ncols = min(ncols, len(visuals)) h, w = next(iter(visuals.values())).shape[:2] table_css = """<style> table {border-collapse: separate; border-spacing: 4px; white-space: nowrap; text-align: center} table td {width: % dpx; height: % dpx; padding: 4px; outline: 4px solid black} </style>""" % (w, h) # create a table css # create a table of images. title = self.name label_html = '' label_html_row = '' images = [] idx = 0 for label, image in visuals.items(): image_numpy = util.tensor2im(image) label_html_row += '<td>%s</td>' % label images.append(image_numpy.transpose([2, 0, 1])) idx += 1 if idx % ncols == 0: label_html += '<tr>%s</tr>' % label_html_row label_html_row = '' white_image = np.ones_like(image_numpy.transpose([2, 0, 1])) * 255 while idx % ncols != 0: images.append(white_image) label_html_row += '<td></td>' idx += 1 if label_html_row != '': label_html += '<tr>%s</tr>' % label_html_row try: self.vis.images(images, nrow=ncols, win=self.display_id + 1, padding=2, opts=dict(title=title + ' images')) label_html = '<table>%s</table>' % label_html self.vis.text(table_css + label_html, win=self.display_id + 2, opts=dict(title=title + ' labels')) except VisdomExceptionBase: self.create_visdom_connections() else: # show each image in a separate visdom panel; idx = 1 try: for label, image in visuals.items(): image_numpy = util.tensor2im(image) self.vis.image(image_numpy.transpose([2, 0, 1]), opts=dict(title=label), win=self.display_id + idx) idx += 1 except VisdomExceptionBase: self.create_visdom_connections() if self.use_html and (save_result or not self.saved): # save images to an HTML file if they haven't been saved. self.saved = True # save images to the disk for label, image in visuals.items(): image_numpy = util.tensor2im(image) img_path = os.path.join(self.img_dir, 'epoch%.3d_%s.png' % (epoch, label)) util.save_image(image_numpy, img_path) # update website webpage = html.HTML(self.web_dir, 'Experiment name = %s' % self.name, refresh=1) for n in range(epoch, 0, -1): webpage.add_header('epoch [%d]' % n) ims, txts, links = [], [], [] for label, image_numpy in visuals.items(): image_numpy = util.tensor2im(image) img_path = 'epoch%.3d_%s.png' % (n, label) ims.append(img_path) txts.append(label) links.append(img_path) webpage.add_images(ims, txts, links, width=self.win_size) webpage.save() def plot_current_losses(self, epoch, counter_ratio, losses): """display the current losses on visdom display: dictionary of error labels and values Parameters: epoch (int) -- current epoch counter_ratio (float) -- progress (percentage) in the current epoch, between 0 to 1 losses (OrderedDict) -- training losses stored in the format of (name, float) pairs """ if not hasattr(self, 'plot_data'): self.plot_data = {'X': [], 'Y': [], 'legend': list(losses.keys())} self.plot_data['X'].append(epoch + counter_ratio) self.plot_data['Y'].append([losses[k] for k in self.plot_data['legend']]) try: self.vis.line( X=np.stack([np.array(self.plot_data['X'])] * len(self.plot_data['legend']), 1), Y=np.array(self.plot_data['Y']), opts={ 'title': self.name + ' loss over time', 'legend': self.plot_data['legend'], 'xlabel': 'epoch', 'ylabel': 'loss'}, win=self.display_id) except VisdomExceptionBase: self.create_visdom_connections() # losses: same format as |losses| of plot_current_losses def print_current_losses(self, epoch, iters, losses, t_comp, t_data): """print current losses on console; also save the losses to the disk Parameters: epoch (int) -- current epoch iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch) losses (OrderedDict) -- training losses stored in the format of (name, float) pairs t_comp (float) -- computational time per data point (normalized by batch_size) t_data (float) -- data loading time per data point (normalized by batch_size) """ message = '(epoch: %d, iters: %d, time: %.3f, data: %.3f) ' % (epoch, iters, t_comp, t_data) for k, v in losses.items(): message += '%s: %.3f ' % (k, v) print(message) # print the message with open(self.log_name, "a") as log_file: log_file.write('%s\n' % message) # save the message
10,460
46.121622
139
py
cycle-transformer
cycle-transformer-main/util/util.py
"""This module contains simple helper functions """ from __future__ import print_function import torch import numpy as np from PIL import Image import os def tensor2im(input_image, imtype=np.uint8): """"Converts a Tensor array into a numpy image array. Parameters: input_image (tensor) -- the input image tensor array imtype (type) -- the desired type of the converted numpy array """ if not isinstance(input_image, np.ndarray): if isinstance(input_image, torch.Tensor): # get the data from a variable image_tensor = input_image.data else: return input_image image_numpy = image_tensor[0].cpu().float().numpy() # convert it into a numpy array if image_numpy.shape[0] == 1: # grayscale to RGB image_numpy = np.tile(image_numpy, (3, 1, 1)) image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0 # post-processing: tranpose and scaling else: # if it is a numpy array, do nothing image_numpy = input_image return image_numpy.astype(imtype) def diagnose_network(net, name='network'): """Calculate and print the mean of average absolute(gradients) Parameters: net (torch network) -- Torch network name (str) -- the name of the network """ mean = 0.0 count = 0 for param in net.parameters(): if param.grad is not None: mean += torch.mean(torch.abs(param.grad.data)) count += 1 if count > 0: mean = mean / count print(name) print(mean) def save_image(image_numpy, image_path, aspect_ratio=1.0): """Save a numpy image to the disk Parameters: image_numpy (numpy array) -- input numpy array image_path (str) -- the path of the image """ image_pil = Image.fromarray(image_numpy) h, w, _ = image_numpy.shape if aspect_ratio > 1.0: image_pil = image_pil.resize((h, int(w * aspect_ratio)), Image.BICUBIC) if aspect_ratio < 1.0: image_pil = image_pil.resize((int(h / aspect_ratio), w), Image.BICUBIC) image_pil.save(image_path) def print_numpy(x, val=True, shp=False): """Print the mean, min, max, median, std, and size of a numpy array Parameters: val (bool) -- if print the values of the numpy array shp (bool) -- if print the shape of the numpy array """ x = x.astype(np.float64) if shp: print('shape,', x.shape) if val: x = x.flatten() print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % ( np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x))) def mkdirs(paths): """create empty directories if they don't exist Parameters: paths (str list) -- a list of directory paths """ if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths) def mkdir(path): """create a single empty directory if it didn't exist Parameters: path (str) -- a single directory path """ if not os.path.exists(path): os.makedirs(path)
3,175
29.538462
119
py
cycle-transformer
cycle-transformer-main/util/__init__.py
"""This package includes a miscellaneous collection of useful helper functions."""
83
41
82
py
cycle-transformer
cycle-transformer-main/util/get_data.py
from __future__ import print_function import os import tarfile import requests from warnings import warn from zipfile import ZipFile from bs4 import BeautifulSoup from os.path import abspath, isdir, join, basename class GetData(object): def __init__(self, technique='cyclegan', verbose=True): url_dict = { 'pix2pix': 'http://efrosgans.eecs.berkeley.edu/pix2pix/datasets/', 'cyclegan': 'https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets' } self.url = url_dict.get(technique.lower()) self._verbose = verbose def _print(self, text): if self._verbose: print(text) @staticmethod def _get_options(r): soup = BeautifulSoup(r.text, 'lxml') options = [h.text for h in soup.find_all('a', href=True) if h.text.endswith(('.zip', 'tar.gz'))] return options def _present_options(self): r = requests.get(self.url) options = self._get_options(r) print('Options:\n') for i, o in enumerate(options): print("{0}: {1}".format(i, o)) choice = input("\nPlease enter the number of the " "dataset above you wish to download:") return options[int(choice)] def _download_data(self, dataset_url, save_path): if not isdir(save_path): os.makedirs(save_path) base = basename(dataset_url) temp_save_path = join(save_path, base) with open(temp_save_path, "wb") as f: r = requests.get(dataset_url) f.write(r.content) if base.endswith('.tar.gz'): obj = tarfile.open(temp_save_path) elif base.endswith('.zip'): obj = ZipFile(temp_save_path, 'r') else: raise ValueError("Unknown File Type: {0}.".format(base)) self._print("Unpacking Data...") obj.extractall(save_path) obj.close() os.remove(temp_save_path) def get(self, save_path, dataset=None): """ Download a dataset. Parameters: save_path (str) -- A directory to save the data to. dataset (str) -- (optional). A specific dataset to download. Note: this must include the file extension. If None, options will be presented for you to choose from. Returns: save_path_full (str) -- the absolute path to the downloaded data. """ if dataset is None: selected_dataset = self._present_options() else: selected_dataset = dataset save_path_full = join(save_path, selected_dataset.split('.')[0]) if isdir(save_path_full): warn("\n'{0}' already exists. Voiding Download.".format( save_path_full)) else: self._print('Downloading Data...') url = "{0}/{1}".format(self.url, selected_dataset) self._download_data(url, save_path=save_path) return abspath(save_path_full)
3,093
31.229167
90
py
cycle-transformer
cycle-transformer-main/datasets/combine_A_and_B.py
import os import numpy as np import cv2 import argparse from multiprocessing import Pool def image_write(path_A, path_B, path_AB): im_A = cv2.imread(path_A, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR im_B = cv2.imread(path_B, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR im_AB = np.concatenate([im_A, im_B], 1) cv2.imwrite(path_AB, im_AB) parser = argparse.ArgumentParser('create image pairs') parser.add_argument('--fold_A', dest='fold_A', help='input directory for image A', type=str, default='../dataset/50kshoes_edges') parser.add_argument('--fold_B', dest='fold_B', help='input directory for image B', type=str, default='../dataset/50kshoes_jpg') parser.add_argument('--fold_AB', dest='fold_AB', help='output directory', type=str, default='../dataset/test_AB') parser.add_argument('--num_imgs', dest='num_imgs', help='number of images', type=int, default=1000000) parser.add_argument('--use_AB', dest='use_AB', help='if true: (0001_A, 0001_B) to (0001_AB)', action='store_true') parser.add_argument('--no_multiprocessing', dest='no_multiprocessing', help='If used, chooses single CPU execution instead of parallel execution', action='store_true',default=False) args = parser.parse_args() for arg in vars(args): print('[%s] = ' % arg, getattr(args, arg)) splits = os.listdir(args.fold_A) if not args.no_multiprocessing: pool=Pool() for sp in splits: img_fold_A = os.path.join(args.fold_A, sp) img_fold_B = os.path.join(args.fold_B, sp) img_list = os.listdir(img_fold_A) if args.use_AB: img_list = [img_path for img_path in img_list if '_A.' in img_path] num_imgs = min(args.num_imgs, len(img_list)) print('split = %s, use %d/%d images' % (sp, num_imgs, len(img_list))) img_fold_AB = os.path.join(args.fold_AB, sp) if not os.path.isdir(img_fold_AB): os.makedirs(img_fold_AB) print('split = %s, number of images = %d' % (sp, num_imgs)) for n in range(num_imgs): name_A = img_list[n] path_A = os.path.join(img_fold_A, name_A) if args.use_AB: name_B = name_A.replace('_A.', '_B.') else: name_B = name_A path_B = os.path.join(img_fold_B, name_B) if os.path.isfile(path_A) and os.path.isfile(path_B): name_AB = name_A if args.use_AB: name_AB = name_AB.replace('_A.', '.') # remove _A path_AB = os.path.join(img_fold_AB, name_AB) if not args.no_multiprocessing: pool.apply_async(image_write, args=(path_A, path_B, path_AB)) else: im_A = cv2.imread(path_A, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR im_B = cv2.imread(path_B, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR im_AB = np.concatenate([im_A, im_B], 1) cv2.imwrite(path_AB, im_AB) if not args.no_multiprocessing: pool.close() pool.join()
3,002
43.161765
181
py
cycle-transformer
cycle-transformer-main/datasets/prepare_cityscapes_dataset.py
import os import glob from PIL import Image help_msg = """ The dataset can be downloaded from https://cityscapes-dataset.com. Please download the datasets [gtFine_trainvaltest.zip] and [leftImg8bit_trainvaltest.zip] and unzip them. gtFine contains the semantics segmentations. Use --gtFine_dir to specify the path to the unzipped gtFine_trainvaltest directory. leftImg8bit contains the dashcam photographs. Use --leftImg8bit_dir to specify the path to the unzipped leftImg8bit_trainvaltest directory. The processed images will be placed at --output_dir. Example usage: python prepare_cityscapes_dataset.py --gitFine_dir ./gtFine/ --leftImg8bit_dir ./leftImg8bit --output_dir ./datasets/cityscapes/ """ def load_resized_img(path): return Image.open(path).convert('RGB').resize((256, 256)) def check_matching_pair(segmap_path, photo_path): segmap_identifier = os.path.basename(segmap_path).replace('_gtFine_color', '') photo_identifier = os.path.basename(photo_path).replace('_leftImg8bit', '') assert segmap_identifier == photo_identifier, \ "[%s] and [%s] don't seem to be matching. Aborting." % (segmap_path, photo_path) def process_cityscapes(gtFine_dir, leftImg8bit_dir, output_dir, phase): save_phase = 'test' if phase == 'val' else 'train' savedir = os.path.join(output_dir, save_phase) os.makedirs(savedir, exist_ok=True) os.makedirs(savedir + 'A', exist_ok=True) os.makedirs(savedir + 'B', exist_ok=True) print("Directory structure prepared at %s" % output_dir) segmap_expr = os.path.join(gtFine_dir, phase) + "/*/*_color.png" segmap_paths = glob.glob(segmap_expr) segmap_paths = sorted(segmap_paths) photo_expr = os.path.join(leftImg8bit_dir, phase) + "/*/*_leftImg8bit.png" photo_paths = glob.glob(photo_expr) photo_paths = sorted(photo_paths) assert len(segmap_paths) == len(photo_paths), \ "%d images that match [%s], and %d images that match [%s]. Aborting." % (len(segmap_paths), segmap_expr, len(photo_paths), photo_expr) for i, (segmap_path, photo_path) in enumerate(zip(segmap_paths, photo_paths)): check_matching_pair(segmap_path, photo_path) segmap = load_resized_img(segmap_path) photo = load_resized_img(photo_path) # data for pix2pix where the two images are placed side-by-side sidebyside = Image.new('RGB', (512, 256)) sidebyside.paste(segmap, (256, 0)) sidebyside.paste(photo, (0, 0)) savepath = os.path.join(savedir, "%d.jpg" % i) sidebyside.save(savepath, format='JPEG', subsampling=0, quality=100) # data for cyclegan where the two images are stored at two distinct directories savepath = os.path.join(savedir + 'A', "%d_A.jpg" % i) photo.save(savepath, format='JPEG', subsampling=0, quality=100) savepath = os.path.join(savedir + 'B', "%d_B.jpg" % i) segmap.save(savepath, format='JPEG', subsampling=0, quality=100) if i % (len(segmap_paths) // 10) == 0: print("%d / %d: last image saved at %s, " % (i, len(segmap_paths), savepath)) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--gtFine_dir', type=str, required=True, help='Path to the Cityscapes gtFine directory.') parser.add_argument('--leftImg8bit_dir', type=str, required=True, help='Path to the Cityscapes leftImg8bit_trainvaltest directory.') parser.add_argument('--output_dir', type=str, required=True, default='./datasets/cityscapes', help='Directory the output images will be written to.') opt = parser.parse_args() print(help_msg) print('Preparing Cityscapes Dataset for val phase') process_cityscapes(opt.gtFine_dir, opt.leftImg8bit_dir, opt.output_dir, "val") print('Preparing Cityscapes Dataset for train phase') process_cityscapes(opt.gtFine_dir, opt.leftImg8bit_dir, opt.output_dir, "train") print('Done')
4,127
40.28
142
py
cycle-transformer
cycle-transformer-main/datasets/make_dataset_aligned.py
import os from PIL import Image def get_file_paths(folder): image_file_paths = [] for root, dirs, filenames in os.walk(folder): filenames = sorted(filenames) for filename in filenames: input_path = os.path.abspath(root) file_path = os.path.join(input_path, filename) if filename.endswith('.png') or filename.endswith('.jpg'): image_file_paths.append(file_path) break # prevent descending into subfolders return image_file_paths def align_images(a_file_paths, b_file_paths, target_path): if not os.path.exists(target_path): os.makedirs(target_path) for i in range(len(a_file_paths)): img_a = Image.open(a_file_paths[i]) img_b = Image.open(b_file_paths[i]) assert(img_a.size == img_b.size) aligned_image = Image.new("RGB", (img_a.size[0] * 2, img_a.size[1])) aligned_image.paste(img_a, (0, 0)) aligned_image.paste(img_b, (img_a.size[0], 0)) aligned_image.save(os.path.join(target_path, '{:04d}.jpg'.format(i))) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument( '--dataset-path', dest='dataset_path', help='Which folder to process (it should have subfolders testA, testB, trainA and trainB' ) args = parser.parse_args() dataset_folder = args.dataset_path print(dataset_folder) test_a_path = os.path.join(dataset_folder, 'testA') test_b_path = os.path.join(dataset_folder, 'testB') test_a_file_paths = get_file_paths(test_a_path) test_b_file_paths = get_file_paths(test_b_path) assert(len(test_a_file_paths) == len(test_b_file_paths)) test_path = os.path.join(dataset_folder, 'test') train_a_path = os.path.join(dataset_folder, 'trainA') train_b_path = os.path.join(dataset_folder, 'trainB') train_a_file_paths = get_file_paths(train_a_path) train_b_file_paths = get_file_paths(train_b_path) assert(len(train_a_file_paths) == len(train_b_file_paths)) train_path = os.path.join(dataset_folder, 'train') align_images(test_a_file_paths, test_b_file_paths, test_path) align_images(train_a_file_paths, train_b_file_paths, train_path)
2,257
34.28125
97
py
cycle-transformer
cycle-transformer-main/data/colorization_dataset.py
import os from data.base_dataset import BaseDataset, get_transform from data import make_dataset from skimage import color # require skimage from PIL import Image import numpy as np import torchvision.transforms as transforms class ColorizationDataset(BaseDataset): """This dataset class can load a set of natural images in RGB, and convert RGB format into (L, ab) pairs in Lab color space. This dataset is required by pix2pix-based colorization model ('--model colorization') """ @staticmethod def modify_commandline_options(parser, is_train): """Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser. By default, the number of channels for input image is 1 (L) and the number of channels for output image is 2 (ab). The direction is from A to B """ parser.set_defaults(input_nc=1, output_nc=2, direction='AtoB') return parser def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseDataset.__init__(self, opt) self.dir = os.path.join(opt.dataroot, opt.phase) self.AB_paths = sorted(make_dataset(self.dir, opt.max_dataset_size)) assert(opt.input_nc == 1 and opt.output_nc == 2 and opt.direction == 'AtoB') self.transform = get_transform(self.opt, convert=False) def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index - - a random integer for data indexing Returns a dictionary that contains A, B, A_paths and B_paths A (tensor) - - the L channel of an image B (tensor) - - the ab channels of the same image A_paths (str) - - image paths B_paths (str) - - image paths (same as A_paths) """ path = self.AB_paths[index] im = Image.open(path).convert('RGB') im = self.transform(im) im = np.array(im) lab = color.rgb2lab(im).astype(np.float32) lab_t = transforms.ToTensor()(lab) A = lab_t[[0], ...] / 50.0 - 1.0 B = lab_t[[1, 2], ...] / 110.0 return {'A': A, 'B': B, 'A_paths': path, 'B_paths': path} def __len__(self): """Return the total number of images in the dataset.""" return len(self.AB_paths)
2,704
38.202899
141
py
cycle-transformer
cycle-transformer-main/data/base_dataset.py
"""This module implements an abstract base class (ABC) 'BaseDataset' for datasets. It also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses. """ import random import numpy as np import torch.utils.data as data from PIL import Image import torchvision.transforms as transforms from abc import ABC, abstractmethod class BaseDataset(data.Dataset, ABC): """This class is an abstract base class (ABC) for datasets. To create a subclass, you need to implement the following four functions: -- <__init__>: initialize the class, first call BaseDataset.__init__(self, opt). -- <__len__>: return the size of dataset. -- <__getitem__>: get a data point. -- <modify_commandline_options>: (optionally) add dataset-specific options and set default options. """ def __init__(self, opt): """Initialize the class; save the options in the class Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions """ self.opt = opt self.root = opt.dataroot @staticmethod def modify_commandline_options(parser, is_train): """Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser. """ return parser @abstractmethod def __len__(self): """Return the total number of images in the dataset.""" return 0 @abstractmethod def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index - - a random integer for data indexing Returns: a dictionary of data with their names. It ususally contains the data itself and its metadata information. """ pass def get_params(opt, size): w, h = size new_h = h new_w = w if opt.preprocess == 'resize_and_crop': new_h = new_w = opt.load_size elif opt.preprocess == 'scale_width_and_crop': new_w = opt.load_size new_h = opt.load_size * h // w x = random.randint(0, np.maximum(0, new_w - opt.crop_size)) y = random.randint(0, np.maximum(0, new_h - opt.crop_size)) flip = random.random() > 0.5 return {'crop_pos': (x, y), 'flip': flip} def get_transform(opt, params=None, grayscale=False, method=Image.BICUBIC, convert=True): transform_list = [] if grayscale: transform_list.append(transforms.Grayscale(1)) if 'resize' in opt.preprocess: osize = [opt.load_size, opt.load_size] transform_list.append(transforms.Resize(osize, method)) elif 'scale_width' in opt.preprocess: transform_list.append(transforms.Lambda(lambda img: __scale_width(img, opt.load_size, opt.crop_size, method))) if 'crop' in opt.preprocess: if params is None: transform_list.append(transforms.RandomCrop(opt.crop_size)) else: transform_list.append(transforms.Lambda(lambda img: __crop(img, params['crop_pos'], opt.crop_size))) if opt.preprocess == 'none': transform_list.append(transforms.Lambda(lambda img: __make_power_2(img, base=4, method=method))) if not opt.no_flip: if params is None: transform_list.append(transforms.RandomHorizontalFlip()) elif params['flip']: transform_list.append(transforms.Lambda(lambda img: __flip(img, params['flip']))) if convert: transform_list += [transforms.ToTensor()] if grayscale: transform_list += [transforms.Normalize((0.5,), (0.5,))] else: transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))] return transforms.Compose(transform_list) def __make_power_2(img, base, method=Image.BICUBIC): ow, oh = img.size h = int(round(oh / base) * base) w = int(round(ow / base) * base) if h == oh and w == ow: return img __print_size_warning(ow, oh, w, h) return img.resize((w, h), method) def __scale_width(img, target_size, crop_size, method=Image.BICUBIC): ow, oh = img.size if ow == target_size and oh >= crop_size: return img w = target_size h = int(max(target_size * oh / ow, crop_size)) return img.resize((w, h), method) def __crop(img, pos, size): ow, oh = img.size x1, y1 = pos tw = th = size if (ow > tw or oh > th): return img.crop((x1, y1, x1 + tw, y1 + th)) return img def __flip(img, flip): if flip: return img.transpose(Image.FLIP_LEFT_RIGHT) return img def __print_size_warning(ow, oh, w, h): """Print warning information about image size(only print once)""" if not hasattr(__print_size_warning, 'has_printed'): print("The image size needs to be a multiple of 4. " "The loaded image size was (%d, %d), so it was adjusted to " "(%d, %d). This adjustment will be done to all images " "whose sizes are not multiples of 4" % (ow, oh, w, h)) __print_size_warning.has_printed = True
5,400
33.183544
141
py
cycle-transformer
cycle-transformer-main/data/unaligned_dataset.py
import os from data.base_dataset import BaseDataset, get_transform from data import make_dataset from PIL import Image import random class UnalignedDataset(BaseDataset): """ This dataset class can load unaligned/unpaired datasets. It requires two directories to host training images from domain A '/path/to/data/trainA' and from domain B '/path/to/data/trainB' respectively. You can train the model with the dataset flag '--dataroot /path/to/data'. Similarly, you need to prepare two directories: '/path/to/data/testA' and '/path/to/data/testB' during test time. """ def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseDataset.__init__(self, opt) self.dir_A = os.path.join(opt.dataroot, opt.phase + 'A') # create a path '/path/to/data/trainA' self.dir_B = os.path.join(opt.dataroot, opt.phase + 'B') # create a path '/path/to/data/trainB' self.A_paths = sorted(make_dataset(self.dir_A, opt.max_dataset_size)) # load images from '/path/to/data/trainA' self.B_paths = sorted(make_dataset(self.dir_B, opt.max_dataset_size)) # load images from '/path/to/data/trainB' self.A_size = len(self.A_paths) # get the size of dataset A self.B_size = len(self.B_paths) # get the size of dataset B btoA = self.opt.direction == 'BtoA' input_nc = self.opt.output_nc if btoA else self.opt.input_nc # get the number of channels of input image output_nc = self.opt.input_nc if btoA else self.opt.output_nc # get the number of channels of output image self.transform_A = get_transform(self.opt, grayscale=(input_nc == 1)) self.transform_B = get_transform(self.opt, grayscale=(output_nc == 1)) def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index (int) -- a random integer for data indexing Returns a dictionary that contains A, B, A_paths and B_paths A (tensor) -- an image in the input domain B (tensor) -- its corresponding image in the target domain A_paths (str) -- image paths B_paths (str) -- image paths """ A_path = self.A_paths[index % self.A_size] # make sure index is within then range if self.opt.serial_batches: # make sure index is within then range index_B = index % self.B_size else: # randomize the index for domain B to avoid fixed pairs. index_B = random.randint(0, self.B_size - 1) B_path = self.B_paths[index_B] A_img = Image.open(A_path).convert('RGB') B_img = Image.open(B_path).convert('RGB') # apply image transformation A = self.transform_A(A_img) B = self.transform_B(B_img) return {'A': A, 'B': B, 'A_paths': A_path, 'B_paths': B_path} def __len__(self): """Return the total number of images in the dataset. As we have two datasets with potentially different number of images, we take a maximum of """ return max(self.A_size, self.B_size)
3,286
44.652778
122
py
cycle-transformer
cycle-transformer-main/data/ct_dataset.py
# This code is released under the CC BY-SA 4.0 license. import pickle import numpy as np import pydicom from data.base_dataset import BaseDataset class CTDataset(BaseDataset): def __init__(self, opt): BaseDataset.__init__(self, opt) self.raw_data = pickle.load(open(opt.dataroot, "rb")) self.labels = None self.Aclass = opt.Aclass self.Bclass = opt.Bclass self._make_dataset() def _make_dataset(self): data = [] for entity in self.raw_data: if entity in self.Aclass: data += self.raw_data[entity] self.raw_data = data def __getitem__(self, index): # Image from A A_image = pydicom.dcmread(self.raw_data[index]).pixel_array A_image[A_image < 0] = 0 A_image = A_image / 1e3 A_image = A_image - 1 A_image = np.expand_dims(A_image, 0).astype(np.float) # Paired image from B path = self.raw_data[index].replace(self.Aclass, self.Bclass) B_image = pydicom.dcmread(path).pixel_array B_image[B_image < 0] = 0 B_image = B_image / 1e3 B_image = B_image - 1 B_image = np.expand_dims(B_image, 0).astype(np.float) return {'A': A_image, 'B': B_image} def __len__(self): return len(self.raw_data)
1,330
26.163265
69
py
cycle-transformer
cycle-transformer-main/data/image_folder.py
"""A modified image folder class We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py) so that this class can load images from both current directory and its subdirectories. """ import torch.utils.data as data from PIL import Image import os IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', '.tif', '.TIF', '.tiff', '.TIFF', ] def is_image_file(filename): return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) def make_dataset(dir, max_dataset_size=float("inf")): images = [] assert os.path.isdir(dir), '%s is not a valid directory' % dir for root, _, fnames in sorted(os.walk(dir)): for fname in fnames: if is_image_file(fname): path = os.path.join(root, fname) images.append(path) return images[:min(max_dataset_size, len(images))] def default_loader(path): return Image.open(path).convert('RGB') class ImageFolder(data.Dataset): def __init__(self, root, transform=None, return_paths=False, loader=default_loader): imgs = make_dataset(root) if len(imgs) == 0: raise(RuntimeError("Found 0 images in: " + root + "\n" "Supported image extensions are: " + ",".join(IMG_EXTENSIONS))) self.root = root self.imgs = imgs self.transform = transform self.return_paths = return_paths self.loader = loader def __getitem__(self, index): path = self.imgs[index] img = self.loader(path) if self.transform is not None: img = self.transform(img) if self.return_paths: return img, path else: return img def __len__(self): return len(self.imgs)
1,885
27.575758
122
py
cycle-transformer
cycle-transformer-main/data/aligned_dataset.py
import os from data.base_dataset import BaseDataset, get_params, get_transform from data import make_dataset from PIL import Image class AlignedDataset(BaseDataset): """A dataset class for paired image dataset. It assumes that the directory '/path/to/data/train' contains image pairs in the form of {A,B}. During test time, you need to prepare a directory '/path/to/data/test'. """ def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseDataset.__init__(self, opt) self.dir_AB = os.path.join(opt.dataroot, opt.phase) # get the image directory self.AB_paths = sorted(make_dataset(self.dir_AB, opt.max_dataset_size)) # get image paths assert(self.opt.load_size >= self.opt.crop_size) # crop_size should be smaller than the size of loaded image self.input_nc = self.opt.output_nc if self.opt.direction == 'BtoA' else self.opt.input_nc self.output_nc = self.opt.input_nc if self.opt.direction == 'BtoA' else self.opt.output_nc def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index - - a random integer for data indexing Returns a dictionary that contains A, B, A_paths and B_paths A (tensor) - - an image in the input domain B (tensor) - - its corresponding image in the target domain A_paths (str) - - image paths B_paths (str) - - image paths (same as A_paths) """ # read a image given a random integer index AB_path = self.AB_paths[index] AB = Image.open(AB_path).convert('RGB') # split AB image into A and B w, h = AB.size w2 = int(w / 2) A = AB.crop((0, 0, w2, h)) B = AB.crop((w2, 0, w, h)) # apply the same transform to both A and B transform_params = get_params(self.opt, A.size) A_transform = get_transform(self.opt, transform_params, grayscale=(self.input_nc == 1)) B_transform = get_transform(self.opt, transform_params, grayscale=(self.output_nc == 1)) A = A_transform(A) B = B_transform(B) return {'A': A, 'B': B} def __len__(self): """Return the total number of images in the dataset.""" return len(self.AB_paths)
2,444
39.081967
118
py
cycle-transformer
cycle-transformer-main/data/__init__.py
"""This package includes all the modules related to data loading and preprocessing To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset. You need to implement four functions: -- <__init__>: initialize the class, first call BaseDataset.__init__(self, opt). -- <__len__>: return the size of dataset. -- <__getitem__>: get a data point from data loader. -- <modify_commandline_options>: (optionally) add dataset-specific options and set default options. Now you can use the dataset class by specifying flag '--dataset_mode dummy'. See our template dataset class 'template_dataset.py' for more details. """ import importlib import torch.utils.data from data.base_dataset import BaseDataset def find_dataset_using_name(dataset_name): """Import the module "data/[dataset_name]_dataset.py". In the file, the class called DatasetNameDataset() will be instantiated. It has to be a subclass of BaseDataset, and it is case-insensitive. """ dataset_filename = "pix2pix.data." + dataset_name + "_dataset" datasetlib = importlib.import_module(dataset_filename) dataset = None target_dataset_name = dataset_name.replace('_', '') + 'dataset' for name, cls in datasetlib.__dict__.items(): if name.lower() == target_dataset_name.lower() \ and issubclass(cls, BaseDataset): dataset = cls if dataset is None: raise NotImplementedError("In %s.py, there should be a subclass of BaseDataset with class name that matches %s in lowercase." % (dataset_filename, target_dataset_name)) return dataset def get_option_setter(dataset_name): """Return the static method <modify_commandline_options> of the dataset class.""" dataset_class = find_dataset_using_name(dataset_name) return dataset_class.modify_commandline_options def create_dataset(opt): data_loader = CustomDatasetDataLoader(opt) dataset = data_loader.load_data() return dataset class CustomDatasetDataLoader: """Wrapper class of Dataset class that performs multi-threaded data loading""" def __init__(self, opt): """Initialize this class Step 1: create a dataset instance given the name [dataset_mode] Step 2: create a multi-threaded data loader. """ self.opt = opt dataset_class = find_dataset_using_name(opt.dataset_mode) self.dataset = dataset_class(opt) print("dataset [%s] was created" % type(self.dataset).__name__) self.dataloader = torch.utils.data.DataLoader( self.dataset, batch_size=opt.batch_size, shuffle=not opt.serial_batches, num_workers=int(opt.num_threads)) def load_data(self): return self def __len__(self): """Return the number of data in the dataset""" return min(len(self.dataset), self.opt.max_dataset_size) def __iter__(self): """Return a batch of data""" for i, data in enumerate(self.dataloader): if i * self.opt.batch_size >= self.opt.max_dataset_size: break yield data
3,270
37.034884
176
py
cycle-transformer
cycle-transformer-main/data/template_dataset.py
from data.base_dataset import BaseDataset, get_transform # from data.image_folder import make_dataset # from PIL import Image class TemplateDataset(BaseDataset): """A template dataset class for you to implement custom datasets.""" @staticmethod def modify_commandline_options(parser, is_train): """Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser. """ parser.add_argument('--new_dataset_option', type=float, default=1.0, help='new dataset option') parser.set_defaults(max_dataset_size=10, new_dataset_option=2.0) # specify dataset-specific default values return parser def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions A few things can be done here. - save the options (have been done in BaseDataset) - get image paths and meta information of the dataset. - define the image transformation. """ # save the option and dataset root BaseDataset.__init__(self, opt) # get the image paths of your dataset; self.image_paths = [] # You can call sorted(make_dataset(self.root, opt.max_dataset_size)) to get all the image paths under the directory self.root # define the default transform function. You can use <base_dataset.get_transform>; You can also define your custom transform function self.transform = get_transform(opt) def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index -- a random integer for data indexing Returns: a dictionary of data with their names. It usually contains the data itself and its metadata information. Step 1: get a random image path: e.g., path = self.image_paths[index] Step 2: load your data from the disk: e.g., image = Image.open(path).convert('RGB'). Step 3: convert your data to a PyTorch tensor. You can use helpder functions such as self.transform. e.g., data = self.transform(image) Step 4: return a data point as a dictionary. """ path = 'temp' # needs to be a string data_A = None # needs to be a tensor data_B = None # needs to be a tensor return {'data_A': data_A, 'data_B': data_B, 'path': path} def __len__(self): """Return the total number of images.""" return len(self.image_paths)
2,822
43.809524
156
py
cycle-transformer
cycle-transformer-main/data/single_dataset.py
from data.base_dataset import BaseDataset, get_transform from data import make_dataset from PIL import Image class SingleDataset(BaseDataset): """This dataset class can load a set of images specified by the path --dataroot /path/to/data. It can be used for generating CycleGAN results only for one side with the model option '-model test'. """ def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseDataset.__init__(self, opt) self.A_paths = sorted(make_dataset(opt.dataroot, opt.max_dataset_size)) input_nc = self.opt.output_nc if self.opt.direction == 'BtoA' else self.opt.input_nc self.transform = get_transform(opt, grayscale=(input_nc == 1)) def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index - - a random integer for data indexing Returns a dictionary that contains A and A_paths A(tensor) - - an image in one domain A_paths(str) - - the path of the image """ A_path = self.A_paths[index] A_img = Image.open(A_path).convert('RGB') A = self.transform(A_img) return {'A': A, 'A_paths': A_path} def __len__(self): """Return the total number of images in the dataset.""" return len(self.A_paths)
1,482
35.170732
105
py
GreedyAC
GreedyAC-master/main.py
# Import modules import numpy as np import environment import experiment import pickle from utils import experiment_utils as exp_utils import click import json from copy import deepcopy import os import utils.hypers as hypers import socket @click.command(help="Run an experiment outlined by an algorithm and " + "environment configuration file") @click.option("--env-json", help="Path to the environment json " + "configuration file", type=str, required=True) @click.option("--agent-json", help="Path to the agent json configuration file", type=str, required=True) @click.option("--index", type=int, required=False, help="The index " + "of the hyperparameter to run", default=1) @click.option("--monitor", "-m", is_flag=True, help="Whether or not to " + "render the scene as the agent trains.", type=bool) @click.option("--after", "-a", type=int, default=-1, help="How many " + "timesteps (training) should pass before " + "rendering the scene") @click.option("--save-dir", type=str, default="./results", help="Which " + "directory to save the results file in", required=False) def run(env_json, agent_json, index, monitor, after, save_dir): """ Perform runs over hyperparameter settings. Performs the runs on the hyperparameter settings indices specified by range(start, stop step), with values over the total number of hyperparameters wrapping around to perform successive runs on the same hyperparameter settings. For example, if there are 10 hyperparameter settings and we run with hyperparameter settings 12, then this is the (12 // 10) = 1 run of hyperparameter settings 12 % 10 = 2, where runs are 0-based indexed. Parameters ---------- env_json : str The path to the JSON environment configuration file agent_json : str The path to the JSON agent configuration file start : int The hyperparameter index to start the sweep at stop : int The hyperparameter index to stop the sweep at step : int The stepping value between hyperparameter settings indices monitor : bool Whether or not to render the scene as the agent trains after : int How many training + evaluation timesteps should pass before rendering the scene save_dir : str The directory to save the data in """ # Read the config files with open(env_json) as in_json: env_config = json.load(in_json) with open(agent_json) as in_json: agent_config = json.load(in_json) main(agent_config, env_config, index, monitor, after, save_dir) def main(agent_config, env_config, index, monitor, after, save_dir="./results"): """ Runs experiments on the agent and environment corresponding the the input JSON files using the hyperparameter settings corresponding to the indices returned from range(start, stop, step). Saves a pickled python dictionary of all training and evaluation data. Note: this function will run the experiments sequentially. Parameters ---------- agent_json : dict The agent JSON configuration file, as a Python dict env_json : dict The environment JSON configuration file, as a Python dict index : int The index of the hyperparameter setting to run monitor : bool Whether to render the scene as the agent trains or not after : int How many training + evaluation timesteps should pass before rendering the scene save_dir : str The directory to save all data in """ # Create the data dictionary data = {} data["experiment"] = {} # Experiment meta-data data["experiment"]["environment"] = env_config data["experiment"]["agent"] = agent_config # Experiment runs per each hyperparameter data["experiment_data"] = {} # Calculate the number of timesteps before rendering. It is inputted as # number of training steps, but the environment uses training + eval steps if after >= 0: eval_steps = env_config["eval_episodes"] * \ env_config["steps_per_episode"] eval_intervals = 1 + (after // env_config["eval_interval_timesteps"]) after = after + eval_steps * eval_intervals print(f"Evaluation intervals before monitor: {eval_intervals}") # Get the directory to save in host = socket.gethostname() if not save_dir.startswith("./results"): save_dir = os.path.join("./results", save_dir) # If running on Compute Canada, then save in project directory if "computecanada" in host.lower(): home = os.path.expanduser("~") save_dir = os.path.join(f"{home}/project/def-whitem/sfneuman/" + "CEM-PyTorch", save_dir[2:]) # Append name of environment and agent to the save directory save_dir = os.path.join(save_dir, env_config["env_name"] + "_" + agent_config["agent_name"] + "results/") # Run the experiments # Get agent params from config file for the next experiment agent_run_params, total_sweeps = hypers.sweeps( agent_config["parameters"], index) agent_run_params["gamma"] = env_config["gamma"] print(f"Total number of hyperparam combinations: {total_sweeps}") # Calculate the run number and the random seed RUN_NUM = index // total_sweeps RANDOM_SEED = np.iinfo(np.int16).max - RUN_NUM # Create the environment env_config["seed"] = RANDOM_SEED if agent_config["agent_name"] == "linearAC" or \ agent_config["agent_name"] == "linearAC_softmax": if "use_tile_coding" in env_config: use_tile_coding = env_config["use_tile_coding"] env_config["use_full_tile_coding"] = use_tile_coding del env_config["use_tile_coding"] env = environment.Environment(env_config, RANDOM_SEED, monitor, after) eval_env = environment.Environment(env_config, RANDOM_SEED) num_features = env.observation_space.shape[0] agent_run_params["feature_size"] = num_features # Set up the data dictionary to store the data from each run hp_sweep = index % total_sweeps if hp_sweep not in data["experiment_data"].keys(): data["experiment_data"][hp_sweep] = {} data["experiment_data"][hp_sweep]["agent_hyperparams"] = \ dict(agent_run_params) data["experiment_data"][hp_sweep]["runs"] = [] SETTING_NUM = index % total_sweeps TOTAL_TIMESTEPS = env_config["total_timesteps"] MAX_EPISODES = env_config.get("max_episodes", -1) EVAL_INTERVAL = env_config["eval_interval_timesteps"] EVAL_EPISODES = env_config["eval_episodes"] # Store the seed in the agent run parameters so that batch algorithms # can sample randomly agent_run_params["seed"] = RANDOM_SEED # Include the environment observation and action spaces in the agent's # configuration so that neural networks can have the corrent number of # output nodes agent_run_params["observation_space"] = env.observation_space agent_run_params["action_space"] = env.action_space # Saving this data is redundant since we save the env_config file as # well. Also, each run has the run number as the random seed run_data = {} run_data["run_number"] = RUN_NUM run_data["random_seed"] = RANDOM_SEED run_data["total_timesteps"] = TOTAL_TIMESTEPS run_data["eval_interval_timesteps"] = EVAL_INTERVAL run_data["episodes_per_eval"] = EVAL_EPISODES # Print some data about the run print(f"SETTING_NUM: {SETTING_NUM}") print(f"RUN_NUM: {RUN_NUM}") print(f"RANDOM_SEED: {RANDOM_SEED}") print('Agent setting: ', agent_run_params) # Create the agent print(agent_config["agent_name"]) agent_run_params["env"] = env agent = exp_utils.create_agent(agent_config["agent_name"], agent_run_params) # Initialize and run experiment exp = experiment.Experiment( agent, env, eval_env, EVAL_EPISODES, TOTAL_TIMESTEPS, EVAL_INTERVAL, MAX_EPISODES, ) exp.run() # Save the agent's learned parameters, with these parameters and the # hyperparams, training can be exactly resumed from the end of the run run_data["learned_params"] = agent.get_parameters() # Save any information the agent saved during training run_data = {**run_data, **agent.info, **exp.info, **env.info} # Save data in parent dictionary data["experiment_data"][hp_sweep]["runs"].append(run_data) # After each run, save the data. Since data is accumulated, the # later runs will overwrite earlier runs with updated data. if not os.path.exists(save_dir): os.makedirs(save_dir) save_file = save_dir + env_config["env_name"] + "_" + \ agent_config["agent_name"] + f"_data_{index}.pkl" print("=== Saving ===") print(save_file) print("==============") with open(save_file, "wb") as out_file: pickle.dump(data, out_file) if __name__ == "__main__": run()
9,203
36.721311
79
py
GreedyAC
GreedyAC-master/environment.py
# Import modules import gym from copy import deepcopy from env.PendulumEnv import PendulumEnv from env.Acrobot import AcrobotEnv import env.MinAtar as MinAtar import numpy as np class Environment: """ Class Environment is a wrapper around OpenAI Gym environments, to ensure logging can be done as well as to ensure that we can restrict the episode time steps. """ def __init__(self, config, seed, monitor=False, monitor_after=0): """ Constructor Parameters ---------- config : dict The environment configuration file seed : int The seed to use for all random number generators monitor : bool Whether or not to render the scenes as the agent learns, by default False monitor_after : int If monitor is True, how many timesteps should pass before the scene is rendered, by default 0. """ # Overwrite rewards and start state if necessary self.overwrite_rewards = config["overwrite_rewards"] self.rewards = config["rewards"] self.start_state = np.array(config["start_state"]) self.steps = 0 self.episodes = 0 # Keep track of monitoring self.monitor = monitor self.steps_until_monitor = monitor_after self.env_name = config["env_name"] self.env = env_factory(config) print("Seeding environment:", seed) self.env.seed(seed=seed) self.steps_per_episode = config["steps_per_episode"] # Increase the episode steps of the wrapped OpenAI gym environment so # that this wrapper will timeout before the OpenAI gym one does self.env._max_episode_steps = self.steps_per_episode + 10 if "info" in dir(self.env): self.info = self.env.info else: self.info = {} @property def action_space(self): """ Gets the action space of the Gym environment Returns ------- gym.spaces.Space The action space """ return self.env.action_space @property def observation_space(self): """ Gets the observation space of the Gym environment Returns ------- gym.spaces.Space The observation space """ return self.env.observation_space def seed(self, seed): """ Seeds the environment with a random seed Parameters ---------- seed : int The random seed to seed the environment with """ self.env.seed(seed) def reset(self): """ Resets the environment by resetting the step counter to 0 and resetting the wrapped environment. This function also increments the total episode count. Returns ------- 2-tuple of array_like, dict The new starting state and an info dictionary """ self.steps = 0 self.episodes += 1 state = self.env.reset() # If the user has inputted a fixed start state, use that instead if self.start_state.shape[0] != 0: state = self.start_state self.env.state = state return state, {"orig_state": state} def render(self): """ Renders the current frame """ self.env.render() def step(self, action): """ Takes a single environmental step Parameters ---------- action : array_like of float The action array. The number of elements in this array should be the same as the action dimension. Returns ------- float, array_like of float, bool, dict The reward and next state as well as a flag specifying if the current episode has been completed and an info dictionary """ if self.monitor and self.steps_until_monitor < 0: self.render() self.steps += 1 self.steps_until_monitor -= (1 if self.steps_until_monitor >= 0 else 0) # Get the next state, reward, and done flag state, reward, done, info = self.env.step(action) info["orig_state"] = state # If the episode completes, return the goal reward if done: info["steps_exceeded"] = False if self.overwrite_rewards: reward = self.rewards["goal"] return state, reward, done, info # If the user has set rewards per timestep if self.overwrite_rewards: reward = self.rewards["timestep"] # If the maximum time-step was reached if self.steps >= self.steps_per_episode > 0: done = True info["steps_exceeded"] = True return state, reward, done, info def env_factory(config): """ Instantiates and returns an environment given an environment name. Parameters ---------- config : dict The environment config Returns ------- gym.Env The environment to train on """ name = config["env_name"] seed = config["seed"] env = None if name == "Pendulum-v0": env = PendulumEnv(seed=seed, continuous_action=config["continuous"]) elif name == "PendulumPenalty-v0": env = pp.PendulumEnv(seed=seed, continuous_action=config["continuous"]) elif name == "PositivePendulumPenalty-v0": env = ppp.PendulumEnv(seed=seed, continuous_action=config["continuous"]) elif name == "PendulumNoShaped-v0": env = pens.PendulumEnv(seed=seed, continuous_action=config["continuous"]) elif name == "PendulumNoShapedPenalty-v0": env = pensp.PendulumEnv(seed=seed, continuous_action=config["continuous"]) elif name == "MountainCarShaped": env = mcs.MountainCar() elif name == "Bimodal" or name == "Bimodal": reward_variance = config.get("reward_variance", True) env = Bimodal(seed, reward_variance) elif name == "Bandit": n_actions = config.get("n_action", 10) env = Bandit(seed, n_actions) elif name == "ContinuousCartpole-v0": env = ContinuousCartPoleEnv() elif name == "IndexGridworld": env = IndexGridworldEnv(config["rows"], config["cols"]) env.seed(seed) elif name == "XYGridworld": env = XYGridworldEnv(config["rows"], config["cols"]) env.seed(seed) elif name == "Gridworld": env = GridworldEnv(config["rows"], config["cols"]) env.seed(seed) elif name == "PuddleWorld-v1": env = PuddleWorldEnv(continuous=config["continuous"], seed=seed) elif name == "Acrobot-v1": env = AcrobotEnv(seed=seed, continuous_action=config["continuous"]) elif name == "CGW": env = CGW.GridWorld() elif name == "ContinuousGridWorld": env = ContinuousGridWorld.GridWorld() elif "minatar" in name.lower(): if "/" in name: raise ValueError(f"specify environment as MinAtar{name} rather " + "than MinAtar/{name}") minimal_actions = config.get("use_minimal_action_set", True) stripped_name = name[7:].lower() # Strip off "MinAtar" env = MinAtar.GymEnv( stripped_name, use_minimal_action_set=minimal_actions, ) else: # Ensure we use the base gym environment. `gym.make` returns a TimeStep # environment wrapper, but we want the underlying environment alone. env = gym.make(name).env env.seed(seed) print(config) return env
7,743
28.444867
79
py
GreedyAC
GreedyAC-master/experiment.py
#!/usr/bin/env python3 # Import modules import time from datetime import datetime from copy import deepcopy import numpy as np class Experiment: """ Class Experiment will run a single experiment, which consists of a single run of agent-environment interaction. """ def __init__(self, agent, env, eval_env, eval_episodes, total_timesteps, eval_interval_timesteps, max_episodes=-1): """ Constructor Parameters ---------- agent : baseAgent.BaseAgent The agent to run the experiment on env : environment.Environment The environment to use for the experiment eval_env : environment.Environment The environment to use for offline evaluation eval_episodes : int The number of evaluation episodes to run when measuring offline performance total_timesteps : int The maximum number of allowable timesteps per experiment eval_interval_timesteps: int The interval of timesteps at which an agent's performance will be evaluated max_episodes : int The maximum number of episodes to run. If <= 0, then there is no episode limit. """ self.agent = agent self.env = env self.eval_env = eval_env self.eval_env.monitor = False self.eval_episodes = eval_episodes self.max_episodes = max_episodes # Track the number of time steps self.timesteps_since_last_eval = 0 self.eval_interval_timesteps = eval_interval_timesteps self.timesteps_elapsed = 0 self.total_timesteps = total_timesteps # Keep track of number of training episodes self.train_episodes = 0 # Track the returns seen at each training episode self.train_ep_return = [] # Track the steps per each training episode self.train_ep_steps = [] # Track the steps at which evaluation occurs self.timesteps_at_eval = [] # Track the returns seen at each eval episode self.eval_ep_return = [] # Track the number of evaluation steps taken in each evaluation episode self.eval_ep_steps = [] # Anything the experiment tracks self.info = {} # Track the total training and evaluation time self.train_time = 0.0 self.eval_time = 0.0 def run(self): """ Runs the experiment """ # Count total run time start_run = time.time() print(f"Starting experiment at: {datetime.now()}") # Evaluate once at the beginning self.eval_time += self.eval() self.timesteps_at_eval.append(self.timesteps_elapsed) # Train i = 0 while self.timesteps_elapsed < self.total_timesteps and \ (self.train_episodes < self.max_episodes if self.max_episodes > 0 else True): # Run the training episode and save the relevant info ep_reward, ep_steps, train_time = self.run_episode_train() self.train_ep_return.append(ep_reward) self.train_ep_steps.append(ep_steps) self.train_time += train_time print(f"=== Train ep: {i}, r: {ep_reward}, n_steps: {ep_steps}, " + f"elapsed: {train_time}") i += 1 # Evaluate once at the end self.eval_time += self.eval() self.timesteps_at_eval.append(self.timesteps_elapsed) end_run = time.time() print(f"End run at time {datetime.now()}") print(f"Total time taken: {end_run - start_run}") print(f"Training time: {self.train_time}") print(f"Evaluation time: {self.eval_time}") self.info["eval_episode_rewards"] = np.array(self.eval_ep_return) self.info["eval_episode_steps"] = np.array(self.eval_ep_steps) self.info["timesteps_at_eval"] = np.array(self.timesteps_at_eval) self.info["train_episode_steps"] = np.array(self.train_ep_steps) self.info["train_episode_rewards"] = np.array(self.train_ep_return) self.info["train_time"] = self.train_time self.info["eval_time"] = self.eval_time self.info["total_train_episodes"] = self.train_episodes def run_episode_train(self): """ Runs a single training episode, saving the evaluation metrics in the corresponding instance variables. Returns ------- float, int, float The return for the episode, the number of steps in the episode, and the total amount of training time for the episode """ # Reset the agent self.agent.reset() self.train_episodes += 1 # Track the sequences of states, rewards, and actions during training episode_rewards = [] start = time.time() episode_return = 0.0 episode_steps = 0 state, _ = self.env.reset() done = False action = self.agent.sample_action(state) while not done: # Evaluate offline at the appropriate intervals if self.timesteps_since_last_eval >= \ self.eval_interval_timesteps: self.eval_time += self.eval() self.timesteps_at_eval.append(self.timesteps_elapsed) # Sample the next transition next_state, reward, done, info = self.env.step(action) episode_steps += 1 episode_rewards.append(reward) episode_return += reward # Compute the done mask, which is 1 if the episode terminated # without the goal being reached or the episode is incomplete, # and 0 if the agent reached the goal or terminal state. When # bootstrapping with target value `target`, we'll use # `effective_target = done_mask * target`. For example, when # updating state-value function v(s) using gradient descent, we'll # use v(s) <- v(s) + α(r + done_mask * v(s') - v(s)) if self.env.steps_per_episode <= 1: # Bandit problem done_mask = 0 else: if episode_steps <= self.env.steps_per_episode and done and \ not info["steps_exceeded"]: done_mask = 0 else: done_mask = 1 # Update agent self.agent.update(state, action, reward, next_state, done_mask) # Continue the episode if not done if not done: action = self.agent.sample_action(next_state) state = next_state # Keep track of the timesteps since we last evaluated so we know # when to evaluate again self.timesteps_since_last_eval += 1 # Keep track of timesteps since we train for a specified number of # timesteps self.timesteps_elapsed += 1 # Stop if we are at the max allowable timesteps if self.timesteps_elapsed >= self.total_timesteps: break end = time.time() return episode_return, episode_steps, (end-start) def eval(self): """ Evaluates the agent's performance offline, for the appropriate number of offline episodes as determined by the self.eval_episodes instance variable. Returns ------- float The total amount of evaluation time """ self.timesteps_since_last_eval = 0 # Set the agent to evaluation mode self.agent.eval() # Save the episodic return and the number of steps per episode temp_rewards_per_episode = [] episode_steps = [] eval_session_time = 0.0 # Evaluate offline for i in range(self.eval_episodes): eval_start_time = time.time() episode_reward, num_steps = self.run_episode_eval() eval_end_time = time.time() # Save the evaluation data temp_rewards_per_episode.append(episode_reward) episode_steps.append(num_steps) # Calculate time eval_elapsed_time = eval_end_time - eval_start_time eval_session_time += eval_elapsed_time # Display the offline episodic return print("=== EVAL ep: " + str(i) + ", r: " + str(episode_reward) + ", n_steps: " + str(num_steps) + ", elapsed: " + time.strftime("%H:%M:%S", time.gmtime(eval_elapsed_time))) # Save evaluation data self.eval_ep_return.append(temp_rewards_per_episode) self.eval_ep_steps.append(episode_steps) self.eval_time += eval_session_time # Return the agent to training mode self.agent.train() return eval_session_time def run_episode_eval(self): """ Runs a single evaluation episode. Returns ------- float, int, list The episodic return and number of steps and the sequence of states, rewards, and actions during the episode """ state, _ = self.eval_env.reset() episode_return = 0.0 episode_steps = 0 done = False action = self.agent.sample_action(state) while not done: next_state, reward, done, _ = self.eval_env.step(action) episode_return += reward if not done: action = self.agent.sample_action(next_state) state = next_state episode_steps += 1 return episode_return, episode_steps
9,747
32.613793
79
py
GreedyAC
GreedyAC-master/combine.py
#!/usr/bin/env python3 import click import utils.experiment_utils as exp import utils.hypers as hypers import json import os import pickle import signal import shutil import sys from tqdm import tqdm signal.signal(signal.SIGINT, lambda: exit(0)) @click.command(help="Combine multiple data dictionaries into one") @click.argument("save_file", type=click.Path()) @click.argument("data_files", nargs=-1) def combine(save_file, data_files): if len(data_files) == 0: return # Create the save directory if it doesn't exist if os.path.dirname(save_file) != "" and not os.path.isdir( os.path.dirname(save_file)): os.makedirs(os.path.dirname(save_file)) if len(data_files) == 1: if os.path.isdir(data_files[0]): new_data_files = list( filter( lambda x: not x.startswith("."), os.listdir(data_files[0]), ) ) # Prepend the directory to the new data files dir_ = data_files[0] data_files = list( map( lambda x: os.path.join(dir_, x), new_data_files, ) ) else: # If only given a single data file, then we just copy it shutil.copy2(data_files[0], save_file) return # Read all input data dicts data = [] for file in tqdm(data_files): print(file) with open(file, "rb") as infile: try: data.append(pickle.load(infile)) except pickle.UnpicklingError: print("could not combine file:", file) # Get the configuration file # Remove the key `batch/replay` if present, since it is only used for # house-keeping when generating the hyper setting. The `batch` and `replay` # keys themselves will still exist in the config separately. config = data[0]["experiment"]["agent"] if "batch/replay" in config["parameters"]: del config["parameters"]["batch/replay"] # Combine all input data dicts new_data = hypers.combine(config, *data) # Write the new data file if os.path.isfile(save_file): print(f"file exists at {save_file}") print("Do you want to overwrite this file? (q/ctrl-c to cancel) ") overwrite = input() if overwrite.lower() == "q": exit(0) with open(save_file, "wb") as outfile: pickle.dump(new_data, outfile) if __name__ == "__main__": combine()
2,542
28.229885
79
py
GreedyAC
GreedyAC-master/env/PendulumEnv.py
#!/usr/bin/env python3 # Adapted from OpenAI Gym Pendulum-v0 # Import modules import gym from gym import spaces from gym.utils import seeding import numpy as np from os import path class PendulumEnv(gym.Env): """ PendulumEnv is a modified version of the Pendulum-v0 OpenAI Gym environment. In this version, the reward is the cosine of the angle between the pendulum and its fixed base. The angle is measured vertically so that if the pendulum stays straight up, the angle is 0 radians, and if the pendulum points straight down, then the angle is π raidans. Therefore, the agent will get reward cos(0) = 1 if the pendulum stays straight up and reward of cos(π) = -1 if the pendulum stays straight down. The goal is to have the pendulum stay straight up as long as possible. In this version of the Pendulum environment, state features may either be encoded as the cosine and sine of the pendulums angle with respect to it fixed base (reference axis vertical above the base) and the angular velocity, or as the angle itself and the angular velocity. If θ is the angle between the pendulum and the positive y-axis (axis straight up above the base) and ω is the angular velocity, then the states may be encoded as [cos(θ), sin(θ), ω] or as [θ, ω] depending on the argument trig_features to the constructor. The encoding [cos(θ), sin(θ), ω] is a somewhat easier problem, since cos(θ) is exactly the reward seen in that state. Let θ be the angle of the pendulum with respect to the vertical axis from the pendulum's base, ω be the angular velocity, and τ be the torque applied to the base. Then: 1. State features are vectors: [cos(θ), sin(θ), ω] if the self.trig_features variable is True, else [θ, ω] 2. Actions are 1-dimensional vectors that denote the torque applied to the pendulum's base: τ ∈ [-2, 2] 3. Reward is the cosine of the pendulum with respect to the fixed base, measured with respect to the vertical axis proceeding above the pendulum's base: cos(θ) 4. The start state is always with the pendulum horizontal, pointing to the right, with 0 angular velocity Note that this is a continuing task. """ metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 30 } def __init__(self, continuous_action=True, g=10.0, trig_features=False, seed=None): """ Constructor Parameters ---------- g : float, optional Gravity, by default 10.0 trig_features : bool Whether to use trigonometric encodings of features or to use the angle itself, by default False. If True, then state features are [cos(θ), sin(θ), ω], else state features are [θ, ω] (see class documentation) seed : int The seed with which to seed the environment, by default None """ self.max_speed = 8 self.max_torque = 2. self.dt = .05 self.g = g self.m = 1. self.length = 1. self.viewer = None self.continuous_action = continuous_action # Set the actions if self.continuous_action: self.action_space = spaces.Box( low=-self.max_torque, high=self.max_torque, shape=(1,), dtype=np.float32 ) else: self.action_space = spaces.Discrete(3) # Set the states self.trig_features = trig_features if trig_features: # Encode states as [cos(θ), sin(θ), ω] high = np.array([1., 1., self.max_speed], dtype=np.float32) self.observation_space = spaces.Box( low=-high, high=high, dtype=np.float32 ) else: # Encode states as [θ, ω] low = np.array([-np.pi, -self.max_speed], dtype=np.float32) high = np.array([np.pi, self.max_speed], dtype=np.float32) self.observation_space = spaces.Box( low=low, high=high, dtype=np.float32 ) self.seed(seed) def seed(self, seed=None): """ Sets the random seed for the environment Parameters ---------- seed : int, optional The random seed for the environment, by default None Returns ------- list The random seed """ self.np_random, seed = seeding.np_random(seed) return [seed] def step(self, u): """ Takes a single environmental step Parameters ---------- u : array_like of float The torque to apply to the base of the pendulum Returns ------- 3-tuple of array_like, float, bool, dict The state observation, the reward, the done flag (always False), and some info about the step """ th, thdot = self.state # th := theta g = self.g m = self.m length = self.length dt = self.dt if self.continuous_action: u = np.clip(u, -self.max_torque, self.max_torque)[0] else: assert self.action_space.contains(u), \ f"{action!r} ({type(action)}) invalid" u = (u - 1) * self.max_torque # [-max_torque, 0, max_torque] self.last_u = u # for rendering newthdot = thdot + (-3 * g / (2 * length) * np.sin(th + np.pi) + 3. / (m * length ** 2) * u) * dt newth = angle_normalize(th + newthdot * dt) newthdot = np.clip(newthdot, -self.max_speed, self.max_speed) self.state = np.array([newth, newthdot]) reward = np.cos(newth) if self.trig_features: # States are encoded as [cos(θ), sin(θ), ω] return self._get_obs(), reward, False, {} # States are encoded as [θ, ω] return self.state, reward, False, {} def reset(self): """ Resets the environment to its starting state Returns ------- array_like of float The starting state feature representation """ state = np.array([np.pi, 0.]) self.state = angle_normalize(state) # self.state = start self.last_u = None if self.trig_features: # States are encoded as [cos(θ), sin(θ), ω] return self._get_obs() # States are encoded as [θ, ω] return self.state def _get_obs(self): """ Creates and returns the state feature vector Returns ------- array_like of float The state feature vector """ theta, thetadot = self.state return np.array([np.cos(theta), np.sin(theta), thetadot]) def render(self, mode='human'): """ Renders the current time frame Parameters ---------- mode : str, optional Which mode to render in, by default 'human' Returns ------- array_like The image of the current time step """ if self.viewer is None: from gym.envs.classic_control import rendering self.viewer = rendering.Viewer(500, 500) self.viewer.set_bounds(-2.2, 2.2, -2.2, 2.2) rod = rendering.make_capsule(1, .2) rod.set_color(.8, .3, .3) self.pole_transform = rendering.Transform() rod.add_attr(self.pole_transform) self.viewer.add_geom(rod) axle = rendering.make_circle(.05) axle.set_color(0, 0, 0) self.viewer.add_geom(axle) fname = path.join(path.dirname(__file__), "assets/clockwise.png") self.img = rendering.Image(fname, 1., 1.) self.imgtrans = rendering.Transform() self.img.add_attr(self.imgtrans) self.viewer.add_onetime(self.img) self.pole_transform.set_rotation(self.state[0] + np.pi / 2) if self.last_u: self.imgtrans.scale = (-self.last_u / 2, np.abs(self.last_u) / 2) return self.viewer.render(return_rgb_array=mode == 'rgb_array') def close(self): """ Closes the viewer """ if self.viewer: self.viewer.close() self.viewer = None def angle_normalize(x): """ Normalizes the input angle to the range [-π, π] Parameters ---------- x : float The angle to normalize Returns ------- float The normalized angle """ # return x % (2 * np.pi) return (((x+np.pi) % (2*np.pi)) - np.pi)
8,838
31.377289
79
py
GreedyAC
GreedyAC-master/env/MinAtar.py
from copy import deepcopy import gym from gym import spaces from gym.envs import register import numpy as np from minatar import Environment class GymEnv(gym.Env): """ GymEnv wraps MinAtar environments to change their interface to the OpenAI Gym interface """ metadata = {"render.modes": ["human", "array"]} def __init__(self, game, display_time=50, use_minimal_action_set=True, **kwargs): self.game_name = game self.display_time = display_time self.game_kwargs = kwargs self.seed() if use_minimal_action_set: self._action_set = self.game.minimal_action_set() else: self._action_set = list(range(self.game.num_actions())) self._action_space = spaces.Discrete(len(self._action_set)) self._observation_space = spaces.Box( 0.0, 1.0, shape=self.game.state_shape(), dtype=bool ) @property def action_space(self): """ Gets the action space of the Gym environment Returns ------- gym.spaces.Space The action space """ return self._action_space @property def observation_space(self): """ Gets the observation space of the Gym environment Returns ------- gym.spaces.Space The observation space """ return self._observation_space def step(self, action): action = self._action_set[action] reward, done = self.game.act(action) return self.game.state(), reward, done, {} def reset(self): self.game.reset() return self.game.state() def seed(self, seed=None): self.game = Environment( env_name=self.game_name, random_seed=seed, **self.game_kwargs ) return seed def render(self, mode="human"): if mode == "array": return self.game.state() elif mode == "human": self.game.display_state(self.display_time) class BatchFirst(gym.Env): """ BatchFirst permutes the axes of state observations for MinAtar environments so that the batch dimension is first. """ def __init__(self, env): self.env = env # Adjust observation space obs = deepcopy(self.env.observation_space) low = obs.low low = np.moveaxis(low, (0, 1, 2), (2, 1, 0)) self._observation_space = spaces.Box( 0.0, 1.0, shape=low.shape, dtype=bool ) @property def action_space(self): """ Gets the action space of the Gym environment Returns ------- gym.spaces.Space The action space """ return self.env.action_space @property def observation_space(self): """ Gets the observation space of the Gym environment Returns ------- gym.spaces.Space The observation space """ return self._observation_space def seed(self, seed): """ Seeds the environment with a random seed Parameters ---------- seed : int The random seed to seed the environment with """ self.env.seed(seed) def reset(self): state = self.env.reset() state = np.moveaxis(state, (0, 1, 2), (2, 1, 0)) return state def step(self, action): state, reward, done, info = self.env.step(action) state = np.moveaxis(state, (0, 1, 2), (2, 1, 0)) print(state.shape) return state, reward, done, info def render(self, mode="human"): return self.env.render(mode)
3,720
23.320261
79
py
GreedyAC
GreedyAC-master/env/Acrobot.py
"""classic Acrobot task""" import numpy as np from numpy import sin, cos, pi from gym import spaces import gym # TODO: Redo documentation string for class class AcrobotEnv(gym.Env): """ Acrobot is a 2-link pendulum with only the second joint actuated. Initially, both links point downwards. The goal is to swing the end-effector at a height at least the length of one link above the base. Both links can swing freely and can pass by each other, i.e., they don't collide when they have the same angle. **STATE:** The state consists of the sin() and cos() of the two rotational joint angles and the joint angular velocities : [cos(theta1) sin(theta1) cos(theta2) sin(theta2) thetaDot1 thetaDot2]. For the first link, an angle of 0 corresponds to the link facing downwards. The angle of the second link is relative to the angle of the first link. An angle of 0 corresponds to having the same angle between the two links. A state of [1, 0, 1, 0, ..., ...] means that both links point downwards. **ACTIONS:** The action is either applying +1, 0 or -1 torque on the joint between the two pendulum links. .. note:: The dynamics equations were missing some terms in the NIPS paper which are present in the book. R. Sutton confirmed in personal correspondence that the experimental results shown in the paper and the book were generated with the equations shown in the book. However, there is the option to run the domain with the paper equations by setting book_or_nips = 'nips' **REFERENCE:** .. seealso:: R. Sutton: Generalization in Reinforcement Learning: Successful Examples Using Sparse Coarse Coding (NIPS 1996) .. seealso:: R. Sutton and A. G. Barto: Reinforcement learning: An introduction. Cambridge: MIT press, 1998. .. warning:: This version of the domain uses the Runge-Kutta method for integrating the system dynamics and is more realistic, but also considerably harder than the original version which employs Euler integration. """ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 15} dt = 0.2 LINK_LENGTH_1 = 1.0 # [m] LINK_LENGTH_2 = 1.0 # [m] LINK_MASS_1 = 1.0 #: [kg] mass of link 1 LINK_MASS_2 = 1.0 #: [kg] mass of link 2 LINK_COM_POS_1 = 0.5 #: [m] position of the center of mass of link 1 LINK_COM_POS_2 = 0.5 #: [m] position of the center of mass of link 2 LINK_MOI = 1.0 #: moments of inertia for both links MAX_VEL_1 = 4 * pi MAX_VEL_2 = 9 * pi AVAIL_TORQUE = [-1.0, 0.0, 1.0] torque_noise_max = 0.0 #: use dynamics equations from the nips paper or the book book_or_nips = "book" action_arrow = None domain_fig = None def __init__(self, seed, continuous_action): self.viewer = None high = np.array( [np.pi, np.pi, self.MAX_VEL_1, self.MAX_VEL_2], dtype=np.float32 ) low = -high self.observation_space = spaces.Box(low=low, high=high, dtype=np.float32) self.random = np.random.default_rng(seed=seed) self.continuous_action = continuous_action if continuous_action: action_low = np.array([-1.0]) action_high = np.array([1.0]) self.action_space = spaces.Box(action_low, action_high) else: self.action_space = spaces.Discrete(3) self.state = None def seed(self, seed): self.random = np.random.default_rng(seed) def reset(self): self.state = np.array([0., 0., 0., 0.]) return self._get_ob() def step(self, a): s = self.state if self.continuous_action: torque = np.clip(a, self.action_space.low, self.action_space.high) else: assert self.action_space.contains( a ), f"{action!r} ({type(action)}) invalid" torque = self.AVAIL_TORQUE[a] # Add noise to the force action if self.torque_noise_max > 0: torque += self.random.uniform( -self.torque_noise_max, self.torque_noise_max ) # Now, augment the state with our force action so it can be passed to # _dsdt s_augmented = np.append(s, torque) ns = rk4(self._dsdt, s_augmented, [0, self.dt]) ns[0] = wrap(ns[0], -pi, pi) ns[1] = wrap(ns[1], -pi, pi) ns[2] = bound(ns[2], -self.MAX_VEL_1, self.MAX_VEL_1) ns[3] = bound(ns[3], -self.MAX_VEL_2, self.MAX_VEL_2) self.state = ns terminal = self._terminal() reward = -1.0 if not terminal else 0.0 return (self._get_ob(), reward, terminal, {}) def _get_ob(self): s = self.state return np.array( [angle_normalize(s[0]), angle_normalize(s[1]), s[2], s[3]], dtype=np.float32 ) def _terminal(self): s = self.state return bool(-cos(s[0]) - cos(s[1] + s[0]) > 1.0) def _dsdt(self, s_augmented): m1 = self.LINK_MASS_1 m2 = self.LINK_MASS_2 l1 = self.LINK_LENGTH_1 lc1 = self.LINK_COM_POS_1 lc2 = self.LINK_COM_POS_2 I1 = self.LINK_MOI I2 = self.LINK_MOI g = 9.8 a = s_augmented[-1] s = s_augmented[:-1] theta1 = s[0] theta2 = s[1] dtheta1 = s[2] dtheta2 = s[3] d1 = ( m1 * lc1 ** 2 + m2 * (l1 ** 2 + lc2 ** 2 + 2 * l1 * lc2 * cos(theta2)) + I1 + I2 ) d2 = m2 * (lc2 ** 2 + l1 * lc2 * cos(theta2)) + I2 phi2 = m2 * lc2 * g * cos(theta1 + theta2 - pi / 2.0) phi1 = ( -m2 * l1 * lc2 * dtheta2 ** 2 * sin(theta2) - 2 * m2 * l1 * lc2 * dtheta2 * dtheta1 * sin(theta2) + (m1 * lc1 + m2 * l1) * g * cos(theta1 - pi / 2) + phi2 ) if self.book_or_nips == "nips": # the following line is consistent with the description in the # paper ddtheta2 = (a + d2 / d1 * phi1 - phi2) / (m2 * lc2 ** 2 + I2 - d2 ** 2 / d1) else: # the following line is consistent with the java implementation and the # book ddtheta2 = ( a + d2 / d1 * phi1 - m2 * l1 * lc2 * dtheta1 ** 2 * sin(theta2) - phi2 ) / (m2 * lc2 ** 2 + I2 - d2 ** 2 / d1) ddtheta1 = -(d2 * ddtheta2 + phi1) / d1 return (dtheta1, dtheta2, ddtheta1, ddtheta2, 0.0) def render(self, mode="human"): from gym.utils import pyglet_rendering s = self.state if self.viewer is None: self.viewer = pyglet_rendering.Viewer(500, 500) bound = self.LINK_LENGTH_1 + self.LINK_LENGTH_2 + 0.2 # 2.2 for default self.viewer.set_bounds(-bound, bound, -bound, bound) if s is None: return None p1 = [-self.LINK_LENGTH_1 * cos(s[0]), self.LINK_LENGTH_1 * sin(s[0])] p2 = [ p1[0] - self.LINK_LENGTH_2 * cos(s[0] + s[1]), p1[1] + self.LINK_LENGTH_2 * sin(s[0] + s[1]), ] xys = np.array([[0, 0], p1, p2])[:, ::-1] thetas = [s[0] - pi / 2, s[0] + s[1] - pi / 2] link_lengths = [self.LINK_LENGTH_1, self.LINK_LENGTH_2] self.viewer.draw_line((-2.2, 1), (2.2, 1)) for ((x, y), th, llen) in zip(xys, thetas, link_lengths): l, r, t, b = 0, llen, 0.1, -0.1 jtransform = pyglet_rendering.Transform(rotation=th, translation=(x, y)) link = self.viewer.draw_polygon([(l, b), (l, t), (r, t), (r, b)]) link.add_attr(jtransform) link.set_color(0, 0.8, 0.8) circ = self.viewer.draw_circle(0.1) circ.set_color(0.8, 0.8, 0) circ.add_attr(jtransform) return self.viewer.render(return_rgb_array=mode == "rgb_array") def close(self): if self.viewer: self.viewer.close() self.viewer = None def wrap(x, m, M): """Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n For example, m = -180, M = 180 (degrees), x = 360 --> returns 0. Args: x: a scalar m: minimum possible value in range M: maximum possible value in range Returns: x: a scalar, wrapped """ diff = M - m while x > M: x = x - diff while x < m: x = x + diff return x def bound(x, m, M=None): """Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR* have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1]. Args: x: scalar Returns: x: scalar, bound between min (m) and Max (M) """ if M is None: M = m[1] m = m[0] # bound x between min (m) and Max (M) return min(max(x, m), M) def rk4(derivs, y0, t): """ Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta. This is a toy implementation which may be useful if you find yourself stranded on a system w/o scipy. Otherwise use :func:`scipy.integrate`. Args: derivs: the derivative of the system and has the signature ``dy = derivs(yi)`` y0: initial state vector t: sample times args: additional arguments passed to the derivative function kwargs: additional keyword arguments passed to the derivative function Example 1 :: ## 2D system def derivs(x): d1 = x[0] + 2*x[1] d2 = -3*x[0] + 4*x[1] return (d1, d2) dt = 0.0005 t = arange(0.0, 2.0, dt) y0 = (1,2) yout = rk4(derivs6, y0, t) If you have access to scipy, you should probably be using the scipy.integrate tools rather than this function. This would then require re-adding the time variable to the signature of derivs. Returns: yout: Runge-Kutta approximation of the ODE """ try: Ny = len(y0) except TypeError: yout = np.zeros((len(t),), np.float_) else: yout = np.zeros((len(t), Ny), np.float_) yout[0] = y0 for i in np.arange(len(t) - 1): thist = t[i] dt = t[i + 1] - thist dt2 = dt / 2.0 y0 = yout[i] k1 = np.asarray(derivs(y0)) k2 = np.asarray(derivs(y0 + dt2 * k1)) k3 = np.asarray(derivs(y0 + dt2 * k2)) k4 = np.asarray(derivs(y0 + dt * k3)) yout[i + 1] = y0 + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4) # We only care about the final timestep and we cleave off action value which will be zero return yout[-1][:4] def angle_normalize(x): return ((x + np.pi) % (2 * np.pi)) - np.pi
10,907
32.155015
93
py
GreedyAC
GreedyAC-master/env/__init__.py
0
0
0
py
GreedyAC
GreedyAC-master/utils/plot_utils.py
# Import modules import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib import ticker, gridspec import experiment_utils as exp import numpy as np from scipy import ndimage from scipy import stats as st import seaborn as sns from collections.abc import Iterable import pickle import matplotlib as mpl import hypers import warnings import runs TRAIN = "train" EVAL = "eval" # Set up plots params = { 'axes.labelsize': 48, 'axes.titlesize': 36, 'legend.fontsize': 16, 'xtick.labelsize': 48, 'ytick.labelsize': 48 } plt.rcParams.update(params) plt.rc('text', usetex=False) # You might want usetex=True to get DejaVu Sans plt.rc('font', **{'family': 'sans-serif', 'serif': ['DejaVu Sans']}) plt.rcParams["font.family"] = "DejaVu Sans" plt.rcParams.update({'font.size': 15}) plt.tick_params(top=False, right=False, labelsize=20) mpl.rcParams["svg.fonttype"] = "none" # Constants EPISODIC = "episodic" CONTINUING = "continuing" # Colours CMAP = "tab10" DEFAULT_COLOURS = list(sns.color_palette(CMAP, 6).as_hex()) plt.rcParams["axes.prop_cycle"] = mpl.cycler(color=sns.color_palette(CMAP)) OFFSET = 0 # The offset to start in DEFAULT_COLOURS def mean_with_err(data, type_, ind, smooth_over, names, fig=None, ax=None, figsize=(12, 6), xlim=None, ylim=None, alpha=0.1, colours=None, linestyles=None, markers=None, env_type="continuing", keep_shape=False, xlabel="", ylabel="", skip=-1, errfn=exp.stderr, linewidth=1, markersize=1): """ Plots the average training or evaluation return over all runs with standard error. Given a list of data dictionaries of the form returned by main.py, this function will plot each episodic return for the list of hyperparameter settings ind each data dictionary. The ind argument is a list, where each element is a list of hyperparameter settings to plot for the data dictionary at the same index as this list. For example, if ind[i] = [1, 2], then plots will be generated for the data dictionary at location i in the data argument for hyperparameter settings ind[i] = [1, 2]. The smooth_over argument tells how many previous data points to smooth over Parameters ---------- data : list of dict The Python data dictionaries generated from running main.py for the agents type_ : str Which type of data to plot, one of "eval" or "train" ind : iter of iter of int The list of lists of hyperparameter settings indices to plot for each agent. For example [[1, 2], [3, 4]] means that the first agent plots will use hyperparameter settings indices 1 and 2, while the second will use 3 and 4. smooth_over : list of int The number of previous data points to smooth over for the agent's plot for each data dictionary. Note that this is *not* the number of timesteps to smooth over, but rather the number of data points to smooth over. For example, if you save the return every 1,000 timesteps, then setting this value to 15 will smooth over the last 15 readings, or 15,000 timesteps. For example, [1, 2] will mean that the plots using the first data dictionary will smooth over the past 1 data points, while the second will smooth over the passed 2 data points for each hyperparameter setting. fig : plt.figure The figure to plot on, by default None. If None, creates a new figure ax : plt.Axes The axis to plot on, by default None, If None, creates a new axis figsize : tuple(int, int) The size of the figure to plot names : list of str The name of the agents, used for the legend xlim : float, optional The x limit for the plot, by default None ylim : float, optional The y limit for the plot, by default None alpha : float, optional The alpha channel for the plot, by default 0.1 colours : list of list of str The colours to use for each hyperparameter settings plot for each data dictionary env_type : str, optional The type of environment, one of 'continuing', 'episodic'. By default 'continuing' Returns ------- plt.figure, plt.Axes The figure and axes of the plot """ # Set the colours to be default if not set if colours is None: colours = _get_default_colours(ind) if linestyles is None: linestyles = _get_default_styles(ind) if markers is None: markers = _get_default_markers(ind) # Set up figure title = f"Average {type_.title()} Return per Run with Standard Error" fig, ax = _setup_fig(fig, ax, figsize, xlim=xlim, ylim=ylim, xlabel=xlabel, ylabel=ylabel, title=title) # Track the total timesteps per hyperparam setting over all episodes and # the cumulative timesteps per episode per data dictionary (timesteps # should be consistent between all hp settings in a single data dict) total_timesteps = [] cumulative_timesteps = [] for i in range(len(data)): if type_ == "train": cumulative_timesteps.append(exp.get_cumulative_timesteps(data[i] ["experiment_data"][ind[i][0]]["runs"] [0]["train_episode_steps"])) elif type_ == "eval": cumulative_timesteps.append(data[i]["experiment_data"][ind[i][0]] ["runs"][0]["timesteps_at_eval"]) else: raise ValueError("type_ must be one of 'train', 'eval'") total_timesteps.append(cumulative_timesteps[-1][-1]) # Find the minimum of total trained-for timesteps. Each plot will only # be plotted on the x-axis until this value min_timesteps = min(total_timesteps) # For each data dictionary, find the minimum index where the timestep at # that index is >= minimum timestep ind_ge_min_timesteps = [] for cumulative_timesteps_per_data in cumulative_timesteps: final_ind = np.where(cumulative_timesteps_per_data >= min_timesteps)[0][0] # Since indexing will stop right before the minimum, increment it ind_ge_min_timesteps.append(final_ind + 1) # Plot all data for all HP settings, only up until the minimum index plot_fn = _plot_mean_with_err_continuing if env_type == "continuing" \ else _plot_mean_with_err_episodic for i in range(len(data)): fig, ax = \ plot_fn(data=data[i], type_=type_, ind=ind[i], smooth_over=smooth_over[i], name=names[i], fig=fig, ax=ax, figsize=figsize, xlim=xlim, ylim=ylim, last_ind=ind_ge_min_timesteps[i], alpha=alpha, colours=colours[i], keep_shape=keep_shape, skip=skip, linestyles=linestyles[i], markers=markers[i], errfn=errfn, linewidth=linewidth, markersize=markersize) return fig, ax def _plot_mean_with_err_continuing(data, type_, ind, smooth_over, fig=None, ax=None, figsize=(12, 6), xlim=None, ylim=None, xlabel=None, ylabel=None, name="", last_ind=-1, timestep_multiply=None, alpha=0.1, colours=None, linestyles=None, markers=None, keep_shape=False, skip=-1, errfn=exp.stderr, linewidth=1, markersize=1): """ Plots the average training or evaluation return over all runs for a single data dictionary on a continuing environment. Standard error is plotted as shaded regions. Parameters ---------- data : dict The Python data dictionary generated from running main.py type_ : str Which type of data to plot, one of "eval" or "train" ind : iter of int The list of hyperparameter settings indices to plot smooth_over : int The number of previous data points to smooth over. Note that this is *not* the number of timesteps to smooth over, but rather the number of data points to smooth over. For example, if you save the return every 1,000 timesteps, then setting this value to 15 will smooth over the last 15 readings, or 15,000 timesteps. fig : plt.figure The figure to plot on, by default None. If None, creates a new figure ax : plt.Axes The axis to plot on, by default None, If None, creates a new axis figsize : tuple(int, int) The size of the figure to plot name : str, optional The name of the agent, used for the legend last_ind : int, optional The index of the last element to plot in the returns list, by default -1. This is useful if you want to plot many things on the same axis, but all of which have a different number of elements. This way, we can plot the first last_ind elements of each returns for each agent. timestep_multiply : array_like of float, optional A value to multiply each timstep by, by default None. This is useful if your agent does multiple updates per timestep and you want to plot performance vs. number of updates. xlim : float, optional The x limit for the plot, by default None ylim : float, optional The y limit for the plot, by default None alpha : float, optional The alpha channel for the plot, by default 0.1 colours : list of str The colours to use for each plot of each hyperparameter setting env_type : str, optional The type of environment, one of 'continuing', 'episodic'. By default 'continuing' Returns ------- plt.figure, plt.Axes The figure and axes of the plot Raises ------ ValueError When an axis is passed but no figure is passed When an appropriate number of colours is not specified to cover all hyperparameter settings """ if skip == 0: skip = 1 if colours is not None and len(colours) != len(ind): raise ValueError("must have one colour for each hyperparameter " + "setting") if linestyles is not None and len(linestyles) != len(ind): raise ValueError("must have one linestyle for each hyperparameter " + "setting") if markers is not None and len(markers) != len(ind): raise ValueError("must have one marker for each hyperparameter " + "setting") if timestep_multiply is None: timestep_multiply = [1] * len(ind) if ax is not None and fig is None: raise ValueError("must pass figure when passing axis") if colours is None: colours = _get_default_colours(ind) if linestyles is None: colours = _get_default_styles(ind) if markers is None: colours = _get_default_markers(ind) # Set up figure if ax is None and fig is None: title = f"Average {type_.title()} Return per Run with Standard Error" fig, ax = _setup_fig(fig, ax, figsize, xlim=xlim, ylim=ylim, xlabel=xlabel, ylabel=ylabel, title=title) episode_length = data["experiment"]["environment"]["steps_per_episode"] # Plot with the standard error for i in range(len(ind)): timesteps, mean, std = exp.get_mean_err(data, type_, ind[i], smooth_over, # exp.t_ci, errfn, keep_shape=keep_shape) timesteps = np.array(timesteps[:last_ind]) * timestep_multiply[i] timesteps = timesteps[::skip] mean = mean[::skip] std = std[::skip] # Plot based on colours label = f"{name}" if colours is not None and linestyles is not None: _plot_shaded(ax, timesteps, mean, std, colours[i], label, alpha, linestyle=linestyles[i], marker=markers[i], linewidth=linewidth, markersize=markersize) elif colours is not None: _plot_shaded(ax, timesteps, mean, std, colours[i], label, alpha, marker=markers[i], linewidth=linewidth, markersize=markersize) elif linestyles is not None: _plot_shaded(ax, timesteps, mean, std, None, label, alpha, linestyle=linestyle[i], marker=markers[i], linewidth=linewidth, markersize=markersize) else: _plot_shaded(ax, timesteps, mean, std, None, label, alpha, marker=markers[i], linewidth=linewidth, markersize=markersize) ax.legend() fig.show() return fig, ax def _plot_mean_with_err_episodic(data, type_, ind, smooth_over, fig=None, ax=None, figsize=(12, 6), name="", last_ind=-1, xlabel="Timesteps", ylabel="Average Return", xlim=None, ylim=None, alpha=0.1, colours=None, keep_shape=False, skip=-1, linestyles=None, markers=None, errfn=exp.stderr, linewidth=1, markersize=1): """ Plots the average training or evaluation return over all runs for a single data dictionary on an episodic environment. Plots shaded retions as standard error. Parameters ---------- data : dict The Python data dictionary generated from running main.py type_ : str Which type of data to plot, one of "eval" or "train" ind : iter of int The list of hyperparameter settings indices to plot smooth_over : int The number of previous data points to smooth over. Note that this is *not* the number of timesteps to smooth over, but rather the number of data points to smooth over. For example, if you save the return every 1,000 timesteps, then setting this value to 15 will smooth over the last 15 readings, or 15,000 timesteps. fig : plt.figure The figure to plot on, by default None. If None, creates a new figure ax : plt.Axes The axis to plot on, by default None, If None, creates a new axis figsize : tuple(int, int) The size of the figure to plot name : str, optional The name of the agent, used for the legend xlim : float, optional The x limit for the plot, by default None ylim : float, optional The y limit for the plot, by default None alpha : float, optional The alpha channel for the plot, by default 0.1 colours : list of str The colours to use for each plot of each hyperparameter setting env_type : str, optional The type of environment, one of 'continuing', 'episodic'. By default 'continuing' Returns ------- plt.figure, plt.Axes The figure and axes of the plot Raises ------ ValueError When an axis is passed but no figure is passed When an appropriate number of colours is not specified to cover all hyperparameter settings """ if colours is not None and len(colours) != len(ind): raise ValueError("must have one colour for each hyperparameter " + "setting") if linestyles is not None and len(colours) != len(ind): raise ValueError("must have one linestyle for each hyperparameter " + "setting") if markers is not None and len(markers) != len(ind): raise ValueError("must have one marker for each hyperparameter " + "setting") if ax is not None and fig is None: raise ValueError("must pass figure when passing axis") if colours is None: colours = _get_default_colours(ind) if linestyles is None: linestyles = _get_default_styles(ind) if markers is None: markers = _get_default_markers(ind) # Set up figure if ax is None and fig is None: fig = plt.figure(figsize=figsize) ax = fig.add_subplot() if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) # Plot with the standard error for i in range(len(ind)): # data = exp.reduce_episodes(data, ind[i], type_=type_) if type_ == "train": data = runs.expand_episodes(data, ind[i], type_=type_, skip=skip) # data has consistent # of episodes, so treat as env_type="continuing" _, mean, std = exp.get_mean_err(data, type_, ind[i], smooth_over, errfn, keep_shape=keep_shape) episodes = np.arange(mean.shape[0]) # Plot based on colours label = f"{name}" if colours is not None and linestyles is not None: _plot_shaded(ax, episodes, mean, std, colours[i], label, alpha, linestyle=linestyles[i], marker=markers[i], linewidth=linewidth, markersize=markersize) elif colours is not None: _plot_shaded(ax, episodes, mean, std, colours[i], label, alpha, marker=markers[i], linewidth=linewidth, markersize=markersize) elif linestyles is not None: _plot_shaded(ax, episodes, mean, std, None, label, alpha, linestyle=linestyles[i], marker=markers[i], linewidth=linewidth, markersize=markersize) else: _plot_shaded(ax, episodes, mean, std, None, label, alpha, marker=markers[i], linewidth=linewidth, markersize=markersize) ax.legend() ax.set_title(f"Average {type_.title()} Return per Run with Standard Error") ax.set_ylabel(ylabel) ax.set_xlabel(xlabel) # fig.show() return fig, ax def _get_default_markers(iter_): markers = [] # Calculate the number of lists at the current level to go through paths = range(len(iter_)) # Return a list of colours if the elements of the list are not lists if not isinstance(iter_[0], Iterable): return ["" for i in paths] # For each list at the current level, get the colours corresponding to # this level for i in paths: markers.append(_get_default_markers(iter_[i])) return markers def _get_default_styles(iter_): styles = [] # Calculate the number of lists at the current level to go through paths = range(len(iter_)) # Return a list of colours if the elements of the list are not lists if not isinstance(iter_[0], Iterable): return ["-" for i in paths] # For each list at the current level, get the colours corresponding to # this level for i in paths: styles.append(_get_default_styles(iter_[i])) return styles def _get_default_colours(iter_): """ Recursively turns elements of an Iterable into strings representing colours. This function will turn each element of an Iterable into strings that represent colours, recursively. If the elements of an Iterable are also Iterable, then this function will recursively descend all the way through every Iterable until it finds an Iterable with non-Iterable elements. These elements will be replaced by strings that represent colours. In effect, this function keeps the data structure, but replaces non-Iterable elements by strings representing colours. Note that this funcion assumes that all elements of an Iterable are of the same type, and so it only checks if the first element of an Iterable object is Iterable or not to stop the recursion. Parameters ---------- iter_ : collections.Iterable The top-level Iterable object to turn into an Iterable of strings of colours, recursively. Returns ------- list of list of ... of strings A data structure that has the same architecture as the input Iterable but with all non-Iterable elements replaced by strings. """ colours = [] # Calculate the number of lists at the current level to go through paths = range(len(iter_)) # Return a list of colours if the elements of the list are not lists if not isinstance(iter_[0], Iterable): global OFFSET col = [DEFAULT_COLOURS[(OFFSET + i) % len(DEFAULT_COLOURS)] for i in paths] OFFSET += len(paths) return col # For each list at the current level, get the colours corresponding to # this level for i in paths: colours.append(_get_default_colours(iter_[i])) return colours def _plot_shaded(ax, x, y, region, colour, label, alpha, linestyle="-", marker="", linewidth=1, markersize=1): """ Plots a curve with a shaded region. Parameters ---------- ax : plt.Axes The axis to plot on x : Iterable The points on the x-axis y : Iterable The points on the y-axis region : list or array_like The region to shade about the y points. The shaded region will be y +/- region. If region is a list or 1D np.ndarray, then the region is used both for the + and - portions. If region is a 2D np.ndarray, then the first row will be used as the lower bound (-) and the second row will be used for the upper bound (+). That is, the region between (lower_bound, upper_bound) will be shaded, and there will be no subtraction/adding of the y-values. colour : str The colour to plot with label : str The label to use for the plot alpha : float The alpha value for the shaded region """ if colour is None: colour = DEFAULT_COLOURS[0] ax.plot(x, y, color=colour, label=label, linestyle=linestyle, marker=marker, linewidth=linewidth, markersize=markersize, markevery=3) if type(region) == list: ax.fill_between(x, y-region, y+region, alpha=alpha, color=colour) elif type(region) == np.ndarray and len(region.shape) == 1: ax.fill_between(x, y-region, y+region, alpha=alpha, color=colour) elif type(region) == np.ndarray and len(region.shape) == 2: ax.fill_between(x, region[0, :], region[1, :], alpha=alpha, color=colour) def _setup_fig(fig, ax, figsize=None, title=None, xlim=None, ylim=None, xlabel=None, ylabel=None, xscale=None, yscale=None, xbase=None, ybase=None): if fig is None: if ax is not None: raise ValueError("Must specify figure when axis given") if figsize is not None: fig = plt.figure(figsize=figsize) else: fig = plt.figure() if ax is None: ax = fig.add_subplot() if title is not None: ax.set_title(title) if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) if xscale is not None: if xbase is not None: ax.set_xscale(xscale, base=xbase) else: ax.set_xscale(xscale) if yscale is not None: if ybase is not None: ax.set_yscale(yscale, base=ybase) else: ax.set_yscale(yscale) return fig, ax
23,905
37.682848
79
py
GreedyAC
GreedyAC-master/utils/runs.py
import numpy as np from copy import deepcopy TRAIN = "train" EVAL = "eval" def episodes_to(in_data, i, type_=TRAIN): """ Restricts the number of `type_` episodes to be from episode 0 to the episode right before episode i. The input data dictionary is not changed. If `type_` is 'train', then the training returns are restricted to be only from episodes 0 to i and the 'eval' episodes are restricted to reflect this. If `type_` is 'eval", then the evaluation returns are restricted to be only from episode 0 to i and the 'train' returns are restricted to reflect this. By 'restricted to reflect this', we mean that the returns are restricted so that the final return is at the same timestep (or nearest timestep, rounding up to episode completion) as the final timestep of episode i for the data of type `type_`. Parameters ---------- in_data : dict The data dictionary i : int The episode to restrict values to type_ : str The type of data to restrict to be from episode 0 to i. One of 'train', 'eval'. Returns ------- dict The modified data dictionary """ data = deepcopy(in_data) if type_ not in (TRAIN, EVAL): raise ValueError("type_ must be one of 'train', 'eval'") key = type_ other = "eval" if key == "train" else "train" for hyper in data["experiment_data"]: for j in range(len(data["experiment_data"][hyper]["runs"])): run_data = data["experiment_data"][hyper]["runs"][j] if i > len(run_data[f"{key}_episode_rewards"]): last = len(run_data[f"{key}_episode_rewards"]) raise IndexError(f"no such episode i={i}, largest episode " + f"index is {last}") # Adjust training data run_data[f"{key}_episode_rewards"] = run_data[ f"{key}_episode_rewards"][:i] run_data[f"{key}_episode_steps"] = run_data[ f"{key}_episode_steps"][:i] # Figure out which timestep episode i happened on last_step = np.cumsum(run_data[f"{key}_episode_steps"])[-1] # Figure out which episodes to keep of the "other" type (if type_ # is 'train' then other is 'eval' and vice versa) to_discard = np.cumsum(run_data[f"{other}_episode_steps"]) \ > last_step if len(to_discard): last_other_step = np.argmax(to_discard) # Adjust "other" data run_data[f"{other}_episode_reward"] = run_data[ f"{other}_episode_reward"][:last_other_step] run_data[f"{other}_episode_steps"] = run_data[ f"{other}_episode_steps"][:last_other_step] else: # Adjust "other" data run_data[f"{other}_episode_reward"] = [] run_data[f"{other}_episode_steps"] = [] return data def expand_episodes(data, ind, type_='train'): """ For each run, repeat each episode's performance measure by how many timesteps that episode took to finish. This results in episodic experiments having the same number of data readings per run, so that performances can be averaged over runs and an be easily plotted. This function will modify a single run's data such that if you plotted only that run's data, then it would appear as a step plot. For example, if we had the following episode performances: [100, 110] with the following number of timesteps for each episode: [2, 3] Then this function will modify the data so that it looks like: [100, 100, 110, 110, 110] Parameters ---------- data : dict The data dictionary generated by the experiment ind : int The hyperparameter index to adjust type_ : str Which data type to adjust, one of 'train', 'eval' """ data = deepcopy(data) runs = data["experiment_data"][ind]["runs"] episodes = [] if type_ == "train": for i in range(len(runs)): run_return = [] for j in range(len(runs[i]["train_episode_rewards"])): run_return.extend([runs[i]["train_episode_rewards"][j] for _ in range(runs[i]["train_episode_steps"][j])]) data["experiment_data"][ind]["runs"][i][ "train_episode_rewards"] = run_return elif type_ == "eval": for i in range(len(runs)): run_return = [] for j in range(len(runs[i]["eval_episode_rewards"])): run_return.extend([runs[i]["eval_episode_rewards"][j] for _ in range(runs[i]["eval_episode_steps"][j])]) data["experiment_data"][ind]["runs"][i][ "eval_episode_rewards"] = run_return else: raise ValueError(f"unknown type {type_}") return data def reduce_episodes(data, ind, type_): """ Reduce the number of episodes in an episodic setting Given a data dictionary, this function will reduce the number of episodes seen on each run to the minimum among all runs for that hyperparameter settings index. This is needed to plot curves by episodic return. Parameters ---------- data : dict The Python data dictionary generated from running main.py ind : int The hyperparameter settings index to reduce the episodes of type_ : str Whether to reduce the training or evaluation returns, one of 'train', 'eval' """ data = deepcopy(data) runs = data["experiment_data"][ind]["runs"] episodes = [] if type_ == "train": for run in data["experiment_data"][ind]["runs"]: episodes.append(len(run["train_episode_rewards"])) min_ = np.min(episodes) for i in range(len(runs)): runs[i]["train_episode_rewards"] = \ runs[i]["train_episode_rewards"][:min_] elif type_ == "eval": for run in data["experiment_data"][ind]["runs"]: episodes.append(run["eval_episode_rewards"].shape[0]) min_ = np.min(episodes) for i in range(len(runs)): runs[i]["eval_episode_rewards"] = \ runs[i]["eval_episode_rewards"][:min_, :] return data def before(data, i): """ Only keep the runs up until i """ for hyper in data["experiment_data"]: data["experiment_data"][hyper]["runs"] = \ data["experiment_data"][hyper]["runs"][:i] return data def after(data, i): """ Only keep runs after i """ for hyper in data["experiment_data"]: data["experiment_data"][hyper]["runs"] = \ data["experiment_data"][hyper]["runs"][i:] return data def combine(data1, data2): """ Adds the runs from `data2` to `data1` if they are not already in `data1` while ignoring hyper settings in `data2` that do not exist in `data1`. This function assumes that the hypers indices are consistent between `data1` and `data2`, i.e. hyper index `i` refers to the same hyperparameter configuration in both data files. `data1` is mutated. Parameters ---------- data1 : dict[any]any The destination data dictionary to add runs to data2 : dict[any]any The source data dictionary to get runs from """ for hyper in data1["experiment_data"]: if hyper not in data2["experiment_data"]: continue used_random_seeds = [] for run1 in data1["experiment_data"][hyper]["runs"]: used_random_seeds.append(run1["random_seed"]) for run2 in data2["experiment_data"][hyper]["runs"]: if run2["random_seed"] not in used_random_seeds: data1["experiment_data"][hyper]["runs"].append(run2) return data1 def to(data, i): return before(data, i)
7,984
31.72541
79
py
GreedyAC
GreedyAC-master/utils/plot_mse.py
# Script to plot mean learning curves with standard error from pprint import pprint import pickle import runs import seaborn as sns from tqdm import tqdm import os from pprint import pprint import matplotlib.pyplot as plt import numpy as np import hypers import json import sys import plot_utils as plot import matplotlib as mpl # ######################################################################## # To produce learning curves, simply fill in the following: # Specify here the name of the environment you are plotting env = "Pendulum-v0" # Specify whether to plot online/training data or offline/evaluation data PLOT_TYPE = "train" # Specify here the data files to plot DATA_FILES = [ "./results/Pendulum-v0_GreedyACresults/data.pkl" ] # Specify the labels for each data file. The length of labels and DATA_FILES # should be equal labels = [ "GreedyAC", ] # Lower and upper bounds on the x and y-axes of the resulting plot. Set to None # to use default axis bounds x_low, x_high = None, None y_low, y_high = None, None # Colours to plot with colours = ["black", "red", "blue", "gold"] # Directory to save the plot at save_dir = os.path.expanduser('~') # Types of files to save filetypes = ["png", "svg", "pdf"] # ######################################################################## mpl.rcParams["font.size"] = 24 mpl.rcParams["svg.fonttype"] = "none" # Configuration stuff CONTINUING = "continuing" EPISODIC = "episodic" type_map = { "MinAtarBreakout": EPISODIC, "MountainCar-v0": EPISODIC, "MountainCarContinuous-v0": EPISODIC, "Pendulum-v0": CONTINUING, "Acrobot-v1": EPISODIC, "Swimmer-v2": EPISODIC, } fig = plt.figure(figsize=(16, 9)) ax = fig.add_subplot() DATA = [] for f in tqdm(DATA_FILES): with open(f, "rb") as infile: d = pickle.load(infile) DATA.append(d) # Find best hypers BEST_IND = [] for agent in DATA: best_hp = hypers.best(agent, to=-1)[0] BEST_IND.append(best_hp) colours = list(map(lambda x: [x], colours)) # Plot the mean + standard error print("=== Plotting mean with standard error") PLOT_TYPE = "train" TYPE = "online" if PLOT_TYPE == "train" else "offline" best_ind = list(map(lambda x: [x], BEST_IND)) fig, ax = plot.mean_with_err( DATA, PLOT_TYPE, best_ind, [0]*len(best_ind), labels, env_type=type_map[env].lower(), figsize=(12, 12), colours=colours, skip=-1, # The number of data points to skip when plotting ) ax.set_title(env) if x_low is not None and x_high is not None: ax.set_xlim(x_low, x_high) if y_low is not None and y_high is not None: ax.set_ylim(y_low, y_high) for filetype in filetypes: print(f"Saving at {save_dir}/{env}.{filetype}") fig.savefig(f"{save_dir}/{env}.{filetype}", bbox_inches="tight")
2,814
24.36036
79
py
GreedyAC
GreedyAC-master/utils/experience_replay.py
# Import modules import numpy as np import torch from abc import ABC, abstractmethod # Class definitions class ExperienceReplay(ABC): """ Abstract base class ExperienceReplay implements an experience replay buffer. The specific kind of buffer is determined by classes which implement this base class. For example, NumpyBuffer stores all transitions in a numpy array while TorchBuffer implements the buffer as a torch tensor. Attributes ---------- self.cast : func A function which will cast data into an appropriate form to be stored in the replay buffer. All incoming data is assumed to be a numpy array. """ def __init__(self, capacity, seed, state_size, action_size, device=None): """ Constructor Parameters ---------- capacity : int The capacity of the buffer seed : int The random seed used for sampling from the buffer state_size : tuple[int] The number of dimensions of the state features action_size : int The number of dimensions in the action vector """ self.device = device self.is_full = False self.position = 0 self.capacity = capacity # Set the casting function, which is needed for implementations which # may keep the ER buffer as a different data structure, for example # a torch tensor, in this case all data needs to be cast to a torch # tensor before storing self.cast = lambda x: x # Set the random number generator self.random = np.random.default_rng(seed=seed) # Save the size of states and actions self.state_size = state_size self.action_size = action_size self._sampleable = False # Buffer of state, action, reward, next_state, done self.state_buffer = None self.action_buffer = None self.reward_buffer = None self.next_state_buffer = None self.done_buffer = None self.init_buffer() @property def sampleable(self): return self._sampleable @abstractmethod def init_buffer(self): """ Initializes the buffers on which to store transitions. Note that different classes which implement this abstract base class may use different data types as buffers. For example, NumpyBuffer stores all transitions using a numpy array, while TorchBuffer stores all transitions on a torch Tensor on a specific device in order to speed up training by keeping transitions on the same device as the device which holds the model. Post-Condition -------------- The replay buffer self.buffer has been initialized """ pass def push(self, state, action, reward, next_state, done): """ Pushes a trajectory onto the replay buffer Parameters ---------- state : array_like The state observation action : array_like The action taken by the agent in the state reward : float The reward seen after taking the argument action in the argument state next_state : array_like The next state transitioned to done : bool Whether or not the transition was a transition to a goal state """ reward = np.array([reward]) done = np.array([done]) state = self.cast(state) action = self.cast(action) reward = self.cast(reward) next_state = self.cast(next_state) done = self.cast(done) self.state_buffer[self.position] = state self.action_buffer[self.position] = action self.reward_buffer[self.position] = reward self.next_state_buffer[self.position] = next_state self.done_buffer[self.position] = done if self.position >= self.capacity - 1: self.is_full = True self.position = (self.position + 1) % self.capacity self._sampleable = False @property def sampleable(self): return self._sampleable def is_sampleable(self, batch_size): if self.position < batch_size and not self.sampleable: return False elif not self._sampleable: self._sampleable = True return self.sampleable def sample(self, batch_size): """ Samples a random batch from the buffer Parameters ---------- batch_size : int The size of the batch to sample Returns ------- 5-tuple of torch.Tensor The arrays of state, action, reward, next_state, and done from the batch """ if not self.is_sampleable(batch_size): return None, None, None, None, None # Get the indices for the batch if self.is_full: indices = self.random.integers(low=0, high=len(self), size=batch_size) else: indices = self.random.integers(low=0, high=self.position, size=batch_size) state = self.state_buffer[indices, :] action = self.action_buffer[indices, :] reward = self.reward_buffer[indices] next_state = self.next_state_buffer[indices, :] done = self.done_buffer[indices] return state, action, reward, next_state, done def __len__(self): """ Gets the number of elements in the buffer Returns ------- int The number of elements currently in the buffer """ if not self.is_full: return self.position else: return self.capacity class NumpyBuffer(ExperienceReplay): """ Class NumpyBuffer implements an experience replay buffer. This class stores all states, actions, and rewards as numpy arrays. For an implementation that uses PyTorch tensors, see TorchExperienceReplay """ def __init__(self, capacity, seed, state_size, action_size, state_dtype=np.int32, action_dtype=np.int32): """ Constructor Parameters ---------- capacity : int The capacity of the buffer seed : int The random seed used for sampling from the buffer state_size : tuple[int] The dimensions of the state features action_size : int The number of dimensions in the action vector """ self._state_dtype = state_dtype self._action_dtype = action_dtype super().__init__(capacity, seed, state_size, action_size, None) def init_buffer(self): self.state_buffer = np.zeros((self.capacity, *self.state_size), dtype=self._state_dtype) self.next_state_buffer = np.zeros((self.capacity, *self.state_size), dtype=self._state_dtype) self.action_buffer = np.zeros((self.capacity, self.action_size), dtype=self._state_dtype) self.reward_buffer = np.zeros((self.capacity, 1)) self.done_buffer = np.zeros((self.capacity, 1), dtype=bool) class TorchBuffer(ExperienceReplay): """ Class TorchBuffer implements an experience replay buffer. The difference between this class and the ExperienceReplay class is that this class keeps all experiences as a torch Tensor on the appropriate device so that if using PyTorch, we do not need to cast the batch to a FloatTensor every time we sample and then place it on the appropriate device, as this is very time consuming. This class is basically a PyTorch efficient implementation of ExperienceReplay. """ def __init__(self, capacity, seed, state_size, action_size, device): """ Constructor Parameters ---------- capacity : int The capacity of the buffer seed : int The random seed used for sampling from the buffer device : torch.device The device on which the buffer instances should be stored state_size : int The number of dimensions in the state feature vector action_size : int The number of dimensions in the action vector """ super().__init__(capacity, seed, state_size, action_size, device) self.cast = torch.from_numpy def init_buffer(self): self.state_buffer = torch.FloatTensor(self.capacity, *self.state_size) self.state_buffer = self.state_buffer.to(self.device) self.next_state_buffer = torch.FloatTensor(self.capacity, *self.state_size) self.next_state_buffer = self.next_state_buffer.to(self.device) self.action_buffer = torch.FloatTensor(self.capacity, self.action_size) self.action_buffer = self.action_buffer.to(self.device) self.reward_buffer = torch.FloatTensor(self.capacity, 1) self.reward_buffer = self.reward_buffer.to(self.device) self.done_buffer = torch.FloatTensor(self.capacity, 1) self.done_buffer = self.done_buffer.to(self.device)
9,362
33.422794
79
py
GreedyAC
GreedyAC-master/utils/hypers.py
from functools import reduce from collections.abc import Iterable from copy import deepcopy import numpy as np import pickle from tqdm import tqdm try: from utils.runs import expand_episodes except ModuleNotFoundError: from runs import expand_episodes TRAIN = "train" EVAL = "eval" def sweeps(parameters, index): """ Gets the parameters for the hyperparameter sweep defined by the index. Each hyperparameter setting has a specific index number, and this function will get the appropriate parameters for the argument index. In addition, this the indices will wrap around, so if there are a total of 10 different hyperparameter settings, then the indices 0 and 10 will return the same hyperparameter settings. This is useful for performing loops. For example, if you had 10 hyperparameter settings and you wanted to do 10 runs, the you could just call this for indices in range(0, 10*10). If you only wanted to do runs for hyperparameter setting i, then you would use indices in range(i, 10, 10*10) Parameters ---------- parameters : dict The dictionary of parameters, as found in the agent's json configuration file index : int The index of the hyperparameters configuration to return Returns ------- dict, int The dictionary of hyperparameters to use for the agent and the total number of combinations of hyperparameters (highest possible unique index) """ # If the algorithm is a batch algorithm, ensure the batch size if less # than the replay buffer size if "batch_size" in parameters and "replay_capacity" in parameters: batches = np.array(parameters["batch_size"]) replays = np.array(parameters["replay_capacity"]) legal_settings = [] # Calculate the legal combinations of batch sizes and replay capacities for batch in batches: legal = np.where(replays >= batch)[0] legal_settings.extend(list(zip([batch] * len(legal), replays[legal]))) # Replace the configs batch/replay combos with the legal ones parameters["batch/replay"] = legal_settings replaced_hps = ["batch_size", "replay_capacity"] else: replaced_hps = [] # Get the hyperparameters corresponding to the argument index out_params = {} accum = 1 for key in parameters: if key in replaced_hps: # Ignore the HPs that have been sanitized and replaced by a new # set of HPs continue num = len(parameters[key]) if key == "batch/replay": # Batch/replay must be treated differently batch_replay_combo = parameters[key][(index // accum) % num] out_params["batch_size"] = batch_replay_combo[0] out_params["replay_capacity"] = batch_replay_combo[1] accum *= num continue out_params[key] = parameters[key][(index // accum) % num] accum *= num return (out_params, accum) def total(parameters): """ Similar to sweeps but only returns the total number of hyperparameter combinations. This number is the total number of distinct hyperparameter settings. If this function returns k, then there are k distinct hyperparameter settings, and indices 0 and k refer to the same distinct hyperparameter setting. Parameters ---------- parameters : dict The dictionary of parameters, as found in the agent's json configuration file Returns ------- int The number of distinct hyperparameter settings """ return sweeps(parameters, 0)[1] def satisfies(data, f): """ Similar to hold_constant, except uses a function rather than a dictionary. Returns all hyperparameter settings that result in f evaluating to True. For each run, the hyperparameter dictionary for that run is inputted to f. If f returns True, then those hypers are kept. Parameters ---------- data : dict The data dictionary generate from running an experiment f : f(dict) -> bool A function mapping hyperparameter settings (in a dictionary) to a boolean value Returns ------- tuple of list[int], dict The list of hyperparameter settings satisfying the constraints defined by constant_hypers and a dictionary of new hyperparameters which satisfy these constraints """ indices = [] # Generate a new hyperparameter configuration based on the old # configuration new_hypers = deepcopy(data["experiment"]["agent"]["parameters"]) # Clear the hyper configuration for key in new_hypers: if isinstance(new_hypers[key], list): new_hypers[key] = set() for index in data["experiment_data"]: hypers = data["experiment_data"][index]["agent_hyperparams"] if not f(hypers): continue # Track the hyper indices and the full hyper settings indices.append(index) for key in new_hypers: if key not in data["experiment_data"][index]["agent_hyperparams"]: # print(f"{key} not in agent hyperparameters, ignoring...") continue if isinstance(new_hypers[key], set): agent_val = data["experiment_data"][index][ "agent_hyperparams"][key] # Convert lists to a washable type if isinstance(agent_val, list): agent_val = tuple(agent_val) new_hypers[key].add(agent_val) else: if key in new_hypers: value = new_hypers[key] raise IndexError("clobbering existing hyper " + f"{key} with value {value} with " + f"new value {agent_val}") new_hypers[key] = agent_val # Convert each set in new_hypers to a list for key in new_hypers: if isinstance(new_hypers[key], set): new_hypers[key] = sorted(list(new_hypers[key])) return indices, new_hypers def index_of(hypers, equals): """ Return the indices of agent hyperparameter settings that equals the single hyperparameter configuration equals. The argument hypers is not modified. Parameters ---------- hypers : dict[str]any A dictionary of agent hyperparameter settings, which may be a collection of hyperparameter configurations. equals : dict[ctr]any The hyperparameters that hypers should equal to. This should be a single hyperparameter configuration, and not a collection of such configurations. Returns ------- list[ind] The list of indices in hypers which equals to equals """ indices = [] for i in range(total(hypers)): setting = sweeps(hypers, i)[0] if equal(setting, equals): indices.append(i) return indices def equal(hyper1, hyper2): """ Return whether two hyperparameter configurations are equal. These may be single configurations or collections of configurations. Parameters ---------- hyper1 : dict[str]any One of the hyperparameter configurations to check equality for hyper2 : dict[str]any The other hyperparameter configuration to check equality for Returns ------- bool Whether the two hyperparameter settings are equal """ newHyper1 = {} newHyper2 = {} for hyper in ("actor_lr_scale", "critic_lr"): newHyper1[hyper] = hyper1[hyper] newHyper2[hyper] = hyper2[hyper] hyper1 = newHyper1 hyper2 = newHyper2 # Ensure both hypers have the same keys if set(hyper1.keys()) != set(hyper2.keys()): return False equal = True for key in hyper1: value1 = hyper1[key] value2 = hyper2[key] if isinstance(value1, list): value1 = tuple(value1) value2 = tuple(value2) if value1 != value2: equal = False break return equal def hold_constant(data, constant_hypers): """ Returns the hyperparameter settings indices and hyperparameter values of the hyperparameter settings satisfying the constraints constant_hypers. Returns the hyperparameter settings indices in the data that satisfy the constraints as well as a new dictionary of hypers which satisfy the constraints. The indices returned are the hyper indices of the original data and not the indices into the new hyperparameter configuration returned. Parameters ---------- data: dict The data dictionary generated from an experiment constant_hypers: dict[string]any A dictionary mapping hyperparameters to a value that they should be equal to. Returns ------- tuple of list[int], dict The list of hyperparameter settings satisfying the constraints defined by constant_hypers and a dictionary of new hyperparameters which satisfy these constraints Example ------- >>> data = ... >>> contraints = {"stepsize": 0.8} >>> hold_constant(data, constraints) ( [0, 1, 6, 7], { "stepsize": [0.8], "decay": [0.0, 0.5], "epsilon": [0.0, 0.1], } ) """ indices = [] # Generate a new hyperparameter configuration based on the old # configuration new_hypers = deepcopy(data["experiment"]["agent"]["parameters"]) # Clear the hyper configuration for key in new_hypers: if isinstance(new_hypers[key], list): new_hypers[key] = set() # Go through each hyperparameter index, checking if it satisfies the # constraints for index in data["experiment_data"]: # Assume we hyperparameter satisfies the constraints constraint_satisfied = True # Check to see if the agent hyperparameter satisfies the constraints for hyper in constant_hypers: constant_val = constant_hypers[hyper] # Ensure the constrained hyper exists in the data if hyper not in data["experiment_data"][index][ "agent_hyperparams"]: raise IndexError(f"no such hyper {hyper} in agent hypers") agent_val = data["experiment_data"][index]["agent_hyperparams"][ hyper] if agent_val != constant_val: # Hyperparameter does not satisfy the constraints constraint_satisfied = False break # If the constraint is satisfied, then we will store the hypers if constraint_satisfied: indices.append(index) # Add the hypers to the configuration for key in new_hypers: if key == "batch/replay": continue if isinstance(new_hypers[key], set): agent_val = data["experiment_data"][index][ "agent_hyperparams"][key] if isinstance(agent_val, list): agent_val = tuple(agent_val) new_hypers[key].add(agent_val) else: if key in new_hypers: value = new_hypers[key] raise IndexError("clobbering existing hyper " + f"{key} with value {value} with " + f"new value {agent_val}") new_hypers[key] = agent_val # Convert each set in new_hypers to a list for key in new_hypers: if isinstance(new_hypers[key], set): new_hypers[key] = sorted(list(new_hypers[key])) return indices, new_hypers def _combine_two(data1, data2, config): """ Combine two data dictionaries into one, with hypers renumbered to satisfy the configuration config Parameters ---------- data1 : dict The first data dictionary data2 : dict The second data dictionary config : dict The hyperparameter configuration Returns ------- dict The combined data dictionary """ agent1_name = data1["experiment"]["agent"]["agent_name"].lower() agent2_name = data2["experiment"]["agent"]["agent_name"].lower() config_agent_name = config["agent_name"].lower() if agent1_name != agent2_name or config_agent_name != agent1_name: raise ValueError("all data should be generate by the same agent " + f"but got agents {agent1_name}, {agent2_name}, " + f"and {config_agent_name}") # Renumber of the configuration file does not match that with which the # experiment was run if data1["experiment"]["agent"]["parameters"] != config["parameters"]: data1 = renumber(data1, config["parameters"]) if data2["experiment"]["agent"]["parameters"] != config["parameters"]: data2 = renumber(data2, config["parameters"]) new_data = {} new_data["experiment"] = data1["experiment"] new_data["experiment_data"] = {} for hyper in data1["experiment_data"]: new_data["experiment_data"][hyper] = data1["experiment_data"][hyper] for hyper in data2["experiment_data"]: # Before we extend the data, ensure we do not overwrite any runs if hyper in new_data["experiment_data"]: # Get a map of run number -> random seed from the already combined # data seeds = [] for run in new_data["experiment_data"][hyper]["runs"]: seeds.append(run["random_seed"]) for run in data2["experiment_data"][hyper]["runs"]: seed = run["random_seed"] # Don't add a run if it already exists in the combined data. A # run exists in the combined data if its seed has been used. if seed in seeds: continue else: # Run does not exist in the data new_data["experiment_data"][hyper]["runs"].append(run) else: new_data["experiment_data"][hyper] = \ data2["experiment_data"][hyper] return new_data def combine(config, *data): """ Combines a number of data dictionaries, renumbering the hyper settings to satisfy config. Parameters ---------- config : dict The hyperparameter configuration *data : iterable of dict The data dictionaries to combine Returns ------- dict The combined data dictionary """ config_agent_name = config["agent_name"].lower() for d in data: agent_name = d["experiment"]["agent"]["agent_name"].lower() if agent_name != config_agent_name: raise ValueError("all data should be generate by the same agent " + f"but got agents {agent_name} and " + f"{config_agent_name}") return reduce(lambda x, y: _combine_two(x, y, config), data) def renumber(data, hypers): """ Renumbers the hyperparameters in data to reflect the hyperparameter map hypers. If any hyperparameter settings exist in data that do not exist in hypers, then those data are discarded. Note that each hyperparameter listed in hypers must also be listed in data and vice versa, but the specific hyperparameter values need not be the same. For example if "decay" ∈ data[hypers], then it also must be in hypers and vice versa. If 0.9 ∈ data[hypers][decay], then it need *not* be in hypers[decay]. This function does not mutate the input data, but rather returns a copy of the input data, appropriately mutated. Parameters ---------- data : dict The data dictionary generated from running the experiment hypers : dict The new dictionary of hyperparameter values Returns ------- dict The modified data dictionary Examples -------- >>> data = ... >>> contraints = {"stepsize": 0.8} >>> new_hypers = hold_constant(data, constraints)[1] >>> new_data = renumber(data, new_hypers) """ if len(hypers) == 0: return data if hypers == data["experiment"]["agent"]["parameters"]: return data # Ensure each hyperparameter is in both hypers and data; hypers need not # list every hyperparameter *value* that is listed in data, but it needs to # have the same hyperparameters. E.g. if "decay" exists in data then it # should also exist in hypers, but if 0.9 ∈ data[hypers][decay], this value # need not exist in hypers. for key in data["experiment"]["agent"]["parameters"]: if key not in hypers and key != "batch/replay": raise ValueError("data and hypers should have all the same " + f"hyperparameters but {key} ∈ data but ∉ hypers") # Ensure each hyperparameter listed in hypers is also listed in data. If it # isn't then it isn't clear which value of this hyperparamter the data in # data should map to. E.g. if "decay" = [0.1, 0.2] ∈ hypers but ∉ data, # which value should we set for the data in data when renumbering? 0.1 or # 0.2? for key in hypers: if key not in data["experiment"]["agent"]["parameters"]: raise ValueError("data and hypers should have all the same " + f"hyperparameters but {key} ∈ hypers but ∉ data") new_data = {} new_data["experiment"] = data["experiment"] new_data["experiment"]["agent"]["parameters"] = hypers new_data["experiment_data"] = {} total_hypers = total(hypers) for i in range(total_hypers): setting = sweeps(hypers, i)[0] for j in data["experiment_data"]: agent_hypers = data["experiment_data"][j]["agent_hyperparams"] setting_in_data = True # For each hyperparameter value in setting, ensure that the # corresponding agent hyperparameter is equal. If not, ignore that # hyperparameter setting. for key in setting: # If the hyper setting is iterable, then check each value in # the iterable to ensure it is equal to the corresponding # value in the agent hyperparameters if isinstance(setting[key], Iterable): if len(setting[key]) != len(agent_hypers[key]): setting_in_data = False break for k in range(len(setting[key])): if setting[key][k] != agent_hypers[key][k]: setting_in_data = False break # Non-iterable data elif setting[key] != agent_hypers[key]: setting_in_data = False break if setting_in_data: new_data["experiment_data"][i] = data["experiment_data"][j] return new_data def get_performance(data, hyper, type_=TRAIN, repeat=True): """ Returns the data for each run of key, optionally adjusting the runs' data so that each run has the same number of data points. This is accomplished by repeating each episode's performance by the number of timesteps the episode took to complete Parameters ---------- data : dict The data dictionary hyper : int The hyperparameter index to get the run data of repeat : bool Whether or not to repeat the runs data Returns ------- np.array The array of performance data """ if type_ not in (TRAIN, EVAL): raise ValueError(f"unknown type {type_}") key = type_ + "_episode_rewards" if repeat: data = expand_episodes(data, hyper, type_) run_data = [] for run in data["experiment_data"][hyper]["runs"]: run_data.append(run[key]) return np.array(run_data) def best_from_files(files, num_hypers=None, perf=TRAIN, scale_by_episode_length=False, to=-1): """ This function is like `best`, but looks through a list of files rather than a single data dictionary. If `num_hypers` is `None`, then finds total number of hyper settings from the data files. Otherwise, assumes `num_hypers` hyper settings exist in the data. """ # Get the hyperparameter indices in files if num_hypers is None: hyper_inds = set() print("Finding total number of hyper settings") for file in tqdm(files): with open(file, "rb") as infile: d = pickle.load(infile) hyper_inds.update(d["experiment_data"].keys()) num_hypers = len(hyper_inds) hypers = [np.finfo(np.float64).min] * num_hypers print("Finding best hyper setting") hyper_to_files = {} for file in tqdm(files): with open(file, "rb") as infile: data = pickle.load(infile) for hyper in data["experiment_data"]: hyper_data = [] # Store a dictionary of hyper indices to files that contain them if hyper not in hyper_to_files: hyper_to_files[hyper] = [] else: hyper_to_files[hyper].append(file) for run in data["experiment_data"][hyper]["runs"]: if to <= 0: # Tune over all timesteps returns = np.array(run[f"{perf}_episode_rewards"]) scale = np.array(run[f"{perf}_episode_steps"]) else: # Tune only to timestep determined by parameter to cum_steps = np.cumsum(run[f"{perf}_episode_steps"]) returns = np.array(run[f"{perf}_episode_rewards"]) scale = np.array(run[f"{perf}_episode_steps"]) # If the total number of steps we ran the experiment for is # more than the number of steps we want to tune to, then # truncate the trailing data and tune only to the # appropriate timestep if cum_steps[-1] > to: last_step = np.argmax(cum_steps > to) returns = returns[:last_step+1] scale = scale[:last_step + 1] if scale_by_episode_length: # Rescale the last episode such that we only # consider the timesteps up to the argument to, and # not beyond that if len(scale) > 1: last_ep_scale = (to - scale[-2]) else: last_ep_scale = to scale[-1] = last_ep_scale if scale_by_episode_length: pass returns *= scale hyper_data.append(returns.mean()) hyper_data = np.array(hyper_data) hypers[hyper] = hyper_data.mean() del data argmax = np.argmax(hypers) return argmax, hypers[argmax], hyper_to_files[argmax] def best(data, perf=TRAIN, scale_by_episode_length=False, to=-1): """ Returns the hyperparameter index of the hyper setting which resulted in the highest AUC of the learning curve. AUC is calculated by computing the AUC for each run, then taking the average over all runs. Parameters ---------- data : dict The data dictionary perf : str The type of performance to evaluate, train or eval scale_by_episode_length : bool Whether or not each return should be scaled by the length of the episode. This is useful for episodic tasks, but has no effect in continuing tasks as long as the value of the parameter to does not result in a episode being truncated. to : int Only tune to this timestep. If <= 0, then all timesteps are considered. If `scale_by_episode_length == True`, then tune based on all timesteps up until this timestep. If `scale_by_episode_length == False`, then tune based on all episodes until the episode which contains this timestep (inclusive). Returns ------- np.array[int], np.float32 The hyper settings that resulted in the maximum return as well as the maximum return """ max_hyper = int(np.max(list(data["experiment_data"].keys()))) hypers = [np.finfo(np.float64).min] * (max_hyper + 1) for hyper in data["experiment_data"]: hyper_data = [] for run in data["experiment_data"][hyper]["runs"]: if to <= 0: # Tune over all timesteps returns = np.array(run[f"{perf}_episode_rewards"]) scale = np.array(run[f"{perf}_episode_steps"]) else: # Tune only to timestep determined by parameter to cum_steps = np.cumsum(run[f"{perf}_episode_steps"]) returns = np.array(run[f"{perf}_episode_rewards"]) scale = np.array(run[f"{perf}_episode_steps"]) # If the total number of steps we ran the experiment for is # more than the number of steps we want to tune to, then # truncate the trailing data and tune only to the appropriate # timestep if cum_steps[-1] > to: last_step = np.argmax(cum_steps > to) returns = returns[:last_step+1] scale = scale[:last_step + 1] if scale_by_episode_length: # Rescale the last episode such that we only # consider the timesteps up to the argument to, and # not beyond that if len(scale) > 1: last_ep_scale = (to - scale[-2]) else: last_ep_scale = to scale[-1] = last_ep_scale if scale_by_episode_length: returns *= scale hyper_data.append(returns.mean()) hyper_data = np.array(hyper_data) hypers[hyper] = hyper_data.mean() return np.argmax(hypers), np.max(hypers) def get(data, ind): """ Gets the hyperparameters for hyperparameter settings index ind data : dict The Python data dictionary generated from running main.py ind : int Gets the returns of the agent trained with this hyperparameter settings index Returns ------- dict The dictionary of hyperparameters """ return data["experiment_data"][ind]["agent_hyperparams"] def which(data, hypers, equal_keys=False): """ Get the hyperparameter index at which all agent hyperparameters are equal to those specified by hypers. Parameters ---------- data : dict The data dictionary that resulted from running an experiment hypers : dict[string]any A dictionary of hyperparameters to the values that those hyperparameters should take on equal_keys : bool, optional Whether or not all keys must be shared between the sets of agent hyperparameters and the argument hypers. By default False. Returns ------- int, None The hyperparameter index at which the agent had hyperparameters equal to those specified in hypers. Examples -------- >>> data = ... # Some data from an experiment >>> hypers = {"critic_lr": 0.01, "actor_lr": 1.0} >>> ind = which(data, hypers) >>> print(ind in data["experiment_data"]) True """ for ind in data["experiment_data"]: is_equal = True agent_hypers = data["experiment_data"][ind]["agent_hyperparams"] # Ensure that all keys in each dictionary are equal if equal_keys and set(agent_hypers.keys()) != set(hypers.keys()): continue # For the current set of agent hyperparameters (index ind), check to # see if all hyperparameters used by the agent are equal to those # specified by hypers. If not, then break and check the next set of # agent hyperparameters. for h in hypers: if h in agent_hypers and hypers[h] != agent_hypers[h]: is_equal = False break if is_equal: return ind # No agent hyperparameters were found that coincided with the argument # hypers return None
28,864
33.945521
79
py
GreedyAC
GreedyAC-master/utils/experiment_utils.py
# Import modules import numpy as np import bootstrapped.bootstrap as bs import bootstrapped.stats_functions as bs_stats try: import runs except ModuleNotFoundError: import utils.runs def create_agent(agent, config): """ Creates an agent given the agent name and configuration dictionary Parameters ---------- agent : str The name of the agent, one of 'linearAC' or 'SAC' config : dict The agent configuration dictionary Returns ------- baseAgent.BaseAgent The agent to train """ # Random agent if agent.lower() == "random": from agent.Random import Random return Random(config["action_space"], config["seed"]) # Vanilla Actor-Critic if agent.lower() == "VAC".lower(): if "activation" in config: activation = config["activation"] else: activation = "relu" from agent.nonlinear.VAC import VAC return VAC( num_inputs=config["feature_size"], action_space=config["action_space"], gamma=config["gamma"], tau=config["tau"], alpha=config["alpha"], policy=config["policy_type"], target_update_interval=config["target_update_interval"], critic_lr=config["critic_lr"], actor_lr_scale=config["actor_lr_scale"], actor_hidden_dim=config["hidden_dim"], critic_hidden_dim=config["hidden_dim"], replay_capacity=config["replay_capacity"], seed=config["seed"], batch_size=config["batch_size"], cuda=config["cuda"], clip_stddev=config["clip_stddev"], init=config["weight_init"], betas=config["betas"], num_samples=config["num_samples"], activation="relu", env=config["env"], ) # Discrete Vanilla Actor-Critic if agent.lower() == "VACDiscrete".lower(): if "activation" in config: activation = config["activation"] else: activation = "relu" from agent.nonlinear.VACDiscrete import VACDiscrete return VACDiscrete( num_inputs=config["feature_size"], action_space=config["action_space"], gamma=config["gamma"], tau=config["tau"], alpha=config["alpha"], policy=config["policy_type"], target_update_interval=config[ "target_update_interval"], critic_lr=config["critic_lr"], actor_lr_scale=config["actor_lr_scale"], actor_hidden_dim=config["hidden_dim"], critic_hidden_dim=config["hidden_dim"], replay_capacity=config["replay_capacity"], seed=config["seed"], batch_size=config["batch_size"], cuda=config["cuda"], clip_stddev=config["clip_stddev"], init=config["weight_init"], betas=config["betas"], activation="relu", ) # Soft Actor-Critic if agent.lower() == "SAC".lower(): if "activation" in config: activation = config["activation"] else: activation = "relu" if "num_hidden" in config: num_hidden = config["num_hidden"] else: num_hidden = 3 from agent.nonlinear.SAC import SAC return SAC( baseline_actions=config["baseline_actions"], gamma=config["gamma"], tau=config["tau"], alpha=config["alpha"], policy=config["policy_type"], target_update_interval=config["target_update_interval"], critic_lr=config["critic_lr"], actor_lr_scale=config["actor_lr_scale"], alpha_lr=config["alpha_lr"], actor_hidden_dim=config["hidden_dim"], critic_hidden_dim=config["hidden_dim"], replay_capacity=config["replay_capacity"], seed=config["seed"], batch_size=config["batch_size"], automatic_entropy_tuning=config["automatic_entropy_tuning"], cuda=config["cuda"], clip_stddev=config["clip_stddev"], init=config["weight_init"], betas=config["betas"], activation=activation, env=config["env"], soft_q=config["soft_q"], reparameterized=config["reparameterized"], double_q=config["double_q"], num_samples=config["num_samples"], ) # Discrete Soft Actor-Critic if agent.lower() == "SACDiscrete".lower(): if "activation" in config: activation = config["activation"] else: activation = "relu" if "num_hidden" in config: num_hidden = config["num_hidden"] else: num_hidden = 3 from agent.nonlinear.SACDiscrete import SACDiscrete return SACDiscrete( env=config["env"], gamma=config["gamma"], tau=config["tau"], alpha=config["alpha"], policy=config["policy_type"], target_update_interval=config["target_update_interval"], critic_lr=config["critic_lr"], actor_lr_scale=config["actor_lr_scale"], actor_hidden_dim=config["hidden_dim"], critic_hidden_dim=config["hidden_dim"], replay_capacity=config["replay_capacity"], seed=config["seed"], batch_size=config["batch_size"], cuda=config["cuda"], clip_stddev=config["clip_stddev"], init=config["weight_init"], betas=config["betas"], activation=activation, double_q=config["double_q"], soft_q=config["soft_q"], ) # Discrete GreedyAC if agent.lower() == "GreedyACDiscrete".lower(): if "activation" in config: activation = config["activation"] else: activation = "relu" from agent.nonlinear.GreedyACDiscrete import GreedyACDiscrete return GreedyACDiscrete( num_inputs=config["feature_size"], action_space=config["action_space"], gamma=config["gamma"], tau=config["tau"], policy=config["policy_type"], target_update_interval=config[ "target_update_interval"], critic_lr=config["critic_lr"], actor_lr_scale=config["actor_lr_scale"], actor_hidden_dim=config["hidden_dim"], critic_hidden_dim=config["hidden_dim"], replay_capacity=config["replay_capacity"], seed=config["seed"], batch_size=config["batch_size"], cuda=config["cuda"], clip_stddev=config["clip_stddev"], init=config["weight_init"], betas=config["betas"], activation=activation, ) # GreedyAC if agent.lower() == "GreedyAC".lower(): if "activation" in config: activation = config["activation"] else: activation = "relu" from agent.nonlinear.GreedyAC import GreedyAC return GreedyAC( num_inputs=config["feature_size"], action_space=config["action_space"], gamma=config["gamma"], tau=config["tau"], alpha=config["alpha"], policy=config["policy_type"], target_update_interval=config["target_update_interval"], critic_lr=config["critic_lr"], actor_lr_scale=config["actor_lr_scale"], actor_hidden_dim=config["hidden_dim"], critic_hidden_dim=config["hidden_dim"], replay_capacity=config["replay_capacity"], seed=config["seed"], batch_size=config["batch_size"], cuda=config["cuda"], clip_stddev=config["clip_stddev"], init=config["weight_init"], rho=config["n_rho"][1], num_samples=config["n_rho"][0], betas=config["betas"], activation=activation, env=config["env"], ) raise NotImplementedError("No agent " + agent) def _calculate_mean_return_episodic(hp_returns, type_, after=0): """ Calculates the mean return for an experiment run on an episodic environment over all runs and episodes Parameters ---------- hp_returns : Iterable of Iterable A list of lists, where the outer list has a single inner list for each run. The inner lists store the return per episode for that run. Note that these returns should be for a single hyperparameter setting, as everything in these lists are averaged and returned as the average return. type_ : str Whether calculating the training or evaluation mean returns, one of 'train', 'eval' after : int, optional Only consider episodes after this episode, by default 0 Returns ------- 2-tuple of float The mean and standard error of the returns over all episodes and all runs """ if type_ == "eval": hp_returns = [np.mean(hp_returns[i][after:], axis=-1) for i in range(len(hp_returns))] # Calculate the average return for all episodes in the run run_returns = [np.mean(hp_returns[i][after:]) for i in range(len(hp_returns))] mean = np.mean(run_returns) stderr = np.std(run_returns) / np.sqrt(len(hp_returns)) return mean, stderr def _calculate_mean_return_episodic_conf(hp_returns, type_, significance, after=0): """ Calculates the mean return for an experiment run on an episodic environment over all runs and episodes Parameters ---------- hp_returns : Iterable of Iterable A list of lists, where the outer list has a single inner list for each run. The inner lists store the return per episode for that run. Note that these returns should be for a single hyperparameter setting, as everything in these lists are averaged and returned as the average return. type_ : str Whether calculating the training or evaluation mean returns, one of 'train', 'eval' significance: float The level of significance for the confidence interval after : int, optional Only consider episodes after this episode, by default 0 Returns ------- 2-tuple of float The mean and standard error of the returns over all episodes and all runs """ if type_ == "eval": hp_returns = [np.mean(hp_returns[i][after:], axis=-1) for i in range(len(hp_returns))] # Calculate the average return for all episodes in the run run_returns = [np.mean(hp_returns[i][after:]) for i in range(len(hp_returns))] mean = np.mean(run_returns) run_returns = np.array(run_returns) conf = bs.bootstrap(run_returns, stat_func=bs_stats.mean, alpha=significance) return mean, conf def _calculate_mean_return_continuing(hp_returns, type_, after=0): """ Calculates the mean return for an experiment run on a continuing environment over all runs and episodes Parameters ---------- hp_returns : Iterable of Iterable A list of lists, where the outer list has a single inner list for each run. The inner lists store the return per episode for that run. Note that these returns should be for a single hyperparameter setting, as everything in these lists are averaged and returned as the average return. type_ : str Whether calculating the training or evaluation mean returns, one of 'train', 'eval' after : int, optional Only consider episodes after this episode, by default 0 Returns ------- 2-tuple of float The mean and standard error of the returns over all episodes and all runs """ hp_returns = np.stack(hp_returns) # If evaluating, use the mean return over all episodes for each # evaluation interval. That is, if 10 eval episodes for each # evaluation the take the average return over all these eval # episodes if type_ == "eval": hp_returns = hp_returns.mean(axis=-1) # Calculate the average return over all runs hp_returns = hp_returns[after:, :].mean(axis=-1) # Calculate the average return over all "episodes" stderr = np.std(hp_returns) / np.sqrt(len(hp_returns)) mean = hp_returns.mean(axis=0) return mean, stderr def _calculate_mean_return_continuing_conf(hp_returns, type_, significance, after=0): """ Calculates the mean return for an experiment run on a continuing environment over all runs and episodes Parameters ---------- hp_returns : Iterable of Iterable A list of lists, where the outer list has a single inner list for each run. The inner lists store the return per episode for that run. Note that these returns should be for a single hyperparameter setting, as everything in these lists are averaged and returned as the average return. type_ : str Whether calculating the training or evaluation mean returns, one of 'train', 'eval' after : int, optional Only consider episodes after this episode, by default 0 Returns ------- 2-tuple of float The mean and standard error of the returns over all episodes and all runs """ hp_returns = np.stack(hp_returns) # If evaluating, use the mean return over all episodes for each # evaluation interval. That is, if 10 eval episodes for each # evaluation the take the average return over all these eval # episodes if type_ == "eval": hp_returns = hp_returns.mean(axis=-1) # Calculate the average return over all episodes hp_returns = hp_returns[after:, :].mean(axis=-1) # Calculate the average return over all runs mean = hp_returns.mean(axis=0) conf = bs.bootstrap(hp_returns, stat_func=bs_stats.mean, alpha=significance) return mean, conf def combine_runs(data1, data2): """ Adds the runs for each hyperparameter setting in data2 to the runs for the corresponding hyperparameter setting in data1. Given two data dictionaries, this function will get each hyperparameter setting and extend the runs done on this hyperparameter setting and saved in data1 by the runs of this hyperparameter setting and saved in data2. In short, this function extends the lists data1["experiment_data"][i]["runs"] by the lists data2["experiment_data"][i]["runs"] for all i. This is useful if multiple runs are done at different times, and the two data files need to be combined. Parameters ---------- data1 : dict A data dictionary as generated by main.py data2 : dict A data dictionary as generated by main.py Raises ------ KeyError If a hyperparameter setting exists in data2 but not in data1. This signals that the hyperparameter settings indices are most likely different, so the hyperparameter index i in data1 does not correspond to the same hyperparameter index in data2. In addition, all other functions expect the number of runs to be consistent for each hyperparameter setting, which would be violated in this case. """ for hp_setting in data1["experiment_data"]: if hp_setting not in list(data2.keys()): # Ensure consistent hyperparam settings indices raise KeyError("hyperparameter settings are different " + "between the two experiments") extra_runs = data2["experiment_data"][hp_setting]["runs"] data1["experiment_data"][hp_setting]["runs"].extend(extra_runs) def get_returns(data, type_, ind, env_type="continuing"): """ Gets the returns seen by an agent Gets the online or offline returns seen by an agent trained with hyperparameter settings index ind. Parameters ---------- data : dict The Python data dictionary generated from running main.py type_ : str Whether to get the training or evaluation returns, one of 'train', 'eval' ind : int Gets the returns of the agent trained with this hyperparameter settings index env_type : str, optional The type of environment, one of 'continuing', 'episodic'. By default 'continuing' Returns ------- array_like The array of returns of the form (N, R, C) where N is the number of runs, R is the number of times a performance was measured, and C is the number of returns generated each time performance was measured (offline >= 1; online = 1). For the online setting, N is the number of runs, and R is the number of episodes and C = 1. For the offline setting, N is the number of runs, R is the number of times offline evaluation was performed, and C is the number of episodes run each time performance was evaluated offline. """ if env_type == "episodic": data = runs.expand_episodes(data, ind, type_) returns = [] if type_ == "eval": # Get the offline evaluation episode returns per run if data['experiment']['environment']['eval_episodes'] == 0: raise ValueError("cannot plot eval performance when " + "experiment was run with eval_episodes = 0 in " + "the configuration file") for run in data["experiment_data"][ind]["runs"]: returns.append(run["eval_episode_rewards"]) returns = np.stack(returns) elif type_ == "train": # Get the returns per episode per run for run in data["experiment_data"][ind]["runs"]: returns.append(run["train_episode_rewards"]) returns = np.expand_dims(np.stack(returns), axis=-1) return returns def get_mean_err(data, type_, ind, smooth_over, error, env_type="continuing", keep_shape=False, err_args={}): """ Gets the timesteps, mean, and standard error to be plotted for a given hyperparameter settings index Note: This function assumes that each run has an equal number of episodes. This is true for continuing tasks. For episodic tasks, you will need to cutoff the episodes so all runs have the same number of episodes. Parameters ---------- data : dict The Python data dictionary generated from running main.py type_ : str Which type of data to plot, one of "eval" or "train" ind : int The hyperparameter settings index to plot smooth_over : int The number of previous data points to smooth over. Note that this is *not* the number of timesteps to smooth over, but rather the number of data points to smooth over. For example, if you save the return every 1,000 timesteps, then setting this value to 15 will smooth over the last 15 readings, or 15,000 timesteps. error: function The error function to compute the error with env_type : str, optional The type of environment the data was generated on keep_shape : bool, optional Whether or not the smoothed data should discard or keep the first few data points before smooth_over. err_args : dict A dictionary of keyword arguments to pass to the error function Returns ------- 3-tuple of list(int), list(float), list(float) The timesteps, mean episodic returns, and standard errors of the episodic returns """ timesteps = None # So the linter doesn't have a temper tantrum # Determine the timesteps to plot at if type_ == "eval": timesteps = \ data["experiment_data"][ind]["runs"][0]["timesteps_at_eval"] elif type_ == "train": timesteps_per_ep = \ data["experiment_data"][ind]["runs"][0]["train_episode_steps"] timesteps = get_cumulative_timesteps(timesteps_per_ep) # Get the mean over all episodes per evaluation step (for online # returns, this axis will have length 1 so we squeeze it) returns = get_returns(data, type_, ind, env_type=env_type) returns = returns.mean(axis=-1) returns = smooth(returns, smooth_over, keep_shape=keep_shape) # Get the standard error of mean episodes per evaluation # step over all runs if error is not None: err = error(returns, **err_args) else: err = None # Get the mean over all runs mean = returns.mean(axis=0) # Return only the valid portion of timesteps. If smoothing and not # keeping the first data points, then the first smooth_over columns # will not have any data if not keep_shape: end = len(timesteps) - smooth_over + 1 timesteps = timesteps[:end] return timesteps, mean, err def stderr(matrix, axis=0): """ Calculates the standard error along a specified axis Parameters ---------- matrix : array_like The matrix to calculate standard error along the rows of axis : int, optional The axis to calculate the standard error along, by default 0 Returns ------- array_like The standard error of each row along the specified axis Raises ------ np.AxisError If an invalid axis is passed in """ if axis > len(matrix.shape) - 1: raise np.AxisError(f"""axis {axis} is out of bounds for array with {len(matrix.shape) - 1} dimensions""") samples = matrix.shape[axis] return np.std(matrix, axis=axis) / np.sqrt(samples) def smooth(matrix, smooth_over, keep_shape=False, axis=1): """ Smooth the rows of returns Smooths the rows of returns by replacing the value at index i in a row of returns with the average of the next smooth_over elements, starting at element i. Parameters ---------- matrix : array_like The array to smooth over smooth_over : int The number of elements to smooth over keep_shape : bool, optional Whether the smoothed array should have the same shape as as the input array, by default True. If True, then for the first few i < smooth_over columns of the input array, the element at position i is replaced with the average of all elements at positions j <= i. Returns ------- array_like The smoothed over array """ if smooth_over > 1: # Smooth each run separately kernel = np.ones(smooth_over) / smooth_over smoothed_matrix = _smooth(matrix, kernel, "valid", axis=axis) # Smooth the first few episodes if keep_shape: beginning_cols = [] for i in range(1, smooth_over): # Calculate smoothing over the first i columns beginning_cols.append(matrix[:, :i].mean(axis=1)) # Numpy will use each smoothed col as a row, so transpose beginning_cols = np.array(beginning_cols).transpose() else: return matrix if keep_shape: # Return the smoothed array return np.concatenate([beginning_cols, smoothed_matrix], axis=1) else: return smoothed_matrix def _smooth(matrix, kernel, mode="valid", axis=0): """ Performs an axis-wise convolution of matrix with kernel Parameters ---------- matrix : array_like The matrix to convolve kernel : array_like The kernel to convolve on each row of matrix mode : str, optional The mode of convolution, by default "valid". One of 'valid', 'full', 'same' axis : int, optional The axis to perform the convolution along, by default 0 Returns ------- array_like The convolved array Raises ------ ValueError If kernel is multi-dimensional """ if len(kernel.shape) != 1: raise ValueError("kernel must be 1D") def convolve(mat): return np.convolve(mat, kernel, mode=mode) return np.apply_along_axis(convolve, axis=axis, arr=matrix) def get_cumulative_timesteps(timesteps_per_episode): """ Creates an array of cumulative timesteps. Creates an array of timesteps, where each timestep is the cumulative number of timesteps up until that point. This is needed for plotting the training data, where the training timesteps are stored for each episode, and we need to plot on the x-axis the cumulative timesteps, not the timesteps per episode. Parameters ---------- timesteps_per_episode : list A list where each element in the list denotes the amount of timesteps for the corresponding episode. Returns ------- array_like An array where each element is the cumulative number of timesteps up until that point. """ timesteps_per_episode = np.array(timesteps_per_episode) cumulative_timesteps = [timesteps_per_episode[:i].sum() for i in range(timesteps_per_episode.shape[0])] return np.array(cumulative_timesteps)
25,362
34.37378
79
py
GreedyAC
GreedyAC-master/agent/Random.py
#!/usr/bin/env python3 # Adapted from https://github.com/pranz24/pytorch-soft-actor-critic # Import modules import torch import numpy as np from agent.baseAgent import BaseAgent class Random(BaseAgent): """ Random implement a random agent, which is one which samples uniformly from all available actions. """ def __init__(self, action_space, seed): super().__init__() self.batch = False self.action_dims = len(action_space.high) self.action_low = action_space.low self.action_high = action_space.high # Set the seed for all random number generators, this includes # everything used by PyTorch, including setting the initial weights # of networks. PyTorch prefers seeds with many non-zero binary units self.torch_rng = torch.manual_seed(seed) self.rng = np.random.default_rng(seed) self.policy = torch.distributions.Uniform( torch.Tensor(action_space.low), torch.Tensor(action_space.high)) def sample_action(self, _): """ Samples an action from the agent Parameters ---------- _ : np.array The state feature vector Returns ------- array_like of float The action to take """ action = self.policy.sample() return action.detach().cpu().numpy() def sample_action_(self, _, size): """ sample_action_ is like sample_action, except the rng for action selection in the environment is not affected by running this function. """ return self.rng.uniform(self.action_low, self.action_high, size=(size, self.action_dims)) def update(self, _, _1, _2, _3, _4): pass def update_value_fn(self, _, _1, _2, _3, _4, _5): pass def reset(self): """ Resets the agent between episodes """ pass def eval(self): pass def train(self): pass # Save model parameters def save_model(self, _, _1="", _2=None, _3=None): pass # Load model parameters def load_model(self, _, _1): pass def get_parameters(self): pass
2,248
24.556818
78
py
GreedyAC
GreedyAC-master/agent/baseAgent.py
#!/usr/bin/env python3 # Import modules from abc import ABC, abstractmethod # TODO: Given a data dictionary generated by main, create a static # function to initialize any agent based on this dict. Note that since the # dict has the agent name, only one function is needed to create ANY agent # we could also use the experiment util create_agent() function class BaseAgent(ABC): """ Class BaseAgent implements the base functionality for all agents Attributes ---------- self.batch : bool Whether or not the agent is using batch updates, by default False. self.info : dict A dictionary which records agent info """ def __init__(self): """ Constructor """ self.batch = False self.info = {} """ BaseAgent is the abstract base class for all agents """ @abstractmethod def sample_action(self, state): """ Samples an action from the agent Parameters ---------- state : np.array The state feature vector Returns ------- array_like of float The action to take """ pass @abstractmethod def update(self, state, action, reward, next_state, done_mask): """ Takes a single update step, which may be a number of offline batch updates Parameters ---------- state : np.array or array_like of np.array The state feature vector action : np.array of float or array_like of np.array The action taken reward : float or array_like of float The reward seen by the agent after taking the action next_state : np.array or array_like of np.array The feature vector of the next state transitioned to after the agent took the argument action done_mask : bool or array_like of bool False if the agent reached the goal, True if the agent did not reach the goal yet the episode ended (e.g. max number of steps reached) Return ------ 4-tuple of array_like A tuple containing array_like, each of which contains the states, actions, rewards, and next states used in the update """ pass @abstractmethod def reset(self): """ Resets the agent between episodes """ pass @abstractmethod def eval(self): """ Sets the agent into offline evaluation mode, where the agent will not explore """ pass @abstractmethod def train(self): """ Sets the agent to online training mode, where the agent will explore """ pass @abstractmethod def get_parameters(self): """ Gets all learned agent parameters such that training can be resumed. Gets all parameters of the agent such that, if given the hyperparameters of the agent, training is resumable from this exact point. This include the learned average reward, the learned entropy, and other such learned values if applicable. This does not only apply to the weights of the agent, but *all* values that have been learned or calculated during training such that, given these values, training can be resumed from this exact point. For example, in the LinearAC class, we must save not only the actor and critic weights, but also the accumulated eligibility traces. Returns ------- dict of str to int, float, array_like, and/or torch.Tensor The agent's weights """ pass
3,716
28.975806
77
py
GreedyAC
GreedyAC-master/agent/nonlinear/VACDiscrete.py
# Import modules import torch import inspect import time from gym.spaces import Box, Discrete import numpy as np import torch.nn.functional as F from torch.optim import Adam from agent.baseAgent import BaseAgent import agent.nonlinear.nn_utils as nn_utils from agent.nonlinear.policy.MLP import Softmax from agent.nonlinear.value_function.MLP import Q as QMLP from utils.experience_replay import TorchBuffer as ExperienceReplay class VACDiscrete(BaseAgent): def __init__(self, num_inputs, action_space, gamma, tau, alpha, policy, target_update_interval, critic_lr, actor_lr_scale, actor_hidden_dim, critic_hidden_dim, replay_capacity, seed, batch_size, betas, cuda=False, clip_stddev=1000, init=None, activation="relu"): """ Constructor Parameters ---------- num_inputs : int The number of input features action_space : gym.spaces.Space The action space from the gym environment gamma : float The discount factor tau : float The weight of the weighted average, which performs the soft update to the target critic network's parameters toward the critic network's parameters, that is: target_parameters = ((1 - τ) * target_parameters) + (τ * source_parameters) alpha : float The entropy regularization temperature. See equation (1) in paper. policy : str The type of policy, currently, only support "softmax" target_update_interval : int The number of updates to perform before the target critic network is updated toward the critic network critic_lr : float The critic learning rate actor_lr : float The actor learning rate actor_hidden_dim : int The number of hidden units in the actor's neural network critic_hidden_dim : int The number of hidden units in the critic's neural network replay_capacity : int The number of transitions stored in the replay buffer seed : int The random seed so that random samples of batches are repeatable batch_size : int The number of elements in a batch for the batch update cuda : bool, optional Whether or not cuda should be used for training, by default False. Note that if True, cuda is only utilized if available. clip_stddev : float, optional The value at which the standard deviation is clipped in order to prevent numerical overflow, by default 1000. If <= 0, then no clipping is done. init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. Raises ------ ValueError If the batch size is larger than the replay buffer """ super().__init__() self.batch = True # Ensure batch size < replay capacity if batch_size > replay_capacity: raise ValueError("cannot have a batch larger than replay " + "buffer capacity") # Set the seed for all random number generators, this includes # everything used by PyTorch, including setting the initial weights # of networks. PyTorch prefers seeds with many non-zero binary units self.torch_rng = torch.manual_seed(seed) self.rng = np.random.default_rng(seed) self.is_training = True self.gamma = gamma self.tau = tau self.alpha = alpha self.discrete_action = isinstance(action_space, Discrete) self.state_dims = num_inputs self.device = torch.device("cuda:0" if cuda and torch.cuda.is_available() else "cpu") if isinstance(action_space, Box): raise ValueError("VACDiscrete can only be used with " + "discrete actions") elif isinstance(action_space, Discrete): self.action_dims = 1 # Keep a replay buffer self.replay = ExperienceReplay(replay_capacity, seed, (num_inputs,), 1, self.device) self.batch_size = batch_size # Set the interval between timesteps when the target network should be # updated and keep a running total of update number self.target_update_interval = target_update_interval self.update_number = 0 # Create the critic Q function if isinstance(action_space, Box): action_shape = action_space.shape[0] elif isinstance(action_space, Discrete): action_shape = 1 self.critic = QMLP(num_inputs, action_shape, critic_hidden_dim, init, activation).to( device=self.device) self.critic_optim = Adam(self.critic.parameters(), lr=critic_lr, betas=betas) self.critic_target = QMLP(num_inputs, action_shape, critic_hidden_dim, init, activation).to( self.device) nn_utils.hard_update(self.critic_target, self.critic) self.policy_type = policy.lower() actor_lr = actor_lr_scale * critic_lr if self.policy_type == "softmax": self.num_actions = action_space.n self.policy = Softmax(num_inputs, self.num_actions, actor_hidden_dim, activation, init).to(self.device) self.policy_optim = Adam(self.policy.parameters(), lr=actor_lr, betas=betas) else: raise NotImplementedError(f"policy type {policy} not implemented") source = inspect.getsource(inspect.getmodule(inspect.currentframe())) self.info = {} self.info = { "source": source, } def sample_action(self, state): state = torch.FloatTensor(state).to(self.device).unsqueeze(0) if self.is_training: action, _, _ = self.policy.sample(state) else: _, _, action = self.policy.sample(state) act = action.detach().cpu().numpy()[0] if not self.discrete_action: return act else: return int(act) def update(self, state, action, reward, next_state, done_mask): if self.discrete_action: action = np.array([action]) # Keep transition in replay buffer self.replay.push(state, action, reward, next_state, done_mask) # Sample a batch from memory state_batch, action_batch, reward_batch, next_state_batch, \ mask_batch = self.replay.sample(batch_size=self.batch_size) if state_batch is None: # Not enough samples in buffer return # When updating Q functions, we don't want to backprop through the # policy and target network parameters with torch.no_grad(): next_state_action, _, _ = \ self.policy.sample(next_state_batch) qf_next_value = self.critic_target(next_state_batch, next_state_action) q_target = reward_batch + mask_batch * self.gamma * qf_next_value q_prediction = self.critic(state_batch, action_batch) q_loss = F.mse_loss(q_prediction, q_target) # Update the critic self.critic_optim.zero_grad() q_loss.backward() self.critic_optim.step() # Calculate the actor loss using Eqn(5) in FKL/RKL paper # No need to use a baseline in this setting state_batch = state_batch.repeat_interleave(self.num_actions, dim=0) actions = torch.tensor([n for n in range(self.num_actions)]) actions = actions.repeat(self.batch_size) actions = actions.unsqueeze(-1) q = self.critic(state_batch, actions) log_prob = self.policy.log_prob(state_batch, actions) prob = log_prob.exp() with torch.no_grad(): scale = q - log_prob * self.alpha policy_loss = prob * scale policy_loss = policy_loss.reshape([self.batch_size, self.num_actions]) policy_loss = -policy_loss.sum(dim=1).mean() # Update the actor self.policy_optim.zero_grad() policy_loss.backward() self.policy_optim.step() # Update target network self.update_number += 1 if self.update_number % self.target_update_interval == 0: self.update_number = 0 nn_utils.soft_update(self.critic_target, self.critic, self.tau) def reset(self): pass def eval(self): self.is_training = False def train(self): self.is_training = True def save_model(self, env_name, suffix="", actor_path=None, critic_path=None): pass def load_model(self, actor_path, critic_path): pass def get_parameters(self): pass
9,344
37.29918
78
py
GreedyAC
GreedyAC-master/agent/nonlinear/GreedyAC.py
# Import modules from gym.spaces import Box, Discrete import torch import torch.nn.functional as F from torch.optim import Adam import numpy as np from agent.baseAgent import BaseAgent from utils.experience_replay import TorchBuffer as ExperienceReplay from agent.nonlinear.value_function.MLP import Q as QMLP from agent.nonlinear.policy.MLP import SquashedGaussian, Gaussian, Softmax import agent.nonlinear.nn_utils as nn_utils import inspect class GreedyAC(BaseAgent): """ GreedyAC implements the GreedyAC algorithm with continuous actions. """ def __init__(self, num_inputs, action_space, gamma, tau, alpha, policy, target_update_interval, critic_lr, actor_lr_scale, actor_hidden_dim, critic_hidden_dim, replay_capacity, seed, batch_size, rho, num_samples, betas, env, cuda=False, clip_stddev=1000, init=None, entropy_from_single_sample=True, activation="relu"): super().__init__() self.batch = True # Ensure batch size < replay capacity if batch_size > replay_capacity: raise ValueError("cannot have a batch larger than replay " + "buffer capacity") # Set the seed for all random number generators, this includes # everything used by PyTorch, including setting the initial weights # of networks. PyTorch prefers seeds with many non-zero binary units self.torch_rng = torch.manual_seed(seed) self.rng = np.random.default_rng(seed) self.is_training = True self.entropy_from_single_sample = entropy_from_single_sample self.gamma = gamma self.tau = tau # Polyak average self.alpha = alpha # Entropy scale self.state_dims = num_inputs self.discrete_action = isinstance(action_space, Discrete) self.action_space = action_space self.device = torch.device("cuda:0" if cuda and torch.cuda.is_available() else "cpu") if isinstance(action_space, Box): self.action_dims = len(action_space.high) # Keep a replay buffer self.replay = ExperienceReplay(replay_capacity, seed, env.observation_space.shape, action_space.shape[0], self.device) elif isinstance(action_space, Discrete): self.action_dims = 1 # Keep a replay buffer self.replay = ExperienceReplay(replay_capacity, seed, env.observation_space.shape, 1, self.device) self.batch_size = batch_size # Set the interval between timesteps when the target network should be # updated and keep a running total of update number self.target_update_interval = target_update_interval self.update_number = 0 # For GreedyAC update self.rho = rho self.num_samples = num_samples # Create the critic Q function if isinstance(action_space, Box): action_shape = action_space.shape[0] elif isinstance(action_space, Discrete): action_shape = 1 self.critic = QMLP(num_inputs, action_shape, critic_hidden_dim, init, activation).to(device=self.device) self.critic_optim = Adam(self.critic.parameters(), lr=critic_lr, betas=betas) self.critic_target = QMLP(num_inputs, action_shape, critic_hidden_dim, init, activation).to( self.device) nn_utils.hard_update(self.critic_target, self.critic) self._create_policies(policy, num_inputs, action_space, actor_hidden_dim, clip_stddev, init, activation) actor_lr = actor_lr_scale * critic_lr self.policy_optim = Adam(self.policy.parameters(), lr=actor_lr, betas=betas) self.sampler_optim = Adam(self.sampler.parameters(), lr=actor_lr, betas=betas) nn_utils.hard_update(self.sampler, self.policy) self.is_training = True source = inspect.getsource(inspect.getmodule(inspect.currentframe())) self.info["source"] = source def update(self, state, action, reward, next_state, done_mask): # Adjust action shape to ensure it fits in replay buffer properly if self.discrete_action: action = np.array([action]) # Keep transition in replay buffer self.replay.push(state, action, reward, next_state, done_mask) # Sample a batch from memory state_batch, action_batch, reward_batch, next_state_batch, \ mask_batch = self.replay.sample(batch_size=self.batch_size) if state_batch is None: # Too few samples in the buffer to sample return # When updating Q functions, we don't want to backprop through the # policy and target network parameters next_state_action, _, _ = self.policy.sample(next_state_batch) with torch.no_grad(): next_q = self.critic_target(next_state_batch, next_state_action) target_q_value = reward_batch + mask_batch * self.gamma * next_q q_value = self.critic(state_batch, action_batch) # Calculate the loss on the critic # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] q_loss = F.mse_loss(target_q_value, q_value) # Update the critic self.critic_optim.zero_grad() q_loss.backward() self.critic_optim.step() # Update target networks self.update_number += 1 if self.update_number % self.target_update_interval == 0: self.update_number = 0 nn_utils.soft_update(self.critic_target, self.critic, self.tau) # Sample actions from the sampler to determine which to update # with action_batch, _, _, = self.sampler.sample(state_batch, self.num_samples) action_batch = action_batch.permute(1, 0, 2) action_batch = action_batch.reshape(self.batch_size * self.num_samples, self.action_dims) stacked_s_batch = state_batch.repeat_interleave(self.num_samples, dim=0) # Get the values of the sampled actions and find the best # ϱ * num_samples actions with torch.no_grad(): q_values = self.critic(stacked_s_batch, action_batch) q_values = q_values.reshape(self.batch_size, self.num_samples, 1) sorted_q = torch.argsort(q_values, dim=1, descending=True) best_ind = sorted_q[:, :int(self.rho * self.num_samples)] best_ind = best_ind.repeat_interleave(self.action_dims, -1) action_batch = action_batch.reshape(self.batch_size, self.num_samples, self.action_dims) best_actions = torch.gather(action_batch, 1, best_ind) # Reshape samples for calculating the loss samples = int(self.rho * self.num_samples) stacked_s_batch = state_batch.repeat_interleave(samples, dim=0) best_actions = torch.reshape(best_actions, (-1, self.action_dims)) # Actor loss # print(stacked_s_batch.shape, best_actions.shape) # print("Computing actor loss") policy_loss = self.policy.log_prob(stacked_s_batch, best_actions) policy_loss = -policy_loss.mean() # Update actor self.policy_optim.zero_grad() policy_loss.backward() self.policy_optim.step() # Calculate sampler entropy stacked_s_batch = state_batch.repeat_interleave(self.num_samples, dim=0) stacked_s_batch = stacked_s_batch.reshape(-1, self.state_dims) action_batch = action_batch.reshape(-1, self.action_dims) sampler_entropy = self.sampler.log_prob(stacked_s_batch, action_batch) with torch.no_grad(): sampler_entropy *= sampler_entropy sampler_entropy = sampler_entropy.reshape(self.batch_size, self.num_samples, 1) if self.entropy_from_single_sample: sampler_entropy = -sampler_entropy[:, 0, :] else: sampler_entropy = -sampler_entropy.mean(axis=1) # Calculate sampler loss stacked_s_batch = state_batch.repeat_interleave(samples, dim=0) sampler_loss = self.sampler.log_prob(stacked_s_batch, best_actions) sampler_loss = sampler_loss.reshape(self.batch_size, samples, 1) sampler_loss = sampler_loss.mean(axis=1) sampler_loss = sampler_loss + (sampler_entropy * self.alpha) sampler_loss = -sampler_loss.mean() # Update the sampler self.sampler_optim.zero_grad() sampler_loss.backward() self.sampler_optim.step() def sample_action(self, state): state = torch.FloatTensor(state).to(self.device).unsqueeze(0) if self.is_training: action, _, _ = self.policy.sample(state) else: _, _, action = self.policy.sample(state) act = action.detach().cpu().numpy()[0] if not self.discrete_action: return act else: return int(act[0]) def reset(self): pass def eval(self): self.is_training = False def train(self): self.is_training = True def _create_policies(self, policy, num_inputs, action_space, actor_hidden_dim, clip_stddev, init, activation): self.policy_type = policy.lower() if self.policy_type == "gaussian": self.policy = Gaussian(num_inputs, action_space.shape[0], actor_hidden_dim, activation, action_space, clip_stddev, init).to(self.device) self.sampler = Gaussian(num_inputs, action_space.shape[0], actor_hidden_dim, activation, action_space, clip_stddev, init).to(self.device) elif self.policy_type == "squashedgaussian": self.policy = SquashedGaussian(num_inputs, action_space.shape[0], actor_hidden_dim, activation, action_space, clip_stddev, init).to(self.device) self.sampler = SquashedGaussian(num_inputs, action_space.shape[0], actor_hidden_dim, activation, action_space, clip_stddev, init).to(self.device) elif self.policy_type == "softmax": num_actions = action_space.n self.policy = Softmax(num_inputs, num_actions, actor_hidden_dim, activation, action_space, init).to(self.device) self.sampler = Softmax(num_inputs, num_actions, actor_hidden_dim, activation, action_space, init).to(self.device) else: raise NotImplementedError def get_parameters(self): pass def save_model(self, env_name, suffix="", actor_path=None, critic_path=None): pass def load_model(self, actor_path, critic_path): pass
11,905
40.340278
79
py
GreedyAC
GreedyAC-master/agent/nonlinear/GreedyACDiscrete.py
# Import modules from gym.spaces import Box, Discrete import inspect import torch import torch.nn.functional as F from torch.optim import Adam import numpy as np from agent.baseAgent import BaseAgent from utils.experience_replay import TorchBuffer as ExperienceReplay from agent.nonlinear.value_function.MLP import Q as QMLP from agent.nonlinear.policy.MLP import Softmax import agent.nonlinear.nn_utils as nn_utils class GreedyACDiscrete(BaseAgent): """ GreedyACDiscrete implements the GreedyAC algorithm with discrete actions """ def __init__(self, num_inputs, action_space, gamma, tau, policy, target_update_interval, critic_lr, actor_lr_scale, actor_hidden_dim, critic_hidden_dim, replay_capacity, seed, batch_size, betas, cuda=False, clip_stddev=1000, init=None, entropy_from_single_sample=True, activation="relu"): super().__init__() self.batch = True # The number of top actions to increase the probability of taking self.top_actions = 1 # Ensure batch size < replay capacity if batch_size > replay_capacity: raise ValueError("cannot have a batch larger than replay " + "buffer capacity") # Set the seed for all random number generators, this includes # everything used by PyTorch, including setting the initial weights # of networks. PyTorch prefers seeds with many non-zero binary units self.torch_rng = torch.manual_seed(seed) self.rng = np.random.default_rng(seed) self.is_training = True self.entropy_from_single_sample = entropy_from_single_sample self.gamma = gamma self.tau = tau # Polyak average self.state_dims = num_inputs self.device = torch.device("cuda:0" if cuda and torch.cuda.is_available() else "cpu") if isinstance(action_space, Discrete): self.action_dims = 1 # Keep a replay buffer self.replay = ExperienceReplay(replay_capacity, seed, (num_inputs,), 1, self.device) else: raise ValueError("GreedyACDiscrete must use discrete action") self.batch_size = batch_size # Set the interval between timesteps when the target network should be # updated and keep a running total of update number self.target_update_interval = target_update_interval self.update_number = 0 # Create the critic Q function if isinstance(action_space, Box): raise ValueError("GreedyACDiscrete must use discrete actions") elif isinstance(action_space, Discrete): action_shape = 1 self.critic = QMLP(num_inputs, action_shape, critic_hidden_dim, init, activation).to( device=self.device) self.critic_optim = Adam(self.critic.parameters(), lr=critic_lr, betas=betas) self.critic_target = QMLP(num_inputs, action_shape, critic_hidden_dim, init, activation).to( self.device) nn_utils.hard_update(self.critic_target, self.critic) self._create_policies(policy, num_inputs, action_space, actor_hidden_dim, clip_stddev, init, activation) actor_lr = actor_lr_scale * critic_lr self.policy_optim = Adam(self.policy.parameters(), lr=actor_lr, betas=betas) self.is_training = True source = inspect.getsource(inspect.getmodule(inspect.currentframe())) self.info = {} self.info = { "action_values": [], "source": source, } def update(self, state, action, reward, next_state, done_mask): # Adjust action shape to ensure it fits in replay buffer properly action = np.array([action]) # Keep transition in replay buffer self.replay.push(state, action, reward, next_state, done_mask) # Sample a batch from memory state_batch, action_batch, reward_batch, next_state_batch, \ mask_batch = self.replay.sample(batch_size=self.batch_size) if state_batch is None: # Not enough samples in buffer return # When updating Q functions, we don't want to backprop through the # policy and target network parameters with torch.no_grad(): next_state_action, _, _ = \ self.policy.sample(next_state_batch) next_q = self.critic_target(next_state_batch, next_state_action) target_q_value = reward_batch + mask_batch * self.gamma * next_q q_value = self.critic(state_batch, action_batch) # Calculate the loss on the critic q_loss = F.mse_loss(target_q_value, q_value) # Update the critic self.critic_optim.zero_grad() q_loss.backward() self.critic_optim.step() # Update target networks self.update_number += 1 if self.update_number % self.target_update_interval == 0: self.update_number = 0 nn_utils.soft_update(self.critic_target, self.critic, self.tau) # Sample actions from the sampler to determine which to update # with with torch.no_grad(): action_batch = self.sampler(state_batch) stacked_s_batch = state_batch.repeat_interleave(self.num_actions, dim=0) # Get the values of the sampled actions and find the best # self.top_actions actions with torch.no_grad(): q_values = self.critic(stacked_s_batch, action_batch) q_values = q_values.reshape(self.batch_size, self.num_actions, 1) sorted_q = torch.argsort(q_values, dim=1, descending=True) best_ind = sorted_q[:, :self.top_actions] best_ind = best_ind.repeat_interleave(self.action_dims, -1) action_batch = action_batch.reshape(self.batch_size, self.num_actions, self.action_dims) best_actions = torch.gather(action_batch, 1, best_ind) # Reshape samples for calculating the loss stacked_s_batch = state_batch.repeat_interleave(self.top_actions, dim=0) best_actions = torch.reshape(best_actions, (-1, self.action_dims)) # Actor loss # print(stacked_s_batch.shape, best_actions.shape) # print("Computing actor loss") policy_loss = self.policy.log_prob(stacked_s_batch, best_actions) policy_loss = -policy_loss.mean() # Update actor self.policy_optim.zero_grad() policy_loss.backward() self.policy_optim.step() def sample_action(self, state): state = torch.FloatTensor(state).to(self.device).unsqueeze(0) if self.is_training: action, _, _ = self.policy.sample(state) else: _, _, action = self.policy.sample(state) act = action.detach().cpu().numpy()[0][0] return act def reset(self): pass def eval(self): self.is_training = False def train(self): self.is_training = True def _create_policies(self, policy, num_inputs, action_space, actor_hidden_dim, clip_stddev, init, activation): self.policy_type = policy.lower() if self.policy_type == "softmax": self.num_actions = action_space.n self.policy = Softmax(num_inputs, self.num_actions, actor_hidden_dim, activation, init).to(self.device) # Sampler returns every available action in each state def sample(state_batch): batch_size = state_batch.shape[0] actions = torch.tensor([n for n in range(self.num_actions)]) actions = actions.repeat(batch_size).unsqueeze(-1) return actions self.sampler = sample else: raise NotImplementedError def get_parameters(self): pass def save_model(self, env_name, suffix="", actor_path=None, critic_path=None): pass def load_model(self, actor_path, critic_path): pass
8,572
36.436681
78
py
GreedyAC
GreedyAC-master/agent/nonlinear/SAC.py
# Import modules import torch import numpy as np import torch.nn.functional as F from torch.optim import Adam from agent.baseAgent import BaseAgent import agent.nonlinear.nn_utils as nn_utils from agent.nonlinear.policy.MLP import SquashedGaussian, Gaussian from agent.nonlinear.value_function.MLP import DoubleQ, Q from utils.experience_replay import TorchBuffer as ExperienceReplay import inspect class SAC(BaseAgent): """ SAC implements the Soft Actor-Critic algorithm for continuous action spaces as found in the paper https://arxiv.org/pdf/1812.05905.pdf. """ def __init__( self, gamma, tau, alpha, policy, target_update_interval, critic_lr, actor_lr_scale, alpha_lr, actor_hidden_dim, critic_hidden_dim, replay_capacity, seed, batch_size, betas, env, baseline_actions=-1, reparameterized=True, soft_q=True, double_q=True, num_samples=1, automatic_entropy_tuning=False, cuda=False, clip_stddev=1000, init=None, activation="relu", ): """ Constructor Parameters ---------- gamma : float The discount factor tau : float The weight of the weighted average, which performs the soft update to the target critic network's parameters toward the critic network's parameters, that is: target_parameters = ((1 - τ) * target_parameters) + (τ * source_parameters) alpha : float The entropy regularization temperature. See equation (1) in paper. policy : str The type of policy, currently, only support "gaussian" target_update_interval : int The number of updates to perform before the target critic network is updated toward the critic network critic_lr : float The critic learning rate actor_lr : float The actor learning rate alpha_lr : float The learning rate for the entropy parameter, if using an automatic entropy tuning algorithm (see automatic_entropy_tuning) parameter below actor_hidden_dim : int The number of hidden units in the actor's neural network critic_hidden_dim : int The number of hidden units in the critic's neural network replay_capacity : int The number of transitions stored in the replay buffer seed : int The random seed so that random samples of batches are repeatable batch_size : int The number of elements in a batch for the batch update automatic_entropy_tuning : bool, optional Whether the agent should automatically tune its entropy hyperparmeter alpha, by default False cuda : bool, optional Whether or not cuda should be used for training, by default False. Note that if True, cuda is only utilized if available. clip_stddev : float, optional The value at which the standard deviation is clipped in order to prevent numerical overflow, by default 1000. If <= 0, then no clipping is done. init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. soft_q : bool Whether or not to learn soft Q functions, by default True. The original SAC uses soft Q functions since we learn an entropy-regularized policy. When learning an entropy regularized policy, guaranteed policy improvement (in the ideal case) only exists with respect to soft action values. reparameterized : bool Whether to use the reparameterization trick to learn the policy or to use the log-likelihood trick. The original SAC uses the reparameterization trick. double_q : bool Whether or not to use a double Q critic, by default True num_samples : int The number of samples to use to estimate the gradient when using a likelihood-based SAC (i.e. `reparameterized == False`), by default 1. Raises ------ ValueError If the batch size is larger than the replay buffer """ super().__init__() self._env = env # Ensure batch size < replay capacity if batch_size > replay_capacity: raise ValueError("cannot have a batch larger than replay " + "buffer capacity") if reparameterized and num_samples != 1: raise ValueError action_space = env.action_space self._action_space = action_space obs_space = env.observation_space self._obs_space = obs_space if len(obs_space.shape) != 1: raise ValueError("SAC only supports vector observations") self._baseline_actions = baseline_actions # Set the seed for all random number generators, this includes # everything used by PyTorch, including setting the initial weights # of networks. self._torch_rng = torch.manual_seed(seed) self._rng = np.random.default_rng(seed) # Random hypers and fields self._is_training = True self._gamma = gamma self._tau = tau self._reparameterized = reparameterized self._soft_q = soft_q self._double_q = double_q if num_samples < 1: raise ValueError("cannot have num_samples < 1") self._num_samples = num_samples # Sample for likelihood-based gradient self._device = torch.device("cuda:0" if cuda and torch.cuda.is_available() else "cpu") # Experience replay buffer self._batch_size = batch_size self._replay = ExperienceReplay(replay_capacity, seed, obs_space.shape, action_space.shape[0], self._device) # Set the interval between timesteps when the target network should be # updated and keep a running total of update number self._target_update_interval = target_update_interval self._update_number = 0 # Automatic entropy tuning self._automatic_entropy_tuning = automatic_entropy_tuning self._alpha_lr = alpha_lr if self._automatic_entropy_tuning and self._alpha_lr <= 0: raise ValueError("should not use entropy lr <= 0") # Set up the critic and target critic self._init_critic( obs_space, action_space, critic_hidden_dim, init, activation, critic_lr, betas, ) # Set up the policy self._policy_type = policy.lower() actor_lr = actor_lr_scale * critic_lr self._init_policy( obs_space, action_space, actor_hidden_dim, init, activation, actor_lr, betas, clip_stddev, ) # Set up auto entropy tuning if self._automatic_entropy_tuning: self._target_entropy = -torch.prod( torch.Tensor(action_space.shape).to(self._device) ).item() self._log_alpha = torch.zeros( 1, requires_grad=True, device=self._device, ) self._alpha = self._log_alpha.exp().detach() self._alpha_optim = Adam([self._log_alpha], lr=self._alpha_lr) else: self._alpha = alpha # Entropy scale source = inspect.getsource(inspect.getmodule(inspect.currentframe())) self.info["source"] = source def sample_action(self, state): state = torch.FloatTensor(state).to(self._device).unsqueeze(0) if self._is_training: action = self._policy.rsample(state)[0] else: action = self._policy.rsample(state)[3] return action.detach().cpu().numpy()[0] def update(self, state, action, reward, next_state, done_mask): # Keep transition in replay buffer self._replay.push(state, action, reward, next_state, done_mask) # Sample a batch from memory state_batch, action_batch, reward_batch, next_state_batch, \ mask_batch = self._replay.sample(batch_size=self._batch_size) if state_batch is None: return self._update_critic(state_batch, action_batch, reward_batch, next_state_batch, mask_batch) self._update_actor(state_batch, action_batch, reward_batch, next_state_batch, mask_batch) def _update_actor(self, state_batch, action_batch, reward_batch, next_state_batch, mask_batch): """ Update the actor given a batch of transitions sampled from a replay buffer. """ # Calculate the actor loss if self._reparameterized: # Reparameterization trick if self._baseline_actions > 0: pi, log_pi = self._policy.rsample( state_batch, num_samples=self._baseline_actions+1, )[:2] pi = pi.transpose(0, 1).reshape( -1, self._action_space.high.shape[0], ) s_state_batch = state_batch.repeat_interleave( self._baseline_actions + 1, dim=0, ) q = self._get_q(s_state_batch, pi) q = q.reshape(self._batch_size, self._baseline_actions + 1, -1) # Don't backprop through the approximate state-value baseline baseline = q[:, 1:].mean(axis=1).squeeze().detach() log_pi = log_pi[0, :, 0] q = q[:, 0, 0] q -= baseline else: pi, log_pi = self._policy.rsample(state_batch)[:2] q = self._get_q(state_batch, pi) policy_loss = ((self._alpha * log_pi) - q).mean() else: # Log likelihood trick baseline = 0 if self._baseline_actions > 0: with torch.no_grad(): pi = self._policy.sample( state_batch, num_samples=self._baseline_actions, )[0] pi = pi.transpose(0, 1).reshape( -1, self._action_space.high.shape[0], ) s_state_batch = state_batch.repeat_interleave( self._baseline_actions, dim=0, ) q = self._get_q(s_state_batch, pi) q = q.reshape( self._batch_size, self._baseline_actions, -1, ) baseline = q[:, 1:].mean(axis=1) sample = self._policy.sample( state_batch, self._num_samples, ) pi, log_pi = sample[:2] # log_pi is differentiable if self._num_samples > 1: pi = pi.reshape(self._num_samples * self._batch_size, -1) state_batch = state_batch.repeat(self._num_samples, 1) with torch.no_grad(): # Context manager ensures that we don't backprop through the q # function when minimizing the policy loss q = self._get_q(state_batch, pi) q -= baseline # Compute the policy loss log_pi = log_pi.reshape(self._num_samples * self._batch_size, -1) with torch.no_grad(): scale = self._alpha * log_pi - q policy_loss = log_pi * scale policy_loss = policy_loss.mean() # Update the actor self._policy_optim.zero_grad() policy_loss.backward() self._policy_optim.step() # Tune the entropy if appropriate if self._automatic_entropy_tuning: alpha_loss = -(self._log_alpha * (log_pi + self._target_entropy).detach()).mean() self._alpha_optim.zero_grad() alpha_loss.backward() self._alpha_optim.step() self._alpha = self._log_alpha.exp().detach() def reset(self): pass def eval(self): self._is_training = False def train(self): self._is_training = True # Save model parameters def save_model(self, env_name, suffix="", actor_path=None, critic_path=None): pass # Load model parameters def load_model(self, actor_path, critic_path): pass def get_parameters(self): pass def _init_critic(self, obs_space, action_space, critic_hidden_dim, init, activation, critic_lr, betas): """ Initializes the critic """ num_inputs = obs_space.shape[0] if self._double_q: critic_type = DoubleQ else: critic_type = Q self._critic = critic_type( num_inputs, action_space.shape[0], critic_hidden_dim, init, activation, ).to(device=self._device) self._critic_target = critic_type( num_inputs, action_space.shape[0], critic_hidden_dim, init, activation, ).to(self._device) # Ensure critic and target critic share the same parameters at the # beginning of training nn_utils.hard_update(self._critic_target, self._critic) self._critic_optim = Adam( self._critic.parameters(), lr=critic_lr, betas=betas, ) def _init_policy(self, obs_space, action_space, actor_hidden_dim, init, activation, actor_lr, betas, clip_stddev): """ Initializes the policy """ num_inputs = obs_space.shape[0] if self._policy_type == "squashedgaussian": self._policy = SquashedGaussian(num_inputs, action_space.shape[0], actor_hidden_dim, activation, action_space, clip_stddev, init).to(self._device) elif self._policy_type == "gaussian": self._policy = Gaussian(num_inputs, action_space.shape[0], actor_hidden_dim, activation, action_space, clip_stddev, init).to(self._device) else: raise NotImplementedError(f"policy {self._policy_type} unknown") self._policy_optim = Adam( self._policy.parameters(), lr=actor_lr, betas=betas, ) def _get_q(self, state_batch, action_batch): """ Gets the Q values for `action_batch` actions in `state_batch` states from the critic, rather than the target critic. Parameters ---------- state_batch : torch.Tensor The batch of states to calculate the action values in. Of the form (batch_size, state_dims). action_batch : torch.Tensor The batch of actions to calculate the action values of in each state. Of the form (batch_size, action_dims). """ if self._double_q: q1, q2 = self._critic(state_batch, action_batch) return torch.min(q1, q2) else: return self._critic(state_batch, action_batch) def _update_critic(self, state_batch, action_batch, reward_batch, next_state_batch, mask_batch): """ Update the critic(s) given a batch of transitions sampled from a replay buffer. """ if self._double_q: self._update_double_critic(state_batch, action_batch, reward_batch, next_state_batch, mask_batch) else: self._update_single_critic(state_batch, action_batch, reward_batch, next_state_batch, mask_batch) # Increment the running total of updates and update the critic target # if needed self._update_number += 1 if self._update_number % self._target_update_interval == 0: self._update_number = 0 nn_utils.soft_update(self._critic_target, self._critic, self._tau) def _update_single_critic(self, state_batch, action_batch, reward_batch, next_state_batch, mask_batch): """ Update the critic using a batch of transitions when using a single Q critic. """ if self._double_q: raise ValueError("cannot call _update_single_critic when using " + "a double Q critic") # When updating Q functions, we don't want to backprop through the # policy and target network parameters with torch.no_grad(): # Sample an action in the next state for the SARSA update next_state_action, next_state_log_pi = \ self._policy.sample(next_state_batch)[:2] if len(next_state_log_pi.shape) == 1: next_state_log_pi = next_state_log_pi.unsqueeze(-1) # Calculate the Q value of the next action in the next state q_next = self._critic_target(next_state_batch, next_state_action) if self._soft_q: q_next -= self._alpha * next_state_log_pi # Calculate the target for the SARSA update q_target = reward_batch + mask_batch * self._gamma * q_next # Calculate the Q value of each action in each respective state q = self._critic(state_batch, action_batch) # Calculate the loss between the target and estimate Q values q_loss = F.mse_loss(q, q_target) # Update the critic self._critic_optim.zero_grad() q_loss.backward() self._critic_optim.step() def _update_double_critic(self, state_batch, action_batch, reward_batch, next_state_batch, mask_batch): """ Update the critic using a batch of transitions when using a double Q critic. """ if not self._double_q: raise ValueError("cannot call _update_single_critic when using " + "a double Q critic") # When updating Q functions, we don't want to backprop through the # policy and target network parameters with torch.no_grad(): # Sample an action in the next state for the SARSA update next_state_action, next_state_log_pi = \ self._policy.sample(next_state_batch)[:2] # Calculate the action values for the next state next_q1, next_q2 = self._critic_target(next_state_batch, next_state_action) # Double Q: target uses the minimum of the two computed action # values min_next_q = torch.min(next_q1, next_q2) # If using soft action value functions, then adjust the target if self._soft_q: min_next_q -= self._alpha * next_state_log_pi # Calculate the target for the action value function update q_target = reward_batch + mask_batch * self._gamma * min_next_q # Calculate the two Q values of each action in each respective state q1, q2 = self._critic(state_batch, action_batch) # Calculate the losses on each critic # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] q1_loss = F.mse_loss(q1, q_target) # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] q2_loss = F.mse_loss(q2, q_target) q_loss = q1_loss + q2_loss # Update the critic self._critic_optim.zero_grad() q_loss.backward() self._critic_optim.step()
20,671
35.587611
79
py
GreedyAC
GreedyAC-master/agent/nonlinear/SACDiscrete.py
#!/usr/bin/env python3 # Import modules import os from gym.spaces import Box import torch import numpy as np import torch.nn.functional as F from torch.optim import Adam from agent.baseAgent import BaseAgent import agent.nonlinear.nn_utils as nn_utils from agent.nonlinear.policy.MLP import Softmax from agent.nonlinear.value_function.MLP import DoubleQ, Q from utils.experience_replay import TorchBuffer as ExperienceReplay class SACDiscrete(BaseAgent): def __init__(self, env, gamma, tau, alpha, policy, target_update_interval, critic_lr, actor_lr_scale, actor_hidden_dim, critic_hidden_dim, replay_capacity, seed, batch_size, betas, double_q=True, soft_q=True, cuda=False, clip_stddev=1000, init=None, activation="relu"): """ Constructor Parameters ---------- env : gym.Environment The environment to run on gamma : float The discount factor tau : float The weight of the weighted average, which performs the soft update to the target critic network's parameters toward the critic network's parameters, that is: target_parameters = ((1 - τ) * target_parameters) + (τ * source_parameters) alpha : float The entropy regularization temperature. See equation (1) in paper. policy : str The type of policy, currently, only support "gaussian" target_update_interval : int The number of updates to perform before the target critic network is updated toward the critic network critic_lr : float The critic learning rate actor_lr : float The actor learning rate actor_hidden_dim : int The number of hidden units in the actor's neural network critic_hidden_dim : int The number of hidden units in the critic's neural network replay_capacity : int The number of transitions stored in the replay buffer seed : int The random seed so that random samples of batches are repeatable batch_size : int The number of elements in a batch for the batch update cuda : bool, optional Whether or not cuda should be used for training, by default False. Note that if True, cuda is only utilized if available. clip_stddev : float, optional The value at which the standard deviation is clipped in order to prevent numerical overflow, by default 1000. If <= 0, then no clipping is done. init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. Raises ------ ValueError If the batch size is larger than the replay buffer """ action_space = env.action_space obs_space = env.observation_space if isinstance(action_space, Box): raise ValueError("SACDiscrete can only be used with " + "discrete actions") super().__init__() self.batch = True # Ensure batch size < replay capacity if batch_size > replay_capacity: raise ValueError("cannot have a batch larger than replay " + "buffer capacity") # Set the seed for all random number generators, this includes # everything used by PyTorch, including setting the initial weights # of networks. PyTorch prefers seeds with many non-zero binary units self.torch_rng = torch.manual_seed(seed) self.rng = np.random.default_rng(seed) self.is_training = True self.gamma = gamma self.tau = tau self.alpha = alpha self.double_q = double_q self.soft_q = soft_q self.num_actions = action_space.n self.device = torch.device("cuda:0" if cuda and torch.cuda.is_available() else "cpu") # Keep a replay buffer action_shape = 1 obs_dim = obs_space.shape self.replay = ExperienceReplay(replay_capacity, seed, obs_dim, action_shape, self.device) self.batch_size = batch_size # Set the interval between timesteps when the target network should be # updated and keep a running total of update number self.target_update_interval = target_update_interval self.update_number = 0 num_inputs = obs_space.shape[0] self._init_critic(obs_space, critic_hidden_dim, init, activation, critic_lr, betas) self.policy_type = policy.lower() self._init_policy(obs_space, action_space, actor_hidden_dim, init, activation, actor_lr_scale * critic_lr, betas, clip_stddev) def sample_action(self, state): state = torch.FloatTensor(state).to(self.device).unsqueeze(0) if self.is_training: action, _, _ = self.policy.sample(state) act = action.detach().cpu().numpy()[0] return int(act[0]) else: _, log_prob, _ = self.policy.sample(state) return log_prob.argmax().item() def update(self, state, action, reward, next_state, done_mask): # Adjust action to ensure it can be sent to the experience replay # buffer properly action = np.array([action]) # Keep transition in replay buffer self.replay.push(state, action, reward, next_state, done_mask) # Sample a batch from memory state_batch, action_batch, reward_batch, next_state_batch, \ mask_batch = self.replay.sample(batch_size=self.batch_size) if state_batch is None: # Not enough samples in buffer return self._update_critic(state_batch, action_batch, reward_batch, next_state_batch, mask_batch) self._update_actor(state_batch, action_batch, reward_batch, next_state_batch, mask_batch) def reset(self): pass def eval(self): self.is_training = False def train(self): self.is_training = True def save_model(self, env_name, suffix="", actor_path=None, critic_path=None): pass def load_model(self, actor_path, critic_path): pass def get_parameters(self): pass def _init_critic(self, obs_space, critic_hidden_dim, init, activation, critic_lr, betas): """ Initializes the critic """ num_inputs = obs_space.shape[0] if self.double_q: critic_type = DoubleQ else: critic_type = Q self.critic = critic_type(num_inputs, 1, critic_hidden_dim, init, activation).to(device=self.device) self.critic_target = critic_type(num_inputs, 1, critic_hidden_dim, init, activation).to(self.device) # Ensure critic and target critic share the same parameters at the # beginning of training nn_utils.hard_update(self.critic_target, self.critic) self.critic_optim = Adam( self.critic.parameters(), lr=critic_lr, betas=betas, ) def _init_policy(self, obs_space, action_space, actor_hidden_dim, init, activation, actor_lr, betas, clip_stddev): """ Initializes the policy """ num_inputs = obs_space.shape[0] num_actions = action_space.n if self.policy_type == "softmax": self.policy = Softmax(num_inputs, num_actions, actor_hidden_dim, activation, init).to(self.device) else: raise NotImplementedError(f"policy {self.policy_type} unknown") self.policy_optim = Adam(self.policy.parameters(), lr=actor_lr, betas=betas) def _update_critic(self, state_batch, action_batch, reward_batch, next_state_batch, mask_batch): if self.double_q: self._update_double_critic(state_batch, action_batch, reward_batch, next_state_batch, mask_batch,) else: self._update_single_critic(state_batch, action_batch, reward_batch, next_state_batch, mask_batch) # Increment the running total of updates and update the critic target # if needed self.update_number += 1 if self.update_number % self.target_update_interval == 0: self.update_number = 0 nn_utils.soft_update(self.critic_target, self.critic, self.tau) def _update_double_critic(self, state_batch, action_batch, reward_batch, next_state_batch, mask_batch): """ Update the critic using a batch of transitions when using a double Q critic. """ if not self.double_q: raise ValueError("cannot call _update_single_critic when using " + "a double Q critic") # When updating Q functions, we don't want to backprop through the # policy and target network parameters with torch.no_grad(): next_state_action, next_state_log_pi, _ = \ self.policy.sample(next_state_batch) next_q1, next_q2 = self.critic_target( next_state_batch, next_state_action, ) next_q = torch.min(next_q1, next_q2) if self.soft_q: next_q -= self.alpha * next_state_log_pi q_target = reward_batch + mask_batch * self.gamma * next_q q1, q2 = self.critic(state_batch, action_batch) # Calculate the losses on each critic # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] q1_loss = F.mse_loss(q1, q_target) # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] q2_loss = F.mse_loss(q2, q_target) q_loss = q1_loss + q2_loss # Update the critic self.critic_optim.zero_grad() q_loss.backward() self.critic_optim.step() def _update_single_critic(self, state_batch, action_batch, reward_batch, next_state_batch, mask_batch): """ Update the critic using a batch of transitions when using a single Q critic. """ if self.double_q: raise ValueError("cannot call _update_single_critic when using " + "a double Q critic") # When updating Q functions, we don't want to backprop through the # policy and target network parameters with torch.no_grad(): next_state_action, next_state_log_pi, _ = \ self.policy.sample(next_state_batch) next_q = self.critic_target(next_state_batch, next_state_action) if self.soft_q: next_q -= self.alpha * next_state_log_pi q_target = reward_batch + mask_batch * self.gamma * next_q q = self.critic(state_batch, action_batch) q_loss = F.mse_loss(q, q_target) # Update the critic self.critic_optim.zero_grad() q_loss.backward() self.critic_optim.step() def _get_q(self, state_batch, action_batch): """ Gets the Q values for `action_batch` actions in `state_batch` states from the critic, rather than the target critic. Parameters ---------- state_batch : torch.Tensor The batch of states to calculate the action values in. Of the form (batch_size, state_dims). action_batch : torch.Tensor The batch of actions to calculate the action values of in each state. Of the form (batch_size, action_dims). """ if self.double_q: q1, q2 = self.critic(state_batch, action_batch) return torch.min(q1, q2) else: return self.critic(state_batch, action_batch) def _update_actor(self, state_batch, action_batch, reward_batch, next_state_batch, mask_batch): # Calculate the actor loss using Eqn(5) in FKL/RKL paper # Repeat the state for each action state_batch = state_batch.repeat_interleave(self.num_actions, dim=0) actions = torch.tensor([n for n in range(self.num_actions)]) actions = actions.repeat(self.batch_size) actions = actions.unsqueeze(-1) with torch.no_grad(): q = self._get_q(state_batch, actions) log_prob = self.policy.log_prob(state_batch, actions) prob = log_prob.exp() with torch.no_grad(): scale = q - log_prob * self.alpha policy_loss = prob * scale policy_loss = policy_loss.reshape([self.batch_size, self.num_actions]) policy_loss = -policy_loss.sum(dim=1).mean() # Update the actor self.policy_optim.zero_grad() policy_loss.backward() self.policy_optim.step()
13,490
36.475
79
py
GreedyAC
GreedyAC-master/agent/nonlinear/VAC.py
# Import modules import torch import inspect from gym.spaces import Box, Discrete import numpy as np import torch.nn.functional as F from torch.optim import Adam from agent.baseAgent import BaseAgent import agent.nonlinear.nn_utils as nn_utils from agent.nonlinear.policy.MLP import Gaussian from agent.nonlinear.value_function.MLP import Q as QMLP from utils.experience_replay import TorchBuffer as ExperienceReplay class VAC(BaseAgent): """ VAC implements the Vanilla Actor-Critic agent """ def __init__(self, num_inputs, action_space, gamma, tau, alpha, policy, target_update_interval, critic_lr, actor_lr_scale, num_samples, actor_hidden_dim, critic_hidden_dim, replay_capacity, seed, batch_size, betas, env, cuda=False, clip_stddev=1000, init=None, activation="relu"): """ Constructor Parameters ---------- num_inputs : int The number of input features action_space : gym.spaces.Space The action space from the gym environment gamma : float The discount factor tau : float The weight of the weighted average, which performs the soft update to the target critic network's parameters toward the critic network's parameters, that is: target_parameters = ((1 - τ) * target_parameters) + (τ * source_parameters) alpha : float The entropy regularization temperature. See equation (1) in paper. policy : str The type of policy, currently, only support "gaussian" target_update_interval : int The number of updates to perform before the target critic network is updated toward the critic network critic_lr : float The critic learning rate actor_lr : float The actor learning rate actor_hidden_dim : int The number of hidden units in the actor's neural network critic_hidden_dim : int The number of hidden units in the critic's neural network replay_capacity : int The number of transitions stored in the replay buffer seed : int The random seed so that random samples of batches are repeatable batch_size : int The number of elements in a batch for the batch update cuda : bool, optional Whether or not cuda should be used for training, by default False. Note that if True, cuda is only utilized if available. clip_stddev : float, optional The value at which the standard deviation is clipped in order to prevent numerical overflow, by default 1000. If <= 0, then no clipping is done. init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. Raises ------ ValueError If the batch size is larger than the replay buffer """ super().__init__() self.batch = True # Ensure batch size < replay capacity if batch_size > replay_capacity: raise ValueError("cannot have a batch larger than replay " + "buffer capacity") # Set the seed for all random number generators, this includes # everything used by PyTorch, including setting the initial weights # of networks. PyTorch prefers seeds with many non-zero binary units self.torch_rng = torch.manual_seed(seed) self.rng = np.random.default_rng(seed) self.is_training = True self.gamma = gamma self.tau = tau self.alpha = alpha self.action_space = action_space if not isinstance(action_space, Box): raise ValueError("VAC only works with Box action spaces") self.state_dims = num_inputs self.num_samples = num_samples - 1 assert num_samples >= 2 self.device = torch.device("cuda:0" if cuda and torch.cuda.is_available() else "cpu") if isinstance(action_space, Box): self.action_dims = action_space.high.shape[0] # Keep a replay buffer self.replay = ExperienceReplay(replay_capacity, seed, (num_inputs,), action_space.shape[0], self.device) elif isinstance(action_space, Discrete): self.action_dims = 1 # Keep a replay buffer self.replay = ExperienceReplay(replay_capacity, seed, num_inputs, 1, self.device) self.batch_size = batch_size # Set the interval between timesteps when the target network should be # updated and keep a running total of update number self.target_update_interval = target_update_interval self.update_number = 0 # Create the critic Q function if isinstance(action_space, Box): action_shape = action_space.shape[0] elif isinstance(action_space, Discrete): action_shape = 1 self.critic = QMLP(num_inputs, action_shape, critic_hidden_dim, init, activation).to(device=self.device) self.critic_optim = Adam(self.critic.parameters(), lr=critic_lr, betas=betas) self.critic_target = QMLP(num_inputs, action_shape, critic_hidden_dim, init, activation).to( self.device) nn_utils.hard_update(self.critic_target, self.critic) self.policy_type = policy.lower() actor_lr = actor_lr_scale * critic_lr if self.policy_type == "gaussian": self.policy = Gaussian(num_inputs, action_space.shape[0], actor_hidden_dim, activation, action_space, clip_stddev, init).to( self.device) self.policy_optim = Adam(self.policy.parameters(), lr=actor_lr, betas=betas) else: raise NotImplementedError source = inspect.getsource(inspect.getmodule(inspect.currentframe())) self.info = {} self.info = { "source": source, } def sample_action(self, state): state = torch.FloatTensor(state).to(self.device).unsqueeze(0) if self.is_training: action, _, _ = self.policy.sample(state) else: _, _, action = self.policy.sample(state) act = action.detach().cpu().numpy()[0] return act def update(self, state, action, reward, next_state, done_mask): # Keep transition in replay buffer self.replay.push(state, action, reward, next_state, done_mask) # Sample a batch from memory state_batch, action_batch, reward_batch, next_state_batch, \ mask_batch = self.replay.sample(batch_size=self.batch_size) if state_batch is None: return # When updating Q functions, we don't want to backprop through the # policy and target network parameters with torch.no_grad(): next_state_action, _, _ = \ self.policy.sample(next_state_batch) qf_next_value = self.critic_target(next_state_batch, next_state_action) q_target = reward_batch + mask_batch * self.gamma * qf_next_value q_prediction = self.critic(state_batch, action_batch) q_loss = F.mse_loss(q_prediction, q_target) # Update the critic self.critic_optim.zero_grad() q_loss.backward() self.critic_optim.step() # Sample action that the agent would take pi, _, _ = self.policy.sample(state_batch) # Calculate the advantage with torch.no_grad(): q_pi = self.critic(state_batch, pi) sampled_actions, _, _ = self.policy.sample(state_batch, self.num_samples) if self.num_samples == 1: sampled_actions = sampled_actions.unsqueeze(0) sampled_actions = torch.permute(sampled_actions, (1, 0, 2)) state_baseline = 0 if self.num_samples > 2: # Baseline computed with self.num_samples - 1 action # value estimates baseline_actions = sampled_actions[:, :-1] baseline_actions = torch.reshape(baseline_actions, [-1, self.action_dims]) stacked_s_batch = torch.repeat_interleave(state_batch, self.num_samples-1, dim=0) stacked_s_batch = torch.reshape(stacked_s_batch, [-1, self.state_dims]) baseline_q_vals = self.critic(stacked_s_batch, baseline_actions) baseline_q_vals = torch.reshape(baseline_q_vals, [self.batch_size, self.num_samples-1]) state_baseline = baseline_q_vals.mean(axis=1).unsqueeze(1) advantage = q_pi - state_baseline # Estimate the entropy from a single sampled action in each state entropy_actions = sampled_actions[:, -1] entropy = self.policy.log_prob(state_batch, entropy_actions) with torch.no_grad(): entropy *= entropy entropy = -entropy policy_loss = self.policy.log_prob(state_batch, pi) * advantage policy_loss = -(policy_loss + (self.alpha * entropy)).mean() # Update the actor self.policy_optim.zero_grad() policy_loss.backward() self.policy_optim.step() # Update target network self.update_number += 1 if self.update_number % self.target_update_interval == 0: self.update_number = 0 nn_utils.soft_update(self.critic_target, self.critic, self.tau) def reset(self): pass def eval(self): self.is_training = False def train(self): self.is_training = True def save_model(self, env_name, suffix="", actor_path=None, critic_path=None): pass def load_model(self, actor_path, critic_path): pass def get_parameters(self): pass
10,808
38.021661
78
py
GreedyAC
GreedyAC-master/agent/nonlinear/nn_utils.py
# Import modules import torch import torch.nn as nn import numpy as np def weights_init_(layer, init="kaiming", activation="relu"): """ Initializes the weights for a fully connected layer of a neural network. Parameters ---------- layer : torch.nn.Module The layer to initialize init : str The type of initialization to use, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', 'kaiming_uniform', 'default', by default 'kaiming_uniform'. activation : str The activation function in use, used to calculate the optimal gain value. """ if "weight" in dir(layer): gain = torch.nn.init.calculate_gain(activation) if init == "xavier_uniform": torch.nn.init.xavier_uniform_(layer.weight, gain=gain) elif init == "xavier_normal": torch.nn.init.xavier_normal_(layer.weight, gain=gain) elif init == "uniform": torch.nn.init.uniform_(layer.weight) / layer.in_features elif init == "normal": torch.nn.init.normal_(layer.weight) / layer.in_features elif init == "orthogonal": torch.nn.init.orthogonal_(layer.weight) elif init == "zeros": torch.nn.init.zeros_(layer.weight) elif init == "kaiming_uniform" or init == "default" or init is None: # PyTorch default return else: raise NotImplementedError(f"init {init} not implemented yet") if "bias" in dir(layer): torch.nn.init.constant_(layer.bias, 0) def soft_update(target, source, tau): """ Updates the parameters of the target network towards the parameters of the source network by a weight average depending on tau. The new parameters for the target network are: ((1 - τ) * target_parameters) + (τ * source_parameters) Parameters ---------- target : torch.nn.Module The target network source : torch.nn.Module The source network tau : float The weighting for the weighted average """ with torch.no_grad(): for target_param, param in zip(target.parameters(), source.parameters()): # Use in-place operations mul_ and add_ to avoid # copying tensor data target_param.data.mul_(1.0 - tau) target_param.data.add_(tau * param.data) def hard_update(target, source): """ Sets the parameters of the target network to the parameters of the source network. Equivalent to soft_update(target, source, 1) Parameters ---------- target : torch.nn.Module The target network source : torch.nn.Module The source network """ with torch.no_grad(): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) def init_layers(layers, init_scheme): """ Initializes the weights for the layers of a neural network. Parameters ---------- layers : list of nn.Module The list of layers init_scheme : str The type of initialization to use, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. """ def fill_weights(layers, init_fn): for i in range(len(layers)): init_fn(layers[i].weight) if init_scheme.lower() == "xavier_uniform": fill_weights(layers, nn.init.xavier_uniform_) elif init_scheme.lower() == "xavier_normal": fill_weights(layers, nn.init.xavier_normal_) elif init_scheme.lower() == "uniform": fill_weights(layers, nn.init.uniform_) elif init_scheme.lower() == "normal": fill_weights(layers, nn.init.normal_) elif init_scheme.lower() == "orthogonal": fill_weights(layers, nn.init.orthogonal_) elif init_scheme is None: # Use PyTorch default return def _calc_conv_outputs(in_height, in_width, kernel_size, dilation=1, padding=0, stride=1): """ Calculates the output height and width given in input height and width and the kernel size. Parameters ---------- in_height : int The height of the input image in_width : int The width of the input image kernel_size : tuple[int, int] or int The kernel size dilation : tuple[int, int] or int Spacing between kernel elements, by default 1 padding : tuple[int, int] or int Padding added to all four sides of the input, by default 0 stride : tuple[int, int] or int Stride of the convolution, by default 1 Returns ------- tuple[int, int] The output width and height """ # Reshape so that kernel_size, padding, dilation, and stride have one # element per dimension if isinstance(kernel_size, int): kernel_size = [kernel_size] * 2 if isinstance(padding, int): padding = [padding] * 2 if isinstance(dilation, int): dilation = [dilation] * 2 if isinstance(stride, int): stride = [stride] * 2 out_height = in_height + 2 * padding[0] - dilation[0] * ( kernel_size[0] - 1) - 1 out_height //= stride[0] out_width = in_width + 2 * padding[1] - dilation[1] * ( kernel_size[1] - 1) - 1 out_width //= stride[1] return out_height + 1, out_width + 1 def _get_activation(activation): """ Returns an activation operation given a string describing the activation operation Parameters ---------- activation : str The string representation of the activation operation, one of 'relu', 'tanh' Returns ------- nn.Module The activation function """ # Set the activation funcitons if activation.lower() == "relu": act = nn.ReLU() elif activation.lower() == "tanh": act = nn.Tanh() else: raise ValueError(f"unknown activation {activation}") return act
6,135
31.638298
79
py
GreedyAC
GreedyAC-master/agent/nonlinear/policy/MLP.py
# Import modules import torch import time import numpy as np import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal, Independent from agent.nonlinear.nn_utils import weights_init_ # Global variables EPSILON = 1e-6 class SquashedGaussian(nn.Module): """ Class SquashedGaussian implements a policy following a squashed Gaussian distribution in each state, parameterized by an MLP. """ def __init__(self, num_inputs, num_actions, hidden_dim, activation, action_space=None, clip_stddev=1000, init=None): """ Constructor Parameters ---------- num_inputs : int The number of elements in the state feature vector num_actions : int The dimensionality of the action vector hidden_dim : int The number of units in each hidden layer of the network activation : str The activation function to use, one of 'relu', 'tanh' action_space : gym.spaces.Space, optional The action space of the environment, by default None. This argument is used to ensure that the actions are within the correct scale. clip_stddev : float, optional The value at which the standard deviation is clipped in order to prevent numerical overflow, by default 1000. If <= 0, then no clipping is done. init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. """ super(SquashedGaussian, self).__init__() self.num_actions = num_actions # Determine standard deviation clipping self.clip_stddev = clip_stddev > 0 self.clip_std_threshold = np.log(clip_stddev) # Set up the layers self.linear1 = nn.Linear(num_inputs, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.mean_linear = nn.Linear(hidden_dim, num_actions) self.log_std_linear = nn.Linear(hidden_dim, num_actions) # Initialize weights self.apply(lambda module: weights_init_(module, init, activation)) # action rescaling if action_space is None: self.action_scale = torch.tensor(1.) self.action_bias = torch.tensor(0.) else: self.action_scale = torch.FloatTensor( (action_space.high - action_space.low) / 2.) self.action_bias = torch.FloatTensor( (action_space.high + action_space.low) / 2.) if activation == "relu": self.act = F.relu elif activation == "tanh": self.act = torch.tanh else: raise ValueError(f"unknown activation function {activation}") def forward(self, state): """ Performs the forward pass through the network, predicting the mean and the log standard deviation. Parameters ---------- state : torch.Tensor of float The input state to predict the policy in Returns ------- 2-tuple of torch.Tensor of float The mean and log standard deviation of the Gaussian policy in the argument state """ x = self.act(self.linear1(state)) x = self.act(self.linear2(x)) mean = self.mean_linear(x) log_std = self.log_std_linear(x) if self.clip_stddev: log_std = torch.clamp(log_std, min=-self.clip_std_threshold, max=self.clip_std_threshold) return mean, log_std def sample(self, state, num_samples=1): """ Samples the policy for an action in the argument state Parameters ---------- state : torch.Tensor of float The input state to predict the policy in Returns ------- torch.Tensor of float A sampled action """ mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(mean, std) if self.num_actions > 1: normal = Independent(normal, 1) x_t = normal.sample((num_samples,)) if num_samples == 1: x_t = x_t.squeeze(0) y_t = torch.tanh(x_t) action = y_t * self.action_scale + self.action_bias log_prob = normal.log_prob(x_t) log_prob -= torch.log(self.action_scale * (1 - y_t.pow(2)) + EPSILON).sum(axis=-1).reshape(log_prob.shape) if self.num_actions > 1: log_prob = log_prob.unsqueeze(-1) mean = torch.tanh(mean) * self.action_scale + self.action_bias return action, log_prob, mean, x_t def rsample(self, state, num_samples=1): """ Samples the policy for an action in the argument state using the reparameterization trick Parameters ---------- state : torch.Tensor of float The input state to predict the policy in Returns ------- torch.Tensor of float A sampled action """ mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(mean, std) if self.num_actions > 1: normal = Independent(normal, 1) # For re-parameterization trick (mean + std * N(0,1)) # rsample() implements the re-parameterization trick x_t = normal.rsample((num_samples,)) if num_samples == 1: x_t = x_t.squeeze(0) y_t = torch.tanh(x_t) action = y_t * self.action_scale + self.action_bias log_prob = normal.log_prob(x_t) log_prob -= torch.log(self.action_scale * (1 - y_t.pow(2)) + EPSILON).sum(axis=-1).reshape(log_prob.shape) if self.num_actions > 1: log_prob = log_prob.unsqueeze(-1) mean = torch.tanh(mean) * self.action_scale + self.action_bias return action, log_prob, mean, x_t def log_prob(self, state_batch, x_t_batch): """ Calculates the log probability of taking the action generated from x_t, where x_t is returned from sample or rsample. The log probability is returned for each action dimension separately. """ mean, log_std = self.forward(state_batch) std = log_std.exp() normal = Normal(mean, std) if self.num_actions > 1: normal = Independent(normal, 1) y_t = torch.tanh(x_t_batch) log_prob = normal.log_prob(x_t_batch) log_prob -= torch.log(self.action_scale * (1 - y_t.pow(2)) + EPSILON).sum(axis=-1).reshape(log_prob.shape) if self.num_actions > 1: log_prob = log_prob.unsqueeze(-1) return log_prob def to(self, device): """ Moves the network to a device Parameters ---------- device : torch.device The device to move the network to Returns ------- nn.Module The current network, moved to a new device """ self.action_scale = self.action_scale.to(device) self.action_bias = self.action_bias.to(device) return super(SquashedGaussian, self).to(device) class Softmax(nn.Module): """ Softmax implements a softmax policy in each state, parameterized using an MLP to predict logits. """ def __init__(self, num_inputs, num_actions, hidden_dim, activation, init=None): super(Softmax, self).__init__() self.num_actions = num_actions self.linear1 = nn.Linear(num_inputs, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, num_actions) # self.apply(weights_init_) self.apply(lambda module: weights_init_(module, init, activation)) if activation == "relu": self.act = F.relu elif activation == "tanh": self.act = torch.tanh else: raise ValueError(f"unknown activation {activation}") def forward(self, state): x = self.act(self.linear1(state)) x = self.act(self.linear2(x)) return self.linear3(x) def sample(self, state, num_samples=1): logits = self.forward(state) if len(logits.shape) != 1 and (len(logits.shape) != 2 and 1 not in logits.shape): shape = logits.shape raise ValueError(f"expected a vector of logits, got shape {shape}") probs = F.softmax(logits, dim=1) policy = torch.distributions.Categorical(probs) actions = policy.sample((num_samples,)) log_prob = F.log_softmax(logits, dim=1) log_prob = torch.gather(log_prob, dim=1, index=actions) if num_samples == 1: actions = actions.squeeze(0) log_prob = log_prob.squeeze(0) actions = actions.unsqueeze(-1) log_prob = log_prob.unsqueeze(-1) # return actions.float(), log_prob, None return actions.int(), log_prob, logits.argmax(dim=-1) def all_log_prob(self, states): logits = self.forward(states) log_probs = F.log_softmax(logits, dim=1) return log_probs def log_prob(self, states, actions): """ Returns the log probability of taking actions in states. """ logits = self.forward(states) log_probs = F.log_softmax(logits, dim=1) log_probs = torch.gather(log_probs, dim=1, index=actions.long()) return log_probs def to(self, device): """ Moves the network to a device Parameters ---------- device : torch.device The device to move the network to Returns ------- nn.Module The current network, moved to a new device """ return super(Softmax, self).to(device) class Gaussian(nn.Module): """ Class Gaussian implements a policy following Gaussian distribution in each state, parameterized as an MLP. The predicted mean is scaled to be within `(action_min, action_max)` using a `tanh` activation. """ def __init__(self, num_inputs, num_actions, hidden_dim, activation, action_space, clip_stddev=1000, init=None): """ Constructor Parameters ---------- num_inputs : int The number of elements in the state feature vector num_actions : int The dimensionality of the action vector hidden_dim : int The number of units in each hidden layer of the network action_space : gym.spaces.Space The action space of the environment clip_stddev : float, optional The value at which the standard deviation is clipped in order to prevent numerical overflow, by default 1000. If <= 0, then no clipping is done. init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. """ super(Gaussian, self).__init__() self.num_actions = num_actions # Determine standard deviation clipping self.clip_stddev = clip_stddev > 0 self.clip_std_threshold = np.log(clip_stddev) self.linear1 = nn.Linear(num_inputs, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.mean_linear = nn.Linear(hidden_dim, num_actions) self.log_std_linear = nn.Linear(hidden_dim, num_actions) # Initialize weights self.apply(lambda module: weights_init_(module, init, activation)) # Action rescaling self.action_max = torch.FloatTensor(action_space.high) self.action_min = torch.FloatTensor(action_space.low) if activation == "relu": self.act = F.relu elif activation == "tanh": self.act = torch.tanh else: raise ValueError(f"unknown activation {activation}") def forward(self, state): """ Performs the forward pass through the network, predicting the mean and the log standard deviation. Parameters ---------- state : torch.Tensor of float The input state to predict the policy in Returns ------- 2-tuple of torch.Tensor of float The mean and log standard deviation of the Gaussian policy in the argument state """ x = self.act(self.linear1(state)) x = self.act(self.linear2(x)) mean = torch.tanh(self.mean_linear(x)) mean = ((mean + 1) / 2) * (self.action_max - self.action_min) + \ self.action_min # ∈ [action_min, action_max] log_std = self.log_std_linear(x) # Works better with std dev clipping to ±1000 if self.clip_stddev: log_std = torch.clamp(log_std, min=-self.clip_std_threshold, max=self.clip_std_threshold) return mean, log_std def rsample(self, state, num_samples=1): """ Samples the policy for an action in the argument state Parameters ---------- state : torch.Tensor of float The input state to predict the policy in Returns ------- torch.Tensor of float A sampled action """ mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(mean, std) if self.num_actions > 1: normal = Independent(normal, 1) # For re-parameterization trick (mean + std * N(0,1)) # rsample() implements the re-parameterization trick action = normal.rsample((num_samples,)) action = torch.clamp(action, self.action_min, self.action_max) if num_samples == 1: action = action.squeeze(0) log_prob = normal.log_prob(action) if self.num_actions == 1: log_prob.unsqueeze(-1) return action, log_prob, mean def sample(self, state, num_samples=1): """ Samples the policy for an action in the argument state Parameters ---------- state : torch.Tensor of float The input state to predict the policy in num_samples : int The number of actions to sample Returns ------- torch.Tensor of float A sampled action """ mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(mean, std) if self.num_actions > 1: normal = Independent(normal, 1) # Non-differentiable action = normal.sample((num_samples,)) action = torch.clamp(action, self.action_min, self.action_max) if num_samples == 1: action = action.squeeze(0) log_prob = normal.log_prob(action) if self.num_actions == 1: log_prob.unsqueeze(-1) # print(action.shape) return action, log_prob, mean def log_prob(self, states, actions, show=False): """ Returns the log probability of taking actions in states. The log probability is returned for each action dimension separately, and should be added together to get the final log probability """ mean, log_std = self.forward(states) std = log_std.exp() normal = Normal(mean, std) if self.num_actions > 1: normal = Independent(normal, 1) log_prob = normal.log_prob(actions) if self.num_actions == 1: log_prob.unsqueeze(-1) if show: print(torch.cat([mean, std], axis=1)[0]) return log_prob def to(self, device): """ Moves the network to a device Parameters ---------- device : torch.device The device to move the network to Returns ------- nn.Module The current network, moved to a new device """ self.action_max = self.action_max.to(device) self.action_min = self.action_min.to(device) return super(Gaussian, self).to(device)
16,553
31.206226
79
py
GreedyAC
GreedyAC-master/agent/nonlinear/value_function/MLP.py
#!/usr/bin/env python3 # Import modules import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import agent.nonlinear.nn_utils as nn_utils # Class definitions class V(nn.Module): """ Class V is an MLP for estimating the state value function `v`. """ def __init__(self, num_inputs, hidden_dim, init, activation): """ Constructor Parameters ---------- num_inputs : int Dimensionality of input feature vector hidden_dim : int The number of units in each hidden layer init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. activation : str The activation function to use; one of 'relu', 'tanh' """ super(V, self).__init__() self.linear1 = nn.Linear(num_inputs, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, 1) self.apply(lambda module: nn_utils.weights_init_(module, init)) if activation == "relu": self.act = F.relu elif activation == "tanh": self.act = torch.tanh else: raise ValueError(f"unknown activation {activation}") def forward(self, state): """ Performs the forward pass through the network, predicting the value of `state`. Parameters ---------- state : torch.Tensor of float The feature vector of the state to compute the value of Returns ------- torch.Tensor of float The value of the state """ x = self.act(self.linear1(state)) x = self.act(self.linear2(x)) x = self.linear3(x) return x class DiscreteQ(nn.Module): """ Class DiscreteQ implements an action value network with number of predicted action values equal to the number of available actions. """ def __init__(self, num_inputs, num_actions, hidden_dim, init, activation): """ Constructor Parameters ---------- num_inputs : int Dimensionality of state feature vector num_actions : int Dimensionality of the action feature vector hidden_dim : int The number of units in each hidden layer init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. activation : str The activation function to use; one of 'relu', 'tanh' """ super(DiscreteQ, self).__init__() self.linear1 = nn.Linear(num_inputs, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, num_actions) self.apply(lambda module: nn_utils.weights_init_(module, init)) if activation == "relu": self.act = F.relu elif activation == "tanh": self.act = torch.tanh else: raise ValueError(f"unknown activation {activation}") def forward(self, state): """ Performs the forward pass through each network, predicting the action-value for `action` in `state`. Parameters ---------- state : torch.Tensor of float The state that the action was taken in Returns ------- torch.Tensor The action value predictions """ x = self.act(self.linear1(state)) x = self.act(self.linear2(x)) return self.linear3(x) class Q(nn.Module): """ Class Q implements an action-value network using an MLP function approximator. The action value is computed by concatenating the action to the state observation as the input to the neural network. """ def __init__(self, num_inputs, num_actions, hidden_dim, init, activation): """ Constructor Parameters ---------- num_inputs : int Dimensionality of state feature vector num_actions : int Dimensionality of the action feature vector hidden_dim : int The number of units in each hidden layer init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. activation : str The activation function to use; one of 'relu', 'tanh' """ super(Q, self).__init__() # Q1 architecture self.linear1 = nn.Linear(num_inputs + num_actions, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, 1) self.apply(lambda module: nn_utils.weights_init_(module, init)) if activation == "relu": self.act = F.relu elif activation == "tanh": self.act = torch.tanh else: raise ValueError(f"unknown activation {activation}") def forward(self, state, action): """ Performs the forward pass through each network, predicting the action-value for `action` in `state`. Parameters ---------- state : torch.Tensor of float The state that the action was taken in action : torch.Tensor of float The action taken in the input state to predict the value function of Returns ------- torch.Tensor The action value prediction """ xu = torch.cat([state, action], 1) x = self.act(self.linear1(xu)) x = self.act(self.linear2(x)) x = self.linear3(x) return x class DoubleQ(nn.Module): """ Class DoubleQ implements two action-value networks, computing the action-value function using two separate fully connected neural net. This is useful for implementing double Q-learning. The action values are computed by concatenating the action to the state observation and using this as input to each neural network. """ def __init__(self, num_inputs, num_actions, hidden_dim, init, activation): """ Constructor Parameters ---------- num_inputs : int Dimensionality of state feature vector num_actions : int Dimensionality of the action feature vector hidden_dim : int The number of units in each hidden layer init : str The initialization scheme to use for the weights, one of 'xavier_uniform', 'xavier_normal', 'uniform', 'normal', 'orthogonal', by default None. If None, leaves the default PyTorch initialization. activation : str The activation function to use; one of 'relu', 'tanh' """ super(DoubleQ, self).__init__() # Q1 architecture self.linear1 = nn.Linear(num_inputs + num_actions, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, 1) # Q2 architecture self.linear4 = nn.Linear(num_inputs + num_actions, hidden_dim) self.linear5 = nn.Linear(hidden_dim, hidden_dim) self.linear6 = nn.Linear(hidden_dim, 1) self.apply(lambda module: nn_utils.weights_init_(module, init)) if activation == "relu": self.act = F.relu elif activation == "tanh": self.act = torch.tanh else: raise ValueError(f"unknown activation {activation}") def forward(self, state, action): """ Performs the forward pass through each network, predicting two action-values (from each action-value approximator) for the input action in the input state. Parameters ---------- state : torch.Tensor of float The state that the action was taken in action : torch.Tensor of float The action taken in the input state to predict the value function of Returns ------- 2-tuple of torch.Tensor of float A 2-tuple of action values, one predicted by each function approximator """ xu = torch.cat([state, action], 1) x1 = self.act(self.linear1(xu)) x1 = self.act(self.linear2(x1)) x1 = self.linear3(x1) x2 = self.act(self.linear4(xu)) x2 = self.act(self.linear5(x2)) x2 = self.linear6(x2) return x1, x2
8,998
30.798587
78
py
ecdata
ecdata-master/scripts/make_tables.py
import sys import os from files import HOME sys.path.append(os.path.join(HOME, 'lmfdb')) from lmfdb import db db.create_table(name='ec_curvedata', search_columns={ 'text': ['Clabel', 'lmfdb_label', 'Ciso', 'lmfdb_iso'], 'numeric': ['regulator', 'absD', 'faltings_height', 'stable_faltings_height'], 'numeric[]': ['ainvs', 'jinv', 'min_quad_twist_ainvs'], 'smallint': ['iso_nlabel', 'Cnumber', 'lmfdb_number', 'cm', 'num_bad_primes', 'optimality', 'manin_constant', 'torsion', 'rank', 'analytic_rank', 'signD', 'class_deg', 'class_size', 'min_quad_twist_disc', 'faltings_index', 'faltings_ratio'], 'smallint[]': ['isogeny_degrees', 'nonmax_primes', 'torsion_structure', 'torsion_primes', 'sha_primes'], 'integer': ['conductor', 'nonmax_rad', 'num_int_pts', 'sha'], 'integer[]': ['bad_primes'], 'bigint': ['degree'], 'boolean': ['semistable', 'potential_good_reduction'], }, label_col='lmfdb_label', sort=['conductor', 'iso_nlabel', 'lmfdb_number'], id_ordered=True ) db.create_table(name='ec_localdata', search_columns={ 'text': ['lmfdb_label'], 'smallint': ['tamagawa_number', 'kodaira_symbol', 'reduction_type', 'root_number', 'conductor_valuation', 'discriminant_valuation', 'j_denominator_valuation'], 'integer': ['prime'] }, label_col='lmfdb_label', sort=['lmfdb_label', 'prime'], id_ordered=False ) db.create_table(name='ec_mwbsd', search_columns={ 'text': ['lmfdb_label'], 'numeric': ['special_value', 'real_period', 'area', 'sha_an'], 'integer': ['tamagawa_product'], 'smallint': ['ngens'], 'smallint[]': ['rank_bounds'], 'numeric[]': ['torsion_generators', 'xcoord_integral_points', 'gens', 'heights'], }, label_col='lmfdb_label', sort=['lmfdb_label'], id_ordered=False ) db.create_table(name='ec_classdata', search_columns={ 'text': ['lmfdb_iso'], 'bigint': ['trace_hash'], 'smallint': ['class_size', 'class_deg'], 'smallint[]': ['isogeny_matrix', 'aplist', 'anlist'], }, label_col='lmfdb_iso', sort=['lmfdb_iso'], id_ordered=False ) db.create_table(name='ec_2adic', search_columns={ 'text': ['lmfdb_label', 'twoadic_label'], 'smallint': ['twoadic_index', 'twoadic_log_level'], 'smallint[]': ['twoadic_gens'], }, label_col='lmfdb_label', sort=['lmfdb_label'], id_ordered=False ) db.create_table(name='ec_galrep', search_columns={ 'text': ['lmfdb_label', 'image'], 'smallint': ['prime'], }, label_col='lmfdb_label', sort=['lmfdb_label', 'prime'], id_ordered=False ) db.create_table(name='ec_torsion_growth', search_columns={ 'text': ['lmfdb_label'], 'smallint': ['degree'], 'numeric[]': ['field'], 'smallint[]': ['torsion'], }, label_col='lmfdb_label', sort=['lmfdb_label', 'degree'], id_ordered=False ) db.create_table(name='ec_iwasawa', search_columns={ 'text': ['lmfdb_label'], 'smallint': ['iwp0'], 'jsonb': ['iwdata'], }, label_col='lmfdb_label', sort=['lmfdb_label'], id_ordered=False ) ####### Indexes ############## db.ec_curvedata.create_index(['isogeny_degrees'], type='gin') db.ec_curvedata.create_index(['nonmax_primes'], type='gin') db.ec_curvedata.create_index(['ainvs'], type='btree') db.ec_curvedata.create_index(['cm'], type='btree') db.ec_curvedata.create_index(['conductor', 'iso_nlabel', 'lmfdb_number'], type='btree') db.ec_curvedata.create_index(['Ciso'], type='btree') db.ec_curvedata.create_index(['jinv', 'id'], type='btree') db.ec_curvedata.create_index(['Clabel'], type='btree') db.ec_curvedata.create_index(['Clabel', 'Cnumber'], type='btree') db.ec_curvedata.create_index(['lmfdb_label'], type='btree') db.ec_curvedata.create_index(['lmfdb_label', 'lmfdb_number'], type='btree') db.ec_curvedata.create_index(['lmfdb_iso'], type='btree') db.ec_curvedata.create_index(['lmfdb_number'], type='btree') db.ec_curvedata.create_index(['Cnumber'], type='btree') db.ec_curvedata.create_index(['rank'], type='btree') db.ec_curvedata.create_index(['rank', 'lmfdb_number'], type='btree') db.ec_curvedata.create_index(['sha', 'id'], type='btree') db.ec_curvedata.create_index(['sha', 'rank', 'id'], type='btree') db.ec_curvedata.create_index(['sha', 'rank', 'torsion', 'id'], type='btree') db.ec_curvedata.create_index(['torsion'], type='btree') db.ec_curvedata.create_index(['torsion_structure'], type='btree') db.ec_curvedata.create_index(['nonmax_rad', 'id'], type='btree') db.ec_curvedata.create_index(['id'], type='btree') db.ec_curvedata.create_index(['semistable'], type='btree') db.ec_curvedata.create_index(['semistable', 'conductor', 'iso_nlabel', 'lmfdb_number'], type='btree') db.ec_curvedata.create_index(['potential_good_reduction'], type='btree') db.ec_curvedata.create_index(['potential_good_reduction', 'conductor', 'iso_nlabel', 'lmfdb_number'], type='btree') db.ec_curvedata.create_index(['class_size'], type='btree') db.ec_curvedata.create_index(['class_deg'], type='btree') db.ec_curvedata.create_index(['conductor'], type='btree') db.ec_curvedata.create_index(['absD'], type='btree') db.ec_curvedata.create_index(['faltings_height'], type='btree') db.ec_curvedata.create_index(['stable_faltings_height'], type='btree') db.ec_classdata.create_index(['lmfdb_iso'], type='btree') db.ec_classdata.create_index(['conductor'], type='btree') db.ec_localdata.create_index(['lmfdb_label'], type='btree') db.ec_localdata.create_index(['lmfdb_label', 'prime'], type='btree') db.ec_localdata.create_index(['conductor'], type='btree') db.ec_mwbsd.create_index(['lmfdb_label'], type='btree') db.ec_mwbsd.create_index(['conductor'], type='btree') db.ec_2adic.create_index(['lmfdb_label'], type='btree') db.ec_2adic.create_index(['conductor'], type='btree') db.ec_galrep.create_index(['lmfdb_label'], type='btree') db.ec_galrep.create_index(['lmfdb_label', 'prime'], type='btree') db.ec_galrep.create_index(['conductor'], type='btree') db.ec_torsion_growth.create_index(['lmfdb_label'], type='btree') db.ec_torsion_growth.create_index(['lmfdb_label', 'degree'], type='btree') db.ec_torsion_growth.create_index(['conductor'], type='btree') db.ec_iwasawa.create_index(['lmfdb_label'], type='btree') db.ec_iwasawa.create_index(['conductor'], type='btree')
7,542
43.89881
179
py
ecdata
ecdata-master/scripts/ecdb.py
import os import sys sys.path.insert(0, '/home/jec/ecdata/scripts/') from sage.all import (EllipticCurve, Integer, ZZ, Set, factorial, mwrank_get_precision, mwrank_set_precision, srange, prod, copy, gcd) from magma import get_magma from red_gens import reduce_tgens, reduce_gens from trace_hash import TraceHashClass from files import (parse_line_label_cols, parse_curvedata_line, parse_allgens_line_simple, parse_extra_gens_line, write_datafiles) from codec import (parse_int_list, parse_int_list_list, point_to_weighted_proj, weighted_proj_to_affine_point, split_galois_image_code, curve_from_inv_string, shortstr, liststr, matstr, shortstrlist, point_to_proj, mat_to_list_list) from twoadic import get_2adic_data from galrep import get_galrep_data from intpts import get_integral_points from aplist import my_aplist from moddeg import get_modular_degree from min_quad_twist import min_quad_twist from ec_utils import (mwrank_saturation_precision, mwrank_saturation_maxprime, get_gens, map_points) from sage.databases.cremona import parse_cremona_label, class_to_int, cremona_letter_code HOME = os.getenv("HOME") sys.path.append(os.path.join(HOME, 'ecdata', 'scripts')) FR_values = srange(1, 20) + [21, 25, 37, 43, 67, 163] # possible values of Faltings ratio modular_degree_bound = 1000000 # do not compute modular degree if conductor greater than this # Given a filename like curves.000-999, read the data in the file, # compute the isogeny class for each curve, and output (1) # allcurves.000-999, (2) allisog.000-999 (with the same suffix). Also # compute the bsd data for each curve and output (3) allbsd.000-999, # (4) allgens.000-999 (with the same suffix), (5) degphi.000-999, (6) # intpts.000-999, (7) alldegphi.000-999 # Version to compute gens & torsion gens too def make_datafiles(infilename, mode='w', verbose=False, prefix="t"): infile = open(infilename) _, suf = infilename.split(".") allcurvefile = open(prefix+"allcurves."+suf, mode=mode) allisogfile = open(prefix+"allisog."+suf, mode=mode) allbsdfile = open(prefix+"allbsd."+suf, mode=mode) allgensfile = open(prefix+"allgens."+suf, mode=mode) degphifile = open(prefix+"degphi."+suf, mode=mode) alldegphifile = open(prefix+"alldegphi."+suf, mode=mode) apfile = open(prefix+"aplist."+suf, mode=mode) intptsfile = open(prefix+"intpts."+suf, mode=mode) for L in infile.readlines(): if verbose: print("="*72) N, cl, _, ainvs, r, _, _ = L.split() E = EllipticCurve(parse_int_list(ainvs)) r = int(r) # Compute the isogeny class Cl = E.isogeny_class() Elist = Cl.curves mat = Cl.matrix() maps = Cl.isogenies() ncurves = len(Elist) print("class {} (rank {}) has {} curve(s)".format(N+cl, r, ncurves)) line = ' '.join([str(N), cl, str(1), ainvs, shortstrlist(Elist), matstr(mat)]) allisogfile.write(line+'\n') if verbose: print("allisogfile: {}".format(line)) # compute BSD data for each curve torgroups = [F.torsion_subgroup() for F in Elist] torlist = [G.order() for G in torgroups] torstruct = [list(G.invariants()) for G in torgroups] torgens = [[P.element() for P in G.gens()] for G in torgroups] cplist = [F.tamagawa_product() for F in Elist] omlist = [F.real_components()*F.period_lattice().real_period() for F in Elist] Lr1 = E.pari_curve().ellanalyticrank()[1].sage() / factorial(r) if r == 0: genlist = [[] for F in Elist] reglist = [1 for F in Elist] else: Plist = get_gens(E, r, verbose) # Saturate these points prec0 = mwrank_get_precision() mwrank_set_precision(mwrank_saturation_precision) if verbose: print("gens (before saturation) = {}".format(Plist)) Plist, ind, _ = Elist[0].saturation(Plist, max_prime=-1) if verbose: print("gens (after saturation) = {}".format(Plist)) if ind>1: print("index gain {}".format(ind)) genlist = map_points(maps, Plist) if verbose: print("genlist (before reduction) = {}".format(genlist)) genlist = [Elist[i].lll_reduce(genlist[i])[0] for i in range(ncurves)] mwrank_set_precision(prec0) if verbose: print("genlist (after reduction)= {}".format(genlist)) reglist = [Elist[i].regulator_of_points(genlist[i]) for i in range(ncurves)] shalist = [Lr1*torlist[i]**2/(cplist[i]*omlist[i]*reglist[i]) for i in range(ncurves)] squares = [n*n for n in srange(1, 100)] for i, s in enumerate(shalist): if round(s) not in squares: print("bad sha value %s for %s" % (s, str(N)+cl+str(i+1))) print("Lr1 = %s" % Lr1) print("#t = %s" % torlist[i]) print("cp = %s" % cplist[i]) print("om = %s" % omlist[i]) print("reg = %s" % reglist[i]) return Elist[i] if verbose: print("shalist = {}".format(shalist)) # compute modular degrees # degphilist = [e.modular_degree(algorithm='magma') for e in Elist] # degphi = degphilist[0] # NB The correctness of the following relies on E being optimal! try: degphi = E.modular_degree(algorithm='magma') except RuntimeError: degphi = ZZ(0) degphilist1 = [degphi*mat[0, j] for j in range(ncurves)] degphilist = degphilist1 if verbose: print("degphilist = {}".format(degphilist)) # compute aplist for optimal curve only aplist = my_aplist(E) if verbose: print("aplist = {}".format(aplist)) # Compute integral points (x-coordinates) intpts = [get_integral_points(Elist[i], genlist[i]) for i in range(ncurves)] if verbose: for i, Ei, xs in zip(range(ncurves), Elist, intpts): print("{}{}{} = {}: intpts = {}".format(N, cl, (i+1), Ei.ainvs(), xs)) # Output data for optimal curves # aplist line = ' '.join([N, cl, aplist]) if verbose: print("aplist: {}".format(line)) apfile.write(line+'\n') # degphi if degphi: line = ' '.join([N, cl, '1', str(degphi), str(Set(degphi.prime_factors())).replace(' ', ''), shortstr(E)]) else: line = ' '.join([N, cl, '1', str(degphi), str(Set([]).replace(' ', '')), shortstr(E)]) if verbose: print("degphifile: {}".format(line)) degphifile.write(line+'\n') # Output data for each curve for i in range(ncurves): # allcurves line = ' '.join([N, cl, str(i+1), shortstr(Elist[i]), str(r), str(torlist[i])]) allcurvefile.write(line+'\n') if verbose: print("allcurvefile: {}".format(line)) # allbsd line = ' '.join([N, cl, str(i+1), shortstr(Elist[i]), str(r), str(torlist[i]), str(cplist[i]), str(omlist[i]), str(Lr1), str(reglist[i]), str(shalist[i])]) allbsdfile.write(line+'\n') if verbose: print("allbsdfile: {}".format(line)) # allgens (including torsion gens, listed last) line = ' '.join([str(N), cl, str(i+1), shortstr(Elist[i]), str(r)] + [liststr(torstruct[i])] + [point_to_proj(P) for P in genlist[i]] + [point_to_proj(P) for P in torgens[i]] ) allgensfile.write(line+'\n') if verbose: print("allgensfile: {}".format(line)) # intpts line = ''.join([str(N), cl, str(i+1)]) + ' ' + shortstr(Elist[i]) + ' ' + liststr(intpts[i]) intptsfile.write(line+'\n') if verbose: print("intptsfile: {}".format(line)) # alldegphi line = ' '.join([str(N), cl, str(i+1), shortstr(Elist[i]), liststr(degphilist[i])]) alldegphifile.write(line+'\n') if verbose: print("alldegphifile: {}".format(line)) infile.close() allbsdfile.close() allgensfile.close() allcurvefile.close() allisogfile.close() degphifile.close() intptsfile.close() apfile.close() # Create manin constant files from allcurves files: # # NB We assume that curve 1 in each class is optimal with constant 1 # # Use this on a range where we have established that the optimal curve # is #1. Otherwise the C++ program h1pperiods outputs a file # opt_man.<range> which includes what can be deduced about optimality # (without a full check) and also outputs Manin constants conditional # on the optimal curve being #1. # The infilename should be an allcurves file, e.g. run in an ecdata # directory and use infilename=allcurves/allcurves.250000-259999. The # part after the "." (here 250000-259999) will be used as suffix to # the output file. # Some classes may be output as "special": two curves in the class # linked by a 2-isogeny with the first lattice having positive # discriminant and the second Manin constant=2. In several cases this # has been an indication that the wrong curve has been tagged as # optimal. def make_manin(infilename, mode='w', verbose=False, prefix=""): infile = open(infilename) _, suf = infilename.split(".") allmaninfile = open(prefix+"opt_man."+suf, mode=mode) allisogfile = open("allisog/allisog."+suf) last_class = "" manins = [] area0 = 0 # else pyflakes objects degrees = [] # else pyflakes objects for L in infile.readlines(): N, cl, num, ainvs, _ = L.split(' ', 4) this_class = N+cl num = int(num) E = EllipticCurve(parse_int_list(ainvs)) lattice1 = None if this_class == last_class: deg = degrees[int(num)-1] #assert ideg == deg area = E.period_lattice().complex_area() mc = round((deg*area/area0).sqrt()) # print("{}{}{}: ".format(N, cl, num)) # print("degree = {}".format(deg)) # print("area = {}".format(area)) # print("area ratio = {}".format(area/area0)) # print("c^2 = {}".format(deg*area/area0)) manins.append(mc) if num == 3: lattice1 = None elif not (num == 2 and deg == 2 and mc == 2): lattice1 = None if lattice1: print("Class {} is special".format(lattice1)) else: # start a new class if manins and verbose: # else we're at the start print("class {} has Manin constants {}".format(last_class, manins)) isogmat = allisogfile.readline().split()[-1] isogmat = parse_int_list_list(isogmat) degrees = isogmat[0] if verbose: print("class {}".format(this_class)) print("isogmat: {}".format(isogmat)) print("degrees: {}".format(isogmat)) area0 = E.period_lattice().complex_area() manins = [1] if num == 1 and len(isogmat) == 2 and isogmat[0][1] == 2 and E.discriminant() > 0: lattice1 = this_class last_class = this_class # construct output line for this curve # # SPECIAL CASE 990h # if N == 90 and cl == 'h': opt = str(int(num == 3)) manins = [1, 1, 1, 1] else: opt = str(int(num == 1)) mc = str(manins[-1]) line = ' '.join([str(N), cl, str(num), shortstr(E), opt, mc]) allmaninfile.write(line+'\n') if verbose: print("allmaninfile: {}".format(line)) # if int(N) > 100: # break if manins and verbose: # else we're at the start # This output line is the only reason we keep the list of all m.c.s print("class {} has Manin constants {}".format(last_class, manins)) infile.close() allmaninfile.close() def make_opt_input(N): """Parse a file in optimality/ and produce an input file for runh1firstx1 which runs h1first1. Find lines containing "possible optimal curves", extract the isogeny class label, convert iso class code to a number, and output. One line is output for each level N, of the form N i_1 i_2 ... i_k 0 where N is the level and i_1,...,i_k are the numbers (from 1) of the newforms / isogeny classes where we do not know which curve is optimal. For example the input lines starting with 250010 are 250010b: c=1; optimal curve is E1 250010d: c=1; 3 possible optimal curves: E1 E2 E3 and produce the output line 250010 2 4 0 while the lines starting with 250020 are 250020b: c=1; optimal curve is E1 250020d: c=1; optimal curve is E1 and produce no output """ outfile = "optx.{0:02d}".format(N) o = open(outfile, 'w') n = 0 lastN = 0 for L in open("optimality/optimality.{0:02d}".format(N)): if "possible" in L: N, c, _ = parse_cremona_label(L.split()[0][:-1]) if N == lastN: o.write(" {}".format(1+class_to_int(c))) else: if lastN != 0: o.write(" 0\n") o.write("{} {}".format(N, 1+class_to_int(c))) lastN = N n += 1 o.write(" 0\n") n += 1 o.close() print("wrote {} lines to {}".format(n, outfile)) def check_sagedb(N1, N2, a4a6bound=100): """Sanity check that Sage's elliptic curve database contains all curves [a1, a2, a3, a4, a6] with a1, a3 in [0, 1], a2 in [-1, 0, 1], a4,a6 in [-100..100] and conductor in the given range. Borrowed from Bill Allombert (who found a missing curve of conductor 406598 this way). """ from sage.all import CremonaDatabase CDB = CremonaDatabase() def CDB_curves(N): return [c[0] for c in CDB.allcurves(N).values()] Nrange = srange(N1, N2+1) ncurves = 12*(2*a4a6bound+1)**2 print("Testing {} curves".format(ncurves)) n = 0 for a1 in range(2): for a2 in range(-1, 2): for a3 in range(2): for a4 in range(-a4a6bound, a4a6bound+1): for a6 in range(-a4a6bound, a4a6bound+1): ai = [a1, a2, a3, a4, a6] n += 1 if n%1000 == 0: print("test #{}/{}".format(n, ncurves)) try: E = EllipticCurve(ai).minimal_model() except ArithmeticError: #singular curve continue N = E.conductor() if N not in Nrange: continue if list(E.ainvs()) not in CDB_curves(N): print("Missing N={}, ai={}".format(N, ai)) # From here on, functions to process a set of "raw" curves, to create # all the data files needed for LMFDB upload # Assume that in directory CURVE_DIR there is a file 'curves.NN' # containing one curve per line (valid formats: as in # process_raw_curves() below). For correct isogeny class labelling it # is necessary that for every conductor present, at least one curve # from each isogeny class is present. The input list need not be # closed under isogeny: if it is not then the 'allcurves.NN' file # will contain more curves than the input file, otherwise they will # contain the same curves. The file suffix 'NN' can be anything # (nonempty) to identify the dataset, e.g. it could be a single # conductor, or a range of conductors. # # Step 1: sort and label. Run sage from ecdata/scripts: # # sage: %runfile ecdb.py # sage: NN = '2357' # (say) # sage: curves_file = 'curves.{}'.format(NN) # sage: allcurves_file = 'allcurves.{}'.format(NN) # sage: process_raw_curves(curves_file, allcurves_file, base_dir=CURVE_DIR) # # If you add split_by_N=True to process_raw_curves() then instead of # one allcurves file you will get one per conductor N, each of the # form allcurves.<N>. This can be useful for using parallel # processing in the next step, after which you have to concatenate all # the output files. In this case allcurves_file will be ignored, and # a file <curves_file>.conductors will also be written containing the # distinct conductors in the input file. # # # Step 2: compute most of the data, run also in ecdb/scripts after reading ecdb.py: # # sage: read_write_data(allcurves_file, CURVE_DIR) # # We now have files CURVE_DIR/F/F.NN for F in ['curvedata', 'classdata', 'intpts', 'alldegphi']. # # Step 2a: if we have processed allcurves.RANGE with more than one # conductor, then for each conductor N we will have files F/F.N for F # in ['curvedata', 'classdata', 'intpts', 'alldegphi']. We now check # that these are complete and merge them into just 4 files F/F.RANGE. # # (o) RANGE=... # CURVE_DIR=... # cd ${CURVE_DIR} # # (i) extract conductors # awk '{print $1;}' allcurves/allcurves.${RANGE} | sort -n | uniq > conductors.RANGE # # (ii) check files are complete (this is quick) # for F in curvedata classdata intpts alldegphi; do echo $F; for N in `cat conductors.${RANGE}`; do if ! [ -e ${CURVE_DIR}/${F}/${F}.${N} ]; then echo ${F}"."${N}" missing"; fi; done; done; # # (iii) merge files (this takes ages for ~200000 conductors) # Here we don't bother with alldegphi files as they will be empty for large N. # for F in curvedata classdata intpts; do echo $F; for N in `cat conductors.${RANGE}`; do cat ${CURVE_DIR}/${F}/${F}.${N} >> ${CURVE_DIR}/${F}/${F}.${RANGE}; done; done # # Better way if you can find all the files easily with a wildcard: # e.g. for all conductors in range 1e7-1e8: # echo curvedata.???????? | xargs cat > curvedata.${RANGE} # # or # pushd curvedata # echo $(for N in $(cat ../conductors.${RANGE}); do echo curvedata\.${N}; done) | xargs cat > curvedata.${RANGE} # popd # # Step 3: run magma scripts to compute galrep and 2adic data. From ecdata/scripts: # ./make_galrep.sh NN CURVE_DIR # # This uses CURVE_DIR/allcurves/allcurves.NN and # creates CURVE_DIR/ft/ft.NN for ft in ['galrep', '2adic']. # # Step 4: create 6 files in UPLOAD_DIR (default ${HOME}/ecq-upload): # # ec_curvedata.NN, ec_classdata.NN, ec_localdata.NN, # ec_mwbsd.NN, ec_galrep.NN, ec_2adic.NN # # In ecdata/scripts run sage: # sage: %runfile files.py # sage: data = read_data(CURVE_DIR, file_types=main_file_types, ranges=[NN]) # sage: make_all_upload_files(data, tables = main_tables, NN=NN) # # ready for upload to LMFDB's db.ec_curvedata (etc) using # # db.ec_curvedata.update_from_file() def process_raw_curves(infilename, outfilename, base_dir='.', split_by_N=False, verbose=1): """File infilename should contain one curve per line, with a-ainvariants or c-invariants as a list (with no internal spaces), optionally preceded by the conductor. Sample lines (all defining the same curve): [0,-1,1,-10,-20] 11 [0,-1,1,-10,-20] [496,20008] 11 [496,20008] We do not assume minimal or reduced models, and if the conductor is given it is checked for consistency. For each input curve we check whether an isogenous curve has already been processed; if not, we compute its isogeny class and process all of them. OUTPUT: one line per curve, sorted by conductor and then by isogeny class. Each line has the format N class_code class_size number lmfdb_number ainvs where "number" is the index of the curve in its class (counting from 1), sorted by Faltings heights, with the lex. order of a-invariants as a tie-breaker. If split_by_N is False, the output will be all in one file. If True, there will be one output file per conductor N, whose name is allcurves file with suffix ".{N}". """ # allcurves will have conductors as keys, values lists of lists of # ainvs, subdivided by isogeny class allcurves = {} ncurves = ncurves_complete = 0 with open(os.path.join(base_dir, infilename)) as infile: for L in infile: data = L.split() assert len(data) in [1, 2] invs = data[-1] E = curve_from_inv_string(invs) ainvs = E.ainvs() N = E.conductor() if len(data) == 2: N1 = ZZ(data[0]) if N1 != N: raise ValueError("curve with invariants {} has conductor {}, not {} as input".format(invs, N, N1)) ncurves += 1 if ncurves%1000 == 0 and verbose: print("{} curves read from {} so far...".format(ncurves, infilename)) # now we have the curve E, check if we have seen it (or an isogenous curve) before repeat = False if N in allcurves: if any(ainvs in c for c in allcurves[N]): repeat = True if verbose > 1: print("Skipping {} of conductor {}: repeat".format(ainvs, N)) else: if verbose > 1: print("New curve {} of conductor {}".format(ainvs, N)) else: allcurves[N] = [] if repeat: continue # to next input line newcurves = [E2.ainvs() for E2 in E.isogeny_class().curves] ncurves_complete += len(newcurves) allcurves[N].append(newcurves) print("{} curves read from {}".format(ncurves, infilename)) if ncurves != ncurves_complete: print("input curves not closed under isogeny! completed list contains {} curves".format(ncurves_complete)) conductors = list(allcurves.keys()) conductors.sort() for N in conductors: C = allcurves[N] ncl = len(C) nc = sum([len(cl) for cl in C]) print("Conductor {}:\t{} isogeny classes,\t{} curves".format(N, ncl, nc)) # Now we work out labels and output a new file def curve_key_LMFDB(E): # lex order of ainvs return E.ainvs() def curve_key_Faltings(E): # Faltings height, with tie-break return [-E.period_lattice().complex_area(), E.ainvs()] def output_one_conductor(N, allcurves_N, outfile): nNcl = nNcu = 0 sN = str(N) # construct the curves from their ainvs: CC = [[EllipticCurve(ai) for ai in cl] for cl in allcurves_N] nap = 100 ok = False while not ok: aplists = dict([(cl[0], cl[0].aplist(100, python_ints=True)) for cl in CC]) aps = list(aplists.values()) ok = (len(list(Set(aps))) == len(aps)) if not ok: print("{} ap not enough for conductor {}, increasing...".format(nap, N)) nap += 100 # sort the isogeny classes: CC.sort(key=lambda cl: aplists[cl[0]]) for ncl, cl in enumerate(CC): nNcl += 1 class_code = cremona_letter_code(ncl) # sort the curves in two ways (LMFDB, Faltings) cl.sort(key=curve_key_LMFDB) cl_Faltings = copy(cl) cl_Faltings.sort(key=curve_key_Faltings) class_size = len(cl) for nE_F, E in enumerate(cl_Faltings): nNcu += 1 ainvs = shortstr(E) nE_L = cl.index(E) line = " ".join([sN, class_code, str(class_size), str(nE_F+1), str(nE_L+1), ainvs]) #print(line) outfile.write(line+"\n") return nNcu, nNcl if split_by_N: with open(os.path.join(base_dir, infilename+".conductors"), 'w') as Nfile: for N in conductors: Nfile.write("{}\n".format(N)) outfilename_N = "allcurves/allcurves.{}".format(N) with open(os.path.join(base_dir, outfilename_N), 'w') as outfile: nNcu, nNcl = output_one_conductor(N, allcurves[N], outfile) print("N={}: {} curves in {} classes output to {}".format(N, nNcu, nNcl, outfilename_N)) else: with open(os.path.join(base_dir, outfilename), 'w') as outfile: for N in conductors: nNcu, nNcl = output_one_conductor(N, allcurves[N], outfile) print("N={}: {} curves in {} classes output to {}".format(N, nNcu, nNcl, outfilename)) def make_new_data(infilename, base_dir, Nmin=None, Nmax=None, PRECISION=128, verbose=1, allgensfilename=None, oldcurvedatafile=None, extragensfilename=None): alldata = {} nc = 0 labels_by_conductor = {} tempdir = os.path.join(base_dir, "temp") with open(os.path.join(base_dir, "allcurves", infilename)) as infile: for L in infile: sN, isoclass, class_size, number, lmfdb_number, ainvs = L.split() N = ZZ(sN) if Nmin and N < Nmin: continue if Nmax and N > Nmax: continue nc += 1 iso = ''.join([sN, isoclass]) label = ''.join([iso, number]) lmfdb_isoclass = isoclass lmfdb_iso = '.'.join([sN, isoclass]) lmfdb_label = ''.join([lmfdb_iso, lmfdb_number]) iso_nlabel = class_to_int(isoclass) number = int(number) lmfdb_number = int(lmfdb_number) class_size = int(class_size) ainvs = parse_int_list(ainvs) bad_p = N.prime_factors() # will be sorted record = { 'label': label, 'isoclass': isoclass, 'iso': iso, 'number': number, 'iso_nlabel': iso_nlabel, 'lmfdb_number': lmfdb_number, 'lmfdb_isoclass': lmfdb_isoclass, 'lmfdb_iso': lmfdb_iso, 'lmfdb_label':lmfdb_label, 'faltings_index': number, 'class_size': class_size, 'ainvs': ainvs, 'conductor': N, 'bad_primes': bad_p, 'num_bad_primes': len(bad_p), } if label in alldata: raise RuntimeError("duplicate label {} in {}".format(label, infilename)) alldata[label] = record if N in labels_by_conductor: labels_by_conductor[N].append(label) else: labels_by_conductor[N] = [label] allN = list(labels_by_conductor.keys()) allN.sort() firstN = min(allN) lastN = max(allN) if verbose: print("{} curves read from {}, with {} distinct conductors from {} to {}".format(nc, infilename, len(labels_by_conductor), firstN, lastN)) gens_dict = {} if allgensfilename: print("Reading from {}".format(allgensfilename)) n = 0 with open(os.path.join(base_dir, allgensfilename)) as allgensfile: for L in allgensfile: if Nmin or Nmax: label, record = parse_line_label_cols(L) N = record['conductor'] if Nmin and N < Nmin: continue if Nmax and N > Nmax: continue n += 1 label, record = parse_allgens_line_simple(L) gens_dict[tuple(record['ainvs'])] = record['gens'] if n%10000 == 0: print("Read {} curves from {}".format(n, allgensfilename)) if oldcurvedatafile: print("Reading from {}".format(oldcurvedatafile)) n = 0 with open(os.path.join(base_dir, "curvedata", oldcurvedatafile)) as oldfile: for L in oldfile: label, record = parse_curvedata_line(L) N = int(record['conductor']) if Nmin and N < Nmin: continue if Nmax and N > Nmax: continue n += 1 gens = [weighted_proj_to_affine_point(P) for P in record['gens']] gens_dict[tuple(record['ainvs'])] = gens if n%10000 == 0: print("Read {} curves from {}".format(n, oldcurvedatafile)) if extragensfilename: print("Reading from {}".format(extragensfilename)) n = 0 with open(os.path.join(base_dir, "allgens", extragensfilename)) as genfile: for L in genfile: N = ZZ(L.split()[0]) if Nmin and N < Nmin: continue if Nmax and N > Nmax: continue N, ainvs, gens = parse_extra_gens_line(L) n += 1 if gens: gens_dict[ainvs] = gens if n%10000 == 0: print("Read {} curves from {}".format(n, extragensfilename)) N0 = 0 for N, labels in labels_by_conductor.items(): if N != N0 and N0: # extract from alldata the labels for conductor N0, and output it if verbose: print("Finished conductor {}".format(N0)) print("Writing data files for conductor {}".format(N0)) write_datafiles(dict([(lab, alldata[lab]) for lab in labels_by_conductor[N0]]), N0, tempdir) N0 = N if verbose: print("Processing conductor {}".format(N)) for label in labels: record = alldata[label] if verbose: print("Processing curve {}".format(label)) iso = record['iso'] number = record['number'] first = (number == 1) # tags first curve in each isogeny class ncurves = record['class_size'] if first: alllabels = [iso+str(k+1) for k in range(ncurves)] allcurves = [EllipticCurve(alldata[lab]['ainvs']) for lab in alllabels] E = allcurves[0] else: record1 = alldata[iso+'1'] E = allcurves[number-1] assert N == E.conductor() if verbose > 1: print("E = {}".format(E.ainvs())) record['jinv'] = Ej = E.j_invariant() record['potential_good_reduction'] = (Ej.denominator() == 1) D = E.discriminant() record['absD'] = ZZ(D).abs() record['signD'] = int(D.sign()) record['cm'] = int(E.cm_discriminant()) if E.has_cm() else 0 if first: record['aplist'] = E.aplist(100, python_ints=True) record['anlist'] = E.anlist(20, python_ints=True) record['trace_hash'] = TraceHashClass(record['iso'], E) else: record['aplist'] = record1['aplist'] record['anlist'] = record1['anlist'] record['trace_hash'] = record1['trace_hash'] if verbose > 1: print("aplist done") local_data = [{'p': int(ld.prime().gen()), 'ord_cond':int(ld.conductor_valuation()), 'ord_disc':int(ld.discriminant_valuation()), 'ord_den_j':int(max(0, -(Ej.valuation(ld.prime().gen())))), 'red':int(ld.bad_reduction_type()), 'rootno':int(E.root_number(ld.prime().gen())), 'kod':ld.kodaira_symbol()._pari_code(), 'cp':int(ld.tamagawa_number())} for ld in E.local_data()] record['tamagawa_numbers'] = cps = [ld['cp'] for ld in local_data] record['kodaira_symbols'] = [ld['kod'] for ld in local_data] record['reduction_types'] = [ld['red'] for ld in local_data] record['root_numbers'] = [ld['rootno'] for ld in local_data] record['conductor_valuations'] = cv = [ld['ord_cond'] for ld in local_data] record['discriminant_valuations'] = [ld['ord_disc'] for ld in local_data] record['j_denominator_valuations'] = [ld['ord_den_j'] for ld in local_data] record['semistable'] = all([v == 1 for v in cv]) record['tamagawa_product'] = tamprod = prod(cps) if verbose > 1: print("local data done") twoadic_data = get_2adic_data(E, get_magma()) record.update(twoadic_data) if verbose > 1: print("2-adic data done") record['modp_images'] = image_codes = get_galrep_data(E, get_magma()) record['nonmax_primes'] = pr = [int(split_galois_image_code(s)[0]) for s in image_codes] record['nonmax_rad'] = prod(pr) if verbose > 1: print("galrep data done") T = E.torsion_subgroup() tgens = [P.element() for P in T.gens()] tgens.sort(key=lambda P: P.order()) tgens = reduce_tgens(tgens) tor_struct = [P.order() for P in tgens] record['torsion_generators'] = [point_to_weighted_proj(gen) for gen in tgens] record['torsion_structure'] = tor_struct record['torsion'] = torsion = prod(tor_struct) record['torsion_primes'] = [int(p) for p in Integer(torsion).support()] if verbose > 1: print("torsion done") if first: # else add later to avoid recomputing a.r. # Analytic rank and special L-value ar, sv = E.pari_curve().ellanalyticrank(precision=PRECISION) record['analytic_rank'] = ar = ar.sage() record['special_value'] = sv = sv.sage()/factorial(ar) # compute isogenies so we can map points from #1 to the rest: cl = E.isogeny_class(order=tuple(allcurves)) record['isogeny_matrix'] = mat = mat_to_list_list(cl.matrix()) record['class_deg'] = max(max(r) for r in mat) record['isogeny_degrees'] = mat[0] isogenies = cl.isogenies() # for mapping points later if N <= modular_degree_bound: record['degree'] = degphi = get_modular_degree(E, label) if verbose > 1: print("degphi = {}".format(degphi)) else: record['degree'] = degphi = 0 if verbose > 1: print("degphi not computed as conductor > {}".format(modular_degree_bound)) record['degphilist'] = [degphi*mat[0][j] for j in range(ncurves)] else: record['analytic_rank'] = ar = record1['analytic_rank'] record['special_value'] = sv = record1['special_value'] record['class_deg'] = record1['class_deg'] record['isogeny_degrees'] = record1['isogeny_matrix'][number-1] record['degree'] = record1['degphilist'][number-1] if verbose > 1: print("analytic rank done: {}".format(ar)) gens_missing = False if ar == 0: record['gens'] = gens = [] record['regulator'] = reg = 1 record['ngens'] = 0 record['heights'] = [] record['rank'] = 0 record['rank_bounds'] = [0, 0] else: # positive rank if first: if verbose > 1: print("{}: an.rk.={}, finding generators".format(label, ar)) #if 'gens' in record: ainvs = tuple(record['ainvs']) if ainvs in gens_dict: gens = [E(P) for P in gens_dict[ainvs]] if verbose > 1: print("..already have gens {}, just saturating (p<{})...".format(gens, mwrank_saturation_maxprime)) gens, n, _ = E.saturation(gens, max_prime=mwrank_saturation_maxprime) ngens = len(gens) if ngens < ar: if verbose: print("Warning: a.r.={} but we only have {} gens".format(ar, ngens)) if verbose > 1: if n and n > 1: print("..saturation index was {}, new gens: {}".format(n, gens)) else: print("..saturated already") else: gens = get_gens(E, ar, verbose) # this returns saturated points ngens = len(gens) if ngens < ar: gens_missing = True print("{}: analytic rank = {} but we only found {} generators".format(label, ar, ngens)) else: if verbose > 1: print("...done, generators {}".format(gens)) record['rank_bounds'] = [ngens, ar] record['rank'] = None if gens_missing else ngens # so the other curves in the class know their gens: record['allgens'] = map_points(isogenies, gens, verbose) # returns saturated sets of gens else: gens = record1['allgens'][number-1] record['rank'] = record1['rank'] record['rank_bounds'] = record1['rank_bounds'] gens_missing = (record['rank'] is None) gens, tgens = reduce_gens(gens, tgens, False, label) record['gens'] = [point_to_weighted_proj(gen) for gen in gens] record['heights'] = heights = [P.height(precision=PRECISION) for P in gens] reg = None if gens_missing else E.regulator_of_points(gens, PRECISION) record['ngens'] = len(gens) record['regulator'] = reg if verbose > 1: print("... finished reduction, gens are now {}, heights {}, reg={}".format(gens, heights, reg)) L = E.period_lattice() record['real_period'] = om = L.omega(prec=PRECISION) # includes #R-components factor record['area'] = A = L.complex_area(prec=PRECISION) F_ht = -A.log()/2 R = om.parent() record['faltings_height'] = F_ht record['stable_faltings_height'] = F_ht - R(gcd(D, E.c4()**3)).log()/12 # Analytic Sha if gens_missing: if verbose: print("Unable to compute analytic Sha since #gens < analytic rank") record['sha_an'] = None record['sha'] = None else: sha_an = sv*torsion**2 / (tamprod*reg*om) sha = sha_an.round() warn = "sha_an = {}, rounds to {}".format(sha_an, sha) assert sha > 0, warn assert sha.is_square(), warn assert ((sha-sha_an).abs() < 1e-10), warn record['sha_an'] = sha_an record['sha'] = int(sha) # Faltings ratio FR = 1 if first else (record1['area']/A).round() assert FR in FR_values, "F ratio = {}/{} = {}".format(record1['area'], A, FR) record['faltings_ratio'] = FR if verbose > 1: print(" -- getting integral points...") record['xcoord_integral_points'] = get_integral_points(E, gens) if verbose > 1: print(" ...done: {}".format(record['xcoord_integral_points'])) Etw, Dtw = min_quad_twist(E) record['min_quad_twist_ainvs'] = [int(a) for a in Etw.ainvs()] record['min_quad_twist_disc'] = int(Dtw) if verbose: print("Finished processing {}".format(label)) if verbose > 1: print("data for {}:\n{}".format(label, record)) # don't forget to output last conductor if verbose: print("Finished conductor {}".format(N0)) print("Writing data files for conductor {}".format(N0)) write_datafiles(dict([(lab, alldata[lab]) for lab in labels_by_conductor[N0]]), N0, tempdir) outfilename = infilename.replace("allcurves.", "") if Nmin or Nmax: outfilename = "{}.{}-{}".format(outfilename, firstN, lastN) if verbose: print("Finished all, writing data files for {}".format(outfilename)) write_datafiles(alldata, outfilename, base_dir) return alldata def read_write_data(infilename, base_dir, verbose=1): print("Reading from {}".format(infilename)) N = ".".join(infilename.split(".")[1:]) data = make_new_data(infilename, base_dir=base_dir, verbose=verbose) write_datafiles(data, N, base_dir) ################################################################################
41,373
41.046748
189
py
ecdata
ecdata-master/scripts/labels.py
# Function to create alllabels file mapping Cremona labels to LMFDB labels # # Input: curves file, e.g. curves.230000-239999 # # Output: alllabels file, e.g. alllabels.230000-239999 # # Format: conductor iso number conductor lmfdb_iso lmfdb_number # # NB we do this by computing the isogeny class and (re)sorting it in # each case. This is ONLY intended for ranges where the classes # themselves are in the correct order. # from sage.all import EllipticCurve from codec import parse_int_list def make_alllabels(infilename, mode='w', pref='t', verbose=False): infile = open(infilename) _, suf = infilename.split(".") alllabelsfile = open(pref+"alllabels."+suf, mode=mode) count = 0 for L in open(infilename).readlines(): count += 1 if count % 1000 == 0: print(L) N, cl, _, ainvs, _, _, _ = L.split() E = EllipticCurve(parse_int_list(ainvs)) curves = E.isogeny_class(order="sage").curves reordered_curves = sorted(curves, key=lambda E: E.a_invariants()) lab1 = range(1, len(curves)+1) lab2 = [1 + reordered_curves.index(EE) for EE in curves] for j in range(len(curves)): line = ' '.join([N, cl, str(lab1[j]), N, cl, str(lab2[j])]) alllabelsfile.write(line + '\n') if verbose: print("alllabelsfile: " + line) infile.close() alllabelsfile.close()
1,410
36.131579
74
py
ecdata
ecdata-master/scripts/galrep.py
# Sage interface to Sutherland's Magma script for Galois images GALREP_SCRIPT_DIR = "/home/jec/galrep" def init_galrep(mag, script_dir=GALREP_SCRIPT_DIR): """ Load the 2adic magma script into this magma process """ mag.eval('cwd:=GetCurrentDirectory();') mag.eval('ChangeDirectory("{}");'.format(script_dir)) mag.eval('load "nfgalrep.m";') mag.eval('ChangeDirectory(cwd);') def get_galrep_data(E, mag): """ Use Magma script to compute mod-p Galois image data E is an elliptic curve over Q mag is a magma process. NB before calling this, the caller must have called init_galrep() Returns a (possibly empty) list of string representing image codes """ return str(mag.ComputeQGaloisImage(E)).split()
766
25.448276
70
py
ecdata
ecdata-master/scripts/magma.py
# Manage child Magma processes: # # User gets a Magma instance using get_magma(), which restarts after # magma_count uses (default 100). This avoid the possible problems # with using Magma on hundreds of thousands of curves, without the # overhead of starting a new one every time. # # Also, the scripts for 2adic and mod p galois images are read in to # the Magam instance. # from sage.all import Magma from twoadic import init_2adic from galrep import init_galrep magma = Magma() init_2adic(magma) init_galrep(magma) magma_count = 0 magma_count_max = 100 # restart magma after this number of uses MagmaEffort = 100000 # 1000 not enough for 282203479a1 (rank 2) def get_magma(verbose=False): global magma, magma_count, magma_count_max if magma_count == magma_count_max: if verbose: print("Restarting Magma") magma.quit() magma = Magma() init_2adic(magma) init_galrep(magma) magma_count = 1 else: if verbose: print("Reusing Magma (count={})".format(magma_count)) magma_count += 1 return magma
1,106
26.675
68
py
ecdata
ecdata-master/scripts/codec.py
###################################################################### # # Utility and coding/decoding functions # ###################################################################### import re from sage.all import ZZ, QQ, RR, sage_eval, EllipticCurve, EllipticCurve_from_c4c6 whitespace = re.compile(r'\s+') def split(line): return whitespace.split(line.strip()) def parse_int_list(s, delims=True): r""" Given a string like '[a1,a2,a3,a4,a6]' returns the list of integers [a1,a2,a3,a4,a6] """ ss = s[1:-1] if delims else s return [] if ss == '' else [ZZ(a) for a in ss.split(',')] def parse_int_list_list(s): r""" Given a string like '[[1,2,3],[4,5,6]]' returns the list of lists of integers [[1,2,3],[4,5,6]] """ ss = s.replace(" ", "") return [] if ss == '[]' else [parse_int_list(a, False) for a in ss[2:-2].split('],[')] def proj_to_aff(s): r""" Converts projective coordinate string '[x:y:z]' to affine coordinate string '[x/z,y/z]' """ x, y, z = [ZZ(c) for c in s[1:-1].split(":")] return "[{},{}]".format(x/z, y/z) def proj_to_weighted_proj(s): r"""Converts projective coordinate string '[x:y:z]' to list [a,b,c] where [x,y,z]=[ac,b,c^3] and [x/z,y/z]=[a/c^2,b/c^3] """ x, b, z = [ZZ(c) for c in s[1:-1].split(":")] c = x.gcd(z) a = x//c return [a, b, c] def weighted_proj_to_proj(s): r"""Converts weighted projective coordinate string '[a,b,c]' representing the point (a/c^2,b/c^3) to projective coordinate string '[x:y:z]' where [x,y,z]=[ac,b,c^3]. """ if isinstance(s, type('string')): a, b, c = [ZZ(t) for t in s[1:-1].split(",")] else: a, b, c = s return "[{}:{}:{}]".format(a*c, b, c**3) def point_to_weighted_proj(P): r"""Converts rational point P=(x,y) to weighted projective coordinates [a,b,c] where x=a/c^2, y=b/c^3 """ x, y, _ = list(P) a = x.numerator() b = y.numerator() c = y.denominator() // x.denominator() return [a, b, c] def point_to_proj(P): r"""Converts rational point P=(x,y) to projective coordinates [a,b,c] where x=a/c, y=b/c """ x, y, _ = list(P) c = y.denominator() a = ZZ(c*x) b = ZZ(c*y) return "[" + ":".join([str(co) for co in [a, b, c]]) + "]" def proj_to_point(s, E): r""" Converts projective coordinate string '[x:y:z]' to a point on E """ return E.point([ZZ(c) for c in s[1:-1].split(":")]) def split_galois_image_code(s): """Each code starts with a prime (1-3 digits but we allow for more) followed by an image code for that prime. This function returns two substrings, the prefix number and the rest. """ p = re.findall(r'\d+', s)[0] return p, s[len(p):] def weighted_proj_to_affine_point(P): r""" Converts a triple of integers representing a point in weighted projective coordinates [a,b,c] to a tuple of rationals (a/c^2,b/c^3). """ a, b, c = [ZZ(x) for x in P] return (a/c**2, b/c**3) def parse_twoadic_string(s, raw=False): r""" Parses one 2-adic string Input a string with 4 fields, as output by the Magma make_2adic_tring() function, e.g. "12 4 [[3,0,0,1],[3,2,2,3],[3,0,0,3]] X24" "inf inf [] CM" Returns a dict with keys 'twoadic_index', 'twoadic_log_level', 'twoadic_gens', 'twoadic_label' """ record = {} data = split(s) assert len(data) == 4 model = data[3] if model == 'CM': record['twoadic_index'] = '0' record['twoadic_log_level'] = None record['twoadic_gens'] = None record['twoadic_label'] = None else: record['twoadic_label'] = model record['twoadic_index'] = data[0] if raw else int(data[0]) log_level = ZZ(data[1]).valuation(2) record['twoadic_log_level'] = str(log_level) if raw else int(log_level) rgens = data[2] if raw: record['twoadic_gens'] = rgens else: if rgens == '[]': record['twoadic_gens'] = [] else: gens = rgens[1:-1].replace('],[', '];[').split(';') record['twoadic_gens'] = [[int(c) for c in g[1:-1].split(',')] for g in gens] return record def curve_from_inv_string(s): """From a string representing a list of 2 or 5 integers, return the elliptic curve defined by these as a- or c-invariants. """ invs = parse_int_list(s) if len(invs) == 5: E = EllipticCurve(invs).minimal_model() elif len(invs) == 2: E = EllipticCurve_from_c4c6(*invs).minimal_model() else: raise ValueError("{}: invariant list must have length 2 or 5".format(s)) return E ###################################################################### # # Coding and decoding functions # str_type = type('abc') bool_type = type(True) list_type = type([1, 2, 3]) int_type = type(int(1)) ZZ_type = type(ZZ(1)) QQ_type = type(QQ(1)) RR_type = type(RR(1)) number_types = [int_type, ZZ_type, RR_type] encoders = {str_type: lambda x: x, bool_type: lambda x: str(int(x)), int_type: str, ZZ_type: str, RR_type: str, QQ_type: lambda x: str([x.numer(), x.denom()]).replace(" ", ""), # handle lists of strings list_type: lambda x: str(x).replace(" ", "").replace("'", ""), } def encode(x): if x is None: return "?" t = type(x) if t in encoders: return encoders[t](x) print("no encoding for {} of type {}".format(x, t)) return x str_cols = ['label', 'iso', 'isoclass', 'lmfdb_label', 'lmfdb_isoclass', 'lmfdb_iso'] int_cols = ['number', 'lmfdb_number', 'iso_nlabel', 'faltings_index', 'faltings_ratio', 'conductor', 'cm', 'signD', 'min_quad_twist_disc', 'rank', 'analytic_rank', 'ngens', 'torsion', 'tamagawa_product', 'sha', 'class_size', 'class_deg', 'nonmax_rad', 'twoadic_index'] bigint_cols = ['trace_hash', 'absD'] int_list_cols = ['ainvs', 'isogeny_degrees', 'min_quad_twist_ainvs', 'bad_primes', 'tamagawa_numbers', 'kodaira_symbols', 'reduction_types', 'root_numbers', 'conductor_valuations', 'discriminant_valuations', 'j_denominator_valuations', 'rank_bounds', 'torsion_structure', 'aplist', 'anlist', 'nonmax_primes'] int_list_list_cols = ['isogeny_matrix', 'gens', 'torsion_generators'] bool_cols = ['semistable'] QQ_cols = ['jinv'] RR_cols = ['regulator', 'real_period', 'area', 'faltings_height', 'stable_faltings_height', 'special_value', 'sha_an'] RR_list_cols = ['heights'] str_list_cols = ['modp_images'] decoders = {} for col in str_cols: decoders[col] = lambda x: x for col in bigint_cols: decoders[col] = ZZ for col in int_cols: decoders[col] = ZZ for col in int_list_cols: decoders[col] = parse_int_list for col in bool_cols: decoders[col] = lambda x: bool(int(x)) for col in int_list_list_cols: decoders[col] = parse_int_list_list for col in RR_cols: decoders[col] = sage_eval for col in QQ_cols: decoders[col] = lambda x: QQ(tuple(parse_int_list(x))) for col in RR_list_cols: decoders[col] = lambda x: [] if x == '[]' else [sage_eval(d) for d in x[1:-1].split(",")] for col in str_list_cols: decoders[col] = lambda x: [] if x == '[]' else x[1:-1].split(",") # Three 2-adic columns are special, their values are None encoded as '?' for CM curves # 'twoadic_label' is string, or None ('?') for CM decoders['twoadic_label'] = lambda x: None if x == '?' else x # 'twoadic_log_level' is int, or None ('?') for CM decoders['twoadic_log_level'] = lambda x: None if x == '?' else ZZ(x) # 'twoadic_label' is lis(list(int)), or None ('?') for CM decoders['twoadic_gens'] = lambda x: None if x == '?' else parse_int_list_list(x) def decode(colname, data): if colname in decoders: return decoders[colname](data) print("No decoder set for column {} (data = {})".format(colname, data)) return data ################################################################################ # some old functions def liststr(l): return str(l).replace(' ', '') def shortstr(E): return liststr(list(E.ainvs())) def shortstrlist(Elist): return str([list(F.ainvs()) for F in Elist]).replace(' ', '') # convert '[x:y:z]' to '[x/z,y/z]' def pointPtoA(P): x, y, z = [ZZ(c) for c in P[1:-1].split(":")] return [x/z, y/z] def matstr(m): return str(list(m)).replace('(', '[').replace(')', ']').replace(' ', '') def mat_to_list_list(M): m, n = M.dimensions() return [[M[i][j] for j in range(n)] for i in range(m)]
8,688
31.912879
118
py
ecdata
ecdata-master/scripts/eqn.py
# Custom function to make a latex 'equation' string from a-invariants # # assume that [a1,a2,a3] are one of the 12 reduced triples. # This is the same as latex(EllipticCurve(ainvs)).replace(" # ","").replace("{3}","3").replace("{2}","2"), i.e. the only # difference is that we have x^3 instead of x^{3} (and x^2 instead of # x^{2} when a2!=0), and have no spaces. I checked this on all curves # of conductor <10000! def latex_equation(ainvs): a1, a2, a3, a4, a6 = [int(a) for a in ainvs] return ''.join([r'\(y^2', '+xy' if a1 else '', '+y' if a3 else '', '=x^3', '+x^2' if a2 == 1 else '-x^2' if a2 == -1 else '', '{:+}x'.format(a4) if abs(a4) > 1 else '+x' if a4 == 1 else '-x' if a4 == -1 else '', '{:+}'.format(a6) if a6 else '', r'\)'])
893
39.636364
105
py
ecdata
ecdata-master/scripts/twoadic.py
# Sage interface to 2adic Magma script import os from codec import parse_twoadic_string TWOADIC_SCRIPT_DIR = "/home/jec/ecdata/scripts" def init_2adic(mag, script_dir=TWOADIC_SCRIPT_DIR): """ Load the 2adic magma script into this magma process """ script = os.path.join(script_dir, "2adic.m") mag.eval('load "{}";'.format(script)) def get_2adic_data(E, mag): """ Use 2adic.m Magma script to compute the 2-adic image data E is an elliptic curve over Q mag is a magma process. NB before calling this, the caller must have called init_2adic() """ if E.has_cm(): s = "inf inf [] CM" else: s = str(mag.make_2adic_string(E)) return parse_twoadic_string(s)
731
21.875
68
py
ecdata
ecdata-master/scripts/update.py
import os import sys from lmfdb import db HOME = os.getenv("HOME") UPLOAD_DIR = os.path.join(HOME, "ecq-upload") sys.path.append(os.path.join(HOME, 'lmfdb')) all_tables = (db.ec_curvedata, db.ec_localdata, db.ec_mwbsd, db.ec_classdata, db.ec_galrep, db.ec_torsion_growth, db.ec_iwasawa) main_tables = (db.ec_curvedata, db.ec_localdata, db.ec_mwbsd, db.ec_classdata, db.ec_2adic, db.ec_galrep) all_ranges = ["{}0000-{}9999".format(n, n) for n in range(50)] iwasawa_ranges = all_ranges[:15] growth_ranges = all_ranges[:40] # This one updates existing rows with revised data. Any new rows are # ignored! # NB This can *only* be used for tables where the label uniquely identifies the row to be changed! These are: # db.ec_curvedata, db.ec_mwbsd, db.ec_classdata, db.ec_2adic, db.ec_iwasawa # but NOT: db.ec_localdata, db.ec_galrep, db.ec_torsion_growth # To update the latter it is necessary to delete the old rows and then use copy_from() instead of update_from_file(). def update_range(r, tables=all_tables, base_dir=UPLOAD_DIR): for t in tables: basefile = ".".join([t.search_table, r]) file = os.path.join(base_dir, basefile) print("updating {} from {}".format(t.search_table, file)) t.update_from_file(file) # Use this one to add rows. NB They must be new rows, else we end up # with duplicate rows. There should *not* be an 'id' column. So a # script to update everything from scratch, deleting all the content # first, would go like this for all tables in all_tables or a subset. # # # Delete the old data in each table: # # for t in tables: # t.delete({}) # # # Read the data files in ranges of 10000, write out the upload data # # files, and upload the data in these to each table: # # for r in all_ranges: # data = read_data(ranges=[r]) # for t in tables: # make_table_upload_file(data, t.search_table, rows=r, include_id=False) # add_data(r, tables=tables) # # # OR: read the data files in all ranges, write out the upload data # # files for the whole range, and upload the data in these to each # # table: # # data = read_data(ranges=all_ranges) # for t in tables: # make_table_upload_file(data, t.search_table, rows='all', include_id=False) # add_data('all', tables=tables) # # To add a new set of curves given upload files for the main tables only, suffix r # # sage: r = "p.500000-999999" # sage: add_data(r, tables=main_tables) # # def add_data(r, tables=all_tables, base_dir=UPLOAD_DIR): for t in tables: basefile = ".".join([t.search_table, r]) file = os.path.join(base_dir, basefile) print("updating {} from {}".format(t.search_table, file)) t.copy_from(file)
2,737
33.225
117
py
ecdata
ecdata-master/scripts/misc.py
import os from sage.all import ZZ, QQ, Integer, EllipticCurve, class_to_int try: from sage.databases.cremona import cmp_code except: pass from files import read_data, MATSCHKE_DIR, write_curvedata from moddeg import get_modular_degree from codec import (parse_int_list, point_to_weighted_proj, liststr, shortstr, shortstrlist, matstr, point_to_proj, mat_to_list_list) # one-off function to fix curvedata encoding of gens and torsion_generators # from e.g. [(-5:625:1),(580/9:1250/27:1)] def fix_gens(r, base_dir=MATSCHKE_DIR): data = read_data(base_dir, ['curvedata'], [r], True) def parse_points(s, E): if s == '[]': return [] else: return [E([QQ(c) for c in pt.split(":")]) for pt in s[2:-2].split("),(")] for record in data.values(): E = EllipticCurve(parse_int_list(record['ainvs'])) for t in ['gens', 'torsion_generators']: record[t] = [point_to_weighted_proj(gen) for gen in parse_points(record[t], E)] write_curvedata(data, r + '.new', base_dir=base_dir) # one-off function to compute modular degrees when we originally # forgot to include them in the main script. def make_degrees(infilename, base_dir, verbose=1): alldata = {} nc = 0 with open(os.path.join(base_dir, infilename)) as infile: for L in infile: nc += 1 sN, isoclass, class_size, number, lmfdb_number, ainvs = L.split() iso = ''.join([sN, isoclass]) label = ''.join([iso, number]) lmfdb_number = int(lmfdb_number) lmfdb_isoclass = isoclass lmfdb_iso = '.'.join([sN, isoclass]) lmfdb_label = ''.join([lmfdb_iso, number]) iso_nlabel = class_to_int(isoclass) number = int(number) class_size = int(class_size) ainvs = parse_int_list(ainvs) N = ZZ(sN) bad_p = N.prime_factors() # will be sorted record = { 'label': label, 'isoclass': isoclass, 'iso': iso, 'number': number, 'iso_nlabel': iso_nlabel, 'lmfdb_number': lmfdb_number, 'lmfdb_isoclass': lmfdb_isoclass, 'lmfdb_iso': lmfdb_iso, 'lmfdb_label':lmfdb_label, 'faltings_index': number, 'class_size': class_size, 'ainvs': ainvs, 'conductor': N, 'bad_primes': bad_p, 'num_bad_primes': len(bad_p), } alldata[label] = record if verbose: print("{} curves read from {}".format(nc, infilename)) nc = 0 for label, record in alldata.items(): nc += 1 if verbose: print("Processing {}".format(label)) N = record['conductor'] iso = record['iso'] number = record['number'] first = (number == 1) # tags first curve in each isogeny class ncurves = record['class_size'] if first: alllabels = [iso+str(n+1) for n in range(ncurves)] allcurves = [EllipticCurve(alldata[lab]['ainvs']) for lab in alllabels] E = allcurves[0] cl = E.isogeny_class(order=tuple(allcurves)) record['isogeny_matrix'] = mat = mat_to_list_list(cl.matrix()) record['class_deg'] = max(max(r) for r in mat) record['isogeny_degrees'] = mat[0] record['degree'] = degphi = get_modular_degree(E, label) record['degphilist'] = degphilist = [degphi*mat[0][j] for j in range(ncurves)] if verbose: print("degphilist = {}".format(degphilist)) else: record1 = alldata[iso+'1'] E = allcurves[number-1] record['class_deg'] = record1['class_deg'] record['isogeny_degrees'] = record1['isogeny_matrix'][number-1] record['degree'] = record1['degphilist'][number-1] if verbose: print("Modular degree = {}".format(record['degree'])) if nc % 1000 == 0: print("{} curves processed...".format(nc)) print("Finished processing {} curves".format(nc)) return alldata # Given a filename like curves.000-999, read the data in the file, # compute the isogeny class for each curve, and output (1) # allcurves.000-999, (2) allisog.000-999 (with the same suffix). def make_allcurves_and_allisog(infilename, mode='w'): infile = open(infilename) _, suf = infilename.split(".") allcurvefile = open("tallcurves." + suf, mode=mode) allisogfile = open("tallisog." + suf, mode=mode) for L in infile.readlines(): N, cl, _, ainvs, r, _, _ = L.split() E = EllipticCurve(parse_int_list(ainvs)) Cl = E.isogeny_class() Elist = Cl.curves mat = Cl.matrix() torlist = [F.torsion_order() for F in Elist] for i, Ei in enumerate(Elist): line = ' '.join([N, cl, str(i+1), shortstr(Ei), r, str(torlist[i])]) allcurvefile.write(line + '\n') print("allcurvefile: {}".format(line)) line = ' '.join([str(N), cl, str(1), ainvs, shortstrlist(Elist), matstr(mat)]) allisogfile.write(line + '\n') print("allisogfile: {}".format(line)) infile.close() allcurvefile.close() allisogfile.close() # Version using David Roe's new Isogeny Class class (trac #12768) def make_allcurves_and_allisog_new(infilename, mode='w', verbose=False): infile = open(infilename) _, suf = infilename.split(".") allcurvefile = open("tallcurves."+suf, mode=mode) allisogfile = open("tallisog."+suf, mode=mode) count = 0 for L in infile.readlines(): count += 1 if count%1000 == 0: print(L) N, cl, _, ainvs, r, _, _ = L.split() E = EllipticCurve(parse_int_list(ainvs)) Cl = E.isogeny_class(order="database") Elist = Cl.curves torlist = [F.torsion_order() for F in Elist] for i, Ei in enumerate(Elist): line = ' '.join([N, cl, str(i+1), shortstr(Ei), r, str(torlist[i])]) allcurvefile.write(line + '\n') if verbose: print("allcurvefile: {}".format(line)) mat = Cl.matrix() line = ' '.join([str(N), cl, str(1), ainvs, shortstrlist(Elist), matstr(mat)]) allisogfile.write(line + '\n') if verbose: print("allisogfile: {}".format(line)) infile.close() allcurvefile.close() allisogfile.close() # # Compute torsion gens only from allcurves file # def make_rank0_torsion(infilename, mode='w', verbose=False, prefix="t"): infile = open(infilename) _, suf = infilename.split(".") allgensfile = open(prefix+"allgens0."+suf, mode=mode) for L in infile.readlines(): N, cl, num, ainvs, r, _ = L.split() if int(r) == 0: E = EllipticCurve(parse_int_list(ainvs)) # compute torsion data T = E.torsion_subgroup() torstruct = list(T.invariants()) torgens = [P.element() for P in T.gens()] gens = [] # Output data line = ' '.join([str(N), cl, num, ainvs, r] + [liststr(torstruct)] + [point_to_proj(P) for P in gens] + [point_to_proj(P) for P in torgens] ) allgensfile.write(line+'\n') if verbose: print("allgensfile: {}".format(line)) infile.close() allgensfile.close() # Read allgens file without torsion and output allgens file with torsion # def add_torsion(infilename, mode='w', verbose=False, prefix="t"): infile = open(infilename) _, suf = infilename.split(".") allgensfile = open(prefix+"allgens."+suf, mode=mode) for L in infile.readlines(): N, cl, num, ainvs, r, gens = L.split(' ', 5) gens = gens.split() E = EllipticCurve(parse_int_list(ainvs)) T = E.torsion_subgroup() torstruct = list(T.invariants()) torgens = [P.element() for P in T.smith_gens()] # allgens (including torsion gens, listed last) line = ' '.join([N, cl, num, ainvs, r] + [liststr(torstruct)] + gens #[point_to_proj(P) for P in gens] + [point_to_proj(P) for P in torgens] ) if verbose: print(line) allgensfile.write(line + '\n') infile.close() allgensfile.close() # Read allgens file and for curves with non-cyclic torsion, make sure # that the gens are in the same order as the group structure # invariants: def fix_torsion(infilename, mode='w', verbose=False, prefix="t"): infile = open(infilename) _, suf = infilename.split(".") allgensfile = open(prefix+"allgens." + suf, mode=mode) for L in infile.readlines(): if verbose: print("old line") print(L) N, cl, num, ainvs, r, gens = L.split(' ', 5) gens = gens.split() tor_invs = gens[0] inf_gens = gens[1:int(r)+1] tor_gens = gens[int(r)+1:] if verbose: print("old line rank = %s, gens=%s"%(r, gens)) print(tor_invs, inf_gens, tor_gens) if len(tor_gens) < 2: allgensfile.write(L) else: if verbose: print("old line") print(L) E = EllipticCurve(parse_int_list(ainvs)) T = E.torsion_subgroup() tor_struct = list(T.invariants()) tor_gens = [P.element() for P in T.smith_form_gens()] assert all([P.order() == n for P, n in zip(tor_gens, tor_struct)]) # allgens (including torsion gens, listed last) line = ' '.join([N, cl, num, ainvs, r] + [liststr(tor_struct)] + inf_gens #[point_to_proj(P) for P in gens] + [point_to_proj(P) for P in tor_gens] ) if verbose: print("new line") print(line) allgensfile.write(line+'\n') infile.close() allgensfile.close() def fix_all_torsion(): for n in range(23): ns = str(n) filename = "allgens." + ns + "0000-" + ns + "9999" print(filename) fix_torsion(filename) def merge_gens(infile1, infile2): _, suf = infile1.split(".") infile1 = open(infile1) infile2 = open(infile2) allgensfile = open("mallgens." + suf, mode='w') L1 = infile1.readline() L2 = infile2.readline() while len(L1) > 0 and len(L2) > 0: N1, cl1, cu1, _ = L1.split(' ', 3) N2, cl2, cu2, _ = L2.split(' ', 3) if compare([N1, cl1, cu1], [N2, cl2, cu2]) < 0: allgensfile.write(L1) L1 = infile1.readline() else: allgensfile.write(L2) L2 = infile2.readline() while len(L1) > 0: allgensfile.write(L1) L1 = infile1.readline() while len(L2) > 0: allgensfile.write(L2) L2 = infile2.readline() infile1.close() infile2.close() allgensfile.close() def compare(Ncc1, Ncc2): d = Integer(Ncc1[0])-Integer(Ncc2[0]) if d != 0: return d code1 = Ncc1[1] + Ncc1[2] code2 = Ncc2[1] + Ncc2[2] d = cmp_code(code1, code2) return d def check_degphi(infilename): infile = open(infilename) for L in infile.readlines(): N, cl, num, _, d = L.split() if int(N) == 990 and cl == 'h': continue d = int(d) if int(num) == 1: d1 = d else: if d1 < d: pass else: print("%s: d=%s but d1=%s (ratio %s)"%(N+cl+str(num), d, d1, d1 // d)) infile.close()
11,920
34.373887
92
py
ecdata
ecdata-master/scripts/summarytable.py
# script used to create table.html from allbsd.* files: #countrank.awk: # cat curves.*0000-*9999 | # gawk -v FIRST=$1 -v LAST=$2 'BEGIN{printf("Curve numbers by rank in the range %d...%d:\nrank:\t0\t1\t2\t3\t4\n",FIRST,LAST);}\ # ($1>=FIRST)&&($1<=LAST){r[$5]+=1;rt+=1;}\ # END {printf("number:\t%d\t%d\t%d\t%d\t%d\nTotal number: %d\n", # r[0],r[1],r[2],r[3],r[4],rt);printf("<tr>\n<th align=right>%d-%d</th>\n<td align=right>%d</td>\n",FIRST,LAST,rt);for(i=0;i<5;i++){printf("<td align=right>%d</td>\n",r[i]);}printf("</tr>\n");}' #countcurves.awk: # cat allcurves.*0000-*9999 | # gawk -v FIRST=$1 -v LAST=$2 'BEGIN{printf("Numbers of isogeny and isomorphism classes in the range %d...%d:\n",FIRST,LAST);ncu=0;ncl=0;}\ # ($1>=FIRST)&&($1<=LAST){;ncu+=1;if($3==1){ncl+=1;}}\ # END {printf("<tr>\n<th align=right>%d-%d</th>\n<td align=right>%d</td>\n<td align=right>%d</td>\n</tr>\n",FIRST,LAST,ncl,ncu);}' # we do not call the output file "table.html" so we can compare the new # version with the old HTML_FILENAME = "newtable.html" MAX_RANK = 4 def make_table(nmax=30, verbose=False): total_tab = {} range_tab = [{} for n in range(nmax)] total = 0 rank_total = [0 for r in range(MAX_RANK+1)] range_total = [0 for n in range(nmax)] range_total_all = [0 for n in range(nmax)] total_all = 0 for n in range(nmax): infilename = ''.join(["allcurves/allcurves.", str(n), "0000-", str(n), "9999"]) range_total_all[n] = len(open(infilename).readlines()) total_all += range_total_all[n] for n in range(nmax): infilename = ''.join(["curves/curves.", str(n), "0000-", str(n), "9999"]) if verbose: print("processing {}".format(infilename)) infile = open(infilename) for L in infile.readlines(): _, _, _, _, r, _, _ = L.split() r = int(r) total_tab[r] = total_tab.get(r, 0) + 1 range_tab[n][r] = range_tab[n].get(r, 0) + 1 total += 1 rank_total[r] += 1 range_total[n] += 1 infile.close() if verbose: print("Totals for range {}0000-{}9999: {} (total {})".format(n, n, range_tab[n], range_total)) if verbose: print("\nTotals for all: {} (total {})\n".format(total_tab, total)) outfilename = HTML_FILENAME outfile = open(outfilename, mode='w') # header info for html file outfile.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n') outfile.write("<HTML>\n") outfile.write("<HEAD>\n") outfile.write("<TITLE>Elliptic Curves</TITLE>\n") outfile.write("</HEAD>\n") outfile.write("<BODY>\n") # Table 1 header outfile.write("<H3 align=center>\n") outfile.write("Number of isogeny classes of curves of conductor N < %s0000, sorted by rank\n"%nmax) outfile.write("</H3>\n") outfile.write("<table border=2 align=center cellpadding=3 rules=groups>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=5>\n") outfile.write("<thead>\n") outfile.write("<tr>\n") outfile.write("<th>N<th>all<th>r=0<th>r=1<th>r=2<th>r=3<th>r=4\n") outfile.write("</tr>\n") outfile.write("</thead>\n") #Table 1 footer outfile.write("<tfoot>\n") outfile.write("<tr>\n") outfile.write("<th align=right>1-%s9999</th>\n" % (nmax - 1)) outfile.write("<td align=right>%s</td>\n" % total) for r in range(MAX_RANK+1): outfile.write("<td align=right>%s</td>\n" % total_tab[r]) outfile.write("</tr>\n") outfile.write("</tfoot>\n") #Table 1 body outfile.write("<tbody>\n") for n in range(nmax): outfile.write("<tr>\n") if n == 0: outfile.write("<th align=right>1-9999</th>\n") else: outfile.write("<th align=right>%s0000-%s9999</th>\n" % (n, n)) outfile.write("<td align=right>%s</td>\n" % range_total[n]) for r in range(MAX_RANK + 1): outfile.write("<td align=right>%s</td>\n" % range_tab[n].get(r, 0)) outfile.write("</tr>\n") outfile.write("</tbody>\n") outfile.write("</table>\n") outfile.write("<P></P>\n") outfile.write("<HR>\n") outfile.write("<P></P>\n") # Table 2 header outfile.write("<H3 align=center>\n") outfile.write("Total number of curves of conductor N < %s0000\n" % nmax) outfile.write("</H3>\n") outfile.write("<table border=2 align=center cellpadding=3 rules=groups>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<thead>\n") outfile.write("<tr>\n") outfile.write("<th>N</th>\n") outfile.write("<th># isogeny classes</th>\n") outfile.write("<th># isomorphism classes</th>\n") outfile.write("</tr>\n") outfile.write("</thead>\n") # Table 2 footer outfile.write("<tfoot>\n") outfile.write("<tr>\n") outfile.write("<th align=right>1-%s9999</th>\n" % (nmax - 1)) outfile.write("<td align=right>%s</td>\n" % total) outfile.write("<td align=right>%s</td>\n" % total_all) outfile.write("</tr>\n") outfile.write("</tfoot>\n") # Table 2 body outfile.write("<tbody>\n") for n in range(nmax): outfile.write("<tr>\n") if n == 0: outfile.write("<th align=right>1-9999</th>\n") else: outfile.write("<th align=right>%s0000-%s9999</th>\n" % (n, n)) outfile.write("<td align=right>%s</td>\n" % range_total[n]) outfile.write("<td align=right>%s</td>\n" % range_total_all[n]) outfile.write("</tr>\n") outfile.write("</tbody>\n") outfile.write("</table>\n") # html footer outfile.write("<P></P>\n") outfile.write("<HR>\n") outfile.write("<P></P>\n") outfile.write(" <p>\n") outfile.write(' <a href="http://validator.w3.org/check?uri=referer"><img border="0"\n') outfile.write(' src="http://www.w3.org/Icons/valid-html401"\n') outfile.write(' alt="Valid HTML 4.01!" height="31" width="88"></a>\n') outfile.write(" </p>\n") outfile.write("</BODY>\n") outfile.write("</HTML>\n") outfile.close()
6,247
33.905028
207
py
ecdata
ecdata-master/scripts/red_gens.py
###################################################################### # # Functions for Minkowski-reduction of generators, and naive reduction # of torsion generators and of generators mod torsion. # ###################################################################### pt_wt = lambda P: len(str(P)) def reduce_tgens(tgens, verbose=False): """ tgens: list of torsion generators (if two, sorted by order) Return a new list of generators which is minimal with respect to string length. """ r = len(tgens) if r == 0: return tgens if r == 1: # cyclic P1 = tgens[0] n1 = P1.order() if n1 == 2: # no choice return tgens Plist = [i * P1 for i in range(1, n1) if n1.gcd(i) == 1] Plist.sort(key=pt_wt) Q = Plist[0] if Q != P1 and verbose: print("Replacing torsion [{}] generator {} with {}".format(n1, P1, Q)) return [Q] # now r=2 and P1 has order n1=2 while n2 = 2, 4, 6, 8. # -- we use brute force assert r == 2 if tgens[0].order() > tgens[1].order(): tgens.reverse() P1, P2 = tgens n1 = P1.order() # = 2 n2 = P2.order() # = 2, 4, 6 or 8 assert n1 == 2 and n2 in [2, 4, 6, 8] m = n2 // 2 P1a = m * P2 # other 2-torsion P1b = P1 + P1a # points gen_pairs = [] for j in range(n2): jP2 = j * P2 for i in range(n1): Q = i * P1 + jP2 if Q.order() != n2: continue Q2 = m * Q for P in [P1, P1a, P1b]: if P != Q2: gen_pairs.append((P, Q)) pt_wt2 = lambda PQ: sum(pt_wt(P) for P in PQ) gen_pairs.sort(key=pt_wt2) rtgens = list(gen_pairs[0]) # for structure [2,2] we swap the two gens over so that the first has smallest x-coordinate if n2 == 2: rtgens.sort(key=lambda P: list(P)[0]) if rtgens != tgens and verbose: print("Replacing torsion [{},{}] generators {} with {}".format(n1, n2, tgens, rtgens)) return rtgens def check_minkowski(gens): """ Check the points are Minkowski-reduced (rank up to 3 only) """ r = len(gens) if r < 2 or r > 3: return True if r == 2: P1, P2 = gens h1 = P1.height() h2 = P2.height() h3 = (P1 + P2).height() return h1 < h2 and h2 < h3 and h3 < 2 * h1 + h2 # r=3 if not check_minkowski(gens[:2]): return False if not check_minkowski(gens[1:]): return False if not check_minkowski(gens[::2]): return False P1, P2, P3 = gens h3 = P3.height() P4 = P1 + P2 if h3 > (P3 + P4).height() or h3 > (P3 - P4).height(): return False P4 = P1 - P2 return h3 < (P3 + P4).height() and h3 < (P3 - P4).height() def reduce_mod_2d(P3, P1, P2, debug=False): """ Assuming [P1,P2] reduced, return P3+n1*P1+n2*P2 of minimal height """ if debug: print("Reducing {} mod [{},{}]".format(P3, P1, P2)) h1 = P1.height() h2 = P2.height() assert h1 <= h2 P12 = P1 + P2 h12 = (P12.height() - h1 - h2) / 2 assert 2 * h12.abs() <= h1 # now the height of x*P1+y*P2 is ax^2+2bxy+cy^2 h3 = P3.height() h13 = ((P1 + P3).height() - h1 - h3) / 2 h23 = ((P2 + P3).height() - h2 - h3) / 2 d = h1 * h2 - h12 * h12 y1 = (h2 * h13 - h12 * h23) / d y2 = (h1 * h23 - h12 * h13) / d # now y1*P1+y2*p2 is the orthogonal projection of P3 onto the P1,P2-plane n1 = y1.round() n2 = y2.round() if debug: print("orthog proj has coords ({},{}), rounded to ({},{})".format(y1, y2, n1, n2)) Q3 = P3 - (n1 * P1 + n2 * P2) # approximate answer if debug: print("base reduction is {}, height {}".format(Q3, Q3.height())) P21 = P1 - P2 Q3list = [Q3, Q3 - P1, Q3 + P1, Q3 - P2, Q3 + P2, Q3 - P12, Q3 + P12, Q3 - P21, Q3 + P21] Q3list.sort(key=lambda P: P.height()) if debug: print("candidates for reduction: {}".format(Q3list)) print(" with heights: {}".format([Q.height() for Q in Q3list])) R = P3 - P1 - P2 print(" P3-P1-P2 ={} has height {}".format(R, R.height())) return Q3list[0] def mreduce_gens(gens, debug=False): r = len(gens) if r < 2 or r > 3: return gens if r == 2: P1, P2 = gens h1 = P1.height() h2 = P2.height() h12 = ((P1 + P2).height() - h1 - h2) / 2 while True: x = (h12/h1).round() y = h12 - x * h1 P1, P2 = P2 - x * P1, P1 h1, h2 = h2, h1 h1 = h1 - x * (y + h12) h12 = y if h1 > h2: return [P2, P1] # now r=3 if check_minkowski(gens): return gens P1, P2, P3 = gens if debug: print("--------------------------------------------------------") while True: if debug: print("At top of loop: {}".format([P1, P2, P3])) P1, P2 = mreduce_gens([P1, P2]) # recursive if debug: print("After one 2D step: {}".format([P1, P2, P3])) P3 = reduce_mod_2d(P3, P1, P2) if debug: print("After reducing P3 mod [P1,P2]: {}".format([P1, P2, P3])) h3 = P3.height() if h3 >= P2.height(): newgens = [P1, P2, P3] if not check_minkowski(newgens): label = gens[0].curve().label() print("{}: gens = {}, newgens = {} are not Minkowski-reduced!".format(label, gens, newgens)) print("heights are {}".format([P.height() for P in newgens])) raise RuntimeError return newgens P1, P2, P3 = (P1, P3, P2) if P1.height() < h3 else (P3, P1, P2) if debug: print("After resorting: {}".format([P1, P2, P3])) def reduce_gens(gens, tgens, verbose=False, label=None): """ gens: list of generators mod torsion tgens: list of torsion generators (1) Reduce the torsion generators w.r.t. string length (2) Minkowki reduce the mod-torsion gens (or just LLL-reduce if rank>3) (3) Reduce the mod-torsion gens mod torsion w.r.t. string length """ rtgens = reduce_tgens(tgens) if not gens: return [], rtgens E = gens[0].curve() newgens = mreduce_gens(E.lll_reduce(gens)[0]) # discard transformation matrix Tlist = E.torsion_points() if tgens else [E(0)] def reduce_one(P): mP = -P Plist = [P + T for T in Tlist] + [mP + T for T in Tlist] Plist.sort(key=pt_wt) return Plist[0] newgens = [reduce_one(P) for P in newgens] if verbose and len(gens) > 1 and newgens != gens: print("replacing {} generators ({}) {} with {}".format(len(gens), label, gens, newgens)) return newgens, rtgens
6,804
31.099057
108
py
ecdata
ecdata-master/scripts/ec_utils.py
# elliptic curve utility functions for finding generators, saturating and mapping around an isogeny class from sage.all import (pari, QQ, mwrank_get_precision, mwrank_set_precision) from magma import get_magma, MagmaEffort mwrank_saturation_precision = 1000 # 500 not enough for 594594bf2 mwrank_saturation_maxprime = 1000 GP = '/usr/local/bin/gp' # Assuming that E is known to have rank 1, returns a point on E # computed by Magma's HeegnerPoint command def magma_rank1_gen(E, mE): mP = mE.HeegnerPoint(nvals=2)[1] P = E([mP[i].sage() for i in [1, 2, 3]]) return P # Assuming that E is known to have rank 1, returns a point on E # computed by GP's ellheegner() command def pari_rank1_gen_old(E, stacksize=1024000000): from os import system, getpid, unlink f = 'tempfile-'+str(getpid()) comm = "LD_LIBRARY_PATH=/usr/local/lib; echo `echo 'ellheegner(ellinit("+str(list(E.ainvs()))+"))' | %s -q -f -s %s` > %s;" % (GP, stacksize, f) system(comm) P = open(f).read() #print(P) P = open(f).read().partition("[")[2].partition("]")[0] P = P.replace("\xb1", "") # needed for 497805u1 #print(P) unlink(f) P = E([QQ(c) for c in P.split(',')]) #print(P) return P def pari_rank1_gen(E): return E(pari(E).ellheegner().sage()) def get_magma_gens(E, mE): MS = mE.MordellWeilShaInformation(RankOnly=True, Effort=MagmaEffort, nvals=3) rank_bounds = [r.sage() for r in MS[0]] gens = [E(P.Eltseq().sage()) for P in MS[1]] return rank_bounds, gens def get_gens_mwrank(E): return E.gens(algorithm='mwrank_lib', descent_second_limit=15, sat_bound=2) def get_rank1_gens(E, mE, verbose=0): if verbose: print(" - trying a point search...") gens = E.point_search(15) if gens: if verbose: print("--success: P = {}".format(gens[0])) return gens if verbose: print("--failed. Trying pari's ellheegner...") gens = [pari_rank1_gen(E)] if gens: if verbose: print("--success: P = {}".format(gens[0])) return gens if verbose: print("--failed. Trying Magma's HeegnerPoint...") try: gens = [magma_rank1_gen(E, mE)] if gens: if verbose: print("--success: P = {}".format(gens[0])) return gens except: pass if verbose: print("-- failed. Trying Magma...") _, gens = get_magma_gens(E, mE) if gens: if verbose: print("--success: P = {}".format(gens[0])) return gens if verbose: print("--failed. Trying mwrank...") return get_gens_mwrank(E) def get_gens_simon(E): E.simon_two_descent(lim3=5000) return E.gens() def get_gens(E, ar, verbose=0): if ar == 0: return [] mag = get_magma() mE = mag(E) if ar == 1: if verbose > 1: print("{}: a.r.=1, finding a generator".format(E.ainvs())) gens = get_rank1_gens(E, mE, verbose) else: # ar >=2 if verbose > 1: print("{}: a.r.={}, finding generators using Magma".format(E.ainvs(), ar)) _, gens = get_magma_gens(E, mE) if verbose > 1: print("gens = {}".format(gens)) # Now we have independent gens, and saturate them prec0 = mwrank_get_precision() mwrank_set_precision(mwrank_saturation_precision) if verbose > 1: print("Starting saturation (automatic saturation bound)...") gens, index, reg = E.saturation(gens, max_prime=-1) # if verbose > 1: # print("Starting saturation (p<{})...".format(mwrank_saturation_maxprime)) # gens, index, reg = E.saturation(gens, max_prime=mwrank_saturation_maxprime) mwrank_set_precision(prec0) if verbose > 1: print("... finished saturation (index {}, new reg={})".format(index, reg)) return gens # Given a matrix of isogenies and a list of points on the initial # curve returns a# list of their images on each other curve. The # complication is that the isogenies will only exist when they have # prime degree. # Here we assume that the points in Plist are saturated, and only # resaturate their images at primes up to the maximum prime dividing # an isogeny degree. def map_points(maps, Plist, verbose=0): ncurves = len(maps) if len(Plist) == 0: return [[] for _ in range(ncurves)] if ncurves == 1: return [Plist] if verbose > 1: print("in map_points with degrees {}".format([[phi.degree() if phi else 0 for phi in r] for r in maps])) maxp = max([max([max(phi.degree().support(), default=0) if phi else 0 for phi in r], default=0) for r in maps], default=0) if verbose > 1: print(" maxp = {}".format(maxp)) Qlists = [Plist] + [[]]*(ncurves-1) nfill = 1 for i in range(ncurves): if nfill == ncurves: break for j in range(1, ncurves): if (maps[i][j] != 0) and Qlists[j] == []: if verbose>1: print("Mapping points from curve {} to curve {} via {}".format(i,j,maps[i][j])) print("points to be mapped: {}".format(Qlists[i])) Qlists[j] = [maps[i][j](P) for P in Qlists[i]] nfill += 1 # now we saturate the points just computed at all primes up to maxp prec0 = mwrank_get_precision() mwrank_set_precision(mwrank_saturation_precision) for i in range(1, ncurves): E = Qlists[i][0].curve() if verbose > 1: print("Saturating curve {} (maxp={})...".format(i, maxp)) Qlists[i], n, _ = E.saturation(Qlists[i], max_prime=maxp) if verbose > 1: print("--saturation index was {}".format(n)) mwrank_set_precision(prec0) return Qlists
5,776
33.801205
148
py
ecdata
ecdata-master/scripts/sharanktable.py
# script used to create shas.html from allbsd.* files: from sage.all import isqrt # we do not call the output file "shas.html" so we can compare the new # version with the old HTML_FILENAME = "newshas.html" MAX_RANK = 4 SHA_LIST = range(2, 35) + [37, 41, 43, 47, 50, 75] def make_rankshatable(nmax=30, verbose=False): total_tab = {} rank_tab = [{} for r in range(MAX_RANK + 1)] range_tab = [{} for n in range(nmax)] total = 0 rank_total = [0 for r in range(MAX_RANK + 1)] range_total = [0 for n in range(nmax)] for n in range(nmax): infilename = ''.join(["allbigsha/allbigsha.", str(n), "0000-", str(n), "9999"]) if verbose: print("processing " + infilename) infile = open(infilename) for L in infile.readlines(): _, _, _, _, r, _, S = L.split() r = int(r) S = int(S) s = int(isqrt(S)) total_tab[s] = total_tab.get(s, 0) + 1 rank_tab[r][s] = rank_tab[r].get(s, 0) + 1 range_tab[n][s] = range_tab[n].get(s, 0) + 1 total += 1 rank_total[r] += 1 range_total[n] += 1 infile.close() if verbose: print("Totals for range {}0000-{}9999: {} (total {})".format(n, n, range_tab[n], range_total)) if verbose: print("\nTotals for all ranks: {} (total {})\n".format(total_tab, total)) outfilename = HTML_FILENAME outfile = open(outfilename, mode='w') # header info for html file outfile.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n') outfile.write("<HTML>\n") outfile.write("<HEAD>\n") outfile.write('<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">\n') outfile.write("<TITLE>Analytic Shas</TITLE>\n") outfile.write("</HEAD>\n") outfile.write("<BODY>\n") # # First table: by ranges, not subdivided by rank # outfile.write("<H3 align=center>\n") outfile.write("Number of curves with nontrivial (analytic) Sha, by conductor range\n") outfile.write("</H3>\n") outfile.write("<P align=center>\n") outfile.write("Details in files allbigsha.00000-09999 etc.\n") outfile.write("</P>\n") # Table head outfile.write("<table border=2 align=center cellpadding=3 rules=groups>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=33>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<thead>\n") outfile.write('<tr style="border: solid">\n') outfile.write("<th>N<th>all>1") for s in SHA_LIST: outfile.write("<th>%s<sup>2</sup>" % s) outfile.write("\n</tr>\n") outfile.write("</thead>\n") # Table foot outfile.write("<tfoot >\n") outfile.write("<tr>\n") outfile.write("<th align=right>1-%s9999</th>\n" % str(nmax-1)) outfile.write("<td align=right>%s</td>\n" % total) for s in SHA_LIST: outfile.write("<td align=right>%s</td>\n" % total_tab.get(s, 0)) outfile.write("\n</tr>\n") outfile.write('<tr style="border: solid">\n') outfile.write("<th>N<th>all>1") for s in SHA_LIST: outfile.write("<th>%s<sup>2</sup>" % s) outfile.write("\n</tr>\n") outfile.write("</tfoot>\n") # Table body outfile.write("<tbody>\n") for n in range(nmax): outfile.write("<tr>\n") if n == 0: outfile.write("<th align=right>1-9999</th>\n") else: outfile.write("<th align=right>%s0000-%s9999</th>\n" % (str(n), str(n))) outfile.write("<td align=right>%s</td>\n" % range_total[n]) for s in SHA_LIST: outfile.write("<td align=right>%s</td>\n" % range_tab[n].get(s, '&nbsp;')) outfile.write("</tr>\n") outfile.write("</tbody>\n") outfile.write("</table>\n") outfile.write("<br>\n") # # Second table: by ranks, not subdivided by range # outfile.write("<H3 align=center>\n") outfile.write("Number of curves with nontrivial (analytic) Sha, by rank\n") outfile.write("</H3>\n") outfile.write("<table border=2 align=center cellpadding=3 rules=groups>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=33>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<colgroup span=1>\n") outfile.write("<thead>\n") outfile.write('<tr style="border: solid">\n') outfile.write("<th>&nbsp;<th>all>1") for s in SHA_LIST: outfile.write("<th>%s<sup>2</sup>" % s) outfile.write("\n</tr>\n") outfile.write("</thead>\n") # Table foot outfile.write("<tfoot >\n") outfile.write("<tr>\n") outfile.write("<th align=right>all ranks</th>\n") outfile.write("<td align=right>%s</td>\n" % total) for s in SHA_LIST: outfile.write("<td align=right>%s</td>\n" % total_tab.get(s, 0)) outfile.write("\n</tr>\n") outfile.write('<tr style="border: solid">\n') outfile.write("<th>&nbsp;<th>all>1") for s in SHA_LIST: outfile.write("<th>%s<sup>2</sup>" % s) outfile.write("\n</tr>\n") outfile.write("</tfoot>\n") # Table body outfile.write("<tbody>\n") for r in range(MAX_RANK+1): if rank_total[r] > 0: outfile.write("<tr>\n") outfile.write("<th align=right>r=%s</th>\n" % str(r)) outfile.write("<td align=right>%s</td>\n" % rank_total[r]) for s in SHA_LIST: outfile.write("<td align=right>%s</td>\n" % rank_tab[r].get(s, '&nbsp;')) outfile.write("</tr>\n") outfile.write("</tbody>\n") outfile.write("</table>\n") outfile.write("<br>\n") # footer info for html file outfile.write("<p>\n") outfile.write(' <a href="http://validator.w3.org/check?uri=referer"><img border="0"\n') outfile.write(' src="http://www.w3.org/Icons/valid-html401"\n') outfile.write(' alt="Valid HTML 4.01!" height="31" width="88"></a>\n') outfile.write("</p>\n") outfile.write("</BODY>\n") outfile.write("</HTML>\n") if verbose: for r in range(MAX_RANK + 1): if rank_total[r] > 0: print("Totals for rank {}: {} (total {})".format(r, rank_tab[r], rank_total[r]))
6,552
34.61413
106
py
ecdata
ecdata-master/scripts/aplist.py
# Sage's E.aplist(100) returns a list of the Fourier coefficients for # p<100. For the aplist files, we want to replace the coefficient for # p|N with the W-eigenvalue (the root number) and append the # W-eigenvalues for p|N, p>100. Not relevant for making LMFDBupload # files. from sage.all import prime_range def wstr(n, w): # str(n) with enough spaces prepended to give width w a = str(n) if len(a) < w: a = ' ' * (w - len(a)) + a return a def my_ap(E, D, p): if p.divides(D): return E.root_number(p) return E.ap(p) def my_ap_str(E, D, p): if p.divides(D): a = E.root_number(p) if a == 1: if p > 23: return ' +' return ' +' if p > 23: return ' -' return ' -' if p > 23: return wstr(E.ap(p), 3) return wstr(E.ap(p), 2) def my_aplist(E): D = E.discriminant() ap = [my_ap_str(E, D, p) for p in prime_range(100)] qlist = D.support() for q in qlist: if q > 100: if E.root_number(q) == 1: ap.append('+('+str(q)+')') else: ap.append('-('+str(q)+')') return ' '.join(ap)
1,200
25.688889
70
py
ecdata
ecdata-master/scripts/moddeg.py
def get_modular_degree(E, label): degphi_magma = 0 degphi_sympow = 0 #return E.modular_degree(algorithm='sympow') try: degphi_magma = E.modular_degree(algorithm='magma') except RuntimeError: print("{}: degphi via magma failed".format(label)) try: degphi_sympow = E.modular_degree(algorithm='sympow') except RuntimeError: print("{}: degphi via sympow failed".format(label)) if degphi_magma: if degphi_sympow: if degphi_magma == degphi_sympow: return degphi_magma else: print("{}: degphi = {} from magma but {} from sympow!".format( label, degphi_magma, degphi_sympow)) return degphi_magma else: return degphi_magma else: if degphi_sympow: return degphi_sympow else: print("{}: no success in computing degphi via magma or sympow".format(label)) return 0
1,008
33.793103
89
py
ecdata
ecdata-master/scripts/min_quad_twist.py
# May 2023 new function for cmputing minimal quadratic twist for any curve /Q # # - for j not 0 or 1728 this only depends on the j-invariant # - for curves with CM (and j not 0, 1728) we use a lookup table for speed # - for non-CM curves it's enough to # (1) find minimal conductor; # (2) sort into isogeny classes (if more than one curve); # (3) return the unique curve in the "first" class if not CM, or # (4) for j=0 or 1728, at step (3) there will be 2 curves in the first # class with distinct discriminants of the same sign, and we # return the one with smaller absolute discriminant. # # NB In step (4) for j=287496, CM discriminant -16 only, both curves # in the first isogeny class have the same discriminant, and we return # the one with positive c6, which is '32a3'=[0, 0, 0, -11, -14] from sage.all import Set, infinity, QQ, EllipticCurve, cm_j_invariants # dictionary to hold the list of a-invariants of the minimal twist for # all CM j-invariants other than 0 and 1728. Keys are j-invariants. min_quad_disc_CM_dict = {} min_quad_disc_CM_dict[-12288000] = [0, 0, 1, -30, 63] # '27a4' CM disc = -27 min_quad_disc_CM_dict[54000] = [0, 0, 0, -15, 22] # '36a2' CM disc = -12 min_quad_disc_CM_dict[287496] = [0, 0, 0, -11, -14] # '32a3' CM disc = -16 min_quad_disc_CM_dict[16581375] = [1, -1, 0, -37, -78] # '49a2' CM disc = -28 min_quad_disc_CM_dict[-3375] = [1, -1, 0, -2, -1] # '49a1' CM disc = -7 min_quad_disc_CM_dict[8000] = [0, 1, 0, -3, 1] # '256a1' CM disc = -8 min_quad_disc_CM_dict[-32768] = [0, -1, 1, -7, 10] # '121b1' CM disc = -11 min_quad_disc_CM_dict[-884736] = [0, 0, 1, -38, 90] # '361a1' CM disc = -19 min_quad_disc_CM_dict[-884736000] = [0, 0, 1, -860, 9707] # '1849a1' CM disc = -43 min_quad_disc_CM_dict[-147197952000] = [0, 0, 1, -7370, 243528] # '4489a1' CM disc = -67 min_quad_disc_CM_dict[-262537412640768000] = [0, 0, 1, -2174420, 1234136692] # '26569a1' CM disc = -163 assert Set(min_quad_disc_CM_dict.keys()) + Set([0,1728]) == Set(cm_j_invariants(QQ)) def isog_key(E): return E.aplist(100) def min_quad_twist(E): """ Input: E, an elliptic curve over Q. Output: Emqt,D where Emqt is the minimal quadratic twist of E, its twist by D """ j = E.j_invariant() try: Emqt = EllipticCurve(min_quad_disc_CM_dict[j]) return Emqt, E.is_quadratic_twist(Emqt) except KeyError: pass assert j in [0,1728] or not E.has_cm() # find minimal quadratic twist of E at primes >3 E = E.global_minimal_model() A = -27*E.c4() B = -54*E.c6() for p in A.gcd(B).support(): eA = A.valuation(p)//2 if A else infinity eB = B.valuation(p)//3 if B else infinity e = min(eA, eB) if e>0: pe = p**e A /= pe**2 B /= pe**3 # now twist by -1,2,3 tw = [1,-1,2,-2,3,-3,6,-6] EAB = EllipticCurve([A,B]) # EAB may not be minimal but the quadratic twist method returns minimal models Elist = [EAB.quadratic_twist(t) for t in tw] # find minimal conductor: min_cond = min(E.conductor() for E in Elist) Elist = [E for E in Elist if E.conductor() == min_cond] if len(Elist)==1: return Elist[0], E.is_quadratic_twist(Elist[0]) # sort into isogeny classes and pick out first from itertools import groupby Elist.sort(key = isog_key) Elist = list(list(next(groupby(Elist, key=isog_key)))[1]) # This should leave 1 curve or 2 when E has CM n = len(Elist) if n==1: return Elist[0], E.is_quadratic_twist(Elist[0]) assert n==2 and j in [0, 1728] Elist.sort(key=lambda e: e.discriminant().abs()) return Elist[0], E.is_quadratic_twist(Elist[0]) # Function to add (or overwrite) the fields 'min_quad_twist_ainvs' and # 'min_quad_twist_disc' from a curve record obtained from # e.g. read_data(file_types=['curvedata'], ranges=['00000-09999']) def add_mqt(record): from codec import decoders, encode E = EllipticCurve(decoders['ainvs'](record['ainvs'])) Emqt, D = min_quad_twist(E) Emqt = encode(list(Emqt.ainvs())) D = encode(D) if Emqt != record['min_quad_twist_ainvs']: record['min_quad_twist_ainvs'] = Emqt record['min_quad_twist_disc'] = D return record def add_mqt_range(r, base_dir): from files import read_data, write_curvedata dat = read_data(base_dir=base_dir, file_types=['curvedata'], ranges=[r]) for lab, rec in dat.items(): dat[lab] = add_mqt(rec) write_curvedata(dat, r, base_dir=base_dir)
4,524
37.347458
103
py
ecdata
ecdata-master/scripts/check_gens.py
###################################################################### # # Functions to check Minkowksi-reduction of generators, and compare # ###################################################################### import os from sage.all import EllipticCurve from codec import split, parse_int_list, proj_to_point, point_to_proj from red_gens import reduce_gens, check_minkowski HOME = os.getenv("HOME") ECDATA_DIR = os.path.join(HOME, "ecdata") BASE_DIR = ECDATA_DIR def check_mink(filename, base_dir=BASE_DIR): infilename = os.path.join(base_dir, filename) with open(infilename) as infile: n = 0 nbad = 0 for line in infile: n += 1 data = split(line) label = "".join(data[:3]) ainvs = parse_int_list(data[3]) E = EllipticCurve(ainvs) rank = int(data[4]) gens = [proj_to_point(gen, E) for gen in data[6:6 + rank]] if not check_minkowski(gens): nbad += 1 print("{}: gens {} are not Minkowski-reduced".format(label, gens)) print("heights: {}".format([P.height() for P in gens])) print("Out of {} curves, {} were reduced and {} not".format(n, n-nbad, nbad)) def rewrite_gens(filename, base_dir=BASE_DIR): oldfile = os.path.join(base_dir, filename) newfile = ".".join([oldfile, 'new']) with open(oldfile) as infile, open(newfile, 'w') as outfile: n = 0 for line in infile: n += 1 data = split(line) label = "".join(data[:3]) ainvs = parse_int_list(data[3]) E = EllipticCurve(ainvs) rank = int(data[4]) gens = [proj_to_point(gen, E) for gen in data[6:6 + rank]] tgens = [proj_to_point(gen, E) for gen in data[6 + rank:]] if len(tgens) == 2 and tgens[0].order() > tgens[1].order(): print("torsion gens for {} in wrong order".format(label)) newgens, tgens = reduce_gens(gens, tgens) newgens = [point_to_proj(P) for P in newgens] tgens = [point_to_proj(P) for P in tgens] data[6:6+rank] = newgens data[6+rank:] = tgens outfile.write(" ".join(data) + "\n") if n%1000 == 0: print("{} lines output...".format(n)) print("Done. {} lines output".format(n)) def compare_gens(filename1, filename2, base_dir=BASE_DIR): file1 = os.path.join(base_dir, filename1) file2 = os.path.join(base_dir, filename2) Egens = {} with open(file1) as infile1, open(file2) as infile2: for infile, infilename in zip([infile1, infile2], [file1, file2]): for line in infile: data = split(line) label = "".join(data[:3]) ainvs = parse_int_list(data[3]) E = EllipticCurve(ainvs) rank = int(data[4]) gens = [proj_to_point(gen, E) for gen in data[6:6 + rank]] if label not in Egens: Egens[label] = {} Egens[label][infilename] = gens print("Finished reading {}".format(infilename)) nsame = 0 ndiff = 0 nsame_uptosign = 0 nsame_uptotorsion = 0 ndiff_really = 0 with open(file1 + '.uptosign.txt', 'w') as logfile2, open(file1 + '.uptotorsion.txt', 'w') as logfile3: for label in Egens: bothgens = Egens[label] gens1 = bothgens[file1] gens2 = bothgens[file2] if gens1 == gens2: nsame += 1 else: ndiff += 1 if all([(P == Q) or (P == -Q) for P, Q in zip(gens1, gens2)]): nsame_uptosign += 1 logfile2.write("{} gens1: {}\n{} gens2: {}\n".format(label, gens1, label, gens2)) else: if all([(P - Q).has_finite_order() or (P + Q).has_finite_order() for P, Q in zip(gens1, gens2)]): nsame_uptotorsion += 1 logfile3.write("{} gens1: {}\n{} gens2: {}\n".format(label, gens1, label, gens2)) else: ndiff_really += 1 print("gens equal in {} cases, different in {} cases".format(nsame, ndiff)) print("gens equal up to sign in {} more cases".format(nsame_uptosign)) print("gens equal up to torsion in {} more cases".format(nsame_uptotorsion)) if ndiff_really: print("gens different, even up to sign and torsion in {} cases".format(ndiff_really)) else: print("In all cases the gens are the same up to sign and torsion")
4,640
41.972222
117
py
ecdata
ecdata-master/scripts/intpts.py
# Find integral points in a fail-safe way uing both Sage and Magma, # comparing, returning the union in all cases and outputting a warning # message if they disagree. from sage.all import Set from magma import get_magma def get_integral_points_with_sage(E, gens): return [P[0] for P in E.integral_points(mw_base=gens)] def get_integral_points_with_magma(E, gens): mag = get_magma() mE = mag(E) xs = [E(P.Eltseq().sage())[0] for P in mE.IntegralPoints(FBasis=[mE(list(P)) for P in gens])] return xs def get_integral_points(E, gens, verbose=True): x_list_magma = get_integral_points_with_magma(E, gens) x_list_sage = get_integral_points_with_sage(E, gens) if x_list_magma != x_list_sage: if verbose: print("Curve {}: \n".format(E.ainvs)) print("Integral points via Magma: {}".format(x_list_magma)) print("Integral points via Sage: {}".format(x_list_sage)) x_list = list(Set(x_list_sage)+Set(x_list_magma)) x_list.sort() return x_list
1,025
34.37931
97
py
ecdata
ecdata-master/scripts/files.py
# Functions to read data from the files: # # alllabels.*, allgens.*, alldegphi.*, allisog.*, # intpts.*, opt_man.*, 2adic.*, galrep.* # # and also torsion growth and Iwasawa data files. The latter used to # be arranged differently; now they are not, but only exist in the # ranges up to 50000. import os from sage.all import ZZ, QQ, RR, RealField, EllipticCurve, Integer, prod, factorial, primes, gcd from sage.databases.cremona import class_to_int, parse_cremona_label from trace_hash import TraceHashClass from codec import split, parse_int_list, parse_int_list_list, proj_to_point, proj_to_aff, point_to_weighted_proj, decode, encode, split_galois_image_code, parse_twoadic_string, shortstr, liststr, weighted_proj_to_proj from red_gens import reduce_gens from moddeg import get_modular_degree from min_quad_twist import min_quad_twist HOME = os.getenv("HOME") # Most data from John Cremona (https://github.com/JohnCremona/ecdata) # which we assume cloned in the home directory ECDATA_DIR = os.path.join(HOME, "ecdata") UPLOAD_DIR = os.path.join(HOME, "ecq-upload") # Iwasawa data from Rob Pollack (https://github.com/rpollack9974/Iwasawa-invariants) but reorganised here: IWASAWA_DATA_DIR = ECDATA_DIR # Data files derived from https://github.com/bmatschke/s-unit-equations/tree/master/elliptic-curve-tables MATSCHKE_DIR = os.path.join(HOME, "MatschkeCurves") # Data files for Stein-Watkins database curves SWDB_DIR = os.path.join(HOME, "swdb") DEFAULT_PRECISION = 53 PRECISION = 53 # precision of heights, regulator, real period and # special value, and hence analytic sha, when these are # computed and not just read from the files. ###################################################################### # # Functions to parse single lines from each of the file types # # In each case the function returns a full label and a dict whose keys # are (exactly?) the relevant table columns # ###################################################################### # # Parsing common label/ainvs columns: # # allgens, allisog, alldegphi, opt_man, 2adic: first 4 cols are N,iso,number,ainvs # alllabels: first 3 cols are N,iso,number # intpts: first 2 cols are label, ainvs # galrep: first 1 col is label # # so there are 1 or 3 label columns, and there may or may not be an ainvs column def parse_line_label_cols(L, label_cols=3, ainvs=True, raw=False): r""" Parse the first columns of one line to extract label and/or ainvs If label_cols is 3, the first 3 columns are conductor, iso, number, else the first column is label. If ainvs is True, the next columnm is the ainvs. If raw is False, 'conductor' is an int and 'ainvs' a list of ints, otherwise they stay as strings. Cols filled: 'label', 'conductor', 'iso', 'number', and optionally 'ainvs'. """ data = L.split() record = {} if label_cols == 1: record['label'] = label = data[0] N, isoclass, num = parse_cremona_label(label) sN = str(N) record['conductor'] = sN if raw else N record['isoclass'] = isoclass record['iso'] = ''.join([sN, isoclass]) record['number'] = str(num) if raw else num else: record['conductor'] = data[0] if raw else int(data[0]) record['isoclass'] = data[1] record['iso'] = ''.join(data[:2]) record['number'] = data[2] if raw else int(data[2]) record['label'] = ''.join(data[:3]) if ainvs: record['ainvs'] = data[label_cols] if raw else parse_int_list(data[label_cols]) return record['label'], record ###################################################################### # # allgens parser # # This is the biggest since it's the only one where curves have to be # constructed and nontrivial dependent column data computed. After # running this on all files and outputting new the computed data to a # new set of files, this will no longer be needed. def parse_allgens_line(line): r""" Parse one line from an allgens file Lines contain 6+t+r fields (columns) conductor iso number ainvs r torsion_structure <tgens> <gens> where: torsion_structure is a list of t = 0,1,2 ints <tgens> is t fields containing torsion generators <gens> is r fields containing generators mod torsion """ label, record = parse_line_label_cols(line, 3, True) first = record['number'] # tags first curve in each isogeny class data = split(line) ainvs = record['ainvs'] E = EllipticCurve(ainvs) N = E.conductor() assert N == record['conductor'] record['bad_primes'] = bad_p = N.prime_factors() # will be sorted record['num_bad_primes'] = len(bad_p) record['jinv'] = E.j_invariant() record['signD'] = int(E.discriminant().sign()) record['cm'] = int(E.cm_discriminant()) if E.has_cm() else 0 if first: record['aplist'] = E.aplist(100, python_ints=True) record['anlist'] = E.anlist(20, python_ints=True) # passing the iso means that we'll only do the computation once per isogeny class record['trace_hash'] = TraceHashClass(record['iso'], E) local_data = [{'p': int(ld.prime().gen()), 'ord_cond':int(ld.conductor_valuation()), 'ord_disc':int(ld.discriminant_valuation()), 'ord_den_j':int(max(0, -(E.j_invariant().valuation(ld.prime().gen())))), 'red':int(ld.bad_reduction_type()), 'rootno':int(E.root_number(ld.prime().gen())), 'kod':ld.kodaira_symbol()._pari_code(), 'cp':int(ld.tamagawa_number())} for ld in E.local_data()] record['tamagawa_numbers'] = cps = [ld['cp'] for ld in local_data] record['kodaira_symbols'] = [ld['kod'] for ld in local_data] record['reduction_types'] = [ld['red'] for ld in local_data] record['root_numbers'] = [ld['rootno'] for ld in local_data] record['conductor_valuations'] = cv = [ld['ord_cond'] for ld in local_data] record['discriminant_valuations'] = [ld['ord_disc'] for ld in local_data] record['j_denominator_valuations'] = [ld['ord_den_j'] for ld in local_data] record['semistable'] = all([v == 1 for v in cv]) record['tamagawa_product'] = tamprod = prod(cps) # NB in the allgens file all points are stored in projective # coordinates as [x:y:z]. In the database (as of 2020.11.18) we # store both sets of generators as lists of strings, using # projective coordinates '(x:y:z)' for gens of infinite order but # affine coordinates '(x/z,y/z)' for torsion gens. Then in the # code (web_ec.py) we convert projective coords to affine anyway, # using code which can handle either, but has less to do if the # point is already affine. So let's do the conversion here. record['rank'] = rank = int(data[4]) record['rank_bounds'] = [rank, rank] record['ngens'] = rank tor_struct = parse_int_list(data[5]) record['torsion_structure'] = tor_struct record['torsion'] = torsion = prod(tor_struct) record['torsion_primes'] = [int(p) for p in Integer(torsion).support()] # read and reduce generators and torsion generators gens = [proj_to_point(gen, E) for gen in data[6:6 + rank]] tgens = [proj_to_point(gen, E) for gen in data[6 + rank:]] gens, tgens = reduce_gens(gens, tgens, False, label) record['gens'] = [point_to_weighted_proj(gen) for gen in gens] record['torsion_generators'] = [point_to_weighted_proj(gen) for gen in tgens] record['heights'] = [P.height(precision=PRECISION) for P in gens] reg = E.regulator_of_points(gens, precision=PRECISION) if gens else 1 record['regulator'] = reg L = E.period_lattice() record['real_period'] = om = L.omega(prec=PRECISION) # includes #R-components factor record['area'] = A = L.complex_area(prec=PRECISION) record['faltings_height'] = -A.log()/2 if first: # else add later to avoid recomputing a.r. # Analytic rank and special L-value ar, sv = E.pari_curve().ellanalyticrank(precision=PRECISION) record['analytic_rank'] = ar = ar.sage() record['special_value'] = sv = sv.sage()/factorial(ar) # Analytic Sha sha_an = sv*torsion**2 / (tamprod*reg*om) sha = sha_an.round() assert sha > 0 assert sha.is_square() assert (sha-sha_an).abs() < 1e-10 record['sha_an'] = sha_an record['sha'] = int(sha) record['sha_primes'] = [int(p) for p in sha.prime_divisors()] Etw, Dtw = min_quad_twist(E) record['min_quad_twist_ainvs'] = [int(a) for a in Etw.ainvs()] record['min_quad_twist_disc'] = int(Dtw) return label, record ###################################################################### # # alllabels parser # def parse_alllabels_line(line): r""" Parses one line from an alllabels file. Returns the label and a dict containing seven fields, 'conductor', 'iso', 'number', 'lmfdb_label', 'lmfdb_iso', 'iso_nlabel', 'lmfdb_number', being strings or ints. Cols filled: 'label', 'conductor', 'iso', 'number', 'lmfdb_label', 'lmfdb_iso', 'lmfdb_number', 'iso_nlabel'. [NO] Also populates two global dictionaries lmfdb_label_to_label and label_to_lmfdb_label, allowing other upload functions to look these up. Input line fields: conductor iso number conductor lmfdb_iso lmfdb_number Sample input line: 57 c 2 57 b 1 """ data = split(line) if data[0] != data[3]: raise ValueError("Inconsistent conductors in alllabels file: %s" % line) label, record = parse_line_label_cols(line, 3, False) record['lmfdb_isoclass'] = data[4] record['lmfdb_iso'] = lmfdb_iso = ''.join([data[3], '.', data[4]]) record['lmfdb_label'] = ''.join([lmfdb_iso, data[5]]) record['lmfdb_number'] = int(data[5]) record['iso_nlabel'] = class_to_int(data[4]) return label, record ###################################################################### # # allisog parser # def parse_allisog_line(line): r""" Parse one line from an allisog file Input line fields: conductor iso number ainvs all_ainvs isogeny_matrix Sample input line: 11 a 1 [0,-1,1,-10,-20] [[0,-1,1,-10,-20],[0,-1,1,-7820,-263580],[0,-1,1,0,0]] [[1,5,5],[5,1,25],[5,25,1]] """ label, record = parse_line_label_cols(line, 3, False) assert record['number'] == 1 isomat = split(line)[5][2:-2].split("],[") record['isogeny_matrix'] = mat = [[int(a) for a in r.split(",")] for r in isomat] record['class_size'] = len(mat) record['class_deg'] = max(max(r) for r in mat) record['all_iso_degs'] = dict([[n+1, sorted(list(set(row)))] for n, row in enumerate(mat)]) record['isogeny_degrees'] = record['all_iso_degs'][1] # NB Every curve in the class has the same 'isogeny_matrix', # 'class_size', 'class_deg', and the for the i'th curve in the # class (for i=1,2,3,...) its 'isogeny_degrees' column is # all_iso_degs[i]. return label, record ###################################################################### # # alldegphi parser # def parse_alldegphi_line(line, raw=False): r""" Parses one line from an alldegphi file. Input line fields: conductor iso number ainvs degree Sample input line: 11 a 1 [0,-1,1,-10,-20] 1 """ label, record = parse_line_label_cols(line, 3, False, raw=raw) deg = split(line)[4] record['degree'] = deg if raw else int(deg) return label, record ###################################################################### # # intpts parser # def make_y_coords(ainvs, x): a1, a2, a3, a4, a6 = ainvs f = ((x + a2) * x + a4) * x + a6 b = (a1*x + a3) d = (ZZ(b*b + 4*f)).isqrt() y = (-b+d)//2 return [y, -b-y] if d else [y] def count_integral_points(ainvs, xs): return sum([len(make_y_coords(ainvs, x)) for x in xs]) def parse_intpts_line(line, raw=False): r""" Parses one line from an intpts file. Input line fields: label ainvs x-coordinates_of_integral_points Sample input line: 11a1 [0,-1,1,-10,-20] [5,16] """ label, record = parse_line_label_cols(line, 1, True, raw=raw) rxs = split(line)[2] xs = parse_int_list(rxs) ainvs = record['ainvs'] if raw: ainvs = parse_int_list(ainvs) nip = count_integral_points(ainvs, xs) record['xcoord_integral_points'] = rxs if raw else xs record['num_int_pts'] = str(nip) if raw else nip return label, record ###################################################################### # # opt_man parser # def parse_opt_man_line(line, raw=False): r"""Parses one line from an opt_man file, giving optimality and Manin constant data. Input line fields: N iso num ainvs opt mc where opt = (0 if not optimal, 1 if optimal, n>1 if one of n possibly optimal curves in the isogeny class), and mc = Manin constant *conditional* on curve #1 in the class being the optimal one. Sample input lines with comments added: 11 a 1 [0,-1,1,-10,-20] 1 1 # optimal, mc=1 11 a 2 [0,-1,1,-7820,-263580] 0 1 # not optimal, mc=1 11 a 3 [0,-1,1,0,0] 0 5 # not optimal, mc=5 499992 a 1 [0,-1,0,4481,148204] 3 1 # one of 3 possible optimal curves in class g, mc=1 for all whichever is optimal 499992 a 2 [0,-1,0,-29964,1526004] 3 1 # one of 3 possible optimal curves in class g, mc=1 for all whichever is optimal 499992 a 3 [0,-1,0,-446624,115024188] 3 1 # one of 3 possible optimal curves in class g, mc=1 for all whichever is optimal 499992 a 4 [0,-1,0,-164424,-24344100] 0 1 # not optimal, mc=1 """ label, record = parse_line_label_cols(line, 3, False) opt, mc = split(line)[4:] record['optimality'] = opt if raw else int(opt) record['manin_constant'] = mc if raw else int(mc) return label, record ###################################################################### # # 2adic parser # def parse_twoadic_line(line, raw=False): r""" Parses one line from a 2adic file. Input line fields: conductor iso number ainvs index level gens label Sample input lines: 110005 a 2 [1,-1,1,-185793,29503856] 12 4 [[3,0,0,1],[3,2,2,3],[3,0,0,3]] X24 27 a 1 [0,0,1,0,-7] inf inf [] CM """ label, record = parse_line_label_cols(line, 3, False, raw=raw) s = line.split(maxsplit=4)[4] record.update(parse_twoadic_string(s, raw=raw)) #print(record) return label, record ###################################################################### # # galrep parser # def parse_galrep_line(line, raw=False): r"""Parses one line from a galrep file. Codes follow Sutherland's coding scheme for subgroups of GL(2,p). Note that these codes start with a 1 or 2 digit prime followed a letter in ['B','C','N','S']. Input line fields: label codes Sample input line: 66c3 2B 5B.1.2 """ label, record = parse_line_label_cols(line, 1, False, raw=raw) image_codes = split(line)[1:] # list of strings pr = [int(split_galois_image_code(s)[0]) for s in image_codes] # list of ints rad = prod(pr) record['modp_images'] = image_codes record['nonmax_primes'] = pr record['nonmax_rad'] = rad return label, record ###################################################################### # # iwasawa parser # def parse_iwasawa_line(line, debug=0, raw=False): r"""Parses one line from an Iwasawa data input file. Sample line: 11 a 1 0,-1,1,-10,-20 7 1,0 0,1,0 0,0 0,1 Fields: label (3 fields) a-invariants (1 field but no brackets) p0 For each bad prime: 'a' if additive lambda,mu if multiplicative (or 'o?' if unknown) For each good prime: lambda,mu if ordinary (or 'o?' if unknown) lambda+,lambda-,mu if supersingular (or 's?' if unknown) """ if debug: print("Parsing input line {}".format(line[:-1])) label, record = parse_line_label_cols(line, 3, False, raw=raw) badp = Integer(record['conductor']).support() nbadp = len(badp) data = split(line) rp0 = data[4] p0 = int(rp0) record['iwp0'] = rp0 if raw else p0 if debug: print("p0={}".format(p0)) iwdata = {} # read data for bad primes for p, pdat in zip(badp, data[5:5+nbadp]): p = str(p) if debug > 1: print("p={}, pdat={}".format(p, pdat)) if pdat in ['o?', 'a']: iwdata[p] = pdat else: iwdata[p] = [int(x) for x in pdat.split(",")] # read data for all primes # NB Current data has p<50: if this increases to over 1000, change the next line. for p, pdat in zip(primes(1000), data[5+nbadp:]): p = str(p) if debug > 1: print("p={}, pdat={}".format(p, pdat)) if pdat in ['s?', 'o?', 'a']: iwdata[p] = pdat else: iwdata[p] = parse_int_list(pdat, delims=False) record['iwdata'] = iwdata if debug: print("label {}, data {}".format(label, record)) return label, record ###################################################################### # # growth parser # def parse_growth_line(line, raw=False): r"""Parses one line from a torsion growth file. Sample line: 14a1 [3,6][1,1,1] [2,6][2,-1,1] Fields: label (single field, Cremona label) 1 or more items of the form TF (with no space between) with T =[n] or [m,n] and F a list of integers of length d+1>=3 containing the coefficients of a monic polynomial of degree d defining a number field (constant coeff first). Notes: (1) in each file d is fixed and contained in the filename (e.g. growth2.000000-399999) but can be recovered from any line from the length of the coefficient lists. (2) The files for degree d only have lines for curves where there is growth in degree d, so each line has at least 2 fields in it. (3) The returned record (dict) has one relevant key 'torsion_growth' which is a dict with a unique key (the degree) and value a list of pairs [F,T] where both F and T are lists of ints. It is up to the calling function to merge these for different degrees. """ label, record = parse_line_label_cols(line, 1, False, raw=raw) data = [[parse_int_list(F, delims=False), parse_int_list(T, delims=False)] for T, F in [s[1:-1].split("][") for s in split(line)[1:]]] degree = len(data[0][0])-1 record['torsion_growth'] = {degree: data} return label, record iwasawa_ranges = ["{}0000-{}9999".format(n, n) for n in range(15)] ###################################################################### # # Function to read all growth data (or a subset) # # (special treatment needed because of the nonstandard filenames, in directories by degree) # growth_degrees = (2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21) #NB the 0'th range is usually '00000-09999' but for growth files it's just '0-9999' growth_ranges = ["0-9999"] + ["{}0000-{}9999".format(k, k) for k in range(1, 40)] def read_all_growth_data(base_dir=ECDATA_DIR, degrees=growth_degrees, ranges=growth_ranges, raw=False): r"""Read all the data in files base_dir/growth/<d>/growth.<r> where d is a list of degrees and r is a range. Return a single dict with keys labels and values curve records with label keys and one 'torsion_growth' key. """ all_data = {} for r in ranges: if r == '00000-09999': r = '0-9999' if r not in growth_ranges: continue for d in degrees: if d not in growth_degrees: continue data_filename = os.path.join(base_dir, 'growth/{}/growth{}.{}'.format(d, d, r)) n = 0 with open(data_filename) as data: for L in data: label, record = parse_growth_line(L, raw=raw) n += 1 if label in all_data: all_data[label]['torsion_growth'].update(record['torsion_growth']) else: all_data[label] = record return all_data def parse_allgens_line_simple(line): r""" Parse one line from an allgens file Lines contain 6+t+r fields (columns) conductor iso number ainvs r torsion_structure <tgens> <gens> where: torsion_structure is a list of t = 0,1,2 ints <tgens> is t fields containing torsion generators <gens> is r fields containing generators mod torsion """ label, record = parse_line_label_cols(line, 3, True) E = EllipticCurve(record['ainvs']) data = split(line) rank = int(data[4]) record['gens'] = [proj_to_point(gen, E) for gen in data[6:6 + rank]] return label, record def parse_extra_gens_line(line): r""" Parse one line from a gens file (e.g. output by my pari wrapper of ellrank) Lines contain 5 fields (columns) conductor ainvs ar [rlb,rub] gens where: ar = analytic rank rlb, rub are lower/upper bounds on the rank gens is a list of pairs of rationals, of length rlb Returns a pair of ainvs (as a tuple) and a list of points """ data = split(line) N = ZZ(data[0]) ainvs = parse_int_list(data[1]) #ar = int(data[2]) #rbds = parse_int_list(data[3]) gens = data[4] if gens == '[]': gens = [] else: E = EllipticCurve(ainvs) gens = [E([QQ(c) for c in g.split(",")]) for g in gens[2:-2].split('],[')] return N, tuple(ainvs), gens # Original columns of a curvedata file: curvedata_cols_old1 = ['label', 'isoclass', 'number', 'lmfdb_label', 'lmfdb_isoclass', 'lmfdb_number', 'iso_nlabel', 'faltings_index', 'faltings_ratio', 'conductor', 'ainvs', 'jinv', 'cm', 'isogeny_degrees', 'semistable', 'signD', 'min_quad_twist_ainvs', 'min_quad_twist_disc', 'bad_primes', 'tamagawa_numbers', 'kodaira_symbols', 'reduction_types', 'root_numbers', 'conductor_valuations', 'discriminant_valuations', 'j_denominator_valuations', 'rank', 'rank_bounds', 'analytic_rank', 'ngens', 'gens', 'heights', 'regulator', 'torsion', 'torsion_structure', 'torsion_generators', 'tamagawa_product', 'real_period', 'area', 'faltings_height', 'special_value', 'sha_an', 'sha'] twoadic_cols = ['twoadic_index', 'twoadic_label', 'twoadic_log_level', 'twoadic_gens'] galrep_cols = ['modp_images', 'nonmax_primes', 'nonmax_rad'] intpts_cols = ['xcoord_integral_points', 'num_int_pts'] # Columns after adding twoadic, galrep and intpts columns (making # those separate files unnecessary) and 'trac_hash' and 'degree': curvedata_cols_old2 = ['label', 'isoclass', 'number', 'lmfdb_label', 'lmfdb_isoclass', 'lmfdb_number', 'iso_nlabel', 'faltings_index', 'faltings_ratio', 'conductor', 'ainvs', 'jinv', 'cm', 'isogeny_degrees', 'semistable', 'signD', 'min_quad_twist_ainvs', 'min_quad_twist_disc', 'bad_primes', 'tamagawa_numbers', 'kodaira_symbols', 'reduction_types', 'root_numbers', 'conductor_valuations', 'discriminant_valuations', 'j_denominator_valuations', 'rank', 'rank_bounds', 'analytic_rank', 'ngens', 'gens', 'heights', 'regulator', 'torsion', 'torsion_structure', 'torsion_generators', 'tamagawa_product', 'real_period', 'area', 'faltings_height', 'special_value', 'sha_an', 'sha', 'trace_hash', 'degree', 'xcoord_integral_points', 'num_int_pts', 'twoadic_index', 'twoadic_label', 'twoadic_log_level', 'twoadic_gens', 'modp_images', 'nonmax_primes', 'nonmax_rad'] # Columns after adding 'absD' and 'stable_faltings_height' curvedata_cols = ['label', 'isoclass', 'number', 'lmfdb_label', 'lmfdb_isoclass', 'lmfdb_number', 'iso_nlabel', 'faltings_index', 'faltings_ratio', 'conductor', 'ainvs', 'jinv', 'cm', 'isogeny_degrees', 'semistable', 'signD', 'absD', 'min_quad_twist_ainvs', 'min_quad_twist_disc', 'bad_primes', 'tamagawa_numbers', 'kodaira_symbols', 'reduction_types', 'root_numbers', 'conductor_valuations', 'discriminant_valuations', 'j_denominator_valuations', 'rank', 'rank_bounds', 'analytic_rank', 'ngens', 'gens', 'heights', 'regulator', 'torsion', 'torsion_structure', 'torsion_generators', 'tamagawa_product', 'real_period', 'area', 'faltings_height', 'stable_faltings_height', 'special_value', 'sha_an', 'sha', 'trace_hash', 'degree', 'xcoord_integral_points', 'num_int_pts', 'twoadic_index', 'twoadic_label', 'twoadic_log_level', 'twoadic_gens', 'modp_images', 'nonmax_primes', 'nonmax_rad'] classdata_cols = ['iso', 'lmfdb_iso', 'trace_hash', 'class_size', 'class_deg', 'isogeny_matrix', 'aplist', 'anlist'] datafile_columns = { 'curvedata': curvedata_cols, 'curvedata_ext': curvedata_cols, 'classdata': classdata_cols, } # datafile_columns['curvedata'] = curvedata_cols_old2 # TEMPORARY # print("curvedata columns") # print(datafile_columns['curvedata']) # print("curvedata_ext columns") # print(datafile_columns['curvedata_ext']) def parse_curvedata_line(line, raw=False, ext=False): """ """ data = split(line) if ext: cols = datafile_columns['curvedata_ext'] else: cols = datafile_columns['curvedata'] if len(data) != len(cols): raise RuntimeError("curvedata line has {} columns but {} were expected".format(len(data), len(cols))) if raw: record = dict([(col, data[n]) for n, col in enumerate(cols)]) record['semistable'] = bool(int(record['semistable'])) record['potential_good_reduction'] = (parse_int_list(record['jinv'])[1] == 1) record['num_bad_primes'] = str(1+record['bad_primes'].count(",")) record['class_size'] = str(1+record['isogeny_degrees'].count(",")) if ext: for c in galrep_cols: record[c] = decode(c, record[c]) if record['twoadic_index'] == '0': for c in twoadic_cols: if c != 'twoadic_index': record[c] = decode(c, record[c]) else: record = dict([(col, decode(col, data[n])) for n, col in enumerate(cols)]) record['potential_good_reduction'] = (record['jinv'].denominator() == 1) record['num_bad_primes'] = len(record['bad_primes']) record['class_size'] = len(record['isogeny_degrees']) # Cremona labels only defined for conductors up to 500000: if ZZ(record['conductor']) < 500000: record['Clabel'] = record['label'] record['Ciso'] = record['label'][:-1] record['Cnumber'] = record['number'] if record['sha'] != "?": record['sha_primes'] = [int(p) for p in Integer(record['sha']).prime_divisors()] record['torsion_primes'] = [int(p) for p in Integer(record['torsion']).prime_divisors()] record['lmfdb_iso'] = ".".join([str(record['conductor']), record['lmfdb_isoclass']]) # The next line was only needed when we added the Faltings height and absD fields #record = add_extra_data(record) ## add absD and stable_faltings_height return record['label'], record def parse_classdata_line(line, raw=False): """ """ data = split(line) if raw: record = dict([(col, data[n]) for n, col in enumerate(datafile_columns['classdata'])]) else: record = dict([(col, decode(col, data[n])) for n, col in enumerate(datafile_columns['classdata'])]) return record['iso']+'1', record ###################################################################### # parsers = {'allgens': parse_allgens_line, 'alllabels': parse_alllabels_line, 'allisog': parse_allisog_line, 'alldegphi': parse_alldegphi_line, 'intpts': parse_intpts_line, 'opt_man': parse_opt_man_line, '2adic': parse_twoadic_line, 'galrep': parse_galrep_line, 'curvedata': parse_curvedata_line, 'classdata': parse_classdata_line, 'growth': parse_growth_line, 'iwasawa': parse_iwasawa_line, } all_file_types = list(parsers.keys()) old_file_types = ['alllabels', 'allgens', 'allisog'] more_old_file_types = ['alldegphi', 'intpts', '2adic', 'galrep'] new_file_types = [ft for ft in all_file_types if ft not in old_file_types] newer_file_types = [ft for ft in new_file_types if ft not in more_old_file_types] optional_file_types = ['opt_man', 'growth', 'iwasawa'] main_file_types = [t for t in new_file_types if t not in optional_file_types] new_main_file_types = [t for t in newer_file_types if t not in optional_file_types] assert new_main_file_types == ['curvedata', 'classdata'] all_ranges = ["{}0000-{}9999".format(n, n) for n in range(50)] iwasawa_ranges = ["{}0000-{}9999".format(n, n) for n in range(15)] ###################################################################### # # Function to read data from ['allgens', 'alllabels', 'allisog'] in # one or more ranges and fill in additional data required for # curvedata and classdata files. # # This is used in the (one-off) function make_curvedata() which makes # curvedata and classdata files for each range. def read_old_data(base_dir=ECDATA_DIR, ranges=all_ranges): r"""Read all the data in files base_dir/<ft>/<ft>.<r> where ft is each of ['allgens', 'alllabels', 'allisog'] and r is a range. Return a single dict with keys labels and values complete curve records. """ all_data = {} for r in ranges: for ft in ['allgens', 'alllabels', 'allisog']: data_filename = os.path.join(base_dir, '{}/{}.{}'.format(ft, ft, r)) parser = parsers[ft] n = 0 with open(data_filename) as data: for L in data: label, record = parser(L) first = (record['number'] == 1) # if n > 100 and first: # break if label: if first: n += 1 if label in all_data: all_data[label].update(record) else: all_data[label] = record if n%1000 == 0 and first: print("Read {} classes from {}".format(n, data_filename)) print("Read {} lines from {}".format(n, data_filename)) # Fill in isogeny data for all curves in each class: for label, record in all_data.items(): n = record['number'] if n > 1: record1 = all_data[label[:-1]+'1'] record['isogeny_degrees'] = record1['all_iso_degs'][n] for col in ['isogeny_matrix', 'class_size', 'class_deg']: record[col] = record1[col] # Fill in MW & BSD data for all curves in each class: FRout = open("FRlists.txt", 'w') for label, record in all_data.items(): n = record['number'] if n == 1: # We sort the curves in each class by Faltings height. # Note that while there is always a unique curve with # minimal height (whose period lattice is a sublattice of # all the others), other heights may appear multiple # times. The possible ordered lists of ratios which have # repeats include: [1,2,2,2], [1,2,4,4], [1,2,4,4,8,8], # [1,2,4,4,8,8,16,16], [1,3,3], [1,3,3,9], # [1,2,3,4,4,6,12,12]. As a tie-breaker we use the LMFDB # ordering. sort_key = lambda lab: [all_data[lab]['faltings_height'], all_data[lab]['lmfdb_number']] class_size = record['class_size'] if class_size == 1: record['faltings_index'] = 0 record['faltings_ratio'] = 1 else: class_labels = [label[:-1]+str(k+1) for k in range(class_size)] class_labels.sort(key=sort_key) base_label = class_labels[0] base_record = all_data[base_label] area = base_record['area'] base_record['faltings_index'] = 0 base_record['faltings_ratio'] = 1 for i, lab in enumerate(class_labels): if i == 0: continue rec = all_data[lab] area_ratio = area/rec['area'] # real, should be an integer rec['faltings_index'] = i rec['faltings_ratio'] = area_ratio.round() FRout.write("{}: {}\n".format(label, [all_data[lab]['faltings_ratio'] for lab in class_labels])) else: record1 = all_data[label[:-1]+'1'] for col in ['analytic_rank', 'special_value', 'aplist', 'anlist', 'trace_hash']: record[col] = record1[col] # Analytic Sha sha_an = record['special_value']*record['torsion']**2 / (record['tamagawa_product']*record['regulator']*record['real_period']) sha = sha_an.round() assert sha > 0 assert sha.is_square() assert (sha-sha_an).abs() < 1e-10 record['sha_an'] = sha_an record['sha'] = int(sha) record['sha_primes'] = [int(p) for p in sha.prime_divisors()] FRout.close() return all_data ###################################################################### # # Output functions # ###################################################################### # # make one line def make_line(E, columns): """ Given a curve record E, return a string of the selected columns. """ return ' '.join([encode(E[col]) for col in columns]) ###################################################################### # # one-off function to read {allgens, alllabels, allisog} files for one # or more ranges, and write {curvedata, classdata} files for # the same ranges. def make_curvedata(base_dir=ECDATA_DIR, ranges=all_ranges, prec=DEFAULT_PRECISION): r"""Read all the data in files base_dir/<ft>/<ft>.<r> for ft in ['allgens', 'alllabels', 'allisog'] and r in ranges. Write files base_dir/<f>/<f>.<r> for the same r and for f in ['curvedata', 'classdata']. """ global PRECISION PRECISION = prec for r in ranges: print("Reading data for range {}".format(r)) all_data = read_old_data(base_dir=base_dir, ranges=[r]) # write out data for ft in ['curvedata', 'classdata']: cols = datafile_columns[ft] filename = os.path.join(base_dir, '{}/{}.{}'.format(ft, ft, r)) print("Writing data to {}".format(filename)) n = 0 with open(filename, 'w') as outfile: for _, record in all_data.items(): if ft == 'curvedata' or record['number'] == 1: line = make_line(record, cols) outfile.write(line +"\n") n += 1 print("{} lines written to {}".format(n, filename)) def read_data(base_dir=ECDATA_DIR, file_types=new_main_file_types, ranges=all_ranges, raw=True, resort=True): r"""Read all the data in files base_dir/<ft>/<ft>.<r> where ft is a file type and r is a range. Return a single dict with keys labels and values complete curve records. Resort permutes the rows/columns of the isogeny matrix to be indexed by LMFDB numbers. """ all_data = {} for r in ranges: for ft in file_types: if ft == 'growth': # special case below continue if ft == 'iwasawa' and r not in iwasawa_ranges + ['0-999']: continue data_filename = os.path.join(base_dir, '{}/{}.{}'.format(ft, ft, r)) print("Starting to read from {}".format(data_filename)) parser = parsers[ft] n = 0 with open(data_filename) as data: for L in data: label, record = parser(L, raw=raw) first = (ft == 'classdata') or (int(record['number']) == 1) if label: if first: n += 1 if label in all_data: all_data[label].update(record) else: all_data[label] = record if n%10000 == 0 and first: print("Read {} classes so far from {}".format(n, data_filename)) print("Finished reading {} classes from {}".format(n, data_filename)) if 'curvedata' in file_types and 'classdata' in file_types: print("filling in class_deg, class_size and trace_hash from class to curve") for label, record in all_data.items(): if int(record['number']) > 1: label1 = label[:-1]+'1' for col in ['class_deg', 'class_size', 'trace_hash']: record[col] = all_data[label1][col] if 'classdata' in file_types and resort: print("permuting isogeny matrices") for label, record in all_data.items(): n = int(record['class_size']) number = int(record['number']) if n <= 2 or number > 1: continue isomat = record['isogeny_matrix'] if raw: isomat = parse_int_list_list(isomat) clabel = label[:-1] def num2Lnum(i): return int(all_data[clabel+str(i)]['lmfdb_number']) # perm = lambda i: next(c for c in self.curves if c['number'] == i+1)['lmfdb_number']-1 # newmat = [[isomat[perm(i)][perm(j)] for i in range(n)] for j in range(n)] newmat = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): ri = num2Lnum(i+1)-1 for j in range(n): rj = num2Lnum(j+1)-1 newmat[ri][rj] = isomat[i][j] if raw: newmat = str(newmat).replace(' ', '') record['isogeny_matrix'] = newmat if 'growth' in file_types: print("reading growth data") growth_data = read_all_growth_data(ranges=ranges) for label, record in all_data.items(): if label in growth_data: record.update(growth_data[label]) return all_data def read_data_ext(base_dir=ECDATA_DIR, file_types=new_main_file_types, ranges=all_ranges, raw=True, resort=True): r"""Read all the data in files base_dir/curvedata/curvedata.<r>.ext and base_dir/classdata/classdata.<r> and r is a range. Return a single dict with keys labels and values complete curve records. Resort permutes the rows/columns of the isogeny matrix to be indexed by LMFDB numbers. """ all_data = {} for r in ranges: for ft in file_types: if ft == 'curvedata': data_filename = os.path.join(base_dir, '{}/{}.{}.ext'.format(ft, ft, r)) else: data_filename = os.path.join(base_dir, '{}/{}.{}'.format(ft, ft, r)) parser = parsers[ft] print("Starting to read from {}".format(data_filename)) n = 0 with open(data_filename) as data: for L in data: if ft == 'curvedata': label, record = parse_curvedata_line(L, raw=raw, ext=True) else: label, record = parser(L, raw=raw) first = (ft == 'classdata') or (int(record['number']) == 1) if label: if first: n += 1 if label in all_data: all_data[label].update(record) else: all_data[label] = record if n%10000 == 0 and first: print("Read {} classes so far from {}".format(n, data_filename)) print("Finished reading {} classes from {}".format(n, data_filename)) print("filling in iso, class_deg, and trace_hash from class to curve") for label, record in all_data.items(): if int(record['number']) > 1: label1 = label[:-1]+'1' for col in ['iso', 'class_deg', 'trace_hash']: record[col] = all_data[label1][col] if 'classdata' in file_types and resort: print("permuting isogeny matrices") for label, record in all_data.items(): n = int(record['class_size']) number = int(record['number']) if n <= 2 or number > 1: continue isomat = record['isogeny_matrix'] if raw: isomat = parse_int_list_list(isomat) clabel = label[:-1] def num2Lnum(i): return int(all_data[clabel+str(i)]['lmfdb_number']) # perm = lambda i: next(c for c in self.curves if c['number'] == i+1)['lmfdb_number']-1 # newmat = [[isomat[perm(i)][perm(j)] for i in range(n)] for j in range(n)] newmat = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): ri = num2Lnum(i+1)-1 for j in range(n): rj = num2Lnum(j+1)-1 newmat[ri][rj] = isomat[i][j] if raw: newmat = str(newmat).replace(' ', '') record['isogeny_matrix'] = newmat if 'growth' in file_types: print("reading growth data") growth_data = read_all_growth_data(ranges=ranges) for label, record in all_data.items(): if label in growth_data: record.update(growth_data[label]) return all_data ###################################################################### # # Function to output files which can be uploaded to the database using copy_from() or update_from_file() # # NB postgresql has various integer types of different *fixed* # bit-lengths, of which the largest is 'bigint' but even that is too # small for a 20-digit integer, so quite a few of the columns have to # use the 'numeric' type. The website code will cast to integers # where necessary. # # NB The LMFDB table ec_curvedata columns 'label', 'iso', 'number' # have been renamed 'Clabel', 'Ciso', 'Cnumber' and will only be # filled for conductor<500000 for which Cremona labels exist. Our # data files currently still have these fields as they are used to # create labels for data processing purposes. None of the other tables # have these columns (any more). schemas = {'ec_curvedata': {'Clabel': 'text', 'lmfdb_label': 'text', 'Ciso': 'text', 'lmfdb_iso': 'text', 'iso_nlabel': 'smallint', 'Cnumber': 'smallint', 'lmfdb_number': 'smallint', 'ainvs': 'numeric[]', 'jinv': 'numeric[]', 'conductor': 'integer', 'cm': 'smallint', 'isogeny_degrees': 'smallint[]', 'nonmax_primes': 'smallint[]', 'nonmax_rad': 'integer', 'bad_primes': 'integer[]', 'num_bad_primes': 'smallint', 'semistable': 'boolean', 'potential_good_reduction': 'boolean', 'optimality': 'smallint', 'manin_constant': 'smallint', 'num_int_pts': 'integer', 'torsion': 'smallint', 'torsion_structure': 'smallint[]', 'torsion_primes': 'smallint[]', 'rank': 'smallint', 'analytic_rank': 'smallint', 'sha': 'integer', 'sha_primes': 'smallint[]', 'regulator': 'numeric', 'signD': 'smallint', 'absD': 'numeric', 'degree': 'bigint', 'class_deg': 'smallint', 'class_size': 'smallint', 'min_quad_twist_ainvs': 'numeric[]', 'min_quad_twist_disc': 'smallint', 'faltings_height': 'numeric', 'stable_faltings_height': 'numeric', 'faltings_index': 'smallint', 'faltings_ratio': 'smallint'}, # local data: one row per (curve, bad prime) 'ec_localdata': {'lmfdb_label': 'text', 'conductor': 'integer', 'prime': 'integer', 'tamagawa_number': 'smallint', 'kodaira_symbol': 'smallint', 'reduction_type': 'smallint', 'root_number': 'smallint', 'conductor_valuation': 'smallint', 'discriminant_valuation': 'smallint', 'j_denominator_valuation': 'smallint'}, 'ec_mwbsd': {'lmfdb_label': 'text', 'conductor': 'integer', 'torsion_generators': 'numeric[]', 'xcoord_integral_points': 'numeric[]', 'special_value': 'numeric', 'real_period': 'numeric', 'area': 'numeric', 'tamagawa_product': 'integer', 'sha_an': 'numeric', 'rank_bounds': 'smallint[]', 'ngens': 'smallint', 'gens': 'numeric[]', 'heights': 'numeric[]'}, # class data: one row per isogeny class 'ec_classdata': {'lmfdb_iso': 'text', 'conductor': 'integer', 'trace_hash': 'bigint', 'class_size': 'smallint', 'class_deg': 'smallint', 'isogeny_matrix': 'smallint[]', 'aplist': 'smallint[]', 'anlist': 'smallint[]'}, 'ec_2adic': {'lmfdb_label': 'text', 'conductor': 'integer', 'twoadic_label': 'text', 'twoadic_index': 'smallint', 'twoadic_log_level': 'smallint', 'twoadic_gens': 'smallint[]'}, # galrep data: one row per (curve, non-maximal prime) 'ec_galrep': {'lmfdb_label': 'text', 'conductor': 'integer', 'prime': 'smallint', 'image': 'text'}, # torsion growth data: one row per (curve, extension field) 'ec_torsion_growth': {'lmfdb_label': 'text', 'conductor': 'integer', 'degree': 'smallint', 'field': 'numeric[]', 'torsion': 'smallint[]'}, 'ec_iwasawa': {'lmfdb_label': 'text', 'conductor': 'integer', 'iwdata': 'jsonb', 'iwp0': 'smallint'} } ###################################################################### Qtype = type(QQ(1)) def postgres_encode(col, coltype): """ Encoding of column data into a string for output to an upload file. NB A list stored in the database as a postgres array (e.g. int[] or numeric[]) must appear as (e.g.) {1,2,3} not [1,2,3]. """ if col is None or col == "?": return "\\N" if coltype == "boolean": return "t" if col else "f" if isinstance(col, Qtype): # to handle the j-invariant col = [col.numer(), col.denom()] scol = str(col).replace(" ", "") if coltype == 'jsonb': scol = scol.replace("'", '"') if '[]' in coltype: scol = scol.replace("[", "{").replace("]", "}") return scol def table_cols(table, include_id=False): """ Get the list of column names for a table, sorted for consistency, with 'label' (or 'iso' for the classdata table) moved to the front, and 'id' at the very front if wanted. """ if table == 'ec_galrep': return ['lmfdb_label', 'conductor', 'prime', 'image'] if table == 'ec_torsion_growth': return ['lmfdb_label', 'conductor', 'degree', 'field', 'torsion'] cols = sorted(list(schemas[table].keys())) # We want the first two columns to be 'id', 'lmfdb_label' or 'id', 'lmfdb_iso' if present if table == 'ec_classdata': cols.remove('lmfdb_iso') cols = ['lmfdb_iso'] + cols else: cols.remove('lmfdb_label') cols = ['lmfdb_label'] + cols if 'id' in cols: cols.remove('id') if include_id: cols = ['id'] + cols return cols def data_to_string(table, cols, record): """ table: a table name: one of schemas.keys() cols: list of columns to output record: a complete curve or class record """ schema = schemas[table] if 'id' in cols: schema['id'] = 'bigint' return "|".join([postgres_encode(record.get(col, None), schema[col]) for col in cols]) tables1 = ('ec_curvedata', 'ec_mwbsd', 'ec_2adic', 'ec_iwasawa') # tables with one row per curve tables2 = ('ec_classdata',) # table with one row per isogeny class tables3 = ('ec_localdata', # one row per bad prime 'ec_galrep', # one row per non-maximal prime 'ec_torsion_growth', # one row per extension degree ) all_tables = tables1 + tables2 + tables3 optional_tables = ('ec_iwasawa', 'ec_torsion_growth') main_tables = tuple(t for t in all_tables if t not in optional_tables) def make_table_upload_file(data, table, NN=None, include_id=True, columns=None): """This version works when there is one row per curve or one per class. The other cases are passed to special versions. If columns is None then all columns for the table will be output, otherwise only those in columns. This is for updating only some columns of a table. """ if not NN: NN = 'all' if table == 'ec_localdata': return make_localdata_upload_file(data, NN) if table == 'ec_galrep': return make_galrep_upload_file(data, NN) if table == 'ec_torsion_growth': return make_torsion_growth_upload_file(data, NN) include_id = include_id and (table == 'ec_curvedata') filename = os.path.join(UPLOAD_DIR, ".".join([table, NN])) allcurves = (table != 'ec_classdata') with open(filename, 'w') as outfile: print("Writing data for table {} to file {}".format(table, filename)) if not allcurves: print(" (only outputting one curve per isogeny class)") cols = table_cols(table, include_id) if columns: cols = [c for c in cols if c in columns] schema = schemas[table] if 'id' in cols: schema['id'] = 'bigint' # Write header lines: (1) column names; (2) column types; (3) blank outfile.write("|".join(cols) + "\n") outfile.write("|".join([schema[col] for col in cols]) + "\n\n") n = 1 for record in data.values(): if table == 'ec_iwasawa' and 'iwdata' not in record: continue if include_id: record['id'] = n if allcurves or int(record['number']) == 1: outfile.write(data_to_string(table, cols, record) +"\n") n += 1 if n%10000 == 0: print("{} lines written so far...".format(n)) n -= 1 print("{} lines written to {}".format(n, filename)) def make_localdata_upload_file(data, NN=None): """ This version is for ec_localdata only. For each curve we output n lines where n is the number of bad primes. """ if not NN: NN = 'all' table = 'ec_localdata' filename = os.path.join(UPLOAD_DIR, ".".join([table, NN])) with open(filename, 'w') as outfile: print("Writing data for table {} to file {}".format(table, filename)) cols = table_cols(table, include_id=False) schema = schemas[table] # Write header lines: (1) column names; (2) column types; (3) blank outfile.write("|".join(cols) + "\n") outfile.write("|".join([schema[col] for col in cols]) + "\n\n") n = 1 for record in data.values(): for i in range(int(record['num_bad_primes'])): # NB if the data is in raw form then we have 8 strongs # representing lists of ints, otherwise we actually # have 8 lists of ints, so we must paerse the strongs # in the first case. for ld in ['bad_primes', 'tamagawa_numbers', 'kodaira_symbols', 'reduction_types', 'root_numbers', 'conductor_valuations', 'discriminant_valuations', 'j_denominator_valuations']: if record[ld][0] == '[': record[ld] = parse_int_list(record[ld]) prime_record = {'label': record['label'], 'lmfdb_label': record['lmfdb_label'], 'conductor': record['conductor'], 'prime': record['bad_primes'][i], 'tamagawa_number': record['tamagawa_numbers'][i], 'kodaira_symbol': record['kodaira_symbols'][i], 'reduction_type': record['reduction_types'][i], 'root_number': record['root_numbers'][i], 'conductor_valuation': record['conductor_valuations'][i], 'discriminant_valuation': record['discriminant_valuations'][i], 'j_denominator_valuation': record['j_denominator_valuations'][i], } line = data_to_string(table, cols, prime_record) outfile.write(line +"\n") n += 1 if n%10000 == 0: print("{} lines written to {} so far...".format(n, filename)) n -= 1 print("{} lines written to {}".format(n, filename)) def make_galrep_upload_file(data, NN=None): """This version is for ec_galrep only. For each curve we output n lines where n is the number of nonmaximal primes, so if there are no non-maximal primes for a curve then there is no line output for that curve. """ if not NN: NN = 'all' table = 'ec_galrep' filename = os.path.join(UPLOAD_DIR, ".".join([table, NN])) with open(filename, 'w') as outfile: print("Writing data for table {} to file {}".format(table, filename)) cols = table_cols(table, include_id=False) schema = schemas[table] # Write header lines: (1) column names; (2) column types; (3) blank outfile.write("|".join(cols) + "\n") outfile.write("|".join([schema[col] for col in cols]) + "\n\n") n = 1 for record in data.values(): #print(record['nonmax_primes'], record['modp_images']) for p, im in zip(record['nonmax_primes'], record['modp_images']): prime_record = {'label': record['label'], 'lmfdb_label': record['lmfdb_label'], 'conductor': record['conductor'], 'prime': p, 'image': im, } outfile.write(data_to_string(table, cols, prime_record) +"\n") n += 1 if n%10000 == 0: print("{} lines written to {} so far...".format(n, filename)) n -= 1 print("{} lines written to {}".format(n, filename)) def make_torsion_growth_upload_file(data, NN=None): """This version is for ec_torsion_growth only. For each curve we output one line for each field (of degree<24 currently) in which the torsion grows. """ if not NN: NN = 'all' table = 'ec_torsion_growth' filename = os.path.join(UPLOAD_DIR, ".".join([table, NN])) with open(filename, 'w') as outfile: print("Writing data for table {} to file {}".format(table, filename)) cols = table_cols(table, include_id=False) schema = schemas[table] # Write header lines: (1) column names; (2) column types; (3) blank outfile.write("|".join(cols) + "\n") outfile.write("|".join([schema[col] for col in cols]) + "\n\n") n = 1 for record in data.values(): if 'torsion_growth' not in record: continue for degree, dat in record['torsion_growth'].items(): for field, torsion in dat: field_record = {'label': record['label'], 'lmfdb_label': record['lmfdb_label'], 'degree': degree, 'field': field, 'torsion': torsion, } outfile.write(data_to_string(table, cols, field_record) +"\n") n += 1 if n%10000 == 0: print("{} lines written to {} so far...".format(n, filename)) n -= 1 print("{} lines written to {}".format(n, filename)) def fix_labels(data, verbose=True): for record in data.values(): lmfdb_label = "".join([record['lmfdb_iso'], record['lmfdb_number']]) if lmfdb_label != record['lmfdb_label']: if verbose: print("changing {} to {}".format(record['lmfdb_label'], lmfdb_label)) record['lmfdb_label'] = lmfdb_label return data def fix_faltings_ratios(data, verbose=True): for label, record in data.items(): if label[-1] == '1': Fratio = '1' if record['faltings_ratio'] != Fratio: if verbose: print("{}: changing F-ratio from {} to {}".format(label, record['faltings_ratio'], Fratio)) record['faltings_ratio'] = Fratio else: label1 = label[:-1]+"1" record1 = data[label1] Fratio = (RR(record1['area'])/RR(record['area'])).round() assert Fratio <= 163 Fratio = str(Fratio) if Fratio != record['faltings_ratio']: if verbose: print("{}: changing F-ratio from {} to {}".format(label, record['faltings_ratio'], Fratio)) record['faltings_ratio'] = str(Fratio) return data def make_all_upload_files(data, tables=all_tables, NN=None, include_id=False): for table in tables: make_table_upload_file(data, table, NN=NN, include_id=include_id) def write_curvedata(data, r, base_dir=MATSCHKE_DIR, suffix=""): r""" Write file base_dir/curvedata/curvedata.<r> (with an optional suffix) """ cols = datafile_columns['curvedata'] fn = f'curvedata.{r}.{suffix}' if suffix else f'curvedata.{r}' filename = os.path.join(base_dir, 'curvedata', fn) #print("Writing data to {}".format(filename)) n = 0 with open(filename, 'w') as outfile: for record in data.values(): line = make_line(record, cols) outfile.write(line +"\n") n += 1 print("{} lines written to {}".format(n, filename)) # temporary function for writing extended curvedata files def write_curvedata_ext(data, r, base_dir=MATSCHKE_DIR): r""" Write file base_dir/curvedata/curvedata.<r>.ext """ cols = datafile_columns['curvedata_ext'] filename = os.path.join(base_dir, 'curvedata', 'curvedata.{}.ext'.format(r)) print("Writing data to {}".format(filename)) # print("--old columns were") # print(datafile_columns['curvedata']) # print("--new columns are") # print(cols) n = 0 with open(filename, 'w') as outfile: for record in data.values(): if 'degree' not in record or record['degree'] == 0: record['degree'] = None line = make_line(record, cols) outfile.write(line +"\n") n += 1 if n%10000 == 0: print("... {} lines written to {} so far".format(n, filename)) print("{} lines written to {}".format(n, filename)) def write_classdata(data, r, base_dir=MATSCHKE_DIR): r""" Write file base_dir/classdata/classdata.<r> """ cols = datafile_columns['classdata'] filename = os.path.join(base_dir, 'classdata', 'classdata.{}'.format(r)) #print("Writing data to {}".format(filename)) n = 0 with open(filename, 'w') as outfile: for record in data.values(): if int(record['number']) == 1: line = make_line(record, cols) outfile.write(line +"\n") n += 1 print("{} lines written to {}".format(n, filename)) def write_intpts(data, r, base_dir=MATSCHKE_DIR): r""" Write file base_dir/intpts/intpts.<r> """ cols = ['label', 'ainvs', 'xcoord_integral_points'] filename = os.path.join(base_dir, 'intpts', 'intpts.{}'.format(r)) #print("Writing data to {}".format(filename)) n = 0 with open(filename, 'w') as outfile: for record in data.values(): line = make_line(record, cols) outfile.write(line +"\n") n += 1 print("{} lines written to {}".format(n, filename)) def write_degphi(data, r, base_dir=MATSCHKE_DIR): r""" Write file base_dir/alldegphi/alldegphi.<r> """ cols = ['conductor', 'isoclass', 'number', 'ainvs', 'degree'] filename = os.path.join(base_dir, 'alldegphi', 'alldegphi.{}'.format(r)) #print("Writing data to {}".format(filename)) n = 0 with open(filename, 'w') as outfile: for record in data.values(): if record['degree']: line = make_line(record, cols) outfile.write(line +"\n") n += 1 print("{} lines written to {}".format(n, filename)) def write_datafiles(data, r, base_dir=MATSCHKE_DIR): r"""Write file base_dir/<ft>/<ft>.<r> for ft in ['curvedata', 'classdata', 'intpts', 'alldegphi'] """ for writer in [write_curvedata, write_classdata, write_intpts, write_degphi]: writer(data, r, base_dir) # Read allgens file (with torsion) and output paricurves file # def make_paricurves(infilename, mode='w', prefix="t"): infile = open(infilename) _, suf = infilename.split(".") paricurvesfile = open(prefix+"paricurves."+suf, mode=mode) for L in infile.readlines(): N, cl, num, ainvs, r, gens = L.split(' ', 5) if int(r) == 0: gens = "[]" else: gens = gens.split()[1:1+int(r)] # ignore torsion struct and gens gens = "[{}]".format(",".join([proj_to_aff(P) for P in gens])) label = '"{}"'.format(''.join([N, cl, num])) line = '[{}]'.format(', '.join([label, ainvs, gens])) paricurvesfile.write(line+'\n') infile.close() paricurvesfile.close() ################################################################################ # old functions before major ecdb rewrite # Create alldegphi files from allcurves files: def make_alldegphi(infilename, mode='w', verbose=False, prefix="t"): infile = open(infilename) _, suf = infilename.split(".") alldegphifile = open(prefix+"alldegphi."+suf, mode=mode) for L in infile.readlines(): N, cl, num, ainvs, _ = L.split(' ', 4) label = "".join([N, cl, num]) E = EllipticCurve(parse_int_list(ainvs)) degphi = get_modular_degree(E, label) line = ' '.join([str(N), cl, str(num), shortstr(E), liststr(degphi)]) alldegphifile.write(line+'\n') if verbose: print("alldegphifile: {}".format(line)) infile.close() alldegphifile.close() def put_allcurves_line(outfile, N, cl, num, ainvs, r, t): line = ' '.join([str(N), cl, str(num), str(ainvs).replace(' ', ''), str(r), str(t)]) outfile.write(line+'\n') def make_allcurves_lines(outfile, code, ainvs, r): E = EllipticCurve(ainvs) N, cl, _ = parse_cremona_label(code) for i, F in enumerate(E.isogeny_class().curves): put_allcurves_line(outfile, N, cl, str(i+1), list(F.ainvs()), r, F.torsion_order()) outfile.flush() def process_curve_file(infilename, outfilename, use): infile = open(infilename) outfile = open(outfilename, mode='a') for L in infile.readlines(): N, iso, num, ainvs, r, tor, _ = L.split() code = N+iso+num N = int(N) num = int(num) r = int(r) tor = int(tor) ainvs = parse_int_list(ainvs) use(outfile, code, ainvs, r, tor) infile.close() outfile.close() def make_allgens_line(E): tgens = parse_int_list_list(E['torsion_generators']) gens = parse_int_list_list(E['gens']) parts = [" ".join([encode(E[col]) for col in ['conductor', 'isoclass', 'number', 'ainvs', 'ngens', 'torsion_structure']]), " ".join([encode(weighted_proj_to_proj(P)) for P in gens]), " ".join([encode(weighted_proj_to_proj(P)) for P in tgens])] return " ".join(parts) def write_allgens_file(data, BASE_DIR, r): r""" Output an allgens file. Used, for example, to run our C++ saturation-checking program on the data. """ allgensfilename = os.path.join(BASE_DIR, 'allgens', 'allgens.{}'.format(r)) n = 0 with open(allgensfilename, 'w') as outfile: for record in data.values(): n += 1 outfile.write(make_allgens_line(record) + "\n") print("{} line written to {}".format(n, allgensfilename)) def make_allgens_file(BASE_DIR, r): data = read_data(BASE_DIR, ['curvedata'], [r]) write_allgens_file(data, BASE_DIR, r) # one-off to add 'absD' and 'stable_faltings_height' def c4c6D(ainvs): (a1, a2, a3, a4, a6) = ainvs (b2, b4, b6, b8) = (a1*a1 + 4*a2, a1*a3 + 2*a4, a3**2 + 4*a6, a1**2 * a6 + 4*a2*a6 - a1*a3*a4 + a2*a3**2 - a4**2) (c4, c6) = (b2**2 - 24*b4, -b2**3 + 36*b2*b4 - 216*b6) D = -b2**2*b8 - 8*b4**3 - 27*b6**2 + 9*b2*b4*b6 return (c4, c6, D) def add_extra_data(record, prec=128): # We avoid constructing the elliptic curve as that is very much slower (c4, _, D) = c4c6D(parse_int_list(record['ainvs'])) record['absD'] = ZZ(D).abs() if gcd(D, c4) == 1: record['stable_faltings_height'] = record['faltings_height'] else: R = RealField(prec) g = gcd(D, c4**3) record['stable_faltings_height'] = R(record['faltings_height']) - R(g).log()/12 return record
67,026
38.684429
217
py
ecdata
ecdata-master/scripts/trace_hash.py
# file copied from lmfdb codebase (lmfdb/lmfdb/utils/trace_hash.py) # Sage translation of the Magma function TraceHash(), just for elliptic curves /Q and /NF from sage.all import GF, ZZ, QQ, pari, prime_range TH_C = [326490430436040986,559705121321738418,1027143540648291608,1614463795034667624,455689193399227776, 812966537786397194,2073755909783565705,1309198521558998535,486216762465058766,1847926951704044964, 2093254198748441889,566490051061970630,150232564538834691,1356728749119613735,987635478950895264, 1799657824218406718,1921416341351658148,1827423174086145070,1750068052304413179,1335382038239683171, 1126485543032891129,2189612557070775619,1588425437950725921,1906114970148501816,1748768066189739575, 1105553649419536683,41823880976068680,2246893936121305098,680675478232219153,1096492737570930588, 1064058600983463886,2124681778445686677,1153253523204927664,1624949962307564146,884760591894578064, 722684359584774534,469294503455959899,1078657853083538250,497558833647780143,430880240537243608, 1008306263808672160,871262219757043849,1895004365215350114,553114791335573273,928282405904509326, 1298199971472090520,1361509731647030069,426420832006230709,750020119738494463,892950654076632414, 1225464410814600612,1911848480297925904,842847261377168671,836690411740782547,36595684701041066, 57074465600036538,35391454785304773,1027606372000412697,858149375821293895,1216392374703443454, 59308853655414224,1030486962058546718,382910609159726501,768789926722341438,762735381378628682, 1005758989771948074,1657009501638647508,1783661361016004740,796798233969021059,1658520847567437422, 502975179223457818,2063998821801160708,2126598223478603304,817551008849328795,1793074162393397615, 1287596263315727892,1629305847068896729,2282065591485919335,1280388906297308209,173159035165825250, 1203194438340773505,2146825320332825798,847076010454532974,2132606604399767971,865350797130078274, 421223214903942949,2202859852828864983,1627572340776304831,1301036100621122535,2151172683210770621, 555918022010940381,1195820575245311406,2060813966122583132,824196499832939747,1252314214858834971, 380498114208176064,621869463771460120,1487674193901485781,1569074147090699661,1723498454689514459, 1489838779667276265,607626788325788389,93543108859195056,1874271115035734974,1456016012787031897, 619764822731213939,1812449603590865741,808484663842074461,2009697952400734786,1525933978789885248, 343887624789001682,1182376379945660137,1982314473921546769,1109549848371395693,1037594154159590924, 1071053104849367160,1322181949714913233,1516660949039528341,960526604699918173,1729904691101240134, 261117919934717464,2271784899875479358,756802274277310875,1289220444092802136,474369139841197116, 1716815258254385285,103716246685267192,543779117105835462,1645057139707767457,895800586311529398, 1255427590538696616,152478208398822237,59235267842928844,1502771737122401274,1149578551939377903, 1470772656511184950,1546086255370076952,1723497785943073942,778240149963762596,240870114509877266, 394305328258085500,2102620516550230799,1039820873553197464,979798654654721830,880027557663442629, 1676981816531131145,1802107305139241263,1972433293052973713,2107405063590590043,1798917982073452520, 1369268024301602286,867033797562981667,1038357135783187942,758476292223849603,1948092882600628075, 2207529277533454374,1821419918118374849,1231889908299259230,566310110224392380,1609356725483962542, 280378617804444931,1072662998681271815,116308709127642766,1193169610307430309,866966243748392804, 166237193327216135,1077013023941018041,404884253921467160,786088301434511589,1383535122407493085, 2280658829488325172,101154688442168806,186007322364504054,132651484623670765,2214024743056683473, 2082072212962344576,1527055902872993253,914904768868572390,828477094595207304,1020679050708770534, 482636846586846145,1930865547754160712,1593671129282272719,1493198467868909485,729902645271416500, 275540268357558312,164114802119030362,788447619988896953,1762740703670330645,660855577878083177, 1651988416921493024,740652833177384429,1112201596451006206,415698847934834932,1211582319647132127, 1146510220721650373,1849436445614060470,2087092872652683432,2118502348483502728,1356524772912098481, 1199384942357517449,172551026757446140,578031956729941707,523340081847222890,1076777027268874489, 504399020033657060,1278551106709414382,2159465951497451565,1178157191616537256,204263226455195995, 1056341819781968292,183521353142147658,2188450004032853736,815413180157425263,1872285744226329343, 959184959959358956,473007083155872003,655761716995053547,1131460430873190185,2139124645518872072, 511733859594496686,15198510254334311,1224323599606986326,717867206610437778,2091512354759023324, 372342232752868676,1361511712413436237,1389190973283340505,394349220142131124,2079377585202309849, 353365880305796299,2032166139485738617,1890917131797951728,242865361432353437,1418792507475867019, 2119099350463010017,1014188227490285243,479492624224518275,1303029569429482669,517247294593876834, 1554557044656123283,750281115903727536,2167122262389919937,760554688782332821,2023636030598854916, 1790146557619247357,386163722563943194,1515274606763521578,2204179368292080266,964158696771121369, 303439105863023359,8182230548124380,1750434984088519049,1725590414598766182,1265114980378421064, 1015227773830014864,229929992560423398,764214183816115409,538352539450824188,1941773060895353999, 1068434172733967371,1355790773646160387,459324502245141234,609129328626229402,1241119177010491262, 1783576433920437207,1523680846139002895,882824005398680507,413096479776864968,522865969927243974, 1858351603281690756,1968585526421383793,2178118415854385403,2071714574011626742,2075065799199309684, 2276241901353008033,303400925906664587,1426227202230524239,1930606302598963877,249953308414640146, 611228839507773914,1672745442514341102,467604306000306674,1474554813214382459,1601661712875312382, 614840167992924737,1228071177654928913,527816710270111610,2217787042387174521,639805394326521740, 222549283662427192,1360905187147121266,2218130040969485290,1295851844663939225,563784543912533038, 1995338666855533310,1570565903061390324,1421390998286027062,1394318358097125191,1259069656723159936, 782274544912671248,727119931274242152,461373271832281770,431218333850664873,1192819027123234430, 2078764559709872649,185598300798682005,753027393642717163,39457098005678485,1334017905593361063, 2208208003949042369,995759906937041788,1045940157364976040,194824647782216037,550631184874398695, 1360200364068800381,1357865448826768161,1831861326200370539,942093021910086667,1640270910790040055, 186615109286328085,1330440696074470319,499018273810238035,502274974614414055,1207335215870481547, 2013999866627689866,1419916425046140717,191559056573160841,1328802988676857752,1405960078185023606, 227507798797399340,1637526486952132401,1076968863810265335,944510191997220613,1301386330701215932, 285779824044017183,1429750858521890899,1618865668058420542,841779507635076338,2271885690336656780, 1950830875641497149,2020789551919109899,975546679421148460,1197104163269028491,1270315990156796392, 748604252817308486,816129261753596233,384118410847738091,2113266006559319391,1338854039375748358, 1361143499198430117,633423014922436774,1290791779633361737,81273616335831288,734007502359373790, 1803343551649794557,178160046107106100,1669700173018758407,1829836142710185153,1253431308749847288, 70019619094993502,939065521645602191,571602252457140250,26887212485499413,984459396949257361, 852773633209386873,2289526104158020696,756333221468239349,478223842701987702,2004947225028724200, 526770890233938212,1661268713623636486,1595033927594418161,1532663022957125952,364955822302609296, 603258635519191127,371859597962583054,94282227629658712,2160611809915747887,27000232625437140, 22687777651226933,734430233276692626,1127699960534747774,346857527391478939,399588948728484631, 1369575405845760568,2217803687757289581,2206814713288610370,130141496340768529,861110681132541840, 230850531138610791,1780590839341524422,1923534983071749673,1055631719355441015,1222514615506258219, 937915311769343786,852868812961957254,718656592041199719,2250542267067365785,2169537354592688250, 1568074419444165342,853778925104674827,105031681250262217,1204393036537417656,592755100672600484, 1509207668054427766,1409630039748867615,433329873945170157,168130078420452894,701434349299435396, 1736119639406860361,1801042332324036889,82826810621030003,581092394588713697,1513323039712657034, 2086339870071049553,512802587457892537,1294754943443095033,1486581673100914879,930909063370627411, 2280060915913643774,219424962331973086,118156503193461485,743557822870685069,1997655344719642813, 393161419260218815,1086985962035808335,2119375969747368461,1650489163325525904,1967094695603069467, 916149623124228391,1122737829960120900,144869810337397940,2261458899736343261,1226838560319847571, 897743852062682980,45750188043851908,1858576614171946931,1568041120172266851,289541060457747472, 1539585379217609033,866887122666596526,6060188892447452,1707684831658632807,1062812350167057257, 887626467969935688,1968363468003847982,2169897168216456361,217716763626832970,413611451367326769, 336255814660537144,1464084696245397914,1902174501258288151,1440415903059217441,302153101507069755, 1558366710940453537,717776382684618355,1206381076465295510,1308718247292688437,555835170043458452, 1029518900794643490,1034197980057311552,131258234416495689,260799345029896943] TH_P = prime_range(2**12,2**13) TH_F = GF(2**61-1) def TraceHash_from_ap(aplist): r"""Return the trace hash of this list of ap, indexed by the primes in TH_P """ return ZZ(sum([TH_F(a*c) for a,c in zip(aplist,TH_C)])) TH_P_cache = {} def TraceHash(E): r"""Return the trace hash of this elliptic curve defined over either QQ or a number field. """ K = E.base_field() if K == QQ: E_pari = pari(E.a_invariants()).ellinit() return TraceHash_from_ap([E_pari.ellap(p) for p in TH_P]) if not K in TH_P_cache: TH_P_cache[K] = dict([(p,[P for P in K.primes_above(p) if P.norm()==p]) for p in TH_P]) def ap(p): return sum([E.reduction(P).trace_of_frobenius() for P in TH_P_cache[K][p]], 0) return TraceHash_from_ap([ap(p) for p in TH_P]) # Dictionary to hold the trace hashes of isogeny classes by label. We # store the trace hash for every curve but isogenous curves have the # same hash. (So do Galois conjugates, but we do not take advantage # of that). TH_dict = {} def TraceHashClass(iso, E): r"""Return the trace hash of this elliptic curve defined over either QQ or a number field, given also the label of its isogeny class. Hash values are cached. For curves over number fields the iso label should include the field label. """ global TH_dict if iso in TH_dict: return TH_dict[iso] else: th = TH_dict[iso] = TraceHash(E) return th
10,937
72.409396
105
py
Vecchia_GPR_var_select
Vecchia_GPR_var_select-master/code/func/reg_tree.py
import numpy as np from sklearn.tree import DecisionTreeRegressor def reg_tree_wrap(XTrn, yTrn, XTst, yTst, pIn): # dataTrn = np.genfromtxt(dataFn + "_train.csv", delimiter=",") # dataTst = np.genfromtxt(dataFn + "_test.csv", delimiter=",") # fkMatch = re.search(r'f([0-9]+)', dataFn) # if fkMatch: # dF = int(fkMatch.group(1)) # else: # dF = 0 nTrn = XTrn.shape[0] nOOS = nTrn - int(nTrn * pIn) yTrn = np.array(yTrn) yTst = np.array(yTst) np.random.seed(123) idxOOS = np.random.choice(nTrn, nOOS, replace=False) XOOS = XTrn[idxOOS, :] XTrn = np.delete(XTrn, idxOOS, axis=0) yOOS = yTrn[idxOOS] yTrn = np.delete(yTrn, idxOOS, axis=0) # nTrn = nTrn - nOOS depths = range(3, 20) OOSScores = [] idx = 0 for i in depths: regTree = DecisionTreeRegressor(max_depth=i, max_features=min(100, XTrn.shape[1]), random_state=123) regTree.fit(XTrn, yTrn) yOOSPred = regTree.predict(XOOS) OOSScores.append(np.sqrt(np.square(yOOSPred - yOOS).mean())) if idx > 0 and OOSScores[idx] > OOSScores[idx - 1] * 0.99: break else: regTreeBst: DecisionTreeRegressor = regTree idx = idx + 1 yTstPred = regTreeBst.predict(XTst) rmseScr = np.sqrt(np.square(yTst - yTstPred).mean() / np.var(yTst)) idxSel = (regTreeBst.feature_importances_ > 0).nonzero()[0] + 1 return dict({"idxSel": idxSel, "yTstPred": yTstPred, "rmseScr": rmseScr})
1,508
30.4375
108
py
Vecchia_GPR_var_select
Vecchia_GPR_var_select-master/code/func/SVGP.py
#!/usr/bin/env python import numpy as np import gpflow import tensorflow as tf from gpflow.ci_utils import ci_niter class Matern25_aniso(gpflow.kernels.AnisotropicStationary): def K_d(self, d): sqrt5 = np.sqrt(5.0) d = tf.square(d) d = tf.reduce_sum(d, -1) d = tf.sqrt(d) tf.debugging.check_numerics(d, message='Checking distance matrix\n') return self.variance * (1.0 + sqrt5 * d + 5.0 / 3.0 * tf.square(d)) * tf.exp(-sqrt5 * d) def run_adam(model, iterations, tensor_data): """ Utility function running the Adam optimizer :param model: GPflow model :param interations: number of iterations """ # Create an Adam Optimizer action logf = [] training_loss = model.training_loss_closure(tensor_data, compile=True) optimizer = tf.optimizers.Adam() @tf.function def optimization_step(): optimizer.minimize(training_loss, model.trainable_variables) for step in range(iterations): print(model.trainable_variables) sys.stdout.flush() optimization_step() if step % 10 == 0: elbo = -training_loss().numpy() logf.append(elbo) return logf def SVGP_wrap(locs, centers, thetaInit): tf.random.set_seed(123) n, d = locs.shape y = np.zeros((n, 1)) theta = np.array(thetaInit) r = np.sqrt(theta[1: d + 1]) l = 1 / r data = (locs, y) tensor_data = tuple(map(tf.convert_to_tensor, data)) kernel = Matern25_aniso(variance=theta[0], lengthscales=l) mdl = gpflow.models.SVGP(kernel, gpflow.likelihoods.Gaussian(), centers, num_data=n, mean_function=None) gpflow.set_trainable(mdl.kernel, False) gpflow.set_trainable(mdl.inducing_variable, True) maxiter = ci_niter(1000) run_adam(mdl, maxiter, tensor_data) return np.array(mdl.inducing_variable.Z.numpy())
1,958
30.095238
76
py