Mechanics of Defect Evolution Library
Loading...
Searching...
No Matches
readFile.py
Go to the documentation of this file.
1import subprocess
2import os
3import pathlib
4import sys
5import numpy as np
6import string, os, math, sys
7
8#Generate file path from directory and file name
9def generate_file_paths(directory, names):
10 file_paths = []
11 for name in names:
12 file_path = os.path.join(directory, name)
13 file_paths.append(file_path)
14 return file_paths
15
16
17# Get variable from a txt file
18def get_scalar(file_path, variable_name):
19 try:
20 with open(file_path, 'r') as file:
21 for line in file:
22 line = line.split(';', 1)[0] # Ignore everything after the first semicolon
23 parts = line.strip().split('=')
24 if len(parts) == 2:
25 name, value = parts
26 if name.strip() == variable_name:
27 print(f"Found variable {variable_name} in the line: {line.strip()}")
28 return float(value.strip())
29 return None # Variable not found in the file
30 except FileNotFoundError:
31 return None # File not found
32
33# Get vector from a txt file
34def get_vector(file_path, variable_name):
35 try:
36 with open(file_path, 'r') as file:
37 for line in file:
38 line = line.split(';', 1)[0] # Ignore everything after the first semicolon
39 parts = line.strip().split('=')
40 if len(parts) == 2:
41 name, value = parts
42 if name.strip() == variable_name:
43 print(f"Found variable {variable_name} in the line: {line.strip()}")
44 try:
45 vector_str = value.strip()
46 # Add commas between values
47 vector_str_with_commas = ','.join(vector_str.split())
48 vector = np.array([float(item) for item in vector_str_with_commas.split(',')])
49 return vector
50 except ValueError as e:
51 print(f"Error converting to a NumPy array: {e}")
52 return None
53 return None # Variable not found in the file
54 except FileNotFoundError:
55 return None # File not found
56
57def is_number(s):
58 """ Helper function to check if a string can be converted to a float. """
59 try:
60 float(s)
61 return True
62 except ValueError:
63 return False
64
65def get_matrix(file_path, variable_name):
66 try:
67 with open(file_path, 'r') as file:
68 found_variable = False
69 matrix_lines = []
70 for line in file:
71 clean_line = line.split(';', 1)[0].strip() # Ignore everything after the first semicolon and strip whitespace
72 if not clean_line:
73 continue # Skip empty lines
74
75 parts = clean_line.split('=')
76 if len(parts) == 2:
77 name, value = parts
78 if name.strip() == variable_name:
79 print(f"Found variable {variable_name} in the line: {line.strip()}")
80 found_variable = True
81 matrix_lines.append(value.strip())
82 elif found_variable:
83 # Continue collecting lines until a semicolon is encountered
84 if ';' in line:
85 matrix_lines.append(line.split(';')[0].strip())
86 break # Stop reading when a semicolon is encountered
87 else:
88 matrix_lines.append(clean_line)
89
90 if matrix_lines:
91 try:
92 # Join all lines into a single string and split into individual elements
93 matrix_str = ' '.join(matrix_lines)
94 matrix_values = [item for item in matrix_str.split() if is_number(item)]
95 matrix_values = [float(item) for item in matrix_values]
96 # Determine the number of rows (number of lines collected)
97 num_rows = len(matrix_lines)
98 # Calculate the number of columns from the first row
99 num_cols = len(matrix_values) // num_rows
100 # Reshape the matrix
101 matrix = np.array(matrix_values).reshape((num_rows, num_cols))
102 return matrix
103 except ValueError as e:
104 print(f"Error converting to a NumPy array: {e}")
105 return None
106 return None # Variable not found in the file
107 except FileNotFoundError:
108 print(f"File not found: {file_path}")
109 return None # File not found
110
111
112#def load_variables_from_file(filename):
113# variables = {}
114# try:
115# with open(filename, 'r') as file:
116# for line in file:
117# line = line.strip()
118# if line and '=' in line:
119# semicolon_index = line.find(';')
120# if semicolon_index != -1:
121# # Cut the line at the first semicolon
122# line = line[:semicolon_index] + '\n'
123# name, value = line.split('=', 1)
124# #value = value.replace('e', 'e')
125# #value = value.replace('-', '-')
126# #value = value.replace('+', '+0')
127# variables[name.strip()] = value.strip()
128# except FileNotFoundError:
129# print(f"File '{filename}' not found.")
130# except Exception as e:
131# print(f"An error occurred: {e}")
132#
133# return variables
134#
135#def copy_file_with_variable_changes(source_file, destination_file, changes):
136# try:
137# with open(source_file, 'r') as src, open(destination_file, 'w') as dest:
138# for line in src:
139# for var_name, new_value in changes.items():
140# line = line.replace(f'{var_name} =', f'{var_name} = {new_value}')
141# dest.write(line)
142#
143# print("File copied with variable changes.")
144# except FileNotFoundError:
145# print(f"Source file '{source_file}' not found.")
146# except Exception as e:
147# print(f"An error occurred: {e}")
is_number(s)
Definition readFile.py:57
get_vector(file_path, variable_name)
Definition readFile.py:34
get_scalar(file_path, variable_name)
Definition readFile.py:18
get_matrix(file_path, variable_name)
Definition readFile.py:65
generate_file_paths(directory, names)
Definition readFile.py:9
REAL split