File size: 6,907 Bytes
68da613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import csv
import os

def read_dat_file(dat_file_path):
    nodes = {}       # node_id -> (x,y,z)
    elements = []    # list of node_id lists for each element

    in_nodes = False
    in_elements = False

    with open(dat_file_path, "r") as file:
        lines = file.readlines()

    for line in lines:
        line = line.strip()

        # Detect node block
        if line.lower().startswith("nblock"):
            in_nodes = True
            in_elements = False
            continue
        if line == "-1":
            if in_nodes:
                in_nodes = False
            elif in_elements:
                in_elements = False
            continue

        # Detect element block
        if line.lower().startswith("eblock"):
            in_elements = True
            in_nodes = False
            continue

        # Parse nodes
        if in_nodes:
            parts = line.split()
            if len(parts) >= 4:
                try:
                    node_id = int(parts[0])
                    x = float(parts[1])
                    y = float(parts[2])
                    z = float(parts[3])
                    nodes[node_id] = (x, y, z)
                except Exception:
                    pass  # ignore malformed lines

        # Parse elements (assuming EBLOCK contains element lines)
        if in_elements:
            parts = line.split()
            if len(parts) >= 15:
                # Extract the 4 node IDs from the standard positions
                # Usually nodes start around index 10 or 11 — adjust if needed
                try:
                    # For tetrahedral elements, pick 4 node IDs.
                    # You need to confirm the exact positions for your .dat file.
                    node_ids = [int(parts[11]), int(parts[12]), int(parts[13]), int(parts[15])]
                    elements.append(node_ids)
                except Exception:
                    pass  # ignore malformed lines

    # Sort node IDs and create a mapping from node_id to zero-based index
    sorted_node_ids = sorted(nodes.keys())
    id_to_index = {nid: i for i, nid in enumerate(sorted_node_ids)}

    # Build positions array ordered by zero-based index
    positions = [nodes[nid] for nid in sorted_node_ids]

    # Convert element connectivity node IDs to zero-based indices
    connectivity = []
    for elem_node_ids in elements:
        try:
            zero_based = [id_to_index[nid] for nid in elem_node_ids]
            connectivity.append(zero_based)
        except KeyError:
            # Skip elements with invalid node IDs
            continue

    return positions, connectivity

"""

def read_dat_file(dat_file_path):

    in_nodes = False

    in_elements = False

    nodes = []

    cells_detail = []



    with open(dat_file_path, "r") as file:

        lines = file.readlines()



    lines_iter = iter(lines)



    for line in lines_iter:



        line = line.strip()



        # Detect node block

        if line.lower().startswith("nblock"):

            in_nodes = True

            continue



        if in_nodes and line.strip() == "-1":

            in_nodes = False

            continue



        # Detect element block (EBLOCK)

        if line.lower().startswith("eblock"):

            in_elements = True

            continue



        if in_elements and line.strip() == "-1":

            in_elements = False

            continue



        # Parse nodes

        if in_nodes:

            parts = line.split()

            if len(parts) == 4:

                #node_id = int(parts[0])

                x = float(parts[1])

                y = float(parts[2])

                z = float(parts[3])

                nodes.append(( x, y, z))



        # Parse elements (EBLOCK, 2-line format)

        if in_elements:

            parts = line.split()

            num_nodes =8

            if len(parts) > 14:

                 # Ensure the line has 4 parts: ID, X, Y, Z

                num_nodes = int(parts[8])

                less = 0

                if num_nodes < 8:

                    less = 8-num_nodes

                node_idsz = []

                # print(parts)

                element_id = [int(parts[10])]  # Element ID

                body_id = [int(parts[0])]

                for i in range(11, 19-less):

                    # print(i)

                    node_idsz.append(int(parts[i]))   # Node IDs

                if num_nodes<=8:

                    cells_detail.append(element_id+body_id+node_idsz)

            if len(parts) == num_nodes-8 and num_nodes>8:  # Ensure the line has 4 parts: ID, X, Y, Z    

                for i in range(0,num_nodes-8 ):

                    node_idsz.append(int(parts[i])) 

            #next_line = next(lines_iter).strip()   # this is only required if the next line contains more node ids in case of hexhedral elements

            #node_ids += [int(x) for x in next_line.split()]

            

                # print(element_id, node_idsz)

                cells_detail.append(element_id+body_id+node_idsz) 







    # Sort nodes and cells

    nodes.sort(key=lambda x: x[0])

    cells_detail.sort(key=lambda x: x[0])



    # Remove duplicates

    cells_detail = [list(item) for item in dict.fromkeys(tuple(cell) for cell in cells_detail)]



    # Extract 4-node face from each cell (can adjust as needed)

    cells = [[cell[2], cell[3], cell[4], cell[6]] for cell in cells_detail]



    return nodes, cells

"""
def read_result_file(result_file_path, encoding='utf-8'):
    parameters = []
    with open(result_file_path, mode='r', encoding=encoding) as file:
        if result_file_path.endswith(".csv"):
            reader = csv.reader(file)
            next(reader)  # Skip header
            for row in reader:
                parameters.append(float(row[-1]))
        elif result_file_path.endswith(".txt"):
            for line in file:
                if "Node Number" in line:
                    continue
                columns = line.split()
                try:
                    parameters.append(float(columns[-1]))
                except ValueError:
                    continue
    return parameters

def main(folder_path):
    folder_base_name = os.path.basename(folder_path).replace("_data", "")
    dat_file_path = os.path.join(folder_path, f"{folder_base_name}.dat")
    fatigue_life_path = os.path.join(folder_path, f"{folder_base_name}.txt")
    
    dat_file_path = "path/to/your/dat_file.dat"
    fatigue_life_path = "path/to/your/fatigue_life.txt"

    nodes = read_dat_file(dat_file_path)
    life = read_result_file(fatigue_life_path)

    # Do something with the data
    print("Nodes:")
    for node in nodes:
        print(node)

    print("\nLife:")
    for param in life:
        print(param)