
SOURCE: sources/0138/repository/airfoil_generation/model/optimal_transport_functional_flow_model.py
  940  
  941      def __init__(
  942          self,
  943          config: EasyDict,
  944          model: nn.Module = None,
  945          prior: torch.Tensor = None,
  946      ):
  947          """
  948          Overview:
  949              Initialize the model.
  950          Arguments:
  951              - config (EasyDict): configuration for the model
  952              - model (nn.Module): intrinsic model
  953              - prior (torch.Tensor): prior
  954          """
  955          super().__init__()
  956  
  957          self.config = config
  958          self.device = config.device
  959          self.path = ConditionalProbabilityPath(config.path)
  960          self.model = IntrinsicModel(config.model.args) if model is None else model
  961  
  962          self.gaussian_process = get_gaussian_process(
  963              config.gaussian_process.type, **config.gaussian_process.args
  964          )
  965          self.stochastic_process = StochasticProcess(self.path, self.gaussian_process)
  966  
  967          if hasattr(config, "solver"):
  968              self.solver = get_solver(config.solver.type)(**config.solver.args)
  969  
  970          self.prior = nn.Parameter(prior)
  971  
  972      def get_type(self):
 1202      def sample_process_with_log_prob(
 1203          self,
 1204          n_dims: List[int] = None,
 1205          n_channels: int = None,
 1206          t_span: torch.Tensor = None,
 1207          batch_size: Union[torch.Size, int, Tuple[int], List[int]] = None,
 1208          x_0: torch.Tensor = None,
 1209          log_prob_x_0: torch.Tensor = None,
 1210          function_log_prob_x_0: Union[callable, nn.Module] = None,
 1211          condition: torch.Tensor = None,
 1212          with_grad: bool = True,
 1213          solver_config: EasyDict = None,
 1214          using_Hutchinson_trace_estimator: bool = True,
 1215      ):
 1216          """
 1217          Overview:
 1218              Sample from the model with log probability.
 1219          Arguments:
 1220              - t_span (torch.Tensor): time span to sample over
 1221              - x_0 (torch.Tensor): initial condition
 1222              - log_prob_x_0 (torch.Tensor): log probability of the initial condition
 1223              - function_log_prob_x_0 (Union[callable, nn.Module]): function to compute the log probability of the initial condition
 1224              - condition (torch.Tensor): condition
 1225              - with_grad (bool): whether to compute gradients
 1226              - solver_config (EasyDict): configuration for the solver
 1227              - using_Hutchinson_trace_estimator (bool): whether to use Hutchinson trace estimator
 1228          Returns:
 1229              - x1 (torch.Tensor): sampled data
 1230          """
 1231  
 1232          model_drift = lambda t, x: self.model(t, x, condition)
 1233          model_params = find_parameters(self)
 1234  
 1235          def compute_trace_of_jacobian_general(dx, x):
 1236              # if x is complex, change to real
 1237              if x.dtype == torch.complex64 or x.dtype == torch.complex128:
 1238                  x = x.real
 1239              # Assuming x has shape (B, D1, ..., Dn)
 1240              shape = x.shape[1:]  # get the shape of a single element in the batch
 1241              outputs = torch.zeros(
 1242                  x.shape[0], device=x.device, dtype=x.dtype
 1243              )  # trace for each batch
 1244              # Iterate through each index in the product of dimensions
 1245              for index in torch.cartesian_prod(*(torch.arange(s) for s in shape)):
 1246                  if len(index.shape) > 0:
 1247                      index = tuple(index)
 1248                  else:
 1249                      index = (index,)
 1250                  grad_outputs = torch.zeros_like(x)
 1251                  grad_outputs[(slice(None), *index)] = (
 1252                      1  # set one at the specific index across all batches
 1253                  )
 1254                  grads = torch.autograd.grad(
 1255                      outputs=dx, inputs=x, grad_outputs=grad_outputs, retain_graph=True
 1256                  )[0]
 1257                  outputs += grads[(slice(None), *index)]
 1258              return outputs
 1259  
 1260          def compute_trace_of_jacobian_by_Hutchinson_Skilling(dx, x, eps):
 1261              """Create the divergence function of `fn` using the Hutchinson-Skilling trace estimator."""
 1262  
 1263              fn_eps = torch.sum(dx * eps)
 1264              grad_fn_eps = torch.autograd.grad(fn_eps, x, create_graph=True)[0]
 1265              outputs = torch.sum(grad_fn_eps * eps, dim=tuple(range(1, len(x.shape))))
 1266              return outputs
 1267  
 1268          def composite_drift(t, x):
 1269              # where x is actually x0_and_diff_logp, (x0, diff_logp), which is a tuple containing x and logp_xt_minus_logp_x0
 1270              with torch.set_grad_enabled(True):
 1271                  t = t.detach()
 1272                  x_t = x[0].detach()
 1273                  logp_xt_minus_logp_x0 = x[1]
 1274  
 1275                  x_t.requires_grad = True
 1276                  t.requires_grad = True
 1277  
 1278                  dx = model_drift(t, x_t)
 1279                  if using_Hutchinson_trace_estimator:
 1280                      noise = torch.randn_like(x_t, device=x_t.device)
 1281                      logp_drift = -compute_trace_of_jacobian_by_Hutchinson_Skilling(
 1282                          dx, x_t, noise
 1283                      )
 1284                      # logp_drift = - divergence_approx(dx, x_t, noise)
 1285                  else:
 1286                      logp_drift = -compute_trace_of_jacobian_general(dx, x_t)
 1287  
 1288                  return dx, logp_drift
 1289  
 1290          if batch_size is None:
 1291              extra_batch_size = torch.tensor((1,), device=self.device)
 1292          elif isinstance(batch_size, int):
 1293              extra_batch_size = torch.tensor((batch_size,), device=self.device)
 1294          else:
 1295              if (
 1296                  isinstance(batch_size, torch.Size)
 1297                  or isinstance(batch_size, Tuple)
 1298                  or isinstance(batch_size, List)
 1299              ):
 1300                  extra_batch_size = torch.tensor(batch_size, device=self.device)
 1301              else:
 1302                  assert False, "Invalid batch size"
 1303  
 1304          if x_0 is not None and condition is not None:
 1305              assert (
 1306                  x_0.shape[0] == condition.shape[0]
 1307              ), "The batch size of x_0 and condition must be the same"
 1308              data_batch_size = x_0.shape[0]
 1309          elif x_0 is not None:
 1310              data_batch_size = x_0.shape[0]
 1311          elif condition is not None:
 1312              data_batch_size = condition.shape[0]
 1313          else:
 1314              data_batch_size = 1
 1315  
 1316          if x_0 is None:
 1317              x_0 = self.gaussian_process.sample_from_prior(
 1318                  dims=n_dims,
 1319                  n_samples=torch.prod(extra_batch_size) * data_batch_size,
 1320                  n_channels=n_channels,
 1321              )
 1322  
 1323          x0_and_diff_logp = (x_0, torch.zeros(x_0.shape[0], device=x_0.device))
 1324  
 1325          if t_span is None:
 1326              t_span = torch.linspace(0.0, 1.0, 1000).to(x.device)
 1327          else:
 1328              t_span = t_span.to(x_0.device)
 1329  
 1330          if solver_config is not None:
 1331              solver = get_solver(solver_config.type)(**solver_config.args)
 1332          else:
 1333              # solver = ODESolver(library="torchdiffeq_adjoint")
 1334              solver = ODESolver(library="torchdiffeq")
 1335  
 1336          if with_grad:
 1337              x1_and_logpx1 = solver.integrate(
 1338                  drift=composite_drift,
 1339                  x0=x0_and_diff_logp,
 1340                  t_span=t_span,
 1341                  # adjoint_params=model_params,
 1342              )
 1343          else:
 1344              # TODO: check if it is correct
 1345              with torch.no_grad():
 1346                  x1_and_logpx1 = solver.integrate(
 1347                      drift=composite_drift,
 1348                      x0=x0_and_diff_logp,
 1349                      t_span=t_span,
 1350                      # adjoint_params=model_params,
 1351                  )
 1352  
 1353          logp_x1_minus_logp_x0 = x1_and_logpx1[1]
 1354          x1 = x1_and_logpx1[0]
 1355  
 1356          if log_prob_x_0 is not None:
 1357              log_likelihood = log_prob_x_0 + logp_x1_minus_logp_x0
 1358          elif function_log_prob_x_0 is not None:
 1359              log_prob_x_0 = function_log_prob_x_0(x0)
 1360              log_likelihood = log_prob_x_0 + logp_x1_minus_logp_x0
 1361          elif x_0 is not None:
 1362              # TODO: check if it is correct
 1363  
 1364              log_prob_x_0 = self.gaussian_process.prior_likelihood(x_0)
 1365              log_likelihood = log_prob_x_0 + logp_x1_minus_logp_x0
 1366          else:
 1367              log_likelihood = torch.zeros_like(
 1368                  logp_x1_minus_logp_x0, device=logp_x1_minus_logp_x0.device
 1369              )
 1370  
 1371          return x1, log_likelihood, logp_x1_minus_logp_x0

