-
Notifications
You must be signed in to change notification settings - Fork 0
/
mgcn.py
216 lines (189 loc) · 8.8 KB
/
mgcn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import numpy as np
import torch
import datetime
import argparse
import os
import copy
import random
import viser
from tqdm import tqdm
import util.loss as Loss
import util.models as Models
import util.datamaker as Datamaker
from util.mesh import Mesh
from util.meshnet import MGCN
import check.dist_check as DIST
def torch_fix_seed(seed=314):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.use_deterministic_algorithms = True
def get_parser():
parser = argparse.ArgumentParser(description="Self-supervised Mesh Completion")
parser.add_argument("-i", "--input", type=str, required=True)
parser.add_argument("-o", "--output", type=str, default="exp")
parser.add_argument("-pos_lr", type=float, default=0.01)
parser.add_argument("-iter", type=int, default=100)
parser.add_argument("-k1", type=float, default=4.0)
parser.add_argument("-k2", type=float, default=4.0)
parser.add_argument("-dm_size", type=int, default=40)
parser.add_argument("-kn", type=int, nargs="*", default=[4])
parser.add_argument("-batch", type=int, default=5)
parser.add_argument("-skip", action="store_true")
parser.add_argument("-gpu", type=int, default=0)
parser.add_argument("-cache", action="store_true")
parser.add_argument("-CAD", action="store_true")
parser.add_argument("-real", action="store_true")
parser.add_argument("-mu", type=float, default=1.0)
parser.add_argument("-viewer", action="store_true", default=True)
parser.add_argument("-port", type=int, default=8081)
args = parser.parse_args()
for k, v in vars(args).items():
print("{:12s}: {}".format(k, v))
return args
def main():
args = get_parser()
if args.viewer:
server = viser.ViserServer(port=args.port)
""" --- create dataset --- """
mesh_dic, dataset = Datamaker.create_dataset(args.input, dm_size=args.dm_size, kn=args.kn, cache=args.cache)
ini_file, smo_file, v_mask, f_mask, mesh_name = mesh_dic["ini_file"], mesh_dic["smo_file"], mesh_dic["v_mask"], mesh_dic["f_mask"], mesh_dic["mesh_name"]
org_mesh, ini_mesh, smo_mesh, out_mesh = mesh_dic["org_mesh"], mesh_dic["ini_mesh"], mesh_dic["smo_mesh"], mesh_dic["out_mesh"]
rot_mesh = copy.deepcopy(ini_mesh)
dt_now = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
vmask_dummy = mesh_dic["vmask_dummy"]
fmask_dummy = mesh_dic["fmask_dummy"]
""" --- create model instance --- """
torch_fix_seed()
device = torch.device("cuda:" + str(args.gpu) if torch.cuda.is_available() else "cpu")
posnet = MGCN(device, smo_mesh, ini_mesh, v_mask, skip=args.skip).to(device)
optimizer_pos = torch.optim.Adam(posnet.parameters(), lr=args.pos_lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer_pos, step_size=50, gamma=0.5)
anss = posnet.poss
v_masks = posnet.v_masks
nvs = posnet.nvs
meshes = posnet.meshes
v_masks_list = posnet.v_masks_list
poss_list = posnet.poss_list
nvs_all = [len(meshes[0].vs)] + nvs
pos_weight = [0.35, 0.3, 0.2, 0.15]
os.makedirs("{}/output/{}_mgcn_{}".format(args.input, dt_now, args.output), exist_ok=True)
scale = 2 / np.max(org_mesh.vs)
if args.viewer:
print("\n\033[42m Viewer at: http://localhost:{} \033[0m\n".format(args.port))
with server.gui.add_folder("Training"):
server.scene.add_mesh_simple(
name="/input",
vertices=org_mesh.vs * scale,
faces=org_mesh.faces,
flat_shading=True,
visible=False,
)
server.scene.add_mesh_simple(
name="/initial",
vertices=ini_mesh.vs * scale,
faces=ini_mesh.faces,
flat_shading=True,
visible=False,
)
gui_counter = server.gui.add_number(
"Epoch",
initial_value=0,
disabled=True,
)
""" --- learning loop --- """
with tqdm(total=args.iter) as pbar:
""" --- training --- """
for epoch in range(1, args.iter+1):
n_data = vmask_dummy.shape[1]
batch_index = torch.randperm(n_data).reshape(-1, args.batch)
epoch_loss_p = 0.0
epoch_loss_n = 0.0
epoch_loss_r = 0.0
epoch_loss_pos = 0.0
epoch_loss = 0.0
for batch in batch_index:
""" original dummy mask """
dm_batch = vmask_dummy[:, batch]
posnet.train()
optimizer_pos.zero_grad()
for i, b in enumerate(batch):
""" original dummy mask """
dm = dm_batch[:, i].reshape(-1, 1)
rm = v_mask.reshape(-1, 1).float()
dm = rm * dm
ini_vs = ini_mesh.vs
poss = posnet(dataset, dm)
pos = poss[0]
norm = Models.compute_fn(pos, ini_mesh.faces)
for mesh_idx, pos_i in enumerate(poss):
if mesh_idx == 0:
loss_p = Loss.mask_pos_rec_loss(pos_i, poss_list[mesh_idx], v_masks_list[mesh_idx].reshape(-1).bool()) * pos_weight[mesh_idx]
epoch_loss_pos += Loss.mask_pos_rec_loss(pos_i, poss_list[0], v_masks_list[0].reshape(-1).bool()).item()
else:
loss_p = loss_p + Loss.mask_pos_rec_loss(pos_i, poss_list[mesh_idx], v_masks_list[mesh_idx].reshape(-1).bool()) * pos_weight[mesh_idx]
# loss_p = Loss.mask_pos_rec_loss(poss, anss, v_masks.reshape(-1).bool())
loss_n = Loss.mask_norm_rec_loss(norm, ini_mesh.fn, f_mask)
if args.CAD:
loss_reg, _ = Loss.fn_bnf_detach_loss(pos, norm, ini_mesh, loop=5)
loss = loss_p + args.k1 * loss_n + args.k2 * loss_reg
epoch_loss_r += loss_reg.item()
else:
# loss_reg = Loss.mesh_laplacian_loss(pos, ini_mesh)
loss = loss_p + args.k1 * loss_n# + 0.0 * loss_reg
epoch_loss_p += loss_p.item()
epoch_loss_n += loss_n.item()
loss.backward()
epoch_loss += loss.item()
optimizer_pos.step()
scheduler.step()
epoch_loss_p /= n_data
epoch_loss_n /= n_data
epoch_loss_r /= n_data
epoch_loss /= n_data
epoch_loss_pos /= n_data
pbar.set_description("Epoch {}".format(epoch))
pbar.set_postfix({"loss": epoch_loss})
if epoch == args.iter:
out_path = "{}/output/{}_mgcn_{}/train.obj".format(args.input, dt_now, args.output)
out_mesh.vs = pos.detach().to("cpu").numpy().copy()
Mesh.save(out_mesh, out_path)
DIST.mesh_distance(mesh_dic["gt_file"], mesh_dic["org_file"], out_path, args.real)
""" --- test --- """
if epoch % 10 == 0:
posnet.eval()
dm = v_mask.reshape(-1, 1).float()
poss = posnet(dataset, dm)
st_nv = 0
for res, mesh in enumerate(meshes):
out_path = "{}/output/{}_mgcn_{}/{}_step_{}.obj".format(args.input, dt_now, args.output, str(epoch), res)
mesh.vs = poss[res].to("cpu").detach().numpy().copy()
st_nv += len(mesh.vs)
Mesh.save(mesh, out_path)
if args.viewer:
server.scene.add_mesh_simple(
name="/output/res-{}".format(res),
vertices=mesh.vs * scale,
faces=mesh.faces,
flat_shading=True,
)
out_path = "{}/output/{}_mgcn_{}/{}_step_0.obj".format(args.input, dt_now, args.output, str(epoch))
if args.viewer:
gui_counter.value = epoch
pbar.update(1)
DIST.mesh_distance(mesh_dic["gt_file"], mesh_dic["org_file"], out_path, args.real)
""" refinement """
posnet.eval()
dm = v_mask.reshape(-1, 1).float()
poss = posnet(dataset, dm)
out_pos = poss[0].to("cpu").detach()
ini_pos = torch.from_numpy(ini_mesh.vs).float()
ref_pos = Mesh.mesh_merge(ini_mesh.Lap, ini_mesh, out_pos, v_mask, w=args.mu)
out_path = "{}/output/{}_mgcn_{}/refine.obj".format(args.input, dt_now, args.output)
out_mesh.vs = ref_pos.detach().numpy().copy()
Mesh.save(out_mesh, out_path)
DIST.mesh_distance(mesh_dic["gt_file"], mesh_dic["org_file"], out_path, args.real)
if __name__ == "__main__":
main()