def run_once(): model = DiffusionModel(n, m, ep, p, q) search_tree = {} nsim_total = 0 while not model.has_stabilized(): best_target, nsim = search(model, search_tree) model.step(best_target) nsim_total += nsim return model.get_value(), nsim_total
def optimize(): log_dir = opt.logging_root cond_mkdir(log_dir) summaries_dir = os.path.join(log_dir, opt.experiment_name) cond_mkdir(summaries_dir) m = DiffusionModel(us_init=opt.us_init, ua_init=opt.ua_init, n_init=opt.n_init) m.to(device) optim = torch.optim.Adam(m.parameters(), lr=opt.lr, amsgrad=True) writer = SummaryWriter(summaries_dir) converged = False converged_eps = opt.convergence prev_loss = 1e6 for ii in range(opt.num_iters): loss, model, data = objective(m) optim.zero_grad() # write summary writer.add_scalar('mse', loss, ii) if not ii % opt.steps_til_summary: write_summary(writer, m, loss, model, data, ii) print(f'{ii}: {loss.detach().cpu().numpy():03f}') loss.backward() optim.step() # values should be non-negative def clamp_nonnegative(m): m.ua.data = torch.clamp(m.ua.data, min=0) m.us.data = torch.clamp(m.us.data, min=0) m.apply(clamp_nonnegative) if torch.abs(loss - prev_loss) < converged_eps: converged = True break prev_loss = loss.clone() out = { 'us': m.us.detach().cpu().numpy().squeeze().item() * m.us_scale, 'ua': m.ua.detach().cpu().numpy().squeeze().item(), 't0': m.t0.detach().cpu().numpy().squeeze(), 'us_init': opt.us_init, 'ua_init': opt.ua_init, 'n_init': opt.n_init, 'mse': loss.detach().cpu().numpy().squeeze().item(), 'iters': ii, 'converged': converged, 'converged_eps': converged_eps } np.save(os.path.join(summaries_dir, 'out.npy'), out)
def run_once(): model = DiffusionModel(n, m, ep, p, q) while not model.has_stabilized(): observed_infected, resistant = model.get_observed_infected(), model.get_resistant() if model.has_stabilized(observed_infected, resistant): # Observed model has stabilized; take no action for one round target = None else: if strategy == 1: target = random.choice(tuple(observed_infected)) elif strategy == 2: target = get_best_target(model, observed_infected, resistant) else: target = random.choice(tuple(set(range(n)).difference(resistant))) model.step(target) return model.get_value()
def objective(m: DiffusionModel): # get predicted diffusion model model = [] for idx, thickness in enumerate(m.thicknesses): d = 0.0254 * thickness model.append(m.forward(d, m.ua, m.us, m.t0[idx])) model = torch.cat(model, dim=0) # convolve model with measured impulse response model = F.conv1d(model, m.laser, padding=(m.laser.shape[-1])) max_vals, _ = torch.max(model, dim=2, keepdim=True) model = model / max_vals # get data data = m.data.clone() # calculate error mse = torch.sum((model - data)**2) return mse, model, data