SOURCE: sources/0138/repository/airfoil_generation/numerical_solvers/ode_solver.py
   23      def __init__(
   24          self,
   25          ode_solver="euler",
   26          dt=0.01,
   27          atol=1e-5,
   28          rtol=1e-5,
   29          library="torchdyn",
   30          **kwargs,
   31      ):
   32          """
   33          Overview:
   34              Initialize the ODE solver using torchdiffeq or torchdyn library.
   35          Arguments:
   36              ode_solver (:obj:`str`): The ODE solver to use.
   37              dt (:obj:`float`): The time step.
   38              atol (:obj:`float`): The absolute tolerance.
   39              rtol (:obj:`float`): The relative tolerance.
   40              library (:obj:`str`): The library to use for the ODE solver. Currently, it supports 'torchdiffeq' and 'torchdyn'.
   41              **kwargs: Additional arguments for the ODE solver.
   42          """
   43          self.ode_solver = ode_solver
   44          self.dt = dt
   45          self.atol = atol
   46          self.rtol = rtol
   47          self.nfe = 0
   48          self.kwargs = kwargs
   49          self.library = library
   69          self.nfe = 0
   70          if self.library == "torchdiffeq":
   71              return self.odeint_by_torchdiffeq(drift, x0, t_span)
   72          elif self.library == "torchdiffeq_adjoint":
   73              return self.odeint_by_torchdiffeq_adjoint(drift, x0, t_span, **kwargs)
   74          elif self.library == "torchdyn":
   75              return self.odeint_by_torchdyn(drift, x0, t_span)
   76          elif self.library == "torchdyn_NeuralODE":
   77              return self.odeint_by_torchdyn_NeuralODE(drift, x0, t_span)
   78          else:
   79              raise ValueError(f"library {self.library} is not supported")
   80  
   81      def odeint_by_torchdiffeq(self, drift, x0, t_span, **kwargs):
   82          if isinstance(x0, torch.Tensor):
   83  
   84              def forward_ode_drift_by_torchdiffeq(t, x):
   85                  self.nfe += 1
   86                  # broadcasting t to match the batch size of x
   87                  t = t.repeat(x.shape[0])
   88                  return drift(t, x)
   89  
   90              trajectory = torchdiffeq_odeint(
   91                  func=forward_ode_drift_by_torchdiffeq,
   92                  y0=x0,
   93                  t=t_span,
   94                  method=self.ode_solver,
   95                  atol=self.atol,
   96                  rtol=self.rtol,
   97                  **self.kwargs,
   98                  **kwargs,
   99              )
  100              return trajectory
  101  
  102          elif isinstance(x0, Tuple):
  103  
  104              def forward_ode_drift_by_torchdiffeq(t, x):
  105                  self.nfe += 1
  106                  # broadcasting t to match the batch size of x
  107                  t = t.repeat(x[0].shape[0])
  108                  return drift(t, x)
  109  
  110              trajectory = torchdiffeq_odeint(
  111                  func=forward_ode_drift_by_torchdiffeq,
  112                  y0=x0,
  113                  t=t_span,
  114                  method=self.ode_solver,
  115                  atol=self.atol,
  116                  rtol=self.rtol,
  117                  **self.kwargs,
  118                  **kwargs,
  119              )
  120              return trajectory

