def evaluate(): """Run Eval once. """ with tf.Session() as sess: # Make image placeholder input_dims = FLAGS.nr_boundary_params input_vector, true_boundary = flow_net.inputs_boundary( input_dims, batch_size=FLAGS.batch_size, shape=shape) # Build a Graph that computes the logits predictions from the predicted_boundary = flow_net.inference_boundary(FLAGS.batch_size, FLAGS.dims * [FLAGS.obj_size], input_vector, full_shape=shape) # Restore for eval init = tf.global_variables_initializer() sess.run(init) graph_def = tf.get_default_graph().as_graph_def(add_shapes=True) # make one input and run on it again and again #input_batch, boundary_batch = flow_net.feed_dict_boundary(input_dims, FLAGS.batch_size, shape) sess.run( predicted_boundary, feed_dict={input_vector: np.zeros((FLAGS.batch_size, input_dims))}) t = time.time() for i in tqdm(xrange(run_steps)): sess.run(predicted_boundary, feed_dict={ input_vector: np.zeros((FLAGS.batch_size, input_dims)) }) elapsed = time.time() - t filename = "./figs/boundary_network_shape_" + FLAGS.shape + "_batch_size_" + str( FLAGS.batch_size) + ".txt" with open(filename, "w") as f: f.write(str(elapsed / float(FLAGS.batch_size * run_steps)))
def evaluate(): """Run Eval once. """ with tf.Session() as sess: # Make image placeholder param_inputs, _ = flow_net.inputs_boundary(FLAGS.nr_boundary_params, 1, shape) # Make boundary boundary = flow_net.inference_boundary(1, FLAGS.dims*[FLAGS.obj_size], param_inputs, full_shape=shape) boundary = tf.round(boundary) # inference model. predicted_flow = flow_net.inference_network(boundary) # init graph init = tf.global_variables_initializer() sess.run(init) # Restore variables variables_to_restore = tf.all_variables() variables_to_restore_boundary = [variable for i, variable in enumerate(variables_to_restore) if "boundary_network" in variable.name[:variable.name.index(':')]] variables_to_restore_flow = [variable for i, variable in enumerate(variables_to_restore) if "flow_network" in variable.name[:variable.name.index(':')]] saver_boundary = tf.train.Saver(variables_to_restore_boundary) saver_flow = tf.train.Saver(variables_to_restore_flow) ckpt_boundary = tf.train.get_checkpoint_state(BOUNDARY_DIR) ckpt_flow = tf.train.get_checkpoint_state(FLOW_DIR) saver_boundary.restore(sess, ckpt_boundary.model_checkpoint_path) saver_flow.restore(sess, ckpt_flow.model_checkpoint_path) global_step = 1 # make graph def graph_def = tf.get_default_graph().as_graph_def(add_shapes=True) for i in xrange(10): # random params rand_param = np.expand_dims(get_random_params(FLAGS.nr_boundary_params, 3), axis=0) rand_param[:,0] = 0 rand_param[:,1] = 0 rand_param[:,2] = 0.5 rand_param[:,3] = 1.0 rand_param = np.load("figs/3d_wing_params_op.npy") rand_param = np.expand_dims(rand_param, axis=0) # calc flow p_flow, p_boundary = sess.run([predicted_flow, boundary],feed_dict={param_inputs: rand_param}) p_flow = p_flow * ((-p_boundary) + 1.0) dim=3 # plt boundary #plt.imshow(p_boundary[0,:,:,72,0]) #plt.show() # save vtk file of it image_vtk = tvtk.ImageData(spacing=(1, 1, 1), origin=(0, 0, 0)) image_vtk.point_data.vectors = p_flow[0,:,:,:,0:3].reshape([shape[0]*shape[1]*shape[2], 3]) image_vtk.point_data.scalars = p_flow[0,:,:,:,3].reshape([shape[0]*shape[1]*shape[2]]) image_vtk.point_data.scalars.name = "pressure" image_vtk.dimensions = shape write_data(image_vtk, "figs/vtk_flow_wing_3d") image_vtk = tvtk.ImageData(spacing=(1, 1, 1), origin=(0, 0, 0)) image_vtk.point_data.scalars = p_boundary[0,:,:,:,0].reshape([shape[0]*shape[1]*shape[2]]) image_vtk.point_data.scalars.name = "boundary" image_vtk.dimensions = shape write_data(image_vtk, "figs/vtk_boundary_wing_3d")
def evaluate(): """Run Eval once. Args: saver: Saver. summary_writer: Summary writer. top_k_op: Top K op. summary_op: Summary op. """ with tf.Graph().as_default(): # Make image placeholder inputs_vector, true_boundary = flow_net.inputs_boundary( FLAGS.nr_boundary_params, batch_size, shape) # Build a Graph that computes the logits predictions from the # inference model. #inputs_vector_noise = inputs_vector + tf.random_normal(shape=tf.shape(inputs_vector), mean=0.0, stddev=0.0001, dtype=tf.float32) boundary = flow_net.inference_boundary(1, FLAGS.dims * [FLAGS.obj_size], inputs=inputs_vector, full_shape=shape) #boundary = tf.round(boundary) predicted_flow = flow_net.inference_network(boundary, keep_prob=1.0) # quantities to optimize force = calc_force(boundary, predicted_flow[:, :, :, 2:3]) drag_x = tf.reduce_sum(force[:, :, :, 0]) drag_y = tf.reduce_sum(force[:, :, :, 1]) drag_ratio = (drag_y / drag_x) # init graph init = tf.global_variables_initializer() # Restore the moving average version of the learned variables for eval. variables_to_restore = tf.all_variables() variables_to_restore_boundary = [ variable for i, variable in enumerate(variables_to_restore) if "boundary_network" in variable.name[:variable.name.index(':')] ] variables_to_restore_flow = [ variable for i, variable in enumerate(variables_to_restore) if "flow_network" in variable.name[:variable.name.index(':')] ] saver_boundary = tf.train.Saver(variables_to_restore_boundary) saver_flow = tf.train.Saver(variables_to_restore_flow) # start ses and init sess = tf.Session() sess.run(init) ckpt_boundary = tf.train.get_checkpoint_state(BOUNDARY_DIR) ckpt_flow = tf.train.get_checkpoint_state(FLOW_DIR) saver_boundary.restore(sess, ckpt_boundary.model_checkpoint_path) saver_flow.restore(sess, ckpt_flow.model_checkpoint_path) graph_def = tf.get_default_graph().as_graph_def(add_shapes=True) params_np = get_random_params(FLAGS.nr_boundary_params, 2) params_np = np.expand_dims(params_np, axis=0) params_np[0, 0] = 0.0 params_np[0, 1] = 0.5 params_np[0, 2] = 1.0 params_np[0, 4] = 0.0 # make store vectors for values resolution = 320 loss_val = np.zeros((resolution)) max_d_ratio = np.zeros((resolution)) d_ratio_store = None boundary_frame_store = [] store_freq = int(resolution / nr_frame_saves) # make store dir for i in tqdm(xrange(resolution)): params_np[0, 4] += (0.3) / resolution velocity_norm_g = sess.run(drag_ratio, feed_dict={ inputs_vector: np.concatenate(batch_size * [params_np], axis=0) }) if i % store_freq == 0: boundary_frame_store.append( sess.run( boundary, feed_dict={ inputs_vector: np.concatenate(batch_size * [params_np], axis=0) })[0, int(FLAGS.obj_size / 2):int(3 * FLAGS.obj_size / 2), int(FLAGS.obj_size / 2):int(3 * FLAGS.obj_size / 2), 0]) loss_val[i] = velocity_norm_g fig = plt.figure(figsize=(10, 5)) a = fig.add_subplot(1, 2, 1) plt.title("Boundary from Parameter Change", fontsize=16) boundary_frame_store = tile_frames(boundary_frame_store) plt.imshow(boundary_frame_store) #plt.tick_params(axis='both', top="off", bottom="off") plt.axis('off') a = fig.add_subplot(1, 2, 2) #plt.imshow(np.concatenate(boundary_frame_store, axis = 0)) plt.plot(np.arange(resolution) / float(resolution) - .5, loss_val) plt.ylabel("Lift/Drag") plt.xlabel("Parameter Value") plt.title("Loss vs Parameter Value", fontsize=16) plt.savefig("./figs/boundary_space_explore.pdf") plt.show()
def train(): """Train ring_net for a number of steps.""" with tf.Graph().as_default(): # global step counter global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False) # make inputs input_dims = FLAGS.nr_boundary_params inputs_vector, true_boundary = flow_net.inputs_boundary( input_dims, FLAGS.batch_size, shape) # create and unrap network predicted_boundary = flow_net.inference_boundary( FLAGS.batch_size, shape, inputs_vector) # calc error error = flow_net.loss_boundary(true_boundary, predicted_boundary) # train hopefuly train_op = flow_net.train(error, FLAGS.lr, train_type="boundary_network", global_step=global_step) # List of all Variables variables = tf.global_variables() # Build a saver saver = tf.train.Saver(tf.global_variables()) # Summary op summary_op = tf.summary.merge_all() # Build an initialization operation to run below. init = tf.global_variables_initializer() # Start running operations on the Graph. sess = tf.Session() # init if this is the very time training sess.run(init) # init from checkpoint variables_to_restore = tf.all_variables() variables_to_restore_flow = [ variable for i, variable in enumerate(variables_to_restore) if ("boundary_network" in variable.name[:variable.name.index(':')]) or ("global_step" in variable.name[:variable.name.index(':')]) ] saver_restore = tf.train.Saver(variables_to_restore_flow) ckpt = tf.train.get_checkpoint_state(TRAIN_DIR) if ckpt is not None: print("init from " + TRAIN_DIR) try: saver_restore.restore(sess, ckpt.model_checkpoint_path) except: tf.gfile.DeleteRecursively(TRAIN_DIR) tf.gfile.MakeDirs(TRAIN_DIR) print( "there was a problem using variables in checkpoint, random init will be used instead" ) # Start que runner tf.train.start_queue_runners(sess=sess) # Summary op graph_def = sess.graph.as_graph_def(add_shapes=True) summary_writer = tf.summary.FileWriter(TRAIN_DIR, graph_def=graph_def) # make boundary dataset dataset = Boundary_data("../../data/", size=FLAGS.obj_size, dim=FLAGS.dims, num_params=input_dims) dataset.parse_data() # calc number of steps left to run run_steps = FLAGS.max_steps - int(sess.run(global_step)) print(sess.run(global_step)) for step in xrange(run_steps): current_step = sess.run(global_step) t = time.time() batch_params, batch_boundary = dataset.minibatch( batch_size=FLAGS.batch_size, signed_distance_function=FLAGS.sdf) _, loss_value, gen_boundary = sess.run( [train_op, error, predicted_boundary], feed_dict={ inputs_vector: batch_params, true_boundary: batch_boundary }) elapsed = time.time() - t assert not np.isnan(loss_value), 'Model diverged with loss = NaN' if current_step % 100 == 0: print("loss value at " + str(loss_value)) print("time per batch is " + str(elapsed)) if current_step % 1000 == 0: summary_str = sess.run(summary_op, feed_dict={ inputs_vector: batch_params, true_boundary: batch_boundary }) summary_writer.add_summary(summary_str, current_step) checkpoint_path = os.path.join(TRAIN_DIR, 'model.ckpt') saver.save(sess, checkpoint_path, global_step=global_step) print("saved to " + TRAIN_DIR)
def evaluate(): """Run Eval once. """ # get a list of image filenames filenames = glb('../data/computed_car_flow/*') filenames.sort(key=alphanum_key) filename_len = len(filenames) batch_size = 1 #shape = [128, 512] #shape = [256, 1024] #shape = [128, 256] #shape = [64, 256] #shape = [16, 64] with tf.Session() as sess: # Make image placeholder input_dims = FLAGS.nr_boundary_params input_vector, true_boundary = flow_net.inputs_boundary(input_dims, batch_size=1, shape=shape) # Build a Graph that computes the logits predictions from the # inference model. #mean, stddev, x_sampled, predicted_boundary = flow_net.inference_boundary(true_boundary, shape) predicted_boundary = flow_net.inference_boundary(1, FLAGS.dims * [FLAGS.obj_size], input_vector, full_shape=shape) # Restore for eval init = tf.global_variables_initializer() sess.run(init) variables_to_restore = tf.all_variables() variables_to_restore_boundary = [ variable for i, variable in enumerate(variables_to_restore) if "boundary_network" in variable.name[:variable.name.index(':')] ] saver = tf.train.Saver(variables_to_restore_boundary) print(BOUNDARY_DIR) ckpt = tf.train.get_checkpoint_state(BOUNDARY_DIR) saver.restore(sess, ckpt.model_checkpoint_path) global_step = 1 graph_def = tf.get_default_graph().as_graph_def(add_shapes=True) #for run in filenames: for i in xrange(1000): # read in boundary #batch_boundary, batch_flow = dataset.minibatch(train=False, batch_size=1) # calc flow input_batch, boundary_batch = flow_net.feed_dict_boundary( input_dims, 1, shape) """ #print(input_batch) input_batch[:,1] = .5 input_batch[:,2] = 1.0 input_batch = [[ 0., 0.50044733, 1.0007602, 0.04609993, 0.02800636, 0.17423785, 0.32387334, 0.02092246, 0.06054832, 0.10314581, 0.00666449, 0.09281126]] """ p_boundary = sess.run(predicted_boundary, feed_dict={input_vector: input_batch}) #p_boundary = sess.run(predicted_boundary,feed_dict={true_boundary: batch_boundary}) dim = 0 #sflow_plot = np.concatenate([p_boundary, batch_boundary], axis=1) sflow_plot = p_boundary sflow_plot = sflow_plot[0, :, :, 0] #sflow_plot = sflow_plot[0,:,:,2] # display it plt.imshow(sflow_plot) plt.colorbar() plt.show()