Peano
Loading...
Searching...
No Matches
TreeReaderWithSplit.py
Go to the documentation of this file.
1import numpy as np
2import matplotlib.pyplot as plt
3from scipy import io
4import os
5import math
6import argparse
7import matplotlib.cm as cm
8
9import re
10from collections import defaultdict
11
12def round_sig(x, sig):
13 return float(np.format_float_positional(x, precision=sig, unique=False, trim='k'))
14
15def read_patches(file_path, size_group):
16 with open(file_path, "r") as f:
17 content = f.read()
18
19 # Regular expression to extract offset and size
20 patch_pattern = re.compile(
21 r'begin patch.*?offset ([\d.eE+\-]+ [\d.eE+\-]+ [\d.eE+\-]+).*?'
22 r'size ([\d.eE+\-]+ [\d.eE+\-]+ [\d.eE+\-]+)',
23 re.DOTALL
24 )
25
26 # Find all matches
27 for match in patch_pattern.findall(content):
28 offset, size = match
29 size_group[size].append(offset) # Group offsets by size
30
31 return size_group
32
33
34def main():
35 #main start here
36 #input parameters
37 parser = argparse.ArgumentParser(description='Tree Reader')
38 parser.add_argument("-file", "--file-path", dest="file", type=str, required="True", help="file path" )
39
40 args = parser.parse_args()
41
42 #folder_path = 'case1'
43 #input parameters, case5 is bottomup(one big tree), case4 is topdown(bad pattern)
44 folder_path=args.file
45 prefix = 'grid-'
46 # List all files in the folder with the specified prefix
47 datafiles = [f for f in os.listdir(folder_path) if f.startswith(prefix)]
48
49 dimension=3
50
51 #extract grid infomation
52 size_groups = [] # Dictionary to store {size: [offsets]}
53 for file_path in datafiles:
54 size_group = defaultdict(list)
55 read_patches(folder_path+'/'+file_path, size_group)
56 size_groups.append(size_group)
57
58
59 total_level=-1
60 for size_group in size_groups:
61 total_level=max(total_level, len(size_group.keys()))
62
63
64 patch_number_for_each_level = defaultdict(list)
65 for size_group in size_groups:
66 for size, offsets in size_group.items():
67 print(f"Size: {size} -> Count: {len(offsets)}")
68 patch_number_for_each_level[size].append(len(offsets))
69 #print("Offsets:")
70 #for offset in offsets:
71 # print(f" {offset}")
72 print("-" * 40)
73 #print(total_patch_count)
74 print("Total Cell Count:")
75 for size, count in patch_number_for_each_level.items():
76 print(f"Size: {size} -> Count: {sum(count)}")
77
78
79 #find the domain info directly from grid plot
80 max_size=0
81
82 for size_group in size_groups:
83 for size in size_group.keys():
84 size_tuple = tuple(map(float, size.split()))
85 if size_tuple[0]>max_size:
86 max_size=size_tuple[0]
87 max_size_key=size
88 #print(max_size)
89
90 leftmost_offset=[999,999,999]
91 for size_group in size_groups:
92 for offset in size_group[max_size_key]:
93 offset_tuple = tuple(map(float, offset.split()))
94 for m in range(dimension):
95 if offset_tuple[m]<leftmost_offset[m]:
96 leftmost_offset[m]=offset_tuple[m]
97 leftmost_offset_key=offset
98 #print(leftmost_offset, leftmost_offset_key)
99
100 domain_offset = tuple(leftmost_offset)#tuple(map(float, leftmost_offset_key.split()))
101 domain_size = tuple(map(float, max_size_key.split()))
102 domain_size = tuple( round_sig(x * 3,5) for x in domain_size)
103
104 print(domain_offset, domain_size)
105
106
107 #preparing tree matrices
108 #total_level=len(size_group.keys())
109 #for i in range(total_level):
110 # print("level "+str(i)+" Matrix total entries:", (3*(3**i))**dimension,"size: "+str(domain_size[0]/3/3**i))
111 tree_matrices = []
112 tree_patches = []
113
114 #print(len(tree_matrix))
115
116 #calculate the tree matrices
117 index=0
118 for size_group in size_groups:
119 tree_matrix = [None]*total_level
120 tree_patch = [None]*total_level
121 for size, offsets in size_group.items():
122 size_tuple = tuple(map(float, size.split()))
123 level=int( math.log( int(round_sig(domain_size[0]/size_tuple[0],1)), 3) )
124 matrix_size=(3**level)
125 #print(level, matrix_size)
126
127 matrix=np.zeros((matrix_size, matrix_size, matrix_size), dtype=bool)
128 for offset in offsets:
129 offset_tuple = tuple(map(float, offset.split()))
130 index=[-1,-1,-1]
131 for i in range(len(offset_tuple)):
132 index[i]=round((offset_tuple[i]-domain_offset[i])/size_tuple[i])
133 matrix[tuple(index)]=1
134
135 #print(len(tree_matrix))
136 tree_matrix[level-1]=matrix
137 tree_patch[level-1]=len(offsets)
138 tree_matrices.append(tree_matrix)
139 tree_patches.append(tree_patch)
140
141 #for i in range(len(datafiles)):
142 # print(tree_patches[i])
143
144 #colors=["black","red"]
145 colors = plt.colormaps['tab10']
146
147 #plotting stuff
148 fig = plt.figure(figsize=(12, 4))
149 axes=[]
150 for k in range(total_level):
151 axes.append(fig.add_subplot(1,total_level,k+1, projection='3d'))
152
153 for j in range(len(datafiles)):
154 color=colors(j)
155 for i in range(total_level):
156 x, y, z = np.where(tree_matrices[j][i])
157 axes[i].scatter(x, y, z, color=color, marker='s',s=50*27/3**(1+i), depthshade=False) # 'c' controls color, 'marker' controls shape
158
159 # Set labels
160 axes[i].set_xlabel("X"); axes[i].set_ylabel("Y"); axes[i].set_zlabel("Z")
161 axes[i].set_xlim([0,3**(1+i)-1]); axes[i].set_ylim([0,3**(1+i)-1]); axes[i].set_zlim([0,3**(1+i)-1]);
162 axes[i].set_title("Level="+str(i))
163
164 # Show the 3D plot
165 plt.show()
166 plt.savefig("TreeStructure.pdf")
167 plt.savefig("TreeStrucutre.png")
168
169
170if __name__ == "__main__":
171 main()
read_patches(file_path, size_group)