SOURCE: sources/0138/repository/examples/funcgenfoil/train_airfoil_editting_with_inverse_prior.py
  510  
  511      flow_model_for_regression = OptimalTransportFunctionalFlowForRegression(
  512          config=config.flow_model_regression,
  513          model=copy.deepcopy(flow_model.model),
  514          prior=torch.zeros(1, 1, config.flow_model.gaussian_process.args.dims[0]),
  515      ).to(device)
  516  
  517      for model_index in track(range(300)):
  518          model_index_inverse = 299 - model_index
  519  
  520          x_test = (
  521              dataset_for_edit[model_index_inverse]["gt"][:, 1]
  522              .unsqueeze(0)
  523              .unsqueeze(0)
  524              .to(device)
  525          )
  526          noise_pattern = (
  527              dataset_for_edit[model_index_inverse]["noise_pattern"]
  528              .unsqueeze(0)
  529              .to(device)
  530          )
  531          pos_mask = dataset_for_edit[model_index_inverse]["pos_mask"].to(device)
  532  
  533          inverse_prior = flow_model.inverse_sample(
  534              n_dims=config.flow_model.gaussian_process.args.dims,
  535              n_channels=1,
  536              t_span=torch.linspace(0.0, 1.0, 1000),
  537              x_0=(x_test - train_dataset.min.to(device)[1])
  538              / (train_dataset.max.to(device)[1] - train_dataset.min.to(device)[1])
  539              * 2
  540              - 1,
  541          )
  542  
  543          # deep copy the flow model for regression
  544          state_dict = flow_model.model.state_dict()
  545          state_dict.pop("_metadata", None)
  546          flow_model_for_regression.model.load_state_dict(state_dict)
  547          flow_model_for_regression.prior = inverse_prior
  548  
  549          optimizer = torch.optim.Adam(
  550              find_parameters(flow_model_for_regression),
  551              lr=config.parameter.learning_rate,
  552          )
  553  
  554          scheduler = CosineAnnealingWarmupLR(
  555              optimizer,
  630              flow_model_for_regression.train()
  631              with accelerator.autocast():
  632                  with accelerator.accumulate(flow_model_for_regression.model):
  633                      x_0_repeat = flow_model_for_regression.prior.repeat(32, 1, 1)
  634                      (
  635                          x_1_repeat,
  636                          logp_1_repeat,
  637                          logp_x1_minus_logp_x0,
  638                      ) = flow_model_for_regression.sample_with_log_prob(
  639                          t_span=t_span,
  640                          x_0=x_0_repeat,
  641                          using_Hutchinson_trace_estimator=True,
  642                      )
  643  
  644                      loss_1 = torch.mean(
  645                          0.5
  646                          * torch.sum(
  647                              (
  648                                  (
  649                                      x_partial_obs_with_noise_norm
  650                                      - x_1_repeat[:, -1, pos_mask]
  651                                  )
  652                                  ** 2
  653                              ),
  654                              dim=1,
  655                          )
  656                          / config.parameter.noise_level
  657                      )
  658                      loss_2 = -logp_1_repeat.mean()
  659  
  660                      loss = loss_1 + loss_2
  661  
  662                      optimizer.zero_grad()
  663                      accelerator.backward(loss)
  664                      if accelerator.sync_gradients:
  665                          accelerator.clip_grad_norm_(
  666                              find_parameters(flow_model_for_regression), max_norm=1.0
  667                          )
  668                      optimizer.step()
  669                      scheduler.step()

SOURCE: sources/0138/repository/examples/funcgenfoil/eval_airfoil_generation_super_resolution.py
  249  def calculate_smoothness(airfoil):
  250      smoothness = 0.0
  251      num_points = airfoil.shape[0]
  252  
  253      for i in range(num_points):
  254          p_idx = (i - 1) % num_points
  255          q_idx = (i + 1) % num_points
  256  
  257          p = airfoil[p_idx]
  258          q = airfoil[q_idx]
  259  
  260          if p[0] == q[0]:  # 处理垂直于x轴的线段
  261              distance = abs(airfoil[i, 0] - p[0])
  262          else:
  263              m = (q[1] - p[1]) / (q[0] - p[0])
  264              b = p[1] - m * p[0]
  265  
  266              distance = abs(m * airfoil[i, 0] - airfoil[i, 1] + b) / np.sqrt(m**2 + 1)
  267  
  268          smoothness += distance
  269  
  270      return smoothness
  271  
  272  
  273  def cal_diversity_score(data, subset_size=10, sample_times=10):
  274      # Average log determinant
  275      N = data.shape[0]
  276      data = data.reshape(N, -1)
  277      mean_logdet = 0
  278      for i in range(sample_times):
  279          ind = np.random.choice(N, size=subset_size, replace=False)
  280          subset = data[ind]
  281          D = squareform(pdist(subset, "euclidean"))
  282          S = np.exp(-0.5 * np.square(D))
  283          (sign, logdet) = np.linalg.slogdet(S)
  284          mean_logdet += logdet
  285      return mean_logdet / sample_times

SOURCE: sources/0138/repository/airfoil_generation/dataset/toy_dataset.py
    1  import torch
    2  import torch.nn as nn
    3  import torch.optim as optim
    4  import numpy as np
    5  
    6  from sklearn.gaussian_process.kernels import (
    7      Matern,
    8      RBF,
    9      WhiteKernel,
   10      ConstantKernel,
   11      RationalQuadratic,
   12  )
   13  
   14  
   15  def make_2d_grid(dims, x_min=0, x_max=1):
   90  def matern_kernel_cov(grids, length_scale, nu):
   91      """
   92      Overview:
   93          Create a Matern kernel covariance matrix for a given grid of points.
   94  
   95      Arguments:
   96          - grids (tensor): grid of points, for example, [n_points, 1 or 2]
   97          - length_scale (float): length scale of the kernel
   98          - nu (float): smoothness parameter of the kernel
   99      Returns:
  100          - kernel (tensor): Matern kernel covariance matrix
  101      """
  102  
  103      kernel = 1.0 * Matern(length_scale=length_scale, length_scale_bounds="fixed", nu=nu)
  104      return kernel(grids)
  105  
  106  
  107  def rbf_kernel_cov(grids, length_scale):
  108      """

OFFICIAL SUPPLEMENT: sources/0138/supplemental/examples/train_airfoil_editting.py
  252      flow_model = flow_model.to(device)
  253  
  254      mse_list = []
  255      smooth_list = []
  256  
  257      flow_model_for_regression = OptimalTransportFunctionalFlowForRegression(
  258          config=config.flow_model_regression,
  259          model=copy.deepcopy(flow_model.model),
  260          prior=torch.zeros(1, 1, config.flow_model.gaussian_process.args.dims[0]),
  261      ).to(device)
  262  
  263      for model_index in track(range(300)):
  264          model_index_inverse = 299 - model_index
  265  
  266          x_test = (
  267              dataset_for_edit[model_index_inverse]["gt"][:, 1]
  268              .unsqueeze(0)
  269              .unsqueeze(0)
  270              .to(device)
  271          )
  272          noise_pattern = (
  273              dataset_for_edit[model_index_inverse]["noise_pattern"]
  274              .unsqueeze(0)
  275              .to(device)
  276          )
  277          pos_mask = dataset_for_edit[model_index_inverse]["pos_mask"].to(device)
  278  
  279          # deep copy the flow model for regression
  280          state_dict = flow_model.model.state_dict()
  281          state_dict.pop("_metadata", None)
  282          flow_model_for_regression.model.load_state_dict(state_dict)
  283  
  284          optimizer = torch.optim.Adam(
  285              find_parameters(flow_model_for_regression),
  286              lr=config.parameter.learning_rate,
  287          )
  288  
  289          scheduler = CosineAnnealingWarmupLR(
  290              optimizer,
  291              T_max=config.parameter.iterations,
  292              eta_min=2e-6,
  293              warmup_steps=config.parameter.warmup_steps,
  294          )
  295  
  296          x_range = torch.linspace(0, 1, config.flow_model.gaussian_process.args.dims[0])
  297  
  298          x_pos_mask = x_range[pos_mask.cpu()]
  299  
  300          x_partial_obs = x_test[-1, :, pos_mask].to(device)
  301  
  302          x_partial_obs_with_noise = x_partial_obs + noise_pattern[
  303              :, pos_mask
  304          ] * torch.sqrt(torch.tensor(edit_scale, device=device))
  305  
  306          t_span = torch.linspace(0.0, 1.0, 10).to(device)
  307          x_partial_obs_norm = (x_partial_obs - train_dataset.min.to(device)[1]) / (
  308              train_dataset.max.to(device)[1] - train_dataset.min.to(device)[1]
  309          ) * 2 - 1
  310          x_partial_obs_with_noise_norm = (
  311              x_partial_obs_with_noise - train_dataset.min.to(device)[1]
  312          ) / (train_dataset.max.to(device)[1] - train_dataset.min.to(device)[1]) * 2 - 1
  313  
  314          xs = (torch.cos(torch.linspace(0, 2 * torch.pi, 257)) + 1) / 2
  315          xs = xs.to(device)
  316  
  317          mp_list = []
  318  
  319          for iteration in range(config.parameter.iterations):
  320  
  321              flow_model_for_regression.train()
  322              with accelerator.autocast():
  323                  with accelerator.accumulate(flow_model_for_regression.model):
  324                      x_0_repeat = flow_model_for_regression.prior.repeat(32, 1, 1)
  325                      (
  326                          x_1_repeat,
  327                          logp_1_repeat,
  328                          logp_x1_minus_logp_x0,
  329                      ) = flow_model_for_regression.sample_with_log_prob(
  330                          t_span=t_span,
  331                          x_0=x_0_repeat,
  332                          using_Hutchinson_trace_estimator=True,
  333                      )
  334  
  335                      loss_1 = torch.mean(
  336                          0.5
  337                          * torch.sum(
  338                              (
  339                                  (
  340                                      x_partial_obs_with_noise_norm
  341                                      - x_1_repeat[:, -1, pos_mask]
  342                                  )
  343                                  ** 2
  344                              ),
  345                              dim=1,
  346                          )
  347                          / config.parameter.noise_level
  348                      )
  349                      loss_2 = -logp_1_repeat.mean()
  350  
  351                      loss = loss_1 + loss_2
  352  
  353                      optimizer.zero_grad()
  354                      accelerator.backward(loss)
  355                      if accelerator.sync_gradients:
  356                          accelerator.clip_grad_norm_(
  357                              find_parameters(flow_model_for_regression), max_norm=1.0
  358                          )
  359                      optimizer.step()
  360                      scheduler.step()
