├── resources
└── teaser.jpg
├── requirements.txt
├── eval.sh
├── LICENSE
├── data_process
├── process.sh
├── deduplicate.sh
├── deduplicate_surfedge.py
├── deduplicate_cad.py
├── process_brep.py
└── convert_utils.py
├── eval_config.yaml
├── vae.py
├── train_vae.sh
├── ldm.py
├── sample_points.py
├── train_ldm.sh
├── .gitignore
├── README.md
├── pc_metric.py
├── sample.py
├── dataset.py
├── LICENSE_GPL
├── utils.py
└── trainer.py
/resources/teaser.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/samxuxiang/BrepGen/HEAD/resources/teaser.jpg
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | --extra-index-url https://download.pytorch.org/whl/cu118
2 | torch
3 | torchvision
4 | torchaudio
5 | diffusers[torch]==0.27
6 | transformers
7 | wandb
8 | matplotlib
9 | scipy
10 | trimesh
11 | plyfile
12 | scikit-learn
13 |
--------------------------------------------------------------------------------
/eval.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash\
2 |
3 | # sample surface point cloud
4 | python sample_points.py --in_dir path/to/your/generated/samples/folder --out_dir sampled_pointcloud
5 |
6 | # Evaluate MMD/COV/JSD
7 | python pc_metric.py --fake sampled_pointcloud --real deepcad_test_pcd
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The code, data and the model weights in this repository are not allowed for commercial usage. For research purposes, the terms follow the GPL v3, as in the separate file "LICENSE_GPL".
2 | -- Authors of the paper "BrepGen: A B-rep Generative Diffusion Model with Structured Latent Geometry".
3 |
--------------------------------------------------------------------------------
/data_process/process.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Adjust the timeout time accordingly, memory could explode when loading few very large cad models
4 |
5 |
6 | ### Process DeepCAD data ###
7 | for i in $(seq 0 18)
8 | do
9 | # Call python script with different interval values
10 | timeout 500 python process_brep.py --input path/to/your/abc_step --interval $i --option 'deepcad'
11 | pkill -f '^python process_brep.py' # cleanup after each run
12 | done
13 |
14 |
15 | ### Process ABC data ###
16 | for i in $(seq 0 99)
17 | do
18 | # Call python script with different interval values
19 | timeout 1000 python process_brep.py --input path/to/your/abc_step --interval $i --option 'abc'
20 | pkill -f '^python process_brep.py' # cleanup after each run
21 | done
22 |
23 |
24 | ### Process Furniture data ###
25 | python process_brep.py --input path/to/your/furniture_step --option 'furniture'
--------------------------------------------------------------------------------
/data_process/deduplicate.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | ### Dedupliate DeepCAD ###
4 | # Deduplicate repeatd CAD B-rep (LDM training)
5 | python deduplicate_cad.py --data deepcad_parsed --bit 6 --option 'deepcad'
6 | # Deduplicate repeated surface & edge (VAE training)
7 | python deduplicate_surfedge.py --data deepcad_parsed --list deepcad_data_split_6bit.pkl --bit 6 --option 'deepcad'
8 | python deduplicate_surfedge.py --data deepcad_parsed --list deepcad_data_split_6bit.pkl --bit 6 --edge --option 'deepcad'
9 |
10 |
11 | ### Dedupliate ABC ###
12 | # Deduplicate repeatd CAD B-rep (LDM training)
13 | python deduplicate_cad.py --data abc_parsed --bit 6 --option 'abc'
14 | # Deduplicate repeated surface & edge (VAE training)
15 | python deduplicate_surfedge.py --data abc_parsed --list abc_data_split_6bit.pkl --bit 6 --option 'abc'
16 | python deduplicate_surfedge.py --data abc_parsed --list abc_data_split_6bit.pkl --bit 6 --edge --option 'abc'
17 |
18 |
19 | ### Dedupliate Furniture ###
20 | # Deduplicate repeatd CAD B-rep (LDM training)
21 | python deduplicate_cad.py --data furniture_parsed --bit 6 --option 'furniture'
22 | # Deduplicate repeated surface & edge (VAE training)
23 | python deduplicate_surfedge.py --data furniture_parsed --list furniture_data_split_6bit.pkl --bit 6 --option 'furniture'
24 | python deduplicate_surfedge.py --data furniture_parsed --list furniture_data_split_6bit.pkl --bit 6 --edge --option 'furniture'
--------------------------------------------------------------------------------
/eval_config.yaml:
--------------------------------------------------------------------------------
1 | abc:
2 | surfpos_weight: abc_ldm_surfpos.pt
3 | surfz_weight: abc_ldm_surfz.pt
4 | edgepos_weight: abc_ldm_edgepos.pt
5 | edgez_weight: abc_ldm_edgez.pt
6 | surfvae_weight: abc_vae_surf.pt
7 | edgevae_weight: abc_vae_edge.pt
8 | save_folder: samples_abc
9 | batch_size: 16
10 | z_threshold: 0.2
11 | bbox_threshold: 0.08
12 | num_surfaces: 50
13 | num_edges: 40
14 | use_cf: False
15 | class_label: []
16 |
17 | deepcad:
18 | surfpos_weight: deepcad_ldm_surfpos.pt
19 | surfz_weight: deepcad_ldm_surfz.pt
20 | edgepos_weight: deepcad_ldm_edgepos.pt
21 | edgez_weight: deepcad_ldm_edgez.pt
22 | surfvae_weight: deepcad_vae_surf.pt
23 | edgevae_weight: deepcad_vae_edge.pt
24 | save_folder: samples_deepcad
25 | batch_size: 16
26 | z_threshold: 0.2
27 | bbox_threshold: 0.08
28 | num_surfaces: 30
29 | num_edges: 30
30 | use_cf: False
31 | class_label: []
32 |
33 | furniture:
34 | surfpos_weight: furniture_ldm_surfpos.pt
35 | surfz_weight: furniture_ldm_surfz.pt
36 | edgepos_weight: furniture_ldm_edgepos.pt
37 | edgez_weight: furniture_ldm_edgez.pt
38 | surfvae_weight: furniture_vae_surf.pt
39 | edgevae_weight: furniture_vae_edge.pt
40 | save_folder: samples_furniture
41 | batch_size: 16
42 | z_threshold: 0.2
43 | bbox_threshold: 0.08
44 | num_surfaces: 60
45 | num_edges: 40
46 | use_cf: True
47 | class_label: chair # option: [bathtub/bed/bench/bookshelf/cabinet/chair/couch/lamp/sofa/table]
48 |
--------------------------------------------------------------------------------
/vae.py:
--------------------------------------------------------------------------------
1 | import os
2 | from utils import get_args_vae
3 |
4 | # Parse input augments
5 | args = get_args_vae()
6 |
7 | # Set PyTorch to use only the specified GPU
8 | os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(map(str, args.gpu))
9 |
10 | # Make project directory if not exist
11 | if not os.path.exists(args.save_dir):
12 | os.makedirs(args.save_dir)
13 |
14 | from trainer import SurfVAETrainer
15 | from dataset import SurfData
16 | from trainer import EdgeVAETrainer
17 | from dataset import EdgeData
18 |
19 | def run(args):
20 | # Initialize dataset loader and trainer
21 | if args.option == 'surface':
22 | train_dataset = SurfData(args.data, args.train_list, validate=False, aug=args.data_aug)
23 | val_dataset = SurfData(args.data, args.val_list, validate=True, aug=False)
24 | vae = SurfVAETrainer(args, train_dataset, val_dataset)
25 | else:
26 | assert args.option == 'edge', 'please choose between surface or edge'
27 | train_dataset = EdgeData(args.data, args.train_list, validate=False, aug=args.data_aug)
28 | val_dataset = EdgeData(args.data, args.val_list, validate=True, aug=False)
29 | vae = EdgeVAETrainer(args, train_dataset, val_dataset)
30 |
31 | # Main training loop
32 | print('Start training...')
33 |
34 | for _ in range(args.train_nepoch):
35 |
36 | # Train for one epoch
37 | vae.train_one_epoch()
38 |
39 | # Evaluate model performance on validation set
40 | if vae.epoch % args.test_nepoch == 0:
41 | vae.test_val()
42 |
43 | # save model
44 | if vae.epoch % args.save_nepoch == 0:
45 | vae.save_model()
46 | return
47 |
48 |
49 | if __name__ == "__main__":
50 | run(args)
--------------------------------------------------------------------------------
/train_vae.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash\
2 |
3 |
4 | ### DeepCAD VAE Training ###
5 | python vae.py --data data_process/deepcad_parsed \
6 | --train_list data_process/deepcad_data_split_6bit_surface.pkl \
7 | --val_list data_process/deepcad_data_split_6bit.pkl \
8 | --option surface --gpu 0 --env deepcad_vae_surf --train_nepoch 400 --data_aug
9 |
10 | python vae.py --data data_process/deepcad_parsed \
11 | --train_list data_process/deepcad_data_split_6bit_edge.pkl \
12 | --val_list data_process/deepcad_data_split_6bit.pkl \
13 | --option edge --gpu 0 --env deepcad_vae_edge --train_nepoch 400 --data_aug
14 |
15 |
16 | ### ABC VAE Training ###
17 | python vae.py --data data_process/abc_parsed \
18 | --train_list data_process/abc_data_split_6bit_surface.pkl \
19 | --val_list data_process/abc_data_split_6bit.pkl \
20 | --option surface --gpu 0 --env abc_vae_surf --train_nepoch 200 --data_aug
21 |
22 | python vae.py --data data_process/abc_parsed \
23 | --train_list data_process/abc_data_split_6bit_edge.pkl \
24 | --val_list data_process/abc_data_split_6bit.pkl \
25 | --option edge --gpu 0 --env abc_vae_edge --train_nepoch 200 --data_aug
26 |
27 |
28 | ### Furniture VAE Training (fintune) ###
29 | python vae.py --data data_process/furniture_parsed \
30 | --train_list data_process/furniture_data_split_6bit_surface.pkl \
31 | --val_list data_process/furniture_data_split_6bit.pkl \
32 | --option surface --gpu 0 --env furniture_vae_surf --train_nepoch 200 --finetune \
33 | --weight proj_log/deepcad_vae_surf.pt
34 |
35 | python vae.py --data data_process/furniture_parsed \
36 | --train_list data_process/furniture_data_split_6bit_edge.pkl \
37 | --val_list data_process/furniture_data_split_6bit.pkl \
38 | --option edge --gpu 0 --env furniture_vae_edge --train_nepoch 200 --finetune \
39 | --weight proj_log/deepcad_vae_edge.pt
--------------------------------------------------------------------------------
/data_process/deduplicate_surfedge.py:
--------------------------------------------------------------------------------
1 | import math
2 | import pickle
3 | import argparse
4 | from tqdm import tqdm
5 | from hashlib import sha256
6 | from convert_utils import *
7 |
8 |
9 | parser = argparse.ArgumentParser()
10 | parser.add_argument("--data", type=str, help="CAD .pkl file", required=True)
11 | parser.add_argument("--list", type=str, help="UID list", required=True)
12 | parser.add_argument("--edge", action='store_true', help='Process edge instead of surface')
13 | parser.add_argument("--bit", type=int, help='Deduplicate precision')
14 | parser.add_argument("--option", type=str, choices=['abc', 'deepcad', 'furniture'], default='abc',
15 | help="Choose between dataset option [abc/deepcad/furniture] (default: abc)")
16 | args = parser.parse_args()
17 |
18 |
19 | with open(args.list, "rb") as file:
20 | data_list = pickle.load(file)['train']
21 |
22 | unique_data = []
23 | unique_hash = set()
24 | total = 0
25 |
26 | for path_idx, uid in tqdm(enumerate(data_list)):
27 | if args.option == 'furniture':
28 | path = os.path.join(args.data, uid)
29 | else:
30 | path = os.path.join(args.data, str(math.floor(int(uid.split('.')[0])/10000)).zfill(4), uid)
31 | with open(path, "rb") as file:
32 | data = pickle.load(file)
33 |
34 | _, _, surf_ncs, edge_ncs, _, _, _, _, _, _, _, _ = data.values()
35 |
36 | if args.edge:
37 | data = edge_ncs
38 | else:
39 | data = surf_ncs
40 |
41 | data_bits = real2bit(data, n_bits=args.bit)
42 |
43 | for np_bit, np_real in zip(data_bits, data):
44 | total += 1
45 |
46 | # Reshape the array to a 2D array
47 | np_bit = np_bit.reshape(-1, 3)
48 | data_hash = sha256(np_bit.tobytes()).hexdigest()
49 |
50 | prev_len = len(unique_hash)
51 | unique_hash.add(data_hash)
52 |
53 | if prev_len < len(unique_hash):
54 | unique_data.append(np_real)
55 | else:
56 | continue
57 |
58 | if path_idx % 2000 == 0:
59 | print(len(unique_hash)/total)
60 |
61 |
62 | if args.edge:
63 | save_path = args.list.split('.')[0] + '_edge.pkl'
64 | else:
65 | save_path = args.list.split('.')[0] + '_surface.pkl'
66 |
67 | with open(save_path, "wb") as tf:
68 | pickle.dump(unique_data, tf)
69 |
--------------------------------------------------------------------------------
/ldm.py:
--------------------------------------------------------------------------------
1 | import os
2 | from utils import *
3 |
4 | # Parse input augments
5 | args = get_args_ldm()
6 |
7 | # Set PyTorch to use only the specified GPU
8 | os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(map(str, args.gpu))
9 |
10 | # Make project directory if not exist
11 | if not os.path.exists(args.save_dir):
12 | os.makedirs(args.save_dir)
13 |
14 | from dataset import *
15 | from trainer import *
16 |
17 | def run(args):
18 | # Initialize dataset and trainer
19 | if args.option == 'surfpos':
20 | train_dataset = SurfPosData(args.data, args.list, validate=False, aug=args.data_aug, args=args)
21 | val_dataset = SurfPosData(args.data, args.list, validate=True, aug=False, args=args)
22 | ldm = SurfPosTrainer(args, train_dataset, val_dataset)
23 |
24 | elif args.option == 'surfz':
25 | train_dataset = SurfZData(args.data, args.list, validate=False, aug=args.data_aug, args=args)
26 | val_dataset = SurfZData(args.data, args.list, validate=True, aug=False, args=args)
27 | ldm = SurfZTrainer(args, train_dataset, val_dataset)
28 |
29 | elif args.option == 'edgepos':
30 | train_dataset = EdgePosData(args.data, args.list, validate=False, aug=args.data_aug, args=args)
31 | val_dataset = EdgePosData(args.data, args.list, validate=True, aug=False, args=args)
32 | ldm = EdgePosTrainer(args, train_dataset, val_dataset)
33 |
34 | elif args.option == 'edgez':
35 | train_dataset = EdgeZData(args.data, args.list, validate=False, aug=args.data_aug, args=args)
36 | val_dataset = EdgeZData(args.data, args.list, validate=True, aug=False, args=args)
37 | ldm = EdgeZTrainer(args, train_dataset, val_dataset)
38 |
39 | else:
40 | assert False, 'please choose between [surfpos, surfz, edgepos, edgez]'
41 |
42 | print('Start training...')
43 |
44 | # Main training loop
45 | for _ in range(args.train_nepoch):
46 |
47 | # Train for one epoch
48 | ldm.train_one_epoch()
49 |
50 | # Evaluate model performance on validation set
51 | if ldm.epoch % args.test_nepoch == 0:
52 | ldm.test_val()
53 |
54 | # save model
55 | if ldm.epoch % args.save_nepoch == 0:
56 | ldm.save_model()
57 |
58 | return
59 |
60 |
61 | if __name__ == "__main__":
62 | run(args)
--------------------------------------------------------------------------------
/data_process/deduplicate_cad.py:
--------------------------------------------------------------------------------
1 | import math
2 | import pickle
3 | import argparse
4 | from tqdm import tqdm
5 | from hashlib import sha256
6 | from convert_utils import *
7 |
8 | parser = argparse.ArgumentParser()
9 | parser.add_argument("--data", type=str, help="Data folder path", required=True)
10 | parser.add_argument("--bit", type=int, help='Deduplicate precision')
11 | parser.add_argument("--option", type=str, choices=['abc', 'deepcad', 'furniture'], default='abc',
12 | help="Choose between dataset option [abc/deepcad/furniture] (default: abc)")
13 | args = parser.parse_args()
14 |
15 | if args.option == 'deepcad':
16 | OUTPUT = f'deepcad_data_split_{args.bit}bit.pkl'
17 | elif args.option == 'abc':
18 | OUTPUT = f'abc_data_split_{args.bit}bit.pkl'
19 | else:
20 | OUTPUT = f'furniture_data_split_{args.bit}bit.pkl'
21 |
22 | # Load all STEP folders
23 | if args.option == 'furniture':
24 | train, val_path, test_path = load_furniture_pkl(args.data)
25 | else:
26 | train, val_path, test_path = load_abc_pkl(args.data, args.option=='deepcad')
27 |
28 | # Remove duplicate for the training set
29 | train_path = []
30 | unique_hash = set()
31 | total = 0
32 |
33 | for path_idx, uid in tqdm(enumerate(train)):
34 | total += 1
35 |
36 | # Load pkl data
37 | if args.option == 'furniture':
38 | path = os.path.join(args.data, uid)
39 | else:
40 | path = os.path.join(args.data, str(math.floor(int(uid.split('.')[0])/10000)).zfill(4), uid)
41 | with open(path, "rb") as file:
42 | data = pickle.load(file)
43 |
44 | # Hash the surface sampled points
45 | surfs_wcs = data['surf_wcs']
46 | surf_hash_total = []
47 | for surf in surfs_wcs:
48 | np_bit = real2bit(surf, n_bits=args.bit).reshape(-1, 3) # bits
49 | data_hash = sha256(np_bit.tobytes()).hexdigest()
50 | surf_hash_total.append(data_hash)
51 | surf_hash_total = sorted(surf_hash_total)
52 | data_hash = '_'.join(surf_hash_total)
53 |
54 | # Save non-duplicate shapes
55 | prev_len = len(unique_hash)
56 | unique_hash.add(data_hash)
57 | if prev_len < len(unique_hash):
58 | train_path.append(uid)
59 | else:
60 | continue
61 |
62 | if path_idx % 2000 == 0:
63 | print(len(unique_hash)/total)
64 |
65 | # save data
66 | data_path = {
67 | 'train':train_path,
68 | 'val':val_path,
69 | 'test':test_path,
70 | }
71 | with open(OUTPUT, "wb") as tf:
72 | pickle.dump(data_path, tf)
73 |
74 |
--------------------------------------------------------------------------------
/sample_points.py:
--------------------------------------------------------------------------------
1 | import os
2 | import argparse
3 | from tqdm import tqdm
4 | import multiprocessing
5 | from pathlib import Path
6 | import trimesh
7 | from trimesh.sample import sample_surface
8 | from plyfile import PlyData, PlyElement
9 | import numpy as np
10 |
11 | def write_ply(points, filename, text=False):
12 | """ input: Nx3, write points to filename as PLY format. """
13 | points = [(points[i,0], points[i,1], points[i,2]) for i in range(points.shape[0])]
14 | vertex = np.array(points, dtype=[('x', 'f4'), ('y', 'f4'),('z', 'f4')])
15 | el = PlyElement.describe(vertex, 'vertex', comments=['vertices'])
16 | with open(filename, mode='wb') as f:
17 | PlyData([el], text=text).write(f)
18 |
19 |
20 | def find_files(folder, extension):
21 | return sorted([Path(os.path.join(folder, f)) for f in os.listdir(folder) if f.endswith(extension)])
22 |
23 |
24 | def load_data_with_prefix(root_folder, prefix):
25 | data_files = []
26 |
27 | # Walk through the directory tree starting from the root folder
28 | for root, dirs, files in os.walk(root_folder):
29 | for filename in files:
30 | # Check if the file ends with the specified prefix
31 | if filename.endswith(prefix):
32 | file_path = os.path.join(root, filename)
33 | data_files.append(file_path)
34 |
35 | return data_files
36 |
37 | class SamplePoints:
38 | """
39 | Perform sampleing of points.
40 | """
41 |
42 | def __init__(self):
43 | """
44 | Constructor.
45 | """
46 | parser = self.get_parser()
47 | self.options = parser.parse_args()
48 |
49 |
50 | def get_parser(self):
51 | """
52 | Get parser of tool.
53 |
54 | :return: parser
55 | """
56 | parser = argparse.ArgumentParser(description='Scale a set of meshes stored as OFF files.')
57 | parser.add_argument('--in_dir', type=str, help='Path to input directory.')
58 | parser.add_argument('--out_dir', type=str, help='Path to output directory; files within are overwritten!')
59 | return parser
60 |
61 |
62 | def run_parallel(self, path):
63 | fileName = os.path.join(self.options.out_dir, path.split('/')[-1][:-4])
64 |
65 | N_POINTS = 2000
66 | out_mesh = trimesh.load(path)
67 | out_pc, _ = sample_surface(out_mesh, N_POINTS)
68 | save_path = os.path.join(fileName+'.ply')
69 | write_ply(out_pc, save_path)
70 | return
71 |
72 |
73 | def run(self):
74 | """
75 | Run simplification.
76 | """
77 | if not os.path.exists(self.options.out_dir):
78 | os.makedirs(self.options.out_dir)
79 |
80 | shape_paths = load_data_with_prefix(self.options.in_dir, '.stl') #+ load_data_with_prefix(self.options.in_dir, '.obj')
81 | # for path in shape_paths:
82 | # self.run_parallel(path)
83 | num_cpus = multiprocessing.cpu_count()
84 | convert_iter = multiprocessing.Pool(num_cpus).imap(self.run_parallel, shape_paths)
85 | for _ in tqdm(convert_iter, total=len(shape_paths)):
86 | pass
87 |
88 |
89 | if __name__ == '__main__':
90 | app = SamplePoints()
91 | app.run()
92 |
--------------------------------------------------------------------------------
/train_ldm.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash\
2 |
3 | ### Train the Latent Diffusion Model ###
4 | # --data_aug is optional
5 | # max_face 30, max_edge 20 for deepcad
6 | # max_face 50, max_edge 30 for abc/furniture
7 | # --surfvae refer to the surface vae weights
8 | # --edgevae refer to the edge vae weights
9 |
10 | ### Training DeepCAD Latent Diffusion Model ###
11 | python ldm.py --data data_process/deepcad_parsed \
12 | --list data_process/deepcad_data_split_6bit.pkl --option surfpos --gpu 0 1 \
13 | --env deepcad_ldm_surfpos --train_nepoch 3000 --test_nepoch 200 --save_nepoch 200 \
14 | --max_face 30 --max_edge 20
15 |
16 | python ldm.py --data data_process/deepcad_parsed \
17 | --list data_process/deepcad_data_split_6bit.pkl --option surfz \
18 | --surfvae proj_log/deepcad_vae_surf.pt --gpu 0 1 \
19 | --env deepcad_ldm_surfz --train_nepoch 3000 --batch_size 256 \
20 | --max_face 30 --max_edge 20
21 |
22 | python ldm.py --data data_process/deepcad_parsed \
23 | --list data_process/deepcad_data_split_6bit.pkl --option edgepos \
24 | --surfvae proj_log/deepcad_vae_surf.pt --gpu 0 1 \
25 | --env deepcad_ldm_edgepos --train_nepoch 1000 --batch_size 128 \
26 | --max_face 30 --max_edge 20
27 |
28 | python ldm.py --data data_process/deepcad_parsed \
29 | --list data_process/deepcad_data_split_6bit.pkl --option edgez \
30 | --surfvae proj_log/deepcad_vae_surf.pt --edgevae proj_log/deepcad_vae_edge.pt --gpu 0 1 \
31 | --env deepcad_ldm_edgez --train_nepoch 1000 --batch_size 128 \
32 | --max_face 30 --max_edge 20
33 |
34 |
35 | ### Training ABC Latent Diffusion Model ###
36 | python ldm.py --data data_process/abc_parsed \
37 | --list data_process/abc_data_split_6bit.pkl --option surfpos --gpu 0 1 \
38 | --env abc_ldm_surfpos --train_nepoch 1000 --test_nepoch 200 --save_nepoch 200 \
39 | --max_face 50 --max_edge 30
40 |
41 | python ldm.py --data data_process/abc_parsed \
42 | --list data_process/abc_data_split_6bit.pkl --option surfz \
43 | --surfvae proj_log/abc_vae_surf.pt --gpu 0 1 \
44 | --env abc_ldm_surfz --train_nepoch 1000 --batch_size 256 \
45 | --max_face 50 --max_edge 30
46 |
47 | python ldm.py --data data_process/abc_parsed \
48 | --list data_process/abc_data_split_6bit.pkl --option edgepos \
49 | --surfvae proj_log/abc_vae_surf.pt --gpu 0 1 \
50 | --env abc_ldm_edgepos --train_nepoch 300 --batch_size 64 \
51 | --max_face 50 --max_edge 30
52 |
53 | python ldm.py --data data_process/abc_parsed \
54 | --list data_process/abc_data_split_6bit.pkl --option edgez \
55 | --surfvae proj_log/abc_vae_surf.pt --edgevae proj_log/abc_vae_edge.pt --gpu 0 1 \
56 | --env abc_ldm_edgez --train_nepoch 300 --batch_size 64 \
57 | --max_face 50 --max_edge 30
58 |
59 |
60 | ### Training Furniture Latent Diffusion Model (classifier-free) ###
61 | python ldm.py --data data_process/furniture_parsed \
62 | --list data_process/furniture_data_split_6bit.pkl --option surfpos --gpu 0 1 \
63 | --env furniture_ldm_surfpos --train_nepoch 3000 --test_nepoch 200 --save_nepoch 200 \
64 | --max_face 50 --max_edge 30 --cf
65 |
66 | python ldm.py --data data_process/furniture_parsed \
67 | --list data_process/furniture_data_split_6bit.pkl --option surfz \
68 | --surfvae proj_log/furniture_vae_surf.pt --gpu 0 1 \
69 | --env furniture_ldm_surfz --train_nepoch 3000 --batch_size 256 \
70 | --max_face 50 --max_edge 30 --cf
71 |
72 | python ldm.py --data data_process/furniture_parsed \
73 | --list data_process/furniture_data_split_6bit.pkl --option edgepos \
74 | --surfvae proj_log/furniture_vae_surf.pt --gpu 0 1 \
75 | --env furniture_ldm_edgepos --train_nepoch 1000 --batch_size 64 \
76 | --max_face 50 --max_edge 30 --cf
77 |
78 | python ldm.py --data data_process/furniture_parsed \
79 | --list data_process/furniture_data_split_6bit.pkl --option edgez \
80 | --surfvae proj_log/furniture_vae_surf.pt --edgevae proj_log/furniture_vae_edge.pt --gpu 0 1 \
81 | --env furniture_ldm_edgez --train_nepoch 1000 --batch_size 64 \
82 | --max_face 50 --max_edge 30 --cf
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # From: https://raw.githubusercontent.com/github/gitignore/main/Python.gitignore
2 | # Byte-compiled / optimized / DLL files
3 | __pycache__/
4 | *.py[cod]
5 | *$py.class
6 |
7 | # C extensions
8 | *.so
9 |
10 | # Distribution / packaging
11 | .Python
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 | cover/
54 |
55 | # Translations
56 | *.mo
57 | *.pot
58 |
59 | # Django stuff:
60 | *.log
61 | local_settings.py
62 | db.sqlite3
63 | db.sqlite3-journal
64 |
65 | # Flask stuff:
66 | instance/
67 | .webassets-cache
68 |
69 | # Scrapy stuff:
70 | .scrapy
71 |
72 | # Sphinx documentation
73 | docs/_build/
74 |
75 | # PyBuilder
76 | .pybuilder/
77 | target/
78 |
79 | # Jupyter Notebook
80 | .ipynb_checkpoints
81 |
82 | # IPython
83 | profile_default/
84 | ipython_config.py
85 |
86 | # pyenv
87 | # For a library or package, you might want to ignore these files since the code is
88 | # intended to run in multiple environments; otherwise, check them in:
89 | # .python-version
90 |
91 | # pipenv
92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
95 | # install all needed dependencies.
96 | #Pipfile.lock
97 |
98 | # poetry
99 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100 | # This is especially recommended for binary packages to ensure reproducibility, and is more
101 | # commonly ignored for libraries.
102 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103 | #poetry.lock
104 |
105 | # pdm
106 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107 | #pdm.lock
108 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109 | # in version control.
110 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
111 | .pdm.toml
112 | .pdm-python
113 | .pdm-build/
114 |
115 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116 | __pypackages__/
117 |
118 | # Celery stuff
119 | celerybeat-schedule
120 | celerybeat.pid
121 |
122 | # SageMath parsed files
123 | *.sage.py
124 |
125 | # Environments
126 | .env
127 | .venv
128 | env/
129 | venv/
130 | ENV/
131 | env.bak/
132 | venv.bak/
133 |
134 | # Spyder project settings
135 | .spyderproject
136 | .spyproject
137 |
138 | # Rope project settings
139 | .ropeproject
140 |
141 | # mkdocs documentation
142 | /site
143 |
144 | # mypy
145 | .mypy_cache/
146 | .dmypy.json
147 | dmypy.json
148 |
149 | # Pyre type checker
150 | .pyre/
151 |
152 | # pytype static type analyzer
153 | .pytype/
154 |
155 | # Cython debug symbols
156 | cython_debug/
157 |
158 | # PyCharm
159 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161 | # and can be added to the global gitignore or merged into this file. For a more nuclear
162 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163 | .idea/
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BrepGen: A B-rep Generative Diffusion Model with Structured Latent Geometry (SIGGRAPH 2024)
2 |
3 | [](https://arxiv.org/abs/2401.15563)
4 | [](https://brepgen.github.io)
5 | [](https://www.youtube.com/xxx)
6 |
7 | *[Xiang Xu](https://samxuxiang.github.io/), [Joseph Lambourne](https://www.research.autodesk.com/people/joseph-george-lambourne/),
8 | [Pradeep Jayaraman](https://www.research.autodesk.com/people/pradeep-kumar-jayaraman/), [Zhengqing Wang](https://www.linkedin.com/in/zhengqing-wang-485854241/?originalSubdomain=ca), [Karl Willis](https://www.karlddwillis.com/), and [Yasutaka Furukawa](https://yasu-furukawa.github.io/)*
9 |
10 | 
11 |
12 | > We present a diffusion-based generative approach that directly outputs a CAD B-rep. BrepGen uses a novel structured latent geometry to encode the CAD geometry and topology. A top-down generation approach is used to denoise the faces, edges, and vertices.
13 |
14 |
15 | ## Requirements
16 |
17 | ### Environment (Tested)
18 | - Linux
19 | - Python 3.9
20 | - CUDA 11.8
21 | - PyTorch 2.2
22 | - Diffusers 0.27
23 |
24 |
25 | ### Dependencies
26 |
27 | Install PyTorch and other dependencies:
28 | ```
29 | conda create --name brepgen_env python=3.9 -y
30 | conda activate brepgen_env
31 |
32 | pip install -r requirements.txt
33 | pip install chamferdist
34 | ```
35 |
36 | If `chamferdist` fails to install here are a few options to try:
37 |
38 | - If there is a CUDA version mismatch error, then try setting the `CUDA_HOME` environment variable to point to CUDA installation folder. The CUDA version of this folder must match with PyTorch's version i.e. 11.8.
39 |
40 | - Try [building from source](https://github.com/krrish94/chamferdist?tab=readme-ov-file#building-from-source).
41 |
42 | Install OCCWL following the instruction [here](https://github.com/AutodeskAILab/occwl).
43 | If conda is stuck in "Solving environment..." there are two options to try:
44 |
45 | - Try using `mamba` as suggested in occwl's README.
46 |
47 | - Install pythonOCC: https://github.com/tpaviot/pythonocc-core?tab=readme-ov-file#install-with-conda and occwl manually: `pip install git+https://github.com/AutodeskAILab/occwl`.
48 |
49 | ## Data
50 | Download [ABC](https://archive.nyu.edu/handle/2451/43778) STEP files (100 folders).
51 |
52 | Download [Furniture Data](https://drive.google.com/drive/folders/1WpV_rgJDXEkBoWaQsqEoO9Ir8CABI8oP?usp=sharing). JSON file contains object UIDs that refer to the original STEP files.
53 |
54 | The faces, edges, and vertices need to be extracted from the STEP files.
55 |
56 | Process the B-reps (under ```data_process``` folder):
57 |
58 | sh process.sh
59 |
60 |
61 | Remove repeated CAD models (under ```data_process``` folder, default is ```6 bit``` ):
62 |
63 | sh deduplicate.sh
64 |
65 | You can download the deduplicated files for [DeepCAD](https://drive.google.com/drive/folders/1N_60VCZKYgPviQgP8lwCOVXrzu9Midfe?usp=drive_link), and [ABC](https://drive.google.com/drive/folders/1bA90Rz5EcwaUhUrgFbSIpgdJ0aeDjy3v?usp=drive_link).
66 |
67 |
68 |
69 | ## Training
70 | Train the surface and edge VAE (wandb for logging):
71 |
72 | sh train_vae.sh
73 |
74 | Train the latent diffusion model (change path to previously trained VAEs):
75 |
76 | sh train_ldm.sh
77 |
78 | ```--cf``` classifier-free training for the Furniture dataset.
79 |
80 | ```--data_aug``` randomly rotate the CAD model during training (optional).
81 |
82 |
83 |
84 |
85 | ## Generation and Evaluation
86 | Randomly generate B-reps from Gaussian noise, both STEP and STL files will be saved:
87 |
88 | python sample.py --mode abc
89 |
90 | This will load the settings in ```eval_config.yaml```. Make sure to update model paths to the correct folder.
91 |
92 | Run this script for evaluation (change the path to generated data folder, with at least 3,000 samples):
93 |
94 | sh eval.sh
95 |
96 | This computes the JSD, MMD, and COV scores. Please also download sampled point clouds for [test set](https://drive.google.com/drive/folders/1kqxSDkS2gUN9_qpuWotFDhl4t7czbfOc?usp=sharing).
97 |
98 |
99 | ## Pretrained Checkpoint
100 | We also provide the individual checkpoints trained on different datasets.
101 | | **Source Dataset** | | |
102 | |--------------------|-----------| -----------|
103 | | DeepCAD | [vae model](https://drive.google.com/drive/folders/1UZYqJ2EmTjzeTcNr_NL3bPpU4WrufvQa?usp=drive_link) | [latent diffusion model](https://drive.google.com/drive/folders/1jonuCzoTBFOKKlnaoGlbmhT6YlnH0lma?usp=drive_link) |
104 | | ABC | [vae model](https://drive.google.com/drive/folders/18Ib9L0kpFf4ylZIRTCYFhXZB_GVIUm53?usp=drive_link) | [latent diffusion model](https://drive.google.com/drive/folders/1hv7ZUcU-L3J0LiONK60-TEh7sAN0zfve?usp=drive_link) |
105 |
106 |
107 | ## Acknowledgement
108 | This research is partially supported by NSERC Discovery Grants with Accelerator Supplements and DND/NSERC Discovery Grant
109 | Supplement, NSERC Alliance Grants, and John R. Evans Leaders Fund (JELF). We also thank Onshape for their support and access of
110 | the publicly available CAD models.
111 |
112 |
113 | ## Citation
114 | If you find our work useful in your research, please cite the following paper
115 | ```
116 | @article{xu2024brepgen,
117 | title={BrepGen: A B-rep Generative Diffusion Model with Structured Latent Geometry},
118 | author={Xu, Xiang and Lambourne, Joseph G and Jayaraman, Pradeep Kumar and Wang, Zhengqing and Willis, Karl DD and Furukawa, Yasutaka},
119 | journal={arXiv preprint arXiv:2401.15563},
120 | year={2024}
121 | }
122 | ```
123 |
--------------------------------------------------------------------------------
/data_process/process_brep.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pickle
3 | import argparse
4 | from tqdm import tqdm
5 | from multiprocessing.pool import Pool
6 | from convert_utils import *
7 | from occwl.io import load_step
8 |
9 |
10 | # To speed up processing, define maximum threshold
11 | MAX_FACE = 70
12 |
13 | def normalize(surf_pnts, edge_pnts, corner_pnts):
14 | """
15 | Various levels of normalization
16 | """
17 | # Global normalization to -1~1
18 | total_points = np.array(surf_pnts).reshape(-1, 3)
19 | min_vals = np.min(total_points, axis=0)
20 | max_vals = np.max(total_points, axis=0)
21 | global_offset = min_vals + (max_vals - min_vals)/2
22 | global_scale = max(max_vals - min_vals)
23 | assert global_scale != 0, 'scale is zero'
24 |
25 | surfs_wcs, edges_wcs, surfs_ncs, edges_ncs = [],[],[],[]
26 |
27 | # Normalize corner
28 | corner_wcs = (corner_pnts - global_offset[np.newaxis,:]) / (global_scale * 0.5)
29 |
30 | # Normalize surface
31 | for surf_pnt in surf_pnts:
32 | # Normalize CAD to WCS
33 | surf_pnt_wcs = (surf_pnt - global_offset[np.newaxis,np.newaxis,:]) / (global_scale * 0.5)
34 | surfs_wcs.append(surf_pnt_wcs)
35 | # Normalize Surface to NCS
36 | min_vals = np.min(surf_pnt_wcs.reshape(-1,3), axis=0)
37 | max_vals = np.max(surf_pnt_wcs.reshape(-1,3), axis=0)
38 | local_offset = min_vals + (max_vals - min_vals)/2
39 | local_scale = max(max_vals - min_vals)
40 | pnt_ncs = (surf_pnt_wcs - local_offset[np.newaxis,np.newaxis,:]) / (local_scale * 0.5)
41 | surfs_ncs.append(pnt_ncs)
42 |
43 | # Normalize edge
44 | for edge_pnt in edge_pnts:
45 | # Normalize CAD to WCS
46 | edge_pnt_wcs = (edge_pnt - global_offset[np.newaxis,:]) / (global_scale * 0.5)
47 | edges_wcs.append(edge_pnt_wcs)
48 | # Normalize Edge to NCS
49 | min_vals = np.min(edge_pnt_wcs.reshape(-1,3), axis=0)
50 | max_vals = np.max(edge_pnt_wcs.reshape(-1,3), axis=0)
51 | local_offset = min_vals + (max_vals - min_vals)/2
52 | local_scale = max(max_vals - min_vals)
53 | pnt_ncs = (edge_pnt_wcs - local_offset) / (local_scale * 0.5)
54 | edges_ncs.append(pnt_ncs)
55 | assert local_scale != 0, 'scale is zero'
56 |
57 | surfs_wcs = np.stack(surfs_wcs)
58 | surfs_ncs = np.stack(surfs_ncs)
59 | edges_wcs = np.stack(edges_wcs)
60 | edges_ncs = np.stack(edges_ncs)
61 |
62 | return surfs_wcs, edges_wcs, surfs_ncs, edges_ncs, corner_wcs
63 |
64 |
65 | def parse_solid(solid):
66 | """
67 | Parse the surface, curve, face, edge, vertex in a CAD solid.
68 |
69 | Args:
70 | - solid (occwl.solid): A single brep solid in occwl data format.
71 |
72 | Returns:
73 | - data: A dictionary containing all parsed data
74 | """
75 | assert isinstance(solid, Solid)
76 |
77 | # Split closed surface and closed curve to halve
78 | solid = solid.split_all_closed_faces(num_splits=0)
79 | solid = solid.split_all_closed_edges(num_splits=0)
80 |
81 | if len(list(solid.faces())) > MAX_FACE:
82 | return None
83 |
84 | # Extract all B-rep primitives and their adjacency information
85 | face_pnts, edge_pnts, edge_corner_pnts, edgeFace_IncM, faceEdge_IncM = extract_primitive(solid)
86 |
87 | # Normalize the CAD model
88 | surfs_wcs, edges_wcs, surfs_ncs, edges_ncs, corner_wcs = normalize(face_pnts, edge_pnts, edge_corner_pnts)
89 |
90 | # Remove duplicate and merge corners
91 | corner_wcs = np.round(corner_wcs,4)
92 | corner_unique = []
93 | for corner_pnt in corner_wcs.reshape(-1,3):
94 | if len(corner_unique) == 0:
95 | corner_unique = corner_pnt.reshape(1,3)
96 | else:
97 | # Check if it exist or not
98 | exists = np.any(np.all(corner_unique == corner_pnt, axis=1))
99 | if exists:
100 | continue
101 | else:
102 | corner_unique = np.concatenate([corner_unique, corner_pnt.reshape(1,3)], 0)
103 |
104 | # Edge-corner adjacency
105 | edgeCorner_IncM = []
106 | for edge_corner in corner_wcs:
107 | start_corner_idx = np.where((corner_unique == edge_corner[0]).all(axis=1))[0].item()
108 | end_corner_idx = np.where((corner_unique == edge_corner[1]).all(axis=1))[0].item()
109 | edgeCorner_IncM.append([start_corner_idx, end_corner_idx])
110 | edgeCorner_IncM = np.array(edgeCorner_IncM)
111 |
112 | # Surface global bbox
113 | surf_bboxes = []
114 | for pnts in surfs_wcs:
115 | min_point, max_point = get_bbox(pnts.reshape(-1,3))
116 | surf_bboxes.append( np.concatenate([min_point, max_point]))
117 | surf_bboxes = np.vstack(surf_bboxes)
118 |
119 | # Edge global bbox
120 | edge_bboxes = []
121 | for pnts in edges_wcs:
122 | min_point, max_point = get_bbox(pnts.reshape(-1,3))
123 | edge_bboxes.append(np.concatenate([min_point, max_point]))
124 | edge_bboxes = np.vstack(edge_bboxes)
125 |
126 | # Convert to float32 to save space
127 | data = {
128 | 'surf_wcs':surfs_wcs.astype(np.float32),
129 | 'edge_wcs':edges_wcs.astype(np.float32),
130 | 'surf_ncs':surfs_ncs.astype(np.float32),
131 | 'edge_ncs':edges_ncs.astype(np.float32),
132 | 'corner_wcs':corner_wcs.astype(np.float32),
133 | 'edgeFace_adj': edgeFace_IncM,
134 | 'edgeCorner_adj':edgeCorner_IncM,
135 | 'faceEdge_adj':faceEdge_IncM,
136 | 'surf_bbox_wcs':surf_bboxes.astype(np.float32),
137 | 'edge_bbox_wcs':edge_bboxes.astype(np.float32),
138 | 'corner_unique':corner_unique.astype(np.float32),
139 | }
140 |
141 | return data
142 |
143 |
144 | def process(step_folder):
145 | """
146 | Helper function to load step files and process in parallel
147 |
148 | Args:
149 | - step_folder (str): Path to the STEP parent folder.
150 |
151 | Returns:
152 | - Complete status: Valid (1) / Non-valid (0).
153 | """
154 | try:
155 | # Load cad data
156 | if step_folder.endswith('.step'):
157 | step_path = step_folder
158 | process_furniture = True
159 | else:
160 | for _, _, files in os.walk(step_folder):
161 | assert len(files) == 1
162 | step_path = os.path.join(step_folder, files[0])
163 | process_furniture = False
164 |
165 | # Check single solid
166 | cad_solid = load_step(step_path)
167 | if len(cad_solid)!=1:
168 | print('Skipping multi solids...')
169 | return 0
170 |
171 | # Start data parsing
172 | data = parse_solid(cad_solid[0])
173 | if data is None:
174 | print ('Exceeding threshold...')
175 | return 0 # number of faces or edges exceed pre-determined threshold
176 |
177 | # Save the parsed result
178 | if process_furniture:
179 | data_uid = step_path.split('/')[-2] + '_' + step_path.split('/')[-1]
180 | sub_folder = step_path.split('/')[-3]
181 | else:
182 | data_uid = step_path.split('/')[-2]
183 | sub_folder = data_uid[:4]
184 |
185 | if data_uid.endswith('.step'):
186 | data_uid = data_uid[:-5] # furniture avoid .step
187 |
188 | data['uid'] = data_uid
189 | save_folder = os.path.join(OUTPUT, sub_folder)
190 | if not os.path.exists(save_folder):
191 | os.makedirs(save_folder)
192 |
193 | save_path = os.path.join(save_folder, data['uid']+'.pkl')
194 | with open(save_path, "wb") as tf:
195 | pickle.dump(data, tf)
196 |
197 | return 1
198 |
199 | except Exception as e:
200 | print('not saving due to error...')
201 | return 0
202 |
203 |
204 | if __name__ == '__main__':
205 | parser = argparse.ArgumentParser()
206 | parser.add_argument("--input", type=str, help="Data folder path", required=True)
207 | parser.add_argument("--option", type=str, choices=['abc', 'deepcad', 'furniture'], default='abc',
208 | help="Choose between dataset option [abc/deepcad/furniture] (default: abc)")
209 | parser.add_argument("--interval", type=int, help="Data range index, only required for abc/deepcad")
210 | args = parser.parse_args()
211 |
212 | if args.option == 'deepcad':
213 | OUTPUT = 'deepcad_parsed'
214 | elif args.option == 'abc':
215 | OUTPUT = 'abc_parsed'
216 | else:
217 | OUTPUT = 'furniture_parsed'
218 |
219 | # Load all STEP files
220 | if args.option == 'furniture':
221 | step_dirs = load_furniture_step(args.input)
222 | else:
223 | step_dirs = load_abc_step(args.input, args.option=='deepcad')
224 | step_dirs = step_dirs[args.interval*10000 : (args.interval+1)*10000]
225 |
226 | # Process B-reps in parallel
227 | valid = 0
228 | convert_iter = Pool(os.cpu_count()).imap(process, step_dirs)
229 | for status in tqdm(convert_iter, total=len(step_dirs)):
230 | valid += status
231 | print(f'Done... Data Converted Ratio {100.0*valid/len(step_dirs)}%')
232 |
233 |
234 |
--------------------------------------------------------------------------------
/data_process/convert_utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | import random
4 | import numpy as np
5 | from occwl.uvgrid import ugrid, uvgrid
6 | from occwl.compound import Compound
7 | from occwl.solid import Solid
8 | from occwl.shell import Shell
9 | from occwl.entity_mapper import EntityMapper
10 |
11 |
12 | def get_bbox(point_cloud):
13 | """
14 | Get the tighest fitting 3D bounding box giving a set of points (axis-aligned)
15 | """
16 | # Find the minimum and maximum coordinates along each axis
17 | min_x = np.min(point_cloud[:, 0])
18 | max_x = np.max(point_cloud[:, 0])
19 |
20 | min_y = np.min(point_cloud[:, 1])
21 | max_y = np.max(point_cloud[:, 1])
22 |
23 | min_z = np.min(point_cloud[:, 2])
24 | max_z = np.max(point_cloud[:, 2])
25 |
26 | # Create the 3D bounding box using the min and max values
27 | min_point = np.array([min_x, min_y, min_z])
28 | max_point = np.array([max_x, max_y, max_z])
29 | return min_point, max_point
30 |
31 |
32 | def real2bit(data, n_bits=8, min_range=-1, max_range=1):
33 | """Convert vertices in [-1., 1.] to discrete values in [0, n_bits**2 - 1]."""
34 | range_quantize = 2**n_bits - 1
35 | data_quantize = (data - min_range) * range_quantize / (max_range - min_range)
36 | data_quantize = np.clip(data_quantize, a_min=0, a_max=range_quantize) # clip values
37 | return data_quantize.astype(int)
38 |
39 |
40 | def load_abc_pkl(root_dir, use_deepcad):
41 | """
42 | Recursively searches through a given parent directory and its subdirectories
43 | to find the paths of all ABC .pkl files.
44 |
45 | Args:
46 | - root_dir (str): Path to the root directory where the search begins.
47 | - use_deepcad (bool): Process deepcad or not
48 |
49 | Returns:
50 | - train [str]: A list containing the paths to all .pkl train data
51 | - val [str]: A list containing the paths to all .pkl validation data
52 | - test [str]: A list containing the paths to all .pkl test data
53 | """
54 | # Load DeepCAD UID
55 | if use_deepcad:
56 | with open('train_val_test_split.json', 'r') as json_file:
57 | deepcad_data = json.load(json_file)
58 | train_uid = set([uid.split('/')[1] for uid in deepcad_data['train']])
59 | val_uid = set([uid.split('/')[1] for uid in deepcad_data['validation']])
60 | test_uid = set([uid.split('/')[1] for uid in deepcad_data['test']])
61 |
62 | # Load ABC UID
63 | else:
64 | full_uids = []
65 | dirs = [f'{root_dir}/{str(i).zfill(4)}' for i in range(100)]
66 | for folder in dirs:
67 | files = os.listdir(folder)
68 | full_uids += files
69 | # 90-5-5 random split, same as deepcad
70 | random.shuffle(full_uids) # randomly shuffle data
71 | train_uid = full_uids[0:int(len(full_uids)*0.9)]
72 | val_uid = full_uids[int(len(full_uids)*0.9):int(len(full_uids)*0.95)]
73 | test_uid = full_uids[int(len(full_uids)*0.95):]
74 | train_uid = set([uid.split('.')[0] for uid in train_uid])
75 | val_uid = set([uid.split('.')[0] for uid in val_uid])
76 | test_uid = set([uid.split('.')[0] for uid in test_uid])
77 |
78 | train = []
79 | val = []
80 | test = []
81 | dirs = [f'{root_dir}/{str(i).zfill(4)}' for i in range(100)]
82 | for folder in dirs:
83 | files = os.listdir(folder)
84 | for file in files:
85 | key_id = file.split('.')[0]
86 | if key_id in train_uid:
87 | train.append(file)
88 | elif key_id in val_uid:
89 | val.append(file)
90 | elif key_id in test_uid:
91 | test.append(file)
92 | else:
93 | print('unknown uid...')
94 | assert False
95 | return train, val, test
96 |
97 |
98 | def load_furniture_pkl(root_dir):
99 | """
100 | Recursively searches through a given parent directory and its subdirectories
101 | to find the paths of all furniture .pkl files.
102 |
103 | Args:
104 | - root_dir (str): Path to the root directory where the search begins.
105 |
106 | Returns:
107 | - train [str]: A list containing the paths to all .pkl train data
108 | - val [str]: A list containing the paths to all .pkl validation data
109 | - test [str]: A list containing the paths to all .pkl test data
110 | """
111 | full_uids = []
112 | for root, dirs, files in os.walk(root_dir):
113 | for filename in files:
114 | # Check if the file ends with the specified prefix
115 | if filename.endswith('.pkl'):
116 | file_path = os.path.join(root, filename)
117 | full_uids.append(file_path)
118 |
119 | # 90-5-5 random split, similary to deepcad
120 | random.shuffle(full_uids) # randomly shuffle data
121 | train_uid = full_uids[0:int(len(full_uids)*0.9)]
122 | val_uid = full_uids[int(len(full_uids)*0.9):int(len(full_uids)*0.95)]
123 | test_uid = full_uids[int(len(full_uids)*0.95):]
124 |
125 | train_uid = ['/'.join(uid.split('/')[-2:]) for uid in train_uid]
126 | val_uid = ['/'.join(uid.split('/')[-2:]) for uid in val_uid]
127 | test_uid = ['/'.join(uid.split('/')[-2:]) for uid in test_uid]
128 |
129 | return train_uid, val_uid, test_uid
130 |
131 |
132 | def load_abc_step(root_dir, use_deepcad):
133 | """
134 | Recursively searches through a given parent directory and its subdirectories
135 | to find the paths of all ABC STEP files.
136 |
137 | Args:
138 | - root_dir (str): Path to the root directory where the search begins.
139 | - use_deepcad (bool): Process deepcad or not
140 |
141 | Returns:
142 | - step_dirs [str]: A list containing the paths to all STEP parent directory
143 | """
144 | # Load DeepCAD UID
145 | if use_deepcad:
146 | with open('train_val_test_split.json', 'r') as json_file:
147 | deepcad_data = json.load(json_file)
148 | deepcad_data = deepcad_data['train'] + deepcad_data['validation'] + deepcad_data['test']
149 | deepcad_uid = set([uid.split('/')[1] for uid in deepcad_data])
150 |
151 | # Create STEP file folder path (based on the default ABC STEP format)
152 | dirs_nested = [[f'{root_dir}/abc_{str(i).zfill(4)}_step_v00']*10000 for i in range(100)]
153 | dirs = [item for sublist in dirs_nested for item in sublist]
154 | subdirs = [f'{str(i).zfill(8)}' for i in range(1000000)]
155 |
156 | if use_deepcad:
157 | step_dirs = [root + '/' + sub for root, sub in zip(dirs, subdirs) if sub in deepcad_uid]
158 | else:
159 | step_dirs = [root + '/' + sub for root, sub in zip(dirs, subdirs)]
160 |
161 | return step_dirs
162 |
163 |
164 | def load_furniture_step(root_dir):
165 | """
166 | Recursively searches through a given parent directory and its subdirectories
167 | to find the paths of all Furniture STEP files.
168 |
169 | Args:
170 | - root_dir (str): Path to the root directory where the search begins.
171 |
172 | Returns:
173 | - data_files [str]: A list containing the paths to all STEP parent directory
174 | """
175 | data_files = []
176 | # Walk through the directory tree starting from the root folder
177 | for root, dirs, files in os.walk(root_dir):
178 | for filename in files:
179 | # Check if the file ends with the specified prefix
180 | if filename.endswith('.step'):
181 | file_path = os.path.join(root, filename)
182 | data_files.append(file_path)
183 | return data_files
184 |
185 |
186 | def update_mapping(data_dict):
187 | """
188 | Remove unused key index from data dictionary.
189 | """
190 | dict_new = {}
191 | mapping = {}
192 | max_idx = max(data_dict.keys())
193 | skipped_indices = np.array(sorted(list(set(np.arange(max_idx)) - set(data_dict.keys()))))
194 | for idx, value in data_dict.items():
195 | skips = (skipped_indices < idx).sum()
196 | idx_new = idx - skips
197 | dict_new[idx_new] = value
198 | mapping[idx] = idx_new
199 | return dict_new, mapping
200 |
201 |
202 | def face_edge_adj(shape):
203 | """
204 | *** COPY AND MODIFIED FROM THE ORIGINAL OCCWL SOURCE CODE ***
205 | Extract face/edge geometry and create a face-edge adjacency
206 | graph from the given shape (Solid or Compound)
207 |
208 | Args:
209 | - shape (Shell, Solid, or Compound): Shape
210 |
211 | Returns:
212 | - face_dict: Dictionary of occwl faces, with face ID as the key
213 | - edge_dict: Dictionary of occwl edges, with edge ID as the key
214 | - edgeFace_IncM: Edge ID as the key, Adjacent faces ID as the value
215 | """
216 | assert isinstance(shape, (Shell, Solid, Compound))
217 | mapper = EntityMapper(shape)
218 |
219 | ### Faces ###
220 | face_dict = {}
221 | for face in shape.faces():
222 | face_idx = mapper.face_index(face)
223 | face_dict[face_idx] = (face.surface_type(), face)
224 |
225 | ### Edges and IncidenceMat ###
226 | edgeFace_IncM = {}
227 | edge_dict = {}
228 | for edge in shape.edges():
229 | if not edge.has_curve():
230 | continue
231 |
232 | connected_faces = list(shape.faces_from_edge(edge))
233 | if len(connected_faces) == 2 and not edge.seam(connected_faces[0]) and not edge.seam(connected_faces[1]):
234 | left_face, right_face = edge.find_left_and_right_faces(connected_faces)
235 | if left_face is None or right_face is None:
236 | continue
237 | edge_idx = mapper.edge_index(edge)
238 | edge_dict[edge_idx] = edge
239 | left_index = mapper.face_index(left_face)
240 | right_index = mapper.face_index(right_face)
241 |
242 | if edge_idx in edgeFace_IncM:
243 | edgeFace_IncM[edge_idx] += [left_index, right_index]
244 | else:
245 | edgeFace_IncM[edge_idx] = [left_index, right_index]
246 | else:
247 | pass # ignore seam
248 |
249 | return face_dict, edge_dict, edgeFace_IncM
250 |
251 |
252 | def extract_primitive(solid):
253 | """
254 | Extract all primitive information from splitted solid
255 |
256 | Args:
257 | - solid (occwl.Solid): A single b-rep solid in occwl format
258 |
259 | Returns:
260 | - face_pnts (N x 32 x 32 x 3): Sampled uv-grid points on the bounded surface region (face)
261 | - edge_pnts (M x 32 x 3): Sampled u-grid points on the boundged curve region (edge)
262 | - edge_corner_pnts (M x 2 x 3): Start & end vertices per edge
263 | - edgeFace_IncM (M x 2): Edge-Face incident matrix, every edge is connect to two face IDs
264 | - faceEdge_IncM: A list of N sublist, where each sublist represents the adjacent edge IDs to a face
265 | """
266 | assert isinstance(solid, Solid)
267 |
268 | # Retrieve face, edge geometry and face-edge adjacency
269 | face_dict, edge_dict, edgeFace_IncM = face_edge_adj(solid)
270 |
271 | # Skip unused index key, and update the adj
272 | face_dict, face_map = update_mapping(face_dict)
273 | edge_dict, edge_map = update_mapping(edge_dict)
274 | edgeFace_IncM_update = {}
275 | for key, value in edgeFace_IncM.items():
276 | new_face_indices = [face_map[x] for x in value]
277 | edgeFace_IncM_update[edge_map[key]] = new_face_indices
278 | edgeFace_IncM = edgeFace_IncM_update
279 |
280 | # Face-edge adj
281 | num_faces = len(face_dict)
282 | edgeFace_IncM = np.stack([x for x in edgeFace_IncM.values()])
283 | faceEdge_IncM = []
284 | for surf_idx in range(num_faces):
285 | surf_edges, _ = np.where(edgeFace_IncM == surf_idx)
286 | faceEdge_IncM.append(surf_edges)
287 |
288 | # Sample uv-grid from surface (32x32)
289 | graph_face_feat = {}
290 | for face_idx, face_feature in face_dict.items():
291 | _, face = face_feature
292 | points = uvgrid(
293 | face, method="point", num_u=32, num_v=32
294 | )
295 | visibility_status = uvgrid(
296 | face, method="visibility_status", num_u=32, num_v=32
297 | )
298 | mask = np.logical_or(visibility_status == 0, visibility_status == 2) # 0: Inside, 1: Outside, 2: On boundary
299 | # Concatenate channel-wise to form face feature tensor
300 | face_feat = np.concatenate((points, mask), axis=-1)
301 | graph_face_feat[face_idx] = face_feat
302 | face_pnts = np.stack([x for x in graph_face_feat.values()])[:,:,:,:3]
303 |
304 | # sample u-grid from curve (1x32)
305 | graph_edge_feat = {}
306 | graph_corner_feat = {}
307 | for edge_idx, edge in edge_dict.items():
308 | points = ugrid(edge, method="point", num_u=32)
309 | graph_edge_feat[edge_idx] = points
310 | #### edge corners as start/end vertex ###
311 | v_start = points[0]
312 | v_end = points[-1]
313 | graph_corner_feat[edge_idx] = (v_start, v_end)
314 | edge_pnts = np.stack([x for x in graph_edge_feat.values()])
315 | edge_corner_pnts = np.stack([x for x in graph_corner_feat.values()])
316 |
317 | return [face_pnts, edge_pnts, edge_corner_pnts, edgeFace_IncM, faceEdge_IncM]
--------------------------------------------------------------------------------
/pc_metric.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import argparse
3 | import os
4 | import numpy as np
5 | from tqdm import tqdm
6 | import random
7 | import warnings
8 | from scipy.stats import entropy
9 | from sklearn.neighbors import NearestNeighbors
10 | from plyfile import PlyData
11 | from pathlib import Path
12 | import multiprocessing
13 | from chamfer_distance import ChamferDistance
14 |
15 | N_POINTS = 2000
16 |
17 |
18 | def find_files(folder, extension):
19 | return sorted([Path(os.path.join(folder, f)) for f in os.listdir(folder) if f.endswith(extension)])
20 |
21 |
22 | def read_ply(path):
23 | with open(path, 'rb') as f:
24 | plydata = PlyData.read(f)
25 | x = np.array(plydata['vertex']['x'])
26 | y = np.array(plydata['vertex']['y'])
27 | z = np.array(plydata['vertex']['z'])
28 | vertex = np.stack([x, y, z], axis=1)
29 | return vertex
30 |
31 |
32 | def distChamfer(a, b):
33 | x, y = a, b
34 | bs, num_points, points_dim = x.size()
35 | xx = torch.bmm(x, x.transpose(2, 1))
36 | yy = torch.bmm(y, y.transpose(2, 1))
37 | zz = torch.bmm(x, y.transpose(2, 1))
38 | diag_ind = torch.arange(0, num_points).to(a).long()
39 | rx = xx[:, diag_ind, diag_ind].unsqueeze(1).expand_as(xx)
40 | ry = yy[:, diag_ind, diag_ind].unsqueeze(1).expand_as(yy)
41 | P = (rx.transpose(2, 1) + ry - 2 * zz)
42 | return P.min(1)[0], P.min(2)[0]
43 |
44 |
45 | def _pairwise_CD(sample_pcs, ref_pcs, batch_size):
46 | N_sample = sample_pcs.shape[0]
47 | N_ref = ref_pcs.shape[0]
48 | all_cd = []
49 | all_emd = []
50 | iterator = range(N_sample)
51 | matched_gt = []
52 | pbar = tqdm(iterator)
53 | chamfer_dist = ChamferDistance()
54 |
55 | for sample_b_start in pbar:
56 | sample_batch = sample_pcs[sample_b_start]
57 |
58 | cd_lst = []
59 | emd_lst = []
60 | for ref_b_start in range(0, N_ref, batch_size):
61 | ref_b_end = min(N_ref, ref_b_start + batch_size)
62 | ref_batch = ref_pcs[ref_b_start:ref_b_end]
63 |
64 | batch_size_ref = ref_batch.size(0)
65 | sample_batch_exp = sample_batch.view(1, -1, 3).expand(batch_size_ref, -1, -1)
66 | sample_batch_exp = sample_batch_exp.contiguous()
67 |
68 | dl, dr, idx1, idx2 = chamfer_dist(sample_batch_exp,ref_batch)
69 | cd_lst.append((dl.mean(dim=1) + dr.mean(dim=1)).view(1, -1))
70 |
71 | cd_lst = torch.cat(cd_lst, dim=1)
72 | all_cd.append(cd_lst)
73 |
74 | hit = np.argmin(cd_lst.detach().cpu().numpy()[0])
75 | matched_gt.append(hit)
76 | pbar.set_postfix({"cov": len(np.unique(matched_gt)) * 1.0 / N_ref})
77 |
78 | all_cd = torch.cat(all_cd, dim=0) # N_sample, N_ref
79 |
80 | return all_cd
81 |
82 |
83 | def compute_cov_mmd(sample_pcs, ref_pcs, batch_size):
84 | all_dist = _pairwise_CD(sample_pcs, ref_pcs, batch_size)
85 | N_sample, N_ref = all_dist.size(0), all_dist.size(1)
86 | min_val_fromsmp, min_idx = torch.min(all_dist, dim=1)
87 | min_val, _ = torch.min(all_dist, dim=0)
88 | mmd = min_val.mean()
89 | cov = float(min_idx.unique().view(-1).size(0)) / float(N_ref)
90 | cov = torch.tensor(cov).to(all_dist)
91 |
92 | return {
93 | 'MMD-CD': mmd.item(),
94 | 'COV-CD': cov.item(),
95 | }
96 |
97 |
98 | def jsd_between_point_cloud_sets(sample_pcs, ref_pcs, in_unit_sphere, resolution=28):
99 | '''Computes the JSD between two sets of point-clouds, as introduced in the paper ```Learning Representations And Generative Models For 3D Point Clouds```.
100 | Args:
101 | sample_pcs: (np.ndarray S1xR2x3) S1 point-clouds, each of R1 points.
102 | ref_pcs: (np.ndarray S2xR2x3) S2 point-clouds, each of R2 points.
103 | resolution: (int) grid-resolution. Affects granularity of measurements.
104 | '''
105 | sample_grid_var = entropy_of_occupancy_grid(sample_pcs, resolution, in_unit_sphere)[1]
106 | ref_grid_var = entropy_of_occupancy_grid(ref_pcs, resolution, in_unit_sphere)[1]
107 | return jensen_shannon_divergence(sample_grid_var, ref_grid_var)
108 |
109 |
110 | def entropy_of_occupancy_grid(pclouds, grid_resolution, in_sphere=False):
111 | '''Given a collection of point-clouds, estimate the entropy of the random variables
112 | corresponding to occupancy-grid activation patterns.
113 | Inputs:
114 | pclouds: (numpy array) #point-clouds x points per point-cloud x 3
115 | grid_resolution (int) size of occupancy grid that will be used.
116 | '''
117 | epsilon = 10e-4
118 | bound = 1 + epsilon
119 | if abs(np.max(pclouds)) > bound or abs(np.min(pclouds)) > bound:
120 | print(abs(np.max(pclouds)), abs(np.min(pclouds)))
121 | warnings.warn('Point-clouds are not in unit cube.')
122 |
123 | if in_sphere and np.max(np.sqrt(np.sum(pclouds ** 2, axis=2))) > bound:
124 | warnings.warn('Point-clouds are not in unit sphere.')
125 |
126 | grid_coordinates, _ = unit_cube_grid_point_cloud(grid_resolution, in_sphere)
127 | grid_coordinates = grid_coordinates.reshape(-1, 3)
128 | grid_counters = np.zeros(len(grid_coordinates))
129 | grid_bernoulli_rvars = np.zeros(len(grid_coordinates))
130 | nn = NearestNeighbors(n_neighbors=1).fit(grid_coordinates)
131 |
132 | for pc in pclouds:
133 | _, indices = nn.kneighbors(pc)
134 | indices = np.squeeze(indices)
135 | for i in indices:
136 | grid_counters[i] += 1
137 | indices = np.unique(indices)
138 | for i in indices:
139 | grid_bernoulli_rvars[i] += 1
140 |
141 | acc_entropy = 0.0
142 | n = float(len(pclouds))
143 | for g in grid_bernoulli_rvars:
144 | p = 0.0
145 | if g > 0:
146 | p = float(g) / n
147 | acc_entropy += entropy([p, 1.0 - p])
148 |
149 | return acc_entropy / len(grid_counters), grid_counters
150 |
151 |
152 | def unit_cube_grid_point_cloud(resolution, clip_sphere=False):
153 | '''Returns the center coordinates of each cell of a 3D grid with resolution^3 cells,
154 | that is placed in the unit-cube.
155 | If clip_sphere it True it drops the "corner" cells that lie outside the unit-sphere.
156 | '''
157 | grid = np.ndarray((resolution, resolution, resolution, 3), np.float32)
158 | spacing = 1.0 / float(resolution - 1) * 2
159 | for i in range(resolution):
160 | for j in range(resolution):
161 | for k in range(resolution):
162 | grid[i, j, k, 0] = i * spacing - 0.5 * 2
163 | grid[i, j, k, 1] = j * spacing - 0.5 * 2
164 | grid[i, j, k, 2] = k * spacing - 0.5 * 2
165 |
166 | if clip_sphere:
167 | grid = grid.reshape(-1, 3)
168 | grid = grid[np.linalg.norm(grid, axis=1) <= 0.5]
169 |
170 | return grid, spacing
171 |
172 |
173 | def jensen_shannon_divergence(P, Q):
174 | if np.any(P < 0) or np.any(Q < 0):
175 | raise ValueError('Negative values.')
176 | if len(P) != len(Q):
177 | raise ValueError('Non equal size.')
178 |
179 | P_ = P / np.sum(P) # Ensure probabilities.
180 | Q_ = Q / np.sum(Q)
181 |
182 | e1 = entropy(P_, base=2)
183 | e2 = entropy(Q_, base=2)
184 | e_sum = entropy((P_ + Q_) / 2.0, base=2)
185 | res = e_sum - ((e1 + e2) / 2.0)
186 |
187 | res2 = _jsdiv(P_, Q_)
188 |
189 | if not np.allclose(res, res2, atol=10e-5, rtol=0):
190 | warnings.warn('Numerical values of two JSD methods don\'t agree.')
191 |
192 | return res
193 |
194 |
195 | def _jsdiv(P, Q):
196 | '''another way of computing JSD'''
197 |
198 | def _kldiv(A, B):
199 | a = A.copy()
200 | b = B.copy()
201 | idx = np.logical_and(a > 0, b > 0)
202 | a = a[idx]
203 | b = b[idx]
204 | return np.sum([v for v in a * np.log2(a / b)])
205 |
206 | P_ = P / np.sum(P)
207 | Q_ = Q / np.sum(Q)
208 |
209 | M = 0.5 * (P_ + Q_)
210 |
211 | return 0.5 * (_kldiv(P_, M) + _kldiv(Q_, M))
212 |
213 |
214 | def downsample_pc(points, n):
215 | sample_idx = random.sample(list(range(points.shape[0])), n)
216 | return points[sample_idx]
217 |
218 |
219 | def normalize_pc(points):
220 | # normalize
221 | mean = np.mean(points, axis=0)
222 | points = (points - mean)
223 | # fit to unit cube
224 | scale = np.max(np.abs(points))
225 | points = points / scale
226 | return points
227 |
228 |
229 | def collect_pc(cad_folder):
230 | pc_path = find_files(os.path.join(cad_folder, 'pcd'), 'final_pcd.ply')
231 | if len(pc_path) == 0:
232 | return []
233 | pc_path = pc_path[-1] # final pcd
234 | pc = read_ply(pc_path)
235 | if pc.shape[0] > N_POINTS:
236 | pc = downsample_pc(pc, N_POINTS)
237 | pc = normalize_pc(pc)
238 | return pc
239 |
240 | def collect_pc2(cad_folder):
241 | pc = read_ply(cad_folder)
242 | if pc.shape[0] > N_POINTS:
243 | pc = downsample_pc(pc, N_POINTS)
244 | pc = normalize_pc(pc)
245 | return pc
246 |
247 | theta_x = np.radians(90) # Rotation angle around X-axis
248 | theta_y = np.radians(90) # Rotation angle around Y-axis
249 | theta_z = np.radians(180) # Rotation angle around Z-axis
250 |
251 | # Create individual rotation matrices
252 | Rx = np.array([[1, 0, 0],
253 | [0, np.cos(theta_x), -np.sin(theta_x)],
254 | [0, np.sin(theta_x), np.cos(theta_x)]])
255 |
256 | Ry = np.array([[np.cos(theta_y), 0, np.sin(theta_y)],
257 | [0, 1, 0],
258 | [-np.sin(theta_y), 0, np.cos(theta_y)]])
259 |
260 | Rz = np.array([[np.cos(theta_z), -np.sin(theta_z), 0],
261 | [np.sin(theta_z), np.cos(theta_z), 0],
262 | [0, 0, 1]])
263 |
264 | rotation_matrix = np.dot(np.dot(Rz, Ry), Rx)
265 |
266 | def collect_pc3(cad_folder):
267 | pc = read_ply(cad_folder)
268 | if pc.shape[0] > N_POINTS:
269 | pc = downsample_pc(pc, N_POINTS)
270 | pc = normalize_pc(pc)
271 | rotated_point_cloud = np.dot(pc, rotation_matrix.T).astype(np.float32) # Transpose the rotation matrix to apply it correctly
272 | return rotated_point_cloud
273 |
274 | def load_data_with_prefix(root_folder, prefix):
275 | data_files = []
276 |
277 | # Walk through the directory tree starting from the root folder
278 | for root, dirs, files in os.walk(root_folder):
279 | for filename in files:
280 | # Check if the file ends with the specified prefix
281 | if filename.endswith(prefix):
282 | file_path = os.path.join(root, filename)
283 | data_files.append(file_path)
284 |
285 | return data_files
286 |
287 | def main():
288 | parser = argparse.ArgumentParser()
289 | parser.add_argument("--fake", type=str)
290 | parser.add_argument("--real", type=str)
291 | parser.add_argument("--n_test", type=int, default=1000)
292 | parser.add_argument("--multi", type=int, default=3)
293 | parser.add_argument("--times", type=int, default=10)
294 | parser.add_argument("--batch_size", type=int, default=64)
295 | args = parser.parse_args()
296 |
297 | print("n_test: {}, multiplier: {}, repeat times: {}".format(args.n_test, args.multi, args.times))
298 |
299 | args.output = args.fake + '_results.txt'
300 |
301 | # Load reference pcd
302 | num_cpus = multiprocessing.cpu_count()
303 | ref_pcs = []
304 | shape_paths = load_data_with_prefix(args.real, '.ply')
305 | load_iter = multiprocessing.Pool(num_cpus).imap(collect_pc2, shape_paths)
306 | for pc in tqdm(load_iter, total=len(shape_paths)):
307 | if len(pc) > 0:
308 | ref_pcs.append(pc)
309 | ref_pcs = np.stack(ref_pcs, axis=0)
310 | print("real point clouds: {}".format(ref_pcs.shape))
311 |
312 |
313 | # Load fake pcd
314 | sample_pcs = []
315 | shape_paths = load_data_with_prefix(args.fake, '.ply')
316 | load_iter = multiprocessing.Pool(num_cpus).imap(collect_pc2, shape_paths)
317 | for pc in tqdm(load_iter, total=len(shape_paths)):
318 | if len(pc) > 0:
319 | sample_pcs.append(pc)
320 | sample_pcs = np.stack(sample_pcs, axis=0)
321 |
322 | print("fake point clouds: {}".format(sample_pcs.shape))
323 |
324 | # Testing
325 | fp = open(args.output, "w")
326 | result_list = []
327 | for i in range(args.times):
328 | print("iteration {}...".format(i))
329 | select_idx = random.sample(list(range(len(sample_pcs))), int(args.multi * args.n_test))
330 | rand_sample_pcs = sample_pcs[select_idx]
331 |
332 | select_idx = random.sample(list(range(len(ref_pcs))), args.n_test)
333 | rand_ref_pcs = ref_pcs[select_idx]
334 |
335 | jsd = jsd_between_point_cloud_sets(rand_sample_pcs, rand_ref_pcs, in_unit_sphere=False)
336 | with torch.no_grad():
337 | rand_sample_pcs = torch.tensor(rand_sample_pcs).cuda()
338 | rand_ref_pcs = torch.tensor(rand_ref_pcs).cuda()
339 | result = compute_cov_mmd(rand_sample_pcs, rand_ref_pcs, batch_size=args.batch_size)
340 | result.update({"JSD": jsd})
341 |
342 | print(result)
343 | print(result, file=fp)
344 | result_list.append(result)
345 | avg_result = {}
346 | for k in result_list[0].keys():
347 | avg_result.update({"avg-" + k: np.mean([x[k] for x in result_list])})
348 | print("average result:")
349 | print(avg_result)
350 | print(avg_result, file=fp)
351 | fp.close()
352 |
353 |
354 | if __name__ == '__main__':
355 | main()
--------------------------------------------------------------------------------
/sample.py:
--------------------------------------------------------------------------------
1 | import os
2 | import yaml
3 | import torch
4 | import argparse
5 | import numpy as np
6 | from tqdm import tqdm
7 | from network import *
8 | from diffusers import DDPMScheduler, PNDMScheduler
9 | from OCC.Extend.DataExchange import write_stl_file, write_step_file
10 | from utils import (
11 | randn_tensor,
12 | compute_bbox_center_and_size,
13 | generate_random_string,
14 | construct_brep,
15 | detect_shared_vertex,
16 | detect_shared_edge,
17 | joint_optimize
18 | )
19 |
20 |
21 | text2int = {'uncond':0,
22 | 'bathtub':1,
23 | 'bed':2,
24 | 'bench':3,
25 | 'bookshelf':4,
26 | 'cabinet':5,
27 | 'chair':6,
28 | 'couch':7,
29 | 'lamp':8,
30 | 'sofa':9,
31 | 'table':10
32 | }
33 |
34 |
35 | def sample(eval_args):
36 |
37 | # Inference configuration
38 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
39 | batch_size = eval_args['batch_size']
40 | z_threshold = eval_args['z_threshold']
41 | bbox_threshold =eval_args['bbox_threshold']
42 | save_folder = eval_args['save_folder']
43 | num_surfaces = eval_args['num_surfaces']
44 | num_edges = eval_args['num_edges']
45 |
46 | if eval_args['use_cf']:
47 | class_label = torch.LongTensor([text2int[eval_args['class_label']]]*batch_size + \
48 | [text2int['uncond']]*batch_size).cuda().reshape(-1,1)
49 | w = 0.6
50 | else:
51 | class_label = None
52 |
53 | if not os.path.exists(save_folder):
54 | os.makedirs(save_folder)
55 |
56 | surfPos_model = SurfPosNet(eval_args['use_cf'])
57 | surfPos_model.load_state_dict(torch.load(eval_args['surfpos_weight']))
58 | surfPos_model = surfPos_model.to(device).eval()
59 |
60 | surfZ_model = SurfZNet(eval_args['use_cf'])
61 | surfZ_model.load_state_dict(torch.load(eval_args['surfz_weight']))
62 | surfZ_model = surfZ_model.to(device).eval()
63 |
64 | edgePos_model = EdgePosNet(eval_args['use_cf'])
65 | edgePos_model.load_state_dict(torch.load(eval_args['edgepos_weight']))
66 | edgePos_model = edgePos_model.to(device).eval()
67 |
68 | edgeZ_model = EdgeZNet(eval_args['use_cf'])
69 | edgeZ_model.load_state_dict(torch.load(eval_args['edgez_weight']))
70 | edgeZ_model = edgeZ_model.to(device).eval()
71 |
72 | surf_vae = AutoencoderKLFastDecode(in_channels=3,
73 | out_channels=3,
74 | down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D'],
75 | up_block_types= ['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D'],
76 | block_out_channels=[128, 256, 512, 512],
77 | layers_per_block=2,
78 | act_fn='silu',
79 | latent_channels=3,
80 | norm_num_groups=32,
81 | sample_size=512,
82 | )
83 | surf_vae.load_state_dict(torch.load(eval_args['surfvae_weight']), strict=False)
84 | surf_vae = surf_vae.to(device).eval()
85 |
86 | edge_vae = AutoencoderKL1DFastDecode(
87 | in_channels=3,
88 | out_channels=3,
89 | down_block_types=['DownBlock1D', 'DownBlock1D', 'DownBlock1D'],
90 | up_block_types=['UpBlock1D', 'UpBlock1D', 'UpBlock1D'],
91 | block_out_channels=[128, 256, 512],
92 | layers_per_block=2,
93 | act_fn='silu',
94 | latent_channels=3,
95 | norm_num_groups=32,
96 | sample_size=512
97 | )
98 | edge_vae.load_state_dict(torch.load(eval_args['edgevae_weight']), strict=False)
99 | edge_vae = edge_vae.to(device).eval()
100 |
101 | pndm_scheduler = PNDMScheduler(
102 | num_train_timesteps=1000,
103 | beta_schedule='linear',
104 | prediction_type='epsilon',
105 | beta_start = 0.0001,
106 | beta_end = 0.02,
107 | )
108 |
109 | ddpm_scheduler = DDPMScheduler(
110 | num_train_timesteps=1000,
111 | beta_schedule='linear',
112 | prediction_type='epsilon',
113 | beta_start = 0.0001,
114 | beta_end = 0.02,
115 | clip_sample = True,
116 | clip_sample_range=3
117 | )
118 |
119 |
120 | with torch.no_grad():
121 | with torch.cuda.amp.autocast():
122 |
123 | ###########################################
124 | # STEP 1-1: generate the surface position #
125 | ###########################################
126 | surfPos = randn_tensor((batch_size, num_surfaces, 6)).to(device)
127 |
128 | pndm_scheduler.set_timesteps(200)
129 | for t in tqdm(pndm_scheduler.timesteps[:158]):#
130 | timesteps = t.reshape(-1).cuda()
131 | if class_label is not None:
132 | _surfPos_ = surfPos.repeat(2,1,1)
133 | pred = surfPos_model(_surfPos_, timesteps, class_label)
134 | pred = pred[:batch_size] * (1+w) - pred[batch_size:] * w
135 | else:
136 | pred = surfPos_model(surfPos, timesteps, class_label)
137 | surfPos = pndm_scheduler.step(pred, t, surfPos).prev_sample
138 |
139 | # Late increase for ABC/DeepCAD (slightly more efficient)
140 | if not eval_args['use_cf']:
141 | surfPos = surfPos.repeat(1,2,1)
142 | num_surfaces *= 2
143 |
144 | ddpm_scheduler.set_timesteps(1000)
145 | for t in tqdm(ddpm_scheduler.timesteps[-250:]):
146 | timesteps = t.reshape(-1).cuda()
147 | if class_label is not None:
148 | _surfPos_ = surfPos.repeat(2,1,1)
149 | pred = surfPos_model(_surfPos_, timesteps, class_label)
150 | pred = pred[:batch_size] * (1+w) - pred[batch_size:] * w
151 | else:
152 | pred = surfPos_model(surfPos, timesteps, class_label)
153 | surfPos = ddpm_scheduler.step(pred, t, surfPos).prev_sample
154 |
155 |
156 | #######################################
157 | # STEP 1-2: remove duplicate surfaces #
158 | #######################################
159 | surfPos_deduplicate = []
160 | surfMask_deduplicate = []
161 | for ii in range(batch_size):
162 | bboxes = np.round(surfPos[ii].unflatten(-1,torch.Size([2,3])).detach().cpu().numpy(), 4)
163 | non_repeat = bboxes[:1]
164 | for bbox_idx, bbox in enumerate(bboxes):
165 | diff = np.max(np.max(np.abs(non_repeat - bbox),-1),-1)
166 | same = diff < bbox_threshold
167 | bbox_rev = bbox[::-1] # also test reverse bbox for matching
168 | diff_rev = np.max(np.max(np.abs(non_repeat - bbox_rev),-1),-1)
169 | same_rev = diff_rev < bbox_threshold
170 | if same.sum()>=1 or same_rev.sum()>=1:
171 | continue # repeat value
172 | else:
173 | non_repeat = np.concatenate([non_repeat, bbox[np.newaxis,:,:]],0)
174 | bboxes = non_repeat.reshape(len(non_repeat),-1)
175 |
176 | surf_mask = torch.zeros((1, len(bboxes))) == 1
177 | bbox_padded = torch.concat([torch.FloatTensor(bboxes), torch.zeros(num_surfaces-len(bboxes),6)])
178 | mask_padded = torch.concat([surf_mask, torch.zeros(1, num_surfaces-len(bboxes))==0], -1)
179 | surfPos_deduplicate.append(bbox_padded)
180 | surfMask_deduplicate.append(mask_padded)
181 |
182 | surfPos = torch.stack(surfPos_deduplicate).cuda()
183 | surfMask = torch.vstack(surfMask_deduplicate).cuda()
184 |
185 |
186 | #################################
187 | # STEP 1-3: generate surface z #
188 | #################################
189 | surfZ = randn_tensor((batch_size, num_surfaces, 48)).to(device)
190 |
191 | pndm_scheduler.set_timesteps(200)
192 | for t in tqdm(pndm_scheduler.timesteps):
193 | timesteps = t.reshape(-1).cuda()
194 | if class_label is not None:
195 | _surfZ_ = surfZ.repeat(2,1,1)
196 | _surfPos_ = surfPos.repeat(2,1,1)
197 | _surfMask_ = surfMask.repeat(2,1)
198 | pred = surfZ_model(_surfZ_, timesteps, _surfPos_, _surfMask_, class_label)
199 | pred = pred[:batch_size] * (1+w) - pred[batch_size:] * w
200 | else:
201 | pred = surfZ_model(surfZ, timesteps, surfPos, surfMask, class_label)
202 | surfZ = pndm_scheduler.step(pred, t, surfZ).prev_sample
203 |
204 |
205 | ########################################
206 | # STEP 2-1: generate the edge position #
207 | ########################################
208 | edgePos = randn_tensor((batch_size, num_surfaces, num_edges, 6)).cuda()
209 |
210 | pndm_scheduler.set_timesteps(200)
211 | for t in tqdm(pndm_scheduler.timesteps[:158]):
212 | timesteps = t.reshape(-1).cuda()
213 | if class_label is not None:
214 | _surfZ_ = surfZ.repeat(2,1,1)
215 | _surfPos_ = surfPos.repeat(2,1,1)
216 | _surfMask_ = surfMask.repeat(2,1)
217 | _edgePos_ = edgePos.repeat(2,1,1,1)
218 | noise_pred = edgePos_model(_edgePos_, timesteps, _surfPos_, _surfZ_, _surfMask_, class_label)
219 | noise_pred = noise_pred[:batch_size] * (1+w) - noise_pred[batch_size:] * w
220 | else:
221 | noise_pred = edgePos_model(edgePos, timesteps, surfPos, surfZ, surfMask, class_label)
222 | edgePos = pndm_scheduler.step(noise_pred, t, edgePos).prev_sample
223 |
224 | ddpm_scheduler.set_timesteps(1000)
225 | for t in tqdm(ddpm_scheduler.timesteps[-250:]):
226 | timesteps = t.reshape(-1).cuda()
227 | if class_label is not None:
228 | _surfZ_ = surfZ.repeat(2,1,1)
229 | _surfPos_ = surfPos.repeat(2,1,1)
230 | _surfMask_ = surfMask.repeat(2,1)
231 | _edgePos_ = edgePos.repeat(2,1,1,1)
232 | noise_pred = edgePos_model(_edgePos_, timesteps, _surfPos_, _surfZ_, _surfMask_, class_label)
233 | noise_pred = noise_pred[:batch_size] * (1+w) - noise_pred[batch_size:] * w
234 | else:
235 | noise_pred = edgePos_model(edgePos, timesteps, surfPos, surfZ, surfMask, class_label)
236 | edgePos = ddpm_scheduler.step(noise_pred, t, edgePos).prev_sample
237 |
238 |
239 | ####################################################
240 | # STEP 2-2: remove duplicate edges per face (bbox) #
241 | ####################################################
242 | edgeM = surfMask.unsqueeze(-1).repeat(1, 1, num_edges)
243 |
244 | for ii in range(batch_size):
245 | edge_bboxs = edgePos[ii][~surfMask[ii]].detach().cpu().numpy()
246 |
247 | for surf_idx, bboxes in enumerate(edge_bboxs):
248 | bboxes = bboxes.reshape(len(bboxes),2,3)
249 | valid_bbox = bboxes[0:1]
250 | for bbox_idx, bbox in enumerate(bboxes):
251 | diff = np.max(np.max(np.abs(valid_bbox - bbox),-1),-1)
252 | bbox_rev = bbox[::-1] # also test reverse bbox for matching
253 | diff_rev = np.max(np.max(np.abs(valid_bbox - bbox_rev),-1),-1)
254 | same = diff < bbox_threshold
255 | same_rev = diff_rev < bbox_threshold
256 | if same.sum()>=1 or same_rev.sum()>=1:
257 | edgeM[ii, surf_idx, bbox_idx] = True
258 | continue # repeat value
259 | else:
260 | valid_bbox = np.concatenate([valid_bbox, bbox[np.newaxis,:,:]],0)
261 | edgeM[ii, surf_idx, 0] = False # set first one to False
262 |
263 |
264 | ##############################
265 | # STEP 2-3: generate edge zv #
266 | ##############################
267 | edgeZV = randn_tensor((batch_size, num_surfaces, num_edges, 18)).cuda()
268 |
269 | pndm_scheduler.set_timesteps(200)
270 | for t in tqdm(pndm_scheduler.timesteps):
271 | timesteps = t.reshape(-1).cuda()
272 | if class_label is not None:
273 | _surfZ_ = surfZ.repeat(2,1,1)
274 | _surfPos_ = surfPos.repeat(2,1,1)
275 | _edgePos_ = edgePos.repeat(2,1,1,1)
276 | _edgeM_ = edgeM.repeat(2,1,1)
277 | _edgeZV_ = edgeZV.repeat(2,1,1,1)
278 | noise_pred = edgeZ_model(_edgeZV_, timesteps, _edgePos_, _surfPos_, _surfZ_, _edgeM_, class_label)
279 | noise_pred = noise_pred[:batch_size] * (1+w) - noise_pred[batch_size:] * w
280 | else:
281 | noise_pred = edgeZ_model(edgeZV, timesteps, edgePos, surfPos, surfZ, edgeM, class_label)
282 | edgeZV = pndm_scheduler.step(noise_pred, t, edgeZV).prev_sample
283 |
284 | edgeZV[edgeM] = 0 # set removed data to 0
285 | edge_z = edgeZV[:,:,:,:12]
286 | edgeV = edgeZV[:,:,:,12:].detach().cpu().numpy()
287 |
288 | # Decode the surfaces
289 | surf_ncs = surf_vae(surfZ.unflatten(-1,torch.Size([16,3])).flatten(0,1).permute(0,2,1).unflatten(-1,torch.Size([4,4])))
290 | surf_ncs = surf_ncs.permute(0,2,3,1).unflatten(0, torch.Size([batch_size, num_surfaces])).detach().cpu().numpy()
291 |
292 | # Decode the edges
293 | edge_ncs = edge_vae(edge_z.unflatten(-1,torch.Size([4,3])).reshape(-1,4,3).permute(0,2,1))
294 | edge_ncs = edge_ncs.permute(0,2,1).reshape(batch_size, num_surfaces, num_edges, 32, 3).detach().cpu().numpy()
295 |
296 |
297 | edge_mask = edgeM.detach().cpu().numpy()
298 | edge_pos = edgePos.detach().cpu().numpy() / 3.0
299 | surfPos = surfPos.detach().cpu().numpy() / 3.0
300 |
301 |
302 | #############################################
303 | ### STEP 3: Post-process (per-single CAD) ###
304 | #############################################
305 | for batch_idx in range(batch_size):
306 | # Per cad (not including invalid faces)
307 | surfMask_cad = surfMask[batch_idx].detach().cpu().numpy()
308 | edge_mask_cad = edge_mask[batch_idx][~surfMask_cad]
309 | edge_pos_cad = edge_pos[batch_idx][~surfMask_cad]
310 | edge_ncs_cad = edge_ncs[batch_idx][~surfMask_cad]
311 | edgeV_cad = edgeV[batch_idx][~surfMask_cad]
312 | edge_z_cad = edge_z[batch_idx][~surfMask[batch_idx]].detach().cpu().numpy()[~edge_mask_cad]
313 | surf_z_cad = surfZ[batch_idx][~surfMask[batch_idx]].detach().cpu().numpy()
314 | surf_pos_cad = surfPos[batch_idx][~surfMask_cad]
315 |
316 | # Retrieve vertices based on edge start/end
317 | edgeV_bbox = []
318 | for bbox, ncs, mask in zip(edge_pos_cad, edge_ncs_cad, edge_mask_cad):
319 | epos = bbox[~mask]
320 | edge = ncs[~mask]
321 | bbox_startends = []
322 | for bb, ee in zip(epos, edge):
323 | bcenter, bsize = compute_bbox_center_and_size(bb[0:3], bb[3:])
324 | wcs = ee*(bsize/2) + bcenter
325 | bbox_start_end = wcs[[0,-1]]
326 | bbox_start_end = bbox_start_end.reshape(2,3)
327 | bbox_startends.append(bbox_start_end.reshape(1,2,3))
328 | bbox_startends = np.vstack(bbox_startends)
329 | edgeV_bbox.append(bbox_startends)
330 |
331 | ### 3-1: Detect shared vertices ###
332 | try:
333 | unique_vertices, new_vertex_dict = detect_shared_vertex(edgeV_cad, edge_mask_cad, edgeV_bbox)
334 | except Exception as e:
335 | print('Vertex detection failed...')
336 | continue
337 |
338 | ### 3-2: Detect shared edges ###
339 | try:
340 | unique_faces, unique_edges, FaceEdgeAdj, EdgeVertexAdj = detect_shared_edge(unique_vertices, new_vertex_dict, edge_z_cad, surf_z_cad, z_threshold, edge_mask_cad)
341 | except Exception as e:
342 | print('Edge detection failed...')
343 | continue
344 |
345 | # Decode unique faces / edges
346 | with torch.no_grad():
347 | with torch.cuda.amp.autocast():
348 | surf_ncs_cad = surf_vae(torch.FloatTensor(unique_faces).cuda().unflatten(-1,torch.Size([16,3])).permute(0,2,1).unflatten(-1,torch.Size([4,4])))
349 | surf_ncs_cad = surf_ncs_cad.permute(0,2,3,1).detach().cpu().numpy()
350 | edge_ncs_cad = edge_vae(torch.FloatTensor(unique_edges).cuda().unflatten(-1,torch.Size([4,3])).permute(0,2,1))
351 | edge_ncs_cad = edge_ncs_cad.permute(0,2,1).detach().cpu().numpy()
352 |
353 | #### 3-3: Joint Optimize ###
354 | num_edge = len(edge_ncs_cad)
355 | num_surf = len(surf_ncs_cad)
356 | surf_wcs, edge_wcs = joint_optimize(surf_ncs_cad, edge_ncs_cad, surf_pos_cad, unique_vertices, EdgeVertexAdj, FaceEdgeAdj, num_edge, num_surf)
357 |
358 | #### 3-4: Build the B-rep ###
359 | try:
360 | solid = construct_brep(surf_wcs, edge_wcs, FaceEdgeAdj, EdgeVertexAdj)
361 | except Exception as e:
362 | print('B-rep rebuild failed...')
363 | continue
364 |
365 | # Save CAD model
366 | random_string = generate_random_string(15)
367 | write_step_file(solid, f'{save_folder}/{random_string}_{batch_idx}.step')
368 | write_stl_file(solid, f'{save_folder}/{random_string}_{batch_idx}.stl', linear_deflection=0.001, angular_deflection=0.5)
369 | return
370 |
371 |
372 | if __name__ == "__main__":
373 | parser = argparse.ArgumentParser()
374 | parser.add_argument("--mode", type=str, choices=['abc', 'deepcad', 'furniture'], default='abc',
375 | help="Choose between evaluation mode [abc/deepcad/furniture] (default: abc)")
376 | args = parser.parse_args()
377 |
378 | # Load evaluation config
379 | with open('eval_config.yaml', 'r') as file:
380 | config = yaml.safe_load(file)
381 | eval_args = config[args.mode]
382 |
383 | while(True):
384 | sample(eval_args)
--------------------------------------------------------------------------------
/dataset.py:
--------------------------------------------------------------------------------
1 | import os
2 | import math
3 | import pickle
4 | import torch
5 | import numpy as np
6 | from tqdm import tqdm
7 | import random
8 | from multiprocessing.pool import Pool
9 | from utils import (
10 | rotate_point_cloud,
11 | bbox_corners,
12 | rotate_axis,
13 | get_bbox,
14 | pad_repeat,
15 | pad_zero,
16 | )
17 |
18 | # furniture class labels
19 | text2int = {'bathtub':0, 'bed':1, 'bench':2, 'bookshelf':3,'cabinet':4, 'chair':5, 'couch':6, 'lamp':7, 'sofa':8, 'table':9}
20 |
21 |
22 | def filter_data(data):
23 | """
24 | Helper function to check if a brep needs to be included
25 | in the training data or not
26 | """
27 | data_path, max_face, max_edge, scaled_value, threshold_value, data_class = data
28 | # Load data
29 | with open(data_path, "rb") as tf:
30 | data = pickle.load(tf)
31 | _, _, _, _, _, _, _, faceEdge_adj, surf_bbox, edge_bbox, _, _ = data.values()
32 |
33 | skip = False
34 |
35 | # Skip over max size data
36 | if len(surf_bbox)>max_face:
37 | skip = True
38 |
39 | for surf_edges in faceEdge_adj:
40 | if len(surf_edges)>max_edge:
41 | skip = True
42 |
43 | # Skip surfaces too close to each other
44 | surf_bbox = surf_bbox * scaled_value # make bbox difference larger
45 |
46 | _surf_bbox_ = surf_bbox.reshape(len(surf_bbox),2,3)
47 | non_repeat = _surf_bbox_[:1]
48 | for bbox in _surf_bbox_:
49 | diff = np.max(np.max(np.abs(non_repeat - bbox),-1),-1)
50 | same = diff < threshold_value
51 | if same.sum()>=1:
52 | continue # repeat value
53 | else:
54 | non_repeat = np.concatenate([non_repeat, bbox[np.newaxis,:,:]],0)
55 | if len(non_repeat) != len(_surf_bbox_):
56 | skip = True
57 |
58 | # Skip edges too close to each other
59 | se_bbox = []
60 | for adj in faceEdge_adj:
61 | if len(edge_bbox[adj]) == 0:
62 | skip = True
63 | se_bbox.append(edge_bbox[adj] * scaled_value)
64 |
65 | for bbb in se_bbox:
66 | _edge_bbox_ = bbb.reshape(len(bbb),2,3)
67 | non_repeat = _edge_bbox_[:1]
68 | for bbox in _edge_bbox_:
69 | diff = np.max(np.max(np.abs(non_repeat - bbox),-1),-1)
70 | same = diff < threshold_value
71 | if same.sum()>=1:
72 | continue # repeat value
73 | else:
74 | non_repeat = np.concatenate([non_repeat, bbox[np.newaxis,:,:]],0)
75 | if len(non_repeat) != len(_edge_bbox_):
76 | skip = True
77 |
78 | if skip:
79 | return None, None
80 | else:
81 | return data_path, data_class
82 |
83 |
84 | def load_data(input_data, input_list, validate, args):
85 | # Filter data list
86 | with open(input_list, "rb") as tf:
87 | if validate:
88 | data_list = pickle.load(tf)['val']
89 | else:
90 | data_list = pickle.load(tf)['train']
91 |
92 | data_paths = []
93 | data_classes = []
94 | for uid in data_list:
95 | try:
96 | path = os.path.join(input_data, str(math.floor(int(uid.split('.')[0])/10000)).zfill(4), uid)
97 | class_label = -1 # unconditional generation (abc/deepcad)
98 | except Exception:
99 | path = os.path.join(input_data, uid)
100 | class_label = text2int[uid.split('/')[0]] # conditional generation (furniture)
101 | data_paths.append(path)
102 | data_classes.append(class_label)
103 |
104 | # Filter data in parallel
105 | loaded_data = []
106 | params = zip(data_paths, [args.max_face]*len(data_list), [args.max_edge]*len(data_list),
107 | [args.bbox_scaled]*len(data_list), [args.threshold]*len(data_list), data_classes)
108 | convert_iter = Pool(os.cpu_count()).imap(filter_data, params)
109 | for data_path, data_class in tqdm(convert_iter, total=len(data_list)):
110 | if data_path is not None:
111 | if data_class<0: # abc or deepcad
112 | loaded_data.append(data_path)
113 | else: # furniture
114 | loaded_data.append((data_path,data_class))
115 |
116 | print(f'Processed {len(loaded_data)}/{len(data_list)}')
117 | return loaded_data
118 |
119 |
120 | class SurfData(torch.utils.data.Dataset):
121 | """ Surface VAE Dataloader """
122 | def __init__(self, input_data, input_list, validate=False, aug=False):
123 | self.validate = validate
124 | self.aug = aug
125 |
126 | # Load validation data
127 | if self.validate:
128 | print('Loading validation data...')
129 | with open(input_list, "rb") as tf:
130 | data_list = pickle.load(tf)['val']
131 |
132 | datas = []
133 | for uid in data_list:
134 | try:
135 | path = os.path.join(input_data, str(math.floor(int(uid.split('.')[0])/10000)).zfill(4), uid)
136 | except Exception:
137 | path = os.path.join(input_data, uid)
138 |
139 | with open(path, "rb") as tf:
140 | data = pickle.load(tf)
141 | _, _, surf_uv, _, _, _, _, _, _, _, _, _ = data.values()
142 | datas.append(surf_uv)
143 | self.data = np.vstack(datas)
144 |
145 | # Load training data (deduplicated)
146 | else:
147 | print('Loading training data...')
148 | with open(input_list, "rb") as tf:
149 | self.data = pickle.load(tf)
150 |
151 | print(len(self.data))
152 | return
153 |
154 | def __len__(self):
155 | return len(self.data)
156 |
157 | def __getitem__(self, index):
158 | surf_uv = self.data[index]
159 | if np.random.rand()>0.5 and self.aug:
160 | for axis in ['x', 'y', 'z']:
161 | angle = random.choice([90, 180, 270])
162 | surf_uv = rotate_point_cloud(surf_uv.reshape(-1, 3), angle, axis).reshape(32, 32, 3)
163 | return torch.FloatTensor(surf_uv)
164 |
165 |
166 | class EdgeData(torch.utils.data.Dataset):
167 | """ Edge VAE Dataloader """
168 | def __init__(self, input_data, input_list, validate=False, aug=False):
169 | self.validate = validate
170 | self.aug = aug
171 |
172 | # Load validation data
173 | if self.validate:
174 | print('Loading validation data...')
175 | with open(input_list, "rb") as tf:
176 | data_list = pickle.load(tf)['val']
177 |
178 | datas = []
179 | for uid in tqdm(data_list):
180 | try:
181 | path = os.path.join(input_data, str(math.floor(int(uid.split('.')[0])/10000)).zfill(4), uid)
182 | except Exception:
183 | path = os.path.join(input_data, uid)
184 |
185 | with open(path, "rb") as tf:
186 | data = pickle.load(tf)
187 |
188 | _, _, _, edge_u, _, _, _, _, _, _, _, _ = data.values()
189 | datas.append(edge_u)
190 | self.data = np.vstack(datas)
191 |
192 | # Load training data (deduplicated)
193 | else:
194 | print('Loading training data...')
195 | with open(input_list, "rb") as tf:
196 | self.data = pickle.load(tf)
197 |
198 | print(len(self.data))
199 | return
200 |
201 | def __len__(self):
202 | return len(self.data)
203 |
204 | def __getitem__(self, index):
205 | edge_u = self.data[index]
206 | # Data augmentation, randomly rotate 50% of the times
207 | if np.random.rand()>0.5 and self.aug:
208 | for axis in ['x', 'y', 'z']:
209 | angle = random.choice([90, 180, 270])
210 | edge_u = rotate_point_cloud(edge_u, angle, axis)
211 | return torch.FloatTensor(edge_u)
212 |
213 |
214 | class SurfPosData(torch.utils.data.Dataset):
215 | """ Surface position (3D bbox) Dataloader """
216 | def __init__(self, input_data, input_list, validate=False, aug=False, args=None):
217 | self.max_face = args.max_face
218 | self.max_edge = args.max_edge
219 | self.bbox_scaled = args.bbox_scaled
220 | self.aug = aug
221 | # Load data
222 | self.data = load_data(input_data, input_list, validate, args)
223 | # Inflate furniture x50 times for training
224 | if len(self.data)<2000 and not validate:
225 | self.data = self.data*50
226 | return
227 |
228 | def __len__(self):
229 | return len(self.data)
230 |
231 | def __getitem__(self, index):
232 | # Load data
233 | data_class = None
234 | if isinstance(self.data[index], tuple):
235 | data_path, data_class = self.data[index]
236 | else:
237 | data_path = self.data[index]
238 |
239 | with open(data_path, "rb") as tf:
240 | data = pickle.load(tf)
241 | _, _, _, _, _, _, _, _, surf_pos, _, _, _ = data.values()
242 |
243 | # Data augmentation
244 | random_num = np.random.rand()
245 |
246 | if random_num>0.5 and self.aug:
247 | # Get all eight corners
248 | surfpos_corners = bbox_corners(surf_pos)
249 |
250 | # Random rotation
251 | for axis in ['x', 'y', 'z']:
252 | angle = random.choice([90, 180, 270])
253 | surfpos_corners = rotate_axis(surfpos_corners, angle, axis, normalized=True)
254 |
255 | # Re-compute the bottom left and top right corners
256 | surf_pos = get_bbox(surfpos_corners)
257 | surf_pos = surf_pos.reshape(len(surf_pos),6)
258 |
259 | # Make bbox range larger
260 | surf_pos = surf_pos * self.bbox_scaled
261 |
262 | # Randomly shuffle the sequence
263 | random_indices = np.random.permutation(surf_pos.shape[0])
264 | surf_pos = surf_pos[random_indices]
265 |
266 | # Padding
267 | surf_pos = pad_repeat(surf_pos, self.max_face)
268 |
269 | # Randomly shuffle the sequence
270 | random_indices = np.random.permutation(surf_pos.shape[0])
271 | surf_pos = surf_pos[random_indices]
272 |
273 | if data_class is not None:
274 | return (
275 | torch.FloatTensor(surf_pos),
276 | torch.LongTensor([data_class+1]) # add 1, class 0 = uncond (furniture)
277 | )
278 | else:
279 | return torch.FloatTensor(surf_pos) # abc or deepcad
280 |
281 |
282 | class SurfZData(torch.utils.data.Dataset):
283 | """ Surface latent geometry Dataloader """
284 | def __init__(self, input_data, input_list, validate=False, aug=False, args=None):
285 | self.max_face = args.max_face
286 | self.max_edge = args.max_edge
287 | self.bbox_scaled = args.bbox_scaled
288 | self.aug = aug
289 | # Load data
290 | self.data = load_data(input_data, input_list, validate, args)
291 | # Inflate furniture x50 times for training
292 | if len(self.data)<2000 and not validate:
293 | self.data = self.data*50
294 | return
295 |
296 | def __len__(self):
297 | return len(self.data)
298 |
299 | def __getitem__(self, index):
300 | # Load data
301 | data_class = None
302 | if isinstance(self.data[index], tuple):
303 | data_path, data_class = self.data[index]
304 | else:
305 | data_path = self.data[index]
306 |
307 | with open(data_path, "rb") as tf:
308 | data = pickle.load(tf)
309 | _, _, surf_ncs, _, _, _, _, _, surf_pos, _, _, _ = data.values()
310 |
311 | # Data augmentation
312 | random_num = np.random.rand()
313 |
314 | if random_num>0.5 and self.aug:
315 | # Get all eight corners
316 | surfpos_corners = bbox_corners(surf_pos)
317 |
318 | # Random rotation
319 | for axis in ['x', 'y', 'z']:
320 | angle = random.choice([90, 180, 270])
321 | surfpos_corners = rotate_axis(surfpos_corners, angle, axis, normalized=True)
322 | surf_ncs = rotate_axis(surf_ncs, angle, axis, normalized=False)
323 |
324 | # Re-compute the bottom left and top right corners
325 | surf_pos = get_bbox(surfpos_corners)
326 | surf_pos = surf_pos.reshape(len(surf_pos),6)
327 |
328 | # Make bbox range larger
329 | surf_pos = surf_pos * self.bbox_scaled
330 |
331 | # Randomly shuffle the sequence
332 | random_indices = np.random.permutation(surf_pos.shape[0])
333 | surf_pos = surf_pos[random_indices]
334 | surf_ncs = surf_ncs[random_indices]
335 |
336 | # Pad data
337 | surf_pos, surf_mask = pad_zero(surf_pos, self.max_face, return_mask=True)
338 | surf_ncs = pad_zero(surf_ncs, self.max_face)
339 |
340 | if data_class is not None:
341 | return (
342 | torch.FloatTensor(surf_pos),
343 | torch.FloatTensor(surf_ncs),
344 | torch.BoolTensor(surf_mask),
345 | torch.LongTensor([data_class+1]) # add 1, class 0 = uncond (furniture)
346 | )
347 | else:
348 | return (
349 | torch.FloatTensor(surf_pos),
350 | torch.FloatTensor(surf_ncs),
351 | torch.BoolTensor(surf_mask),
352 | ) # abc or deepcad
353 |
354 |
355 | class EdgePosData(torch.utils.data.Dataset):
356 | """ Edge Position (3D bbox) Dataloader """
357 | def __init__(self, input_data, input_list, validate=False, aug=False, args=None):
358 | self.max_face = args.max_face
359 | self.max_edge = args.max_edge
360 | self.bbox_scaled = args.bbox_scaled
361 | self.aug = aug
362 | self.data = []
363 | # Load data
364 | self.data = load_data(input_data, input_list, validate, args)
365 | # Inflate furniture x50 times for training
366 | if len(self.data)<2000 and not validate:
367 | self.data = self.data*50
368 | return
369 |
370 | def __len__(self):
371 | return len(self.data)
372 |
373 | def __getitem__(self, index):
374 | # Load data
375 | data_class = None
376 | if isinstance(self.data[index], tuple):
377 | data_path, data_class = self.data[index]
378 | else:
379 | data_path = self.data[index]
380 |
381 | with open(data_path, "rb") as tf:
382 | data = pickle.load(tf)
383 |
384 | _, _, surf_ncs, _, _, _, _, faceEdge_adj, surf_pos, edge_pos, _, _ = data.values()
385 |
386 | # Data augmentation
387 | random_num = np.random.rand()
388 | if random_num > 0.5 and self.aug:
389 | # Get all eight corners
390 | surfpos_corners = bbox_corners(surf_pos)
391 | edgepos_corners = bbox_corners(edge_pos)
392 |
393 | # Random rotation
394 | for axis in ['x', 'y', 'z']:
395 | angle = random.choice([90, 180, 270])
396 | surfpos_corners = rotate_axis(surfpos_corners, angle, axis, normalized=True)
397 | edgepos_corners = rotate_axis(edgepos_corners, angle, axis, normalized=True)
398 | surf_ncs = rotate_axis(surf_ncs, angle, axis, normalized=False)
399 |
400 | # Re-compute the bottom left and top right corners
401 | surf_pos = get_bbox(surfpos_corners)
402 | surf_pos = surf_pos.reshape(len(surf_pos),6)
403 | edge_pos = get_bbox(edgepos_corners)
404 | edge_pos = edge_pos.reshape(len(edge_pos),6)
405 |
406 | # Increase bbox value range
407 | surf_pos = surf_pos * self.bbox_scaled
408 | edge_pos = edge_pos * self.bbox_scaled
409 |
410 | # Mating duplication
411 | edge_pos_duplicated = []
412 | for adj in faceEdge_adj:
413 | edge_pos_duplicated.append(edge_pos[adj])
414 |
415 | # Randomly shuffle the edges per face
416 | edge_pos_new = []
417 | for pos in edge_pos_duplicated:
418 | random_indices = np.random.permutation(pos.shape[0])
419 | pos = pos[random_indices]
420 | pos = pad_repeat(pos, self.max_edge) #make sure some values are always repeated
421 | random_indices = np.random.permutation(pos.shape[0])
422 | pos = pos[random_indices]
423 | edge_pos_new.append(pos)
424 | edge_pos = np.stack(edge_pos_new)
425 |
426 | # Randomly shuffle the face sequence
427 | random_indices = np.random.permutation(surf_pos.shape[0])
428 | surf_pos = surf_pos[random_indices]
429 | edge_pos = edge_pos[random_indices]
430 | surf_ncs = surf_ncs[random_indices]
431 |
432 | # Padding
433 | surf_pos, surf_mask = pad_zero(surf_pos, self.max_face, return_mask=True)
434 | surf_ncs = pad_zero(surf_ncs, self.max_face)
435 | edge_pos = pad_zero(edge_pos, self.max_face)
436 |
437 | if data_class is not None:
438 | return (
439 | torch.FloatTensor(edge_pos),
440 | torch.FloatTensor(surf_ncs),
441 | torch.FloatTensor(surf_pos),
442 | torch.BoolTensor(surf_mask),
443 | torch.LongTensor([data_class+1]) # add 1, class 0 = uncond (furniture)
444 | )
445 | else:
446 | return (
447 | torch.FloatTensor(edge_pos),
448 | torch.FloatTensor(surf_ncs),
449 | torch.FloatTensor(surf_pos),
450 | torch.BoolTensor(surf_mask),
451 | )# abc or deepcad
452 |
453 |
454 |
455 | class EdgeZData(torch.utils.data.Dataset):
456 | """ Edge Latent z Dataloader """
457 | def __init__(self, input_data, input_list, validate=False, aug=False, args=None):
458 | self.max_face = args.max_face
459 | self.max_edge = args.max_edge
460 | self.bbox_scaled = args.bbox_scaled
461 | self.aug = aug
462 | self.data = []
463 | # Load data
464 | self.data = load_data(input_data, input_list, validate, args)
465 | # Inflate furniture x50 times for training
466 | if len(self.data)<2000 and not validate:
467 | self.data = self.data*50
468 | return
469 |
470 | def __len__(self):
471 | return len(self.data)
472 |
473 | def __getitem__(self, index):
474 | # Load data
475 | data_class = None
476 | if isinstance(self.data[index], tuple):
477 | data_path, data_class = self.data[index]
478 | else:
479 | data_path = self.data[index]
480 |
481 | with open(data_path, "rb") as tf:
482 | data = pickle.load(tf)
483 |
484 | _, _, surf_ncs, edge_ncs, corner_wcs, _, _, faceEdge_adj, surf_pos, edge_pos, _, _ = data.values()
485 |
486 | # Data augmentation
487 | random_num = np.random.rand()
488 | if random_num > 0.5 and self.aug:
489 | # Get all eight corners
490 | surfpos_corners = bbox_corners(surf_pos)
491 | edgepos_corners = bbox_corners(edge_pos)
492 |
493 | # Random rotation
494 | for axis in ['x', 'y', 'z']:
495 | angle = random.choice([90, 180, 270])
496 | surfpos_corners = rotate_axis(surfpos_corners, angle, axis, normalized=True)
497 | edgepos_corners = rotate_axis(edgepos_corners, angle, axis, normalized=True)
498 | corner_wcs = rotate_axis(corner_wcs, angle, axis, normalized=True)
499 | surf_ncs = rotate_axis(surf_ncs, angle, axis, normalized=False)
500 | edge_ncs = rotate_axis(edge_ncs, angle, axis, normalized=False)
501 |
502 | # Re-compute the bottom left and top right corners
503 | surf_pos = get_bbox(surfpos_corners)
504 | surf_pos = surf_pos.reshape(len(surf_pos),6)
505 | edge_pos = get_bbox(edgepos_corners)
506 | edge_pos = edge_pos.reshape(len(edge_pos),6)
507 |
508 | # Increase value range
509 | surf_pos = surf_pos * self.bbox_scaled
510 | edge_pos = edge_pos * self.bbox_scaled
511 | corner_wcs = corner_wcs * self.bbox_scaled
512 |
513 | # Mating duplication
514 | edge_pos_duplicated = []
515 | vertex_pos_duplicated = []
516 | edge_ncs_duplicated = []
517 | for adj in faceEdge_adj:
518 | edge_ncs_duplicated.append(edge_ncs[adj])
519 | edge_pos_duplicated.append(edge_pos[adj])
520 | corners = corner_wcs[adj]
521 | corners_sorted = []
522 | for corner in corners:
523 | sorted_indices = np.lexsort((corner[:, 2], corner[:, 1], corner[:, 0]))
524 | corners_sorted.append(corner[sorted_indices].flatten()) # 1 x 6 corner pos
525 | corners = np.stack(corners_sorted)
526 | vertex_pos_duplicated.append(corners)
527 |
528 | # Edge Shuffle and Padding
529 | edge_pos_new = []
530 | edge_ncs_new = []
531 | vert_pos_new = []
532 | edge_mask = []
533 | for pos, ncs, vert in zip(edge_pos_duplicated, edge_ncs_duplicated, vertex_pos_duplicated):
534 | random_indices = np.random.permutation(pos.shape[0])
535 | pos = pos[random_indices]
536 | ncs = ncs[random_indices]
537 | vert = vert[random_indices]
538 |
539 | pos, mask = pad_zero(pos, self.max_edge, return_mask=True)
540 | ncs = pad_zero(ncs, self.max_edge)
541 | vert = pad_zero(vert, self.max_edge)
542 |
543 | edge_pos_new.append(pos)
544 | edge_ncs_new.append(ncs)
545 | edge_mask.append(mask)
546 | vert_pos_new.append(vert)
547 |
548 | edge_pos = np.stack(edge_pos_new)
549 | edge_ncs = np.stack(edge_ncs_new)
550 | edge_mask = np.stack(edge_mask)
551 | vertex_pos = np.stack(vert_pos_new)
552 |
553 | # Face Shuffle and Padding
554 | random_indices = np.random.permutation(surf_pos.shape[0])
555 | surf_pos = surf_pos[random_indices]
556 | edge_pos = edge_pos[random_indices]
557 | surf_ncs = surf_ncs[random_indices]
558 | edge_ncs = edge_ncs[random_indices]
559 | edge_mask = edge_mask[random_indices]
560 | vertex_pos = vertex_pos[random_indices]
561 |
562 | # Padding
563 | surf_pos = pad_zero(surf_pos, self.max_face)
564 | surf_ncs = pad_zero(surf_ncs, self.max_face)
565 | edge_pos = pad_zero(edge_pos, self.max_face)
566 | edge_ncs = pad_zero(edge_ncs, self.max_face)
567 | vertex_pos = pad_zero(vertex_pos, self.max_face)
568 | padding = np.zeros((self.max_face-len(edge_mask), *edge_mask.shape[1:]))==0
569 | edge_mask = np.concatenate([edge_mask, padding], 0)
570 |
571 | if data_class is not None:
572 | return (
573 | torch.FloatTensor(edge_ncs),
574 | torch.FloatTensor(edge_pos),
575 | torch.BoolTensor(edge_mask),
576 | torch.FloatTensor(surf_ncs),
577 | torch.FloatTensor(surf_pos),
578 | torch.FloatTensor(vertex_pos),
579 | torch.LongTensor([data_class+1]) # add 1, class 0 = uncond (furniture)
580 | )
581 | else:
582 | return (
583 | torch.FloatTensor(edge_ncs),
584 | torch.FloatTensor(edge_pos),
585 | torch.BoolTensor(edge_mask),
586 | torch.FloatTensor(surf_ncs),
587 | torch.FloatTensor(surf_pos),
588 | torch.FloatTensor(vertex_pos), # uncond deepcad/abc
589 | )
590 |
591 |
--------------------------------------------------------------------------------
/LICENSE_GPL:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import math
3 | import torch
4 | import torch.nn as nn
5 | import random
6 | import string
7 | import argparse
8 | from chamferdist import ChamferDistance
9 | from mpl_toolkits.mplot3d.art3d import Poly3DCollection
10 | from typing import List, Optional, Tuple, Union
11 |
12 | from OCC.Core.gp import gp_Pnt, gp_Pnt
13 | from OCC.Core.TColgp import TColgp_Array2OfPnt
14 | from OCC.Core.GeomAPI import GeomAPI_PointsToBSplineSurface, GeomAPI_PointsToBSpline
15 | from OCC.Core.GeomAbs import GeomAbs_C2
16 | from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeWire, BRepBuilderAPI_MakeFace, BRepBuilderAPI_MakeEdge
17 | from OCC.Extend.TopologyUtils import TopologyExplorer, WireExplorer
18 | from OCC.Core.TColgp import TColgp_Array1OfPnt
19 | from OCC.Core.gp import gp_Pnt
20 | from OCC.Core.ShapeFix import ShapeFix_Face, ShapeFix_Wire, ShapeFix_Edge
21 | from OCC.Core.ShapeAnalysis import ShapeAnalysis_Wire
22 | from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_Sewing, BRepBuilderAPI_MakeSolid
23 |
24 |
25 | def generate_random_string(length):
26 | characters = string.ascii_letters + string.digits # You can include other characters if needed
27 | random_string = ''.join(random.choice(characters) for _ in range(length))
28 | return random_string
29 |
30 |
31 | def get_bbox_norm(point_cloud):
32 | # Find the minimum and maximum coordinates along each axis
33 | min_x = np.min(point_cloud[:, 0])
34 | max_x = np.max(point_cloud[:, 0])
35 |
36 | min_y = np.min(point_cloud[:, 1])
37 | max_y = np.max(point_cloud[:, 1])
38 |
39 | min_z = np.min(point_cloud[:, 2])
40 | max_z = np.max(point_cloud[:, 2])
41 |
42 | # Create the 3D bounding box using the min and max values
43 | min_point = np.array([min_x, min_y, min_z])
44 | max_point = np.array([max_x, max_y, max_z])
45 | return np.linalg.norm(max_point - min_point)
46 |
47 |
48 | def compute_bbox_center_and_size(min_corner, max_corner):
49 | # Calculate the center
50 | center_x = (min_corner[0] + max_corner[0]) / 2
51 | center_y = (min_corner[1] + max_corner[1]) / 2
52 | center_z = (min_corner[2] + max_corner[2]) / 2
53 | center = np.array([center_x, center_y, center_z])
54 | # Calculate the size
55 | size_x = max_corner[0] - min_corner[0]
56 | size_y = max_corner[1] - min_corner[1]
57 | size_z = max_corner[2] - min_corner[2]
58 | size = max(size_x, size_y, size_z)
59 | return center, size
60 |
61 |
62 | def randn_tensor(
63 | shape: Union[Tuple, List],
64 | generator: Optional[Union[List["torch.Generator"], "torch.Generator"]] = None,
65 | device: Optional["torch.device"] = None,
66 | dtype: Optional["torch.dtype"] = None,
67 | layout: Optional["torch.layout"] = None,
68 | ):
69 | """This is a helper function that allows to create random tensors on the desired `device` with the desired `dtype`. When
70 | passing a list of generators one can seed each batched size individually. If CPU generators are passed the tensor
71 | will always be created on CPU.
72 | """
73 | # device on which tensor is created defaults to device
74 | rand_device = device
75 | batch_size = shape[0]
76 |
77 | layout = layout or torch.strided
78 | device = device or torch.device("cpu")
79 |
80 | if generator is not None:
81 | gen_device_type = generator.device.type if not isinstance(generator, list) else generator[0].device.type
82 | if gen_device_type != device.type and gen_device_type == "cpu":
83 | rand_device = "cpu"
84 | elif gen_device_type != device.type and gen_device_type == "cuda":
85 | raise ValueError(f"Cannot generate a {device} tensor from a generator of type {gen_device_type}.")
86 |
87 | if isinstance(generator, list):
88 | shape = (1,) + shape[1:]
89 | latents = [
90 | torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype, layout=layout)
91 | for i in range(batch_size)
92 | ]
93 | latents = torch.cat(latents, dim=0).to(device)
94 | else:
95 | latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype, layout=layout).to(device)
96 |
97 | return latents
98 |
99 |
100 | def pad_repeat(x, max_len):
101 | repeat_times = math.floor(max_len/len(x))
102 | sep = max_len-repeat_times*len(x)
103 | sep1 = np.repeat(x[:sep], repeat_times+1, axis=0)
104 | sep2 = np.repeat(x[sep:], repeat_times, axis=0)
105 | x_repeat = np.concatenate([sep1, sep2], 0)
106 | return x_repeat
107 |
108 |
109 | def pad_zero(x, max_len, return_mask=False):
110 | keys = np.ones(len(x))
111 | padding = np.zeros((max_len-len(x))).astype(int)
112 | mask = 1-np.concatenate([keys, padding]) == 1
113 | padding = np.zeros((max_len-len(x), *x.shape[1:]))
114 | x_padded = np.concatenate([x, padding], axis=0)
115 | if return_mask:
116 | return x_padded, mask
117 | else:
118 | return x_padded
119 |
120 |
121 | def plot_3d_bbox(ax, min_corner, max_corner, color='r'):
122 | """
123 | Helper function for plotting 3D bounding boxese
124 | """
125 | vertices = [
126 | (min_corner[0], min_corner[1], min_corner[2]),
127 | (max_corner[0], min_corner[1], min_corner[2]),
128 | (max_corner[0], max_corner[1], min_corner[2]),
129 | (min_corner[0], max_corner[1], min_corner[2]),
130 | (min_corner[0], min_corner[1], max_corner[2]),
131 | (max_corner[0], min_corner[1], max_corner[2]),
132 | (max_corner[0], max_corner[1], max_corner[2]),
133 | (min_corner[0], max_corner[1], max_corner[2])
134 | ]
135 | # Define the 12 triangles composing the box
136 | faces = [
137 | [vertices[0], vertices[1], vertices[2], vertices[3]],
138 | [vertices[4], vertices[5], vertices[6], vertices[7]],
139 | [vertices[0], vertices[1], vertices[5], vertices[4]],
140 | [vertices[2], vertices[3], vertices[7], vertices[6]],
141 | [vertices[1], vertices[2], vertices[6], vertices[5]],
142 | [vertices[4], vertices[7], vertices[3], vertices[0]]
143 | ]
144 | ax.add_collection3d(Poly3DCollection(faces, facecolors='blue', linewidths=1, edgecolors=color, alpha=0))
145 | return
146 |
147 |
148 | def get_args_vae():
149 | parser = argparse.ArgumentParser()
150 | parser.add_argument('--data', type=str, default='data_process/deepcad_parsed',
151 | help='Path to data folder')
152 | parser.add_argument('--train_list', type=str, default='data_process/deepcad_data_split_6bit_surface.pkl',
153 | help='Path to training list')
154 | parser.add_argument('--val_list', type=str, default='data_process/deepcad_data_split_6bit.pkl',
155 | help='Path to validation list')
156 | # Training parameters
157 | parser.add_argument("--option", type=str, choices=['surface', 'edge'], default='surface',
158 | help="Choose between option surface or edge (default: surface)")
159 | parser.add_argument('--batch_size', type=int, default=512, help='input batch size')
160 | parser.add_argument('--train_nepoch', type=int, default=200, help='number of epochs to train for')
161 | parser.add_argument('--save_nepoch', type=int, default=20, help='number of epochs to save model')
162 | parser.add_argument('--test_nepoch', type=int, default=10, help='number of epochs to test model')
163 | parser.add_argument("--data_aug", action='store_true', help='Use data augmentation')
164 | parser.add_argument("--finetune", action='store_true', help='Finetune from existing weights')
165 | parser.add_argument("--weight", type=str, default=None, help='Weight path when finetuning')
166 | parser.add_argument("--gpu", type=int, nargs='+', default=[0], help="GPU IDs to use for training (default: [0])")
167 | # Save dirs and reload
168 | parser.add_argument('--env', type=str, default="surface_vae", help='environment')
169 | parser.add_argument('--dir_name', type=str, default="proj_log", help='name of the log folder.')
170 | args = parser.parse_args()
171 | # saved folder
172 | args.save_dir = f'{args.dir_name}/{args.env}'
173 | return args
174 |
175 |
176 | def get_args_ldm():
177 | parser = argparse.ArgumentParser()
178 | parser.add_argument('--data', type=str, default='data_process/deepcad_parsed',
179 | help='Path to data folder')
180 | parser.add_argument('--list', type=str, default='data_process/deepcad_data_split_6bit.pkl',
181 | help='Path to data list')
182 | parser.add_argument('--surfvae', type=str, default='proj_log/deepcad_surfvae/epoch_400.pt',
183 | help='Path to pretrained surface vae weights')
184 | parser.add_argument('--edgevae', type=str, default='proj_log/deepcad_edgevae/epoch_300.pt',
185 | help='Path to pretrained edge vae weights')
186 | parser.add_argument("--option", type=str, choices=['surfpos', 'surfz', 'edgepos', 'edgez'], default='surfpos',
187 | help="Choose between option [surfpos,edgepos,surfz,edgez] (default: surfpos)")
188 | # Training parameters
189 | parser.add_argument('--batch_size', type=int, default=512, help='input batch size')
190 | parser.add_argument('--train_nepoch', type=int, default=3000, help='number of epochs to train for')
191 | parser.add_argument('--test_nepoch', type=int, default=25, help='number of epochs to test model')
192 | parser.add_argument('--save_nepoch', type=int, default=50, help='number of epochs to save model')
193 | parser.add_argument('--max_face', type=int, default=50, help='maximum number of faces')
194 | parser.add_argument('--max_edge', type=int, default=30, help='maximum number of edges per face')
195 | parser.add_argument('--threshold', type=float, default=0.05, help='minimum threshold between two faces')
196 | parser.add_argument('--bbox_scaled', type=float, default=3, help='scaled the bbox')
197 | parser.add_argument('--z_scaled', type=float, default=1, help='scaled the latent z')
198 | parser.add_argument("--gpu", type=int, nargs='+', default=[0, 1], help="GPU IDs to use for training (default: [0, 1])")
199 | parser.add_argument("--data_aug", action='store_true', help='Use data augmentation')
200 | parser.add_argument("--cf", action='store_true', help='Use data augmentation')
201 | # Save dirs and reload
202 | parser.add_argument('--env', type=str, default="surface_pos", help='environment')
203 | parser.add_argument('--dir_name', type=str, default="proj_log", help='name of the log folder.')
204 | args = parser.parse_args()
205 | # saved folder
206 | args.save_dir = f'{args.dir_name}/{args.env}'
207 | return args
208 |
209 |
210 | def rotate_point_cloud(point_cloud, angle_degrees, axis):
211 | """
212 | Rotate a point cloud around its center by a specified angle in degrees along a specified axis.
213 |
214 | Args:
215 | - point_cloud: Numpy array of shape (N, 3) representing the point cloud.
216 | - angle_degrees: Angle of rotation in degrees.
217 | - axis: Axis of rotation. Can be 'x', 'y', or 'z'.
218 |
219 | Returns:
220 | - rotated_point_cloud: Numpy array of shape (N, 3) representing the rotated point cloud.
221 | """
222 |
223 | # Convert angle to radians
224 | angle_radians = np.radians(angle_degrees)
225 |
226 | # Compute rotation matrix based on the specified axis
227 | if axis == 'x':
228 | rotation_matrix = np.array([[1, 0, 0],
229 | [0, np.cos(angle_radians), -np.sin(angle_radians)],
230 | [0, np.sin(angle_radians), np.cos(angle_radians)]])
231 | elif axis == 'y':
232 | rotation_matrix = np.array([[np.cos(angle_radians), 0, np.sin(angle_radians)],
233 | [0, 1, 0],
234 | [-np.sin(angle_radians), 0, np.cos(angle_radians)]])
235 | elif axis == 'z':
236 | rotation_matrix = np.array([[np.cos(angle_radians), -np.sin(angle_radians), 0],
237 | [np.sin(angle_radians), np.cos(angle_radians), 0],
238 | [0, 0, 1]])
239 | else:
240 | raise ValueError("Invalid axis. Must be 'x', 'y', or 'z'.")
241 |
242 | # Center the point cloud
243 | center = np.mean(point_cloud, axis=0)
244 | centered_point_cloud = point_cloud - center
245 |
246 | # Apply rotation
247 | rotated_point_cloud = np.dot(centered_point_cloud, rotation_matrix.T)
248 |
249 | # Translate back to original position
250 | rotated_point_cloud += center
251 |
252 | # Find the maximum absolute coordinate value
253 | max_abs_coord = np.max(np.abs(rotated_point_cloud))
254 |
255 | # Scale the point cloud to fit within the -1 to 1 cube
256 | normalized_point_cloud = rotated_point_cloud / max_abs_coord
257 |
258 | return normalized_point_cloud
259 |
260 |
261 | def get_bbox(pnts):
262 | """
263 | Get the tighest fitting 3D (axis-aligned) bounding box giving a set of points
264 | """
265 | bbox_corners = []
266 | for point_cloud in pnts:
267 | # Find the minimum and maximum coordinates along each axis
268 | min_x = np.min(point_cloud[:, 0])
269 | max_x = np.max(point_cloud[:, 0])
270 |
271 | min_y = np.min(point_cloud[:, 1])
272 | max_y = np.max(point_cloud[:, 1])
273 |
274 | min_z = np.min(point_cloud[:, 2])
275 | max_z = np.max(point_cloud[:, 2])
276 |
277 | # Create the 3D bounding box using the min and max values
278 | min_point = np.array([min_x, min_y, min_z])
279 | max_point = np.array([max_x, max_y, max_z])
280 | bbox_corners.append([min_point, max_point])
281 | return np.array(bbox_corners)
282 |
283 |
284 | def bbox_corners(bboxes):
285 | """
286 | Given the bottom-left and top-right corners of the bbox
287 | Return all eight corners
288 | """
289 | bboxes_all_corners = []
290 | for bbox in bboxes:
291 | bottom_left, top_right = bbox[:3], bbox[3:]
292 | # Bottom 4 corners
293 | bottom_front_left = bottom_left
294 | bottom_front_right = (top_right[0], bottom_left[1], bottom_left[2])
295 | bottom_back_left = (bottom_left[0], top_right[1], bottom_left[2])
296 | bottom_back_right = (top_right[0], top_right[1], bottom_left[2])
297 |
298 | # Top 4 corners
299 | top_front_left = (bottom_left[0], bottom_left[1], top_right[2])
300 | top_front_right = (top_right[0], bottom_left[1], top_right[2])
301 | top_back_left = (bottom_left[0], top_right[1], top_right[2])
302 | top_back_right = top_right
303 |
304 | # Combine all coordinates
305 | all_corners = [
306 | bottom_front_left,
307 | bottom_front_right,
308 | bottom_back_left,
309 | bottom_back_right,
310 | top_front_left,
311 | top_front_right,
312 | top_back_left,
313 | top_back_right,
314 | ]
315 | bboxes_all_corners.append(np.vstack(all_corners))
316 | bboxes_all_corners = np.array(bboxes_all_corners)
317 | return bboxes_all_corners
318 |
319 |
320 | def rotate_axis(pnts, angle_degrees, axis, normalized=False):
321 | """
322 | Rotate a point cloud around its center by a specified angle in degrees along a specified axis.
323 |
324 | Args:
325 | - point_cloud: Numpy array of shape (N, ..., 3) representing the point cloud.
326 | - angle_degrees: Angle of rotation in degrees.
327 | - axis: Axis of rotation. Can be 'x', 'y', or 'z'.
328 |
329 | Returns:
330 | - rotated_point_cloud: Numpy array of shape (N, 3) representing the rotated point cloud.
331 | """
332 |
333 | # Convert angle to radians
334 | angle_radians = np.radians(angle_degrees)
335 |
336 | # Convert points to homogeneous coordinates
337 | shape = list(np.shape(pnts))
338 | shape[-1] = 1
339 | pnts_homogeneous = np.concatenate((pnts, np.ones(shape)), axis=-1)
340 |
341 | # Compute rotation matrix based on the specified axis
342 | if axis == 'x':
343 | rotation_matrix = np.array([
344 | [1, 0, 0, 0],
345 | [0, np.cos(angle_radians), -np.sin(angle_radians), 0],
346 | [0, np.sin(angle_radians), np.cos(angle_radians), 0],
347 | [0, 0, 0, 1]
348 | ])
349 | elif axis == 'y':
350 | rotation_matrix = np.array([
351 | [np.cos(angle_radians), 0, np.sin(angle_radians), 0],
352 | [0, 1, 0, 0],
353 | [-np.sin(angle_radians), 0, np.cos(angle_radians), 0],
354 | [0, 0, 0, 1]
355 | ])
356 | elif axis == 'z':
357 | rotation_matrix = np.array([
358 | [np.cos(angle_radians), -np.sin(angle_radians), 0, 0],
359 | [np.sin(angle_radians), np.cos(angle_radians), 0, 0],
360 | [0, 0, 1, 0],
361 | [0, 0, 0, 1]
362 | ])
363 | else:
364 | raise ValueError("Invalid axis. Must be 'x', 'y', or 'z'.")
365 |
366 | # Apply rotation
367 | rotated_pnts_homogeneous = np.dot(pnts_homogeneous, rotation_matrix.T)
368 | rotated_pnts = rotated_pnts_homogeneous[...,:3]
369 |
370 | # Scale the point cloud to fit within the -1 to 1 cube
371 | if normalized:
372 | max_abs_coord = np.max(np.abs(rotated_pnts))
373 | rotated_pnts = rotated_pnts / max_abs_coord
374 |
375 | return rotated_pnts
376 |
377 |
378 | def rescale_bbox(bboxes, scale):
379 | # Apply scaling factors to bounding boxes
380 | scaled_bboxes = bboxes*scale
381 | return scaled_bboxes
382 |
383 |
384 | def translate_bbox(bboxes):
385 | """
386 | Randomly move object within the cube (x,y,z direction)
387 | """
388 | point_cloud = bboxes.reshape(-1,3)
389 | min_x = np.min(point_cloud[:, 0])
390 | max_x = np.max(point_cloud[:, 0])
391 | min_y = np.min(point_cloud[:, 1])
392 | max_y = np.max(point_cloud[:, 1])
393 | min_z = np.min(point_cloud[:, 2])
394 | max_z = np.max(point_cloud[:, 2])
395 | x_offset = np.random.uniform( np.min(-1-min_x,0), np.max(1-max_x,0) )
396 | y_offset = np.random.uniform( np.min(-1-min_y,0), np.max(1-max_y,0) )
397 | z_offset = np.random.uniform( np.min(-1-min_z,0), np.max(1-max_z,0) )
398 | random_translation = np.array([x_offset,y_offset,z_offset])
399 | bboxes_translated = bboxes + random_translation
400 | return bboxes_translated
401 |
402 |
403 | def edge2loop(face_edges):
404 | face_edges_flatten = face_edges.reshape(-1,3)
405 | # connect end points by closest distance
406 | merged_vertex_id = []
407 | for edge_idx, startend in enumerate(face_edges):
408 | self_id = [2*edge_idx, 2*edge_idx+1]
409 | # left endpoint
410 | distance = np.linalg.norm(face_edges_flatten - startend[0], axis=1)
411 | min_id = list(np.argsort(distance))
412 | min_id_noself = [x for x in min_id if x not in self_id]
413 | merged_vertex_id.append(sorted([2*edge_idx, min_id_noself[0]]))
414 | # right endpoint
415 | distance = np.linalg.norm(face_edges_flatten - startend[1], axis=1)
416 | min_id = list(np.argsort(distance))
417 | min_id_noself = [x for x in min_id if x not in self_id]
418 | merged_vertex_id.append(sorted([2*edge_idx+1, min_id_noself[0]]))
419 |
420 | merged_vertex_id = np.unique(np.array(merged_vertex_id),axis=0)
421 | return merged_vertex_id
422 |
423 |
424 | def keep_largelist(int_lists):
425 | # Initialize a list to store the largest integer lists
426 | largest_int_lists = []
427 |
428 | # Convert each list to a set for efficient comparison
429 | sets = [set(lst) for lst in int_lists]
430 |
431 | # Iterate through the sets and check if they are subsets of others
432 | for i, s1 in enumerate(sets):
433 | is_subset = False
434 | for j, s2 in enumerate(sets):
435 | if i!=j and s1.issubset(s2) and s1 != s2:
436 | is_subset = True
437 | break
438 | if not is_subset:
439 | largest_int_lists.append(list(s1))
440 |
441 | # Initialize a set to keep track of seen tuples
442 | seen_tuples = set()
443 |
444 | # Initialize a list to store unique integer lists
445 | unique_int_lists = []
446 |
447 | # Iterate through the input list
448 | for int_list in largest_int_lists:
449 | # Convert the list to a tuple for hashing
450 | int_tuple = tuple(sorted(int_list))
451 |
452 | # Check if the tuple is not in the set of seen tuples
453 | if int_tuple not in seen_tuples:
454 | # Add the tuple to the set of seen tuples
455 | seen_tuples.add(int_tuple)
456 |
457 | # Add the original list to the list of unique integer lists
458 | unique_int_lists.append(int_list)
459 |
460 | return unique_int_lists
461 |
462 |
463 | def detect_shared_vertex(edgeV_cad, edge_mask_cad, edgeV_bbox):
464 | """
465 | Find the shared vertices
466 | """
467 | edge_id_offset = 2 * np.concatenate([np.array([0]),np.cumsum((edge_mask_cad==False).sum(1))])[:-1]
468 | valid = True
469 |
470 | # Detect shared-vertex on seperate face loop
471 | used_vertex = []
472 | face_sep_merges = []
473 | for face_idx, (face_edges, face_edges_mask, bbox_edges) in enumerate(zip(edgeV_cad, edge_mask_cad, edgeV_bbox)):
474 | face_edges = face_edges[~face_edges_mask]
475 | face_edges = face_edges.reshape(len(face_edges),2,3)
476 | face_start_id = edge_id_offset[face_idx]
477 |
478 | # connect end points by closest distance (edge bbox)
479 | merged_vertex_id = edge2loop(bbox_edges)
480 | if len(merged_vertex_id) == len(face_edges):
481 | merged_vertex_id = face_start_id + merged_vertex_id
482 | face_sep_merges.append(merged_vertex_id)
483 | used_vertex.append(bbox_edges*3)
484 | print('[PASS]')
485 | continue
486 |
487 | # connect end points by closest distance (vertex pos)
488 | merged_vertex_id = edge2loop(face_edges)
489 | if len(merged_vertex_id) == len(face_edges):
490 | merged_vertex_id = face_start_id + merged_vertex_id
491 | face_sep_merges.append(merged_vertex_id)
492 | used_vertex.append(face_edges)
493 | print('[PASS]')
494 | continue
495 |
496 | print('[FAILED]')
497 | valid = False
498 | break
499 |
500 | # Invalid
501 | if not valid:
502 | assert False
503 |
504 | # Detect shared-vertex across faces
505 | total_pnts = np.vstack(used_vertex)
506 | total_pnts = total_pnts.reshape(len(total_pnts),2,3)
507 | total_pnts_flatten = total_pnts.reshape(-1,3)
508 |
509 | total_ids = []
510 | for face_idx, face_merge in enumerate(face_sep_merges):
511 | # non-self merge centers
512 | nonself_face_idx = list(set(np.arange(len(face_sep_merges))) - set([face_idx]))
513 | nonself_face_merges = [face_sep_merges[x] for x in nonself_face_idx]
514 | nonself_face_merges = np.vstack(nonself_face_merges)
515 | nonself_merged_centers = total_pnts_flatten[nonself_face_merges].mean(1)
516 |
517 | # connect end points by closest distance
518 | across_merge_id = []
519 | for merge_id in face_merge:
520 | merged_center = total_pnts_flatten[merge_id].mean(0)
521 | distance = np.linalg.norm(nonself_merged_centers - merged_center, axis=1)
522 | nonself_match_id = nonself_face_merges[np.argsort(distance)[0]]
523 | joint_merge_id = list(nonself_match_id) + list(merge_id)
524 | across_merge_id.append(joint_merge_id)
525 | total_ids += across_merge_id
526 |
527 | # Merge T-junctions
528 | while (True):
529 | no_merge = True
530 | final_merge_id = []
531 |
532 | # iteratelly merge until no changes happen
533 | for i in range(len(total_ids)):
534 | perform_merge = False
535 |
536 | for j in range(i+1,len(total_ids)):
537 | # check if vertex can be further merged
538 | max_num = max(len(total_ids[i]), len(total_ids[j]))
539 | union = set(total_ids[i]).union(set(total_ids[j]))
540 | common = set(total_ids[i]).intersection(set(total_ids[j]))
541 | if len(union) > max_num and len(common)>0:
542 | final_merge_id.append(list(union))
543 | perform_merge = True
544 | no_merge = False
545 | break
546 |
547 | if not perform_merge:
548 | final_merge_id.append(total_ids[i]) # no-merge
549 |
550 | total_ids = final_merge_id
551 | if no_merge: break
552 |
553 | # remove subsets
554 | total_ids = keep_largelist(total_ids)
555 |
556 | # merge again base on absolute coordinate value, required for >3 T-junction
557 | tobe_merged_centers = [total_pnts_flatten[x].mean(0) for x in total_ids]
558 | tobe_centers = np.array(tobe_merged_centers)
559 | distances = np.linalg.norm(tobe_centers[:, np.newaxis, :] - tobe_centers, axis=2)
560 | close_points = distances < 0.1
561 | mask = np.tril(np.ones_like(close_points, dtype=bool), k=-1)
562 | non_diagonal_indices = np.where(close_points & mask)
563 | row_indices, column_indices = non_diagonal_indices
564 |
565 | # update the total_ids
566 | total_ids_updated = []
567 | for row, col in zip(row_indices, column_indices):
568 | total_ids_updated.append(total_ids[row] + total_ids[col])
569 | for index, ids in enumerate(total_ids):
570 | if index not in list(row_indices) and index not in list(column_indices):
571 | total_ids_updated.append(ids)
572 | total_ids = total_ids_updated
573 |
574 | # merged vertices
575 | unique_vertices = []
576 | for center_id in total_ids:
577 | center_pnts = total_pnts_flatten[center_id].mean(0) / 3.0
578 | unique_vertices.append(center_pnts)
579 | unique_vertices = np.vstack(unique_vertices)
580 |
581 | new_vertex_dict = {}
582 | for new_id, old_ids in enumerate(total_ids):
583 | new_vertex_dict[new_id] = old_ids
584 |
585 | return [unique_vertices, new_vertex_dict]
586 |
587 |
588 | def detect_shared_edge(unique_vertices, new_vertex_dict, edge_z_cad, surf_z_cad, z_threshold, edge_mask_cad):
589 | """
590 | Find the shared edges
591 | """
592 | init_edges = edge_z_cad
593 |
594 | # re-assign edge start/end to unique vertices
595 | new_ids = []
596 | for old_id in np.arange(2*len(init_edges)):
597 | new_id = []
598 | for key, value in new_vertex_dict.items():
599 | # Check if the desired number is in the associated list
600 | if old_id in value:
601 | new_id.append(key)
602 | assert len(new_id) == 1 # should only return one unique value
603 | new_ids.append(new_id[0])
604 |
605 | EdgeVertexAdj = np.array(new_ids).reshape(-1,2)
606 |
607 | # find edges assigned to the same start/end
608 | similar_edges = []
609 | for i, s1 in enumerate(EdgeVertexAdj):
610 | for j, s2 in enumerate(EdgeVertexAdj):
611 | if i!=j and set(s1) == set(s2): # same start/end
612 | z1 = init_edges[i]
613 | z2 = init_edges[j]
614 | z_diff = np.abs(z1-z2).mean()
615 | if z_diff < z_threshold: # check z difference
616 | similar_edges.append(sorted([i,j]))
617 | # else:
618 | # print('z latent beyond...')
619 | similar_edges = np.unique(np.array(similar_edges),axis=0)
620 |
621 | # should reduce total edges by two
622 | if not 2*len(similar_edges) == len(EdgeVertexAdj):
623 | assert False, 'edge not reduced by 2'
624 |
625 | # unique edges
626 | unique_edge_id = similar_edges[:,0]
627 | EdgeVertexAdj = EdgeVertexAdj[unique_edge_id]
628 | unique_edges = init_edges[unique_edge_id]
629 |
630 | # unique faces
631 | unique_faces = surf_z_cad
632 | FaceEdgeAdj = []
633 | ranges = np.concatenate([np.array([0]),np.cumsum((edge_mask_cad==False).sum(1))])
634 | for index in range(len(ranges)-1):
635 | adj_ids = np.arange(ranges[index], ranges[index+1])
636 | new_ids = []
637 | for id in adj_ids:
638 | new_id = np.where(similar_edges == id)[0]
639 | assert len(new_id) == 1
640 | new_ids.append(new_id[0])
641 | FaceEdgeAdj.append(new_ids)
642 |
643 | print(f'Post-process: F-{len(unique_faces)} E-{len(unique_edges)} V-{len(unique_vertices)}')
644 |
645 | return [unique_faces, unique_edges, FaceEdgeAdj, EdgeVertexAdj]
646 |
647 |
648 | class STModel(nn.Module):
649 | def __init__(self, num_edge, num_surf):
650 | super().__init__()
651 | self.edge_t = nn.Parameter(torch.zeros((num_edge, 3)))
652 | self.surf_st = nn.Parameter(torch.FloatTensor([1,0,0,0]).unsqueeze(0).repeat(num_surf,1))
653 |
654 |
655 | def get_bbox_minmax(point_cloud):
656 | # Find the minimum and maximum coordinates along each axis
657 | min_x = np.min(point_cloud[:, 0])
658 | max_x = np.max(point_cloud[:, 0])
659 |
660 | min_y = np.min(point_cloud[:, 1])
661 | max_y = np.max(point_cloud[:, 1])
662 |
663 | min_z = np.min(point_cloud[:, 2])
664 | max_z = np.max(point_cloud[:, 2])
665 |
666 | # Create the 3D bounding box using the min and max values
667 | min_point = np.array([min_x, min_y, min_z])
668 | max_point = np.array([max_x, max_y, max_z])
669 | return (min_point, max_point)
670 |
671 |
672 | def joint_optimize(surf_ncs, edge_ncs, surfPos, unique_vertices, EdgeVertexAdj, FaceEdgeAdj, num_edge, num_surf):
673 | """
674 | Jointly optimize the face/edge/vertex based on topology
675 | """
676 | loss_func = ChamferDistance()
677 |
678 | model = STModel(num_edge, num_surf)
679 | model = model.cuda().train()
680 | optimizer = torch.optim.AdamW(
681 | model.parameters(),
682 | lr=1e-3,
683 | betas=(0.95, 0.999),
684 | weight_decay=1e-6,
685 | eps=1e-08,
686 | )
687 |
688 | # Optimize edges (directly compute)
689 | edge_ncs_se = edge_ncs[:,[0,-1]]
690 | edge_vertex_se = unique_vertices[EdgeVertexAdj]
691 |
692 | edge_wcs = []
693 | print('Joint Optimization...')
694 | for wcs, ncs_se, vertex_se in zip(edge_ncs, edge_ncs_se, edge_vertex_se):
695 | # scale
696 | scale_target = np.linalg.norm(vertex_se[0] - vertex_se[1])
697 | scale_ncs = np.linalg.norm(ncs_se[0] - ncs_se[1])
698 | edge_scale = scale_target / scale_ncs
699 |
700 | edge_updated = wcs*edge_scale
701 | edge_se = ncs_se*edge_scale
702 |
703 | # offset
704 | offset = (vertex_se - edge_se)
705 | offset_rev = (vertex_se - edge_se[::-1])
706 |
707 | # swap start / end if necessary
708 | offset_error = np.abs(offset[0] - offset[1]).mean()
709 | offset_rev_error =np.abs(offset_rev[0] - offset_rev[1]).mean()
710 | if offset_rev_error < offset_error:
711 | edge_updated = edge_updated[::-1]
712 | offset = offset_rev
713 |
714 | edge_updated = edge_updated + offset.mean(0)[np.newaxis,np.newaxis,:]
715 | edge_wcs.append(edge_updated)
716 |
717 | edge_wcs = np.vstack(edge_wcs)
718 |
719 | # Replace start/end points with corner, and backprop change along curve
720 | for index in range(len(edge_wcs)):
721 | start_vec = edge_vertex_se[index,0] - edge_wcs[index, 0]
722 | end_vec = edge_vertex_se[index,1] - edge_wcs[index, -1]
723 | weight = np.tile((np.arange(32)/31)[:,np.newaxis], (1,3))
724 | weighted_vec = np.tile(start_vec[np.newaxis,:],(32,1))*(1-weight) + np.tile(end_vec,(32,1))*weight
725 | edge_wcs[index] += weighted_vec
726 |
727 | # Optimize surfaces
728 | face_edges = []
729 | for adj in FaceEdgeAdj:
730 | all_pnts = edge_wcs[adj]
731 | face_edges.append(torch.FloatTensor(all_pnts).cuda())
732 |
733 | # Initialize surface in wcs based on surface pos
734 | surf_wcs_init = []
735 | bbox_threshold_min = []
736 | bbox_threshold_max = []
737 | for edges_perface, ncs, bbox in zip(face_edges, surf_ncs, surfPos):
738 | surf_center, surf_scale = compute_bbox_center_and_size(bbox[0:3], bbox[3:])
739 | edges_perface_flat = edges_perface.reshape(-1, 3).detach().cpu().numpy()
740 | min_point, max_point = get_bbox_minmax(edges_perface_flat)
741 | edge_center, edge_scale = compute_bbox_center_and_size(min_point, max_point)
742 | bbox_threshold_min.append(min_point)
743 | bbox_threshold_max.append(max_point)
744 |
745 | # increase surface size if does not fully cover the wire bbox
746 | if surf_scale < edge_scale:
747 | surf_scale = 1.05*edge_scale
748 |
749 | wcs = ncs * (surf_scale/2) + surf_center
750 | surf_wcs_init.append(wcs)
751 |
752 | surf_wcs_init = np.stack(surf_wcs_init)
753 |
754 | # optimize the surface offset
755 | surf = torch.FloatTensor(surf_wcs_init).cuda()
756 | for iters in range(200):
757 | surf_scale = model.surf_st[:,0].reshape(-1,1,1,1)
758 | surf_offset = model.surf_st[:,1:].reshape(-1,1,1,3)
759 | surf_updated = surf + surf_offset
760 |
761 | surf_loss = 0
762 | for surf_pnt, edge_pnts in zip(surf_updated, face_edges):
763 | surf_pnt = surf_pnt.reshape(-1,3)
764 | edge_pnts = edge_pnts.reshape(-1,3).detach()
765 | surf_loss += loss_func(surf_pnt.unsqueeze(0), edge_pnts.unsqueeze(0), bidirectional=False, reverse=True)
766 | surf_loss /= len(surf_updated)
767 |
768 | optimizer.zero_grad()
769 | (surf_loss).backward()
770 | optimizer.step()
771 |
772 | # print(f'Iter {iters} surf:{surf_loss:.5f}')
773 |
774 | surf_wcs = surf_updated.detach().cpu().numpy()
775 |
776 | return (surf_wcs, edge_wcs)
777 |
778 |
779 | def add_pcurves_to_edges(face):
780 | edge_fixer = ShapeFix_Edge()
781 | top_exp = TopologyExplorer(face)
782 | for wire in top_exp.wires():
783 | wire_exp = WireExplorer(wire)
784 | for edge in wire_exp.ordered_edges():
785 | edge_fixer.FixAddPCurve(edge, face, False, 0.001)
786 |
787 |
788 | def fix_wires(face, debug=False):
789 | top_exp = TopologyExplorer(face)
790 | for wire in top_exp.wires():
791 | if debug:
792 | wire_checker = ShapeAnalysis_Wire(wire, face, 0.01)
793 | print(f"Check order 3d {wire_checker.CheckOrder()}")
794 | print(f"Check 3d gaps {wire_checker.CheckGaps3d()}")
795 | print(f"Check closed {wire_checker.CheckClosed()}")
796 | print(f"Check connected {wire_checker.CheckConnected()}")
797 | wire_fixer = ShapeFix_Wire(wire, face, 0.01)
798 |
799 | # wire_fixer.SetClosedWireMode(True)
800 | # wire_fixer.SetFixConnectedMode(True)
801 | # wire_fixer.SetFixSeamMode(True)
802 |
803 | assert wire_fixer.IsReady()
804 | ok = wire_fixer.Perform()
805 | # assert ok
806 |
807 |
808 | def fix_face(face):
809 | fixer = ShapeFix_Face(face)
810 | fixer.SetPrecision(0.01)
811 | fixer.SetMaxTolerance(0.1)
812 | ok = fixer.Perform()
813 | # assert ok
814 | fixer.FixOrientation()
815 | face = fixer.Face()
816 | return face
817 |
818 |
819 | def construct_brep(surf_wcs, edge_wcs, FaceEdgeAdj, EdgeVertexAdj):
820 | """
821 | Fit parametric surfaces / curves and trim into B-rep
822 | """
823 | print('Building the B-rep...')
824 | # Fit surface bspline
825 | recon_faces = []
826 | for points in surf_wcs:
827 | num_u_points, num_v_points = 32, 32
828 | uv_points_array = TColgp_Array2OfPnt(1, num_u_points, 1, num_v_points)
829 | for u_index in range(1,num_u_points+1):
830 | for v_index in range(1,num_v_points+1):
831 | pt = points[u_index-1, v_index-1]
832 | point_3d = gp_Pnt(float(pt[0]), float(pt[1]), float(pt[2]))
833 | uv_points_array.SetValue(u_index, v_index, point_3d)
834 | approx_face = GeomAPI_PointsToBSplineSurface(uv_points_array, 3, 8, GeomAbs_C2, 5e-2).Surface()
835 | recon_faces.append(approx_face)
836 |
837 | recon_edges = []
838 | for points in edge_wcs:
839 | num_u_points = 32
840 | u_points_array = TColgp_Array1OfPnt(1, num_u_points)
841 | for u_index in range(1,num_u_points+1):
842 | pt = points[u_index-1]
843 | point_2d = gp_Pnt(float(pt[0]), float(pt[1]), float(pt[2]))
844 | u_points_array.SetValue(u_index, point_2d)
845 | try:
846 | approx_edge = GeomAPI_PointsToBSpline(u_points_array, 0, 8, GeomAbs_C2, 5e-3).Curve()
847 | except Exception as e:
848 | print('high precision failed, trying mid precision...')
849 | try:
850 | approx_edge = GeomAPI_PointsToBSpline(u_points_array, 0, 8, GeomAbs_C2, 8e-3).Curve()
851 | except Exception as e:
852 | print('mid precision failed, trying low precision...')
853 | approx_edge = GeomAPI_PointsToBSpline(u_points_array, 0, 8, GeomAbs_C2, 5e-2).Curve()
854 | recon_edges.append(approx_edge)
855 |
856 | # Create edges from the curve list
857 | edge_list = []
858 | for curve in recon_edges:
859 | edge = BRepBuilderAPI_MakeEdge(curve).Edge()
860 | edge_list.append(edge)
861 |
862 | # Cut surface by wire
863 | post_faces = []
864 | post_edges = []
865 | for idx,(surface, edge_incides) in enumerate(zip(recon_faces, FaceEdgeAdj)):
866 | corner_indices = EdgeVertexAdj[edge_incides]
867 |
868 | # ordered loop
869 | loops = []
870 | ordered = [0]
871 | seen_corners = [corner_indices[0,0], corner_indices[0,1]]
872 | next_index = corner_indices[0,1]
873 |
874 | while len(ordered)