MoxTools 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of MoxTools might be problematic. Click here for more details.

MxTools/dataIO.py ADDED
@@ -0,0 +1,152 @@
1
+ import math
2
+ import csv
3
+ import numpy as np
4
+ import logging
5
+ from PIL import Image
6
+ from itertools import zip_longest
7
+ import logging
8
+
9
+ ##########################################################################
10
+ # csv file
11
+ ##########################################################################
12
+
13
+
14
+ # read csv file and save array(str)
15
+ # csv:
16
+ # param1,param2
17
+ # 1,2
18
+ # 3,4
19
+ # [[param1,param2],[1,2],[3,4]]
20
+ def readCSV_to_array(fpath):
21
+ data_array = []
22
+ with open(fpath, newline="") as csv_file:
23
+ rows = csv.reader(csv_file, delimiter=",")
24
+ for row in rows:
25
+ # cleaned_row = [value for value in row if value.strip()]
26
+ # if cleaned_row:
27
+ data_array.append(row)
28
+ return data_array
29
+
30
+
31
+ # read CSV file to array as type:float w/o empty
32
+ # empty show "None"
33
+ def readCSV_to_arrayFloat(fpath):
34
+ data_array = []
35
+ with open(fpath, newline="") as csv_file:
36
+ rows = csv.reader(csv_file, delimiter=",")
37
+ for row in rows:
38
+ data_array.append([float(value) if value.strip() else None for value in row])
39
+ return data_array
40
+
41
+ # read CSV config file
42
+ # format as below
43
+ # Hpos,Vpos
44
+ # 0,0
45
+ # 80,62
46
+ # column can different length.
47
+ def readCSV_cfgFile1(fpath):
48
+ cfg_dict = {}
49
+ dataArray = readCSV_to_array(fpath)
50
+ dataArray = np.array(dataArray)
51
+ rows, cols = dataArray.shape
52
+ logging.info(f"row,col=({rows},{cols})")
53
+ headers = [value for value in dataArray[0, :] if value.strip()] # remove none&empty
54
+ # logging.info(f"dataArray=({headers}")
55
+
56
+ for col in range(cols):
57
+ cfg_dict[str(headers[col])] = [str(value) for value in dataArray[1:, col] if value.strip()] # remove none&empty
58
+
59
+ # logging.info(f"cfg_dict=({cfg_dict}")
60
+
61
+ return cfg_dict
62
+
63
+
64
+ # write 2DArray data directly
65
+ def writeCSV_from_array(fpath, data):
66
+
67
+ with open(fpath, "w", newline="") as csvfile:
68
+ fd = csv.writer(csvfile)
69
+ fd.writerows(data)
70
+
71
+
72
+ # write CSV file from below format
73
+ # dict={'name1': [data1-1, data1-2], 'name2': [data2-1, data2-2]}
74
+ # save as csv format:
75
+ # name1, name2
76
+ # data1-1,data2-1
77
+ # data1-2,data2-2
78
+ def writeCSV_from_dict1(FilePath, dataDict: dict):
79
+ header = []
80
+ data = []
81
+ for i in dataDict.keys():
82
+ header.append(i)
83
+ data.append(dataDict[i])
84
+ columnTable = list(zip_longest(*data)) # row switch to column
85
+ with open(FilePath, "w", newline="") as csvfile:
86
+ fd = csv.writer(csvfile)
87
+ fd.writerow(header) # write Header
88
+ fd.writerows(columnTable) # write data table
89
+
90
+
91
+ ##########################################################################
92
+ # txt file
93
+ ##########################################################################
94
+
95
+
96
+ # read one config param value from txt
97
+ # txt file foramt:
98
+ # sort_key1 p70_d p60_d p45_d _00_d
99
+ # sort_key2 p70_a p60_a p45_a _00_a
100
+ # param1=sort_key1, value=p70_d p60_d p45_d _00_d
101
+ # param2=sort_key2, value=p70_a p60_a p45_a _00_a
102
+ def readTXT_cfgParam(fpath, param: str):
103
+ with open(fpath, newline="") as txt:
104
+ rows = csv.reader(txt, delimiter=" ")
105
+ for row in rows:
106
+ if param == row[0]:
107
+ value = row[1 : len(row)]
108
+ return value
109
+
110
+
111
+ ##########################################################################
112
+ # Pillow Image
113
+ ##########################################################################
114
+
115
+
116
+ # 2D array to 8bit gray format image
117
+ def array_to8bGaryImage(array):
118
+ img = Image.fromarray(array, "L")
119
+ return img
120
+
121
+
122
+ # save 2D array(uint8) data to image(.png) file
123
+ def array_to8bGaryImageFile(imgArray, path):
124
+
125
+ img = Image.fromarray(imgArray, "L")
126
+ img.save(path)
127
+
128
+
129
+ def array_to16bGaryImageFile_normal(array, output_path, normalized):
130
+ array_max = np.max(array)
131
+ logging.info(f"input image array_max={array_max}")
132
+
133
+ normalized_array = normalized * (array / array_max)
134
+ normalized_array = normalized_array.astype(np.uint16)
135
+ logging.info(f"normalized_array max={np.max(normalized_array)}")
136
+
137
+ img = Image.fromarray(normalized_array, mode="I;16") # 將 numpy array 轉換為圖像
138
+ img.save(output_path)
139
+
140
+
141
+ # save image arrays to GIF
142
+ # images.append(array_to_8bGaryImage(array))
143
+ # duration uint:ms
144
+ def arrays_ToGifFile(images, path, duration):
145
+
146
+ images[0].save(path, save_all=True, append_images=images[1:], loop=0, duration=duration)
147
+
148
+
149
+ def imageFile_to16bArray(image_path):
150
+ img = Image.open(image_path).convert("I;16") # "L" 表示灰階模式
151
+ img_array = np.array(img) # 將圖像轉換為 numpy array
152
+ return img_array
MxTools/dataProc.py ADDED
@@ -0,0 +1,92 @@
1
+ # import math
2
+ import re
3
+ import numpy as np
4
+ import logging
5
+ # from scipy.ndimage import zoom # for scale
6
+
7
+ # data = ["hpos", "1", "2", "3"]
8
+ # return rd = [1, 2, 3]
9
+ def removeHeader(data, type:str):
10
+ rd = data[1:] # remove header "hpos"
11
+ if type == "INT":
12
+ rd = [int(value) for value in rd if value.strip()] # remove empty data
13
+ else:
14
+ rd = [float(value) for value in rd if value.strip()]
15
+ return rd
16
+
17
+ # input data: "r16c5"
18
+ # output: row=16 col=5
19
+ def parseCMD_rowCol(data:str):
20
+ matches = re.search(r"r(\d+)c(\d+)", data)
21
+ if matches:
22
+ row = int(matches.group(1))
23
+ col = int(matches.group(2))
24
+ else:
25
+ row = "none"
26
+ col = "none"
27
+ return row, col
28
+
29
+
30
+ import re
31
+
32
+ def parseCMD_indexRange(data: str):
33
+ """
34
+ Parses a command string with start and end index in the format 's{start}e{end}'.
35
+ Converts it into a Python `slice` object for use with DataFrame indexing.
36
+
37
+ Parameters:
38
+ data (str): A string containing the command, e.g., "s100e200".
39
+
40
+ Returns:
41
+ slice: A slice object representing the index range (e.g., slice(100, 200)).
42
+ If the pattern is not found, returns slice(None, None) which is equivalent to [:].
43
+ """
44
+
45
+ # Ensure the input is a valid string
46
+ if not isinstance(data, str) or not data:
47
+ return slice(None, None) # Return [:] if the input is invalid
48
+
49
+ # Search for a pattern like "s100e200"
50
+ matches = re.search(r"s(\d+)e(\d+)", data)
51
+
52
+ if matches:
53
+ start = int(matches.group(1)) # Extract the start index as an integer
54
+ end = int(matches.group(2)) # Extract the end index as an integer
55
+ else:
56
+ start, end = None, None # Default to full range if no match is found
57
+
58
+ return slice(start, end) # Create and return a slice object
59
+
60
+
61
+ # round list value with digi-number
62
+ def round_list(data: list, digi):
63
+ ret_list = [round(x, digi) for x in data]
64
+ return ret_list
65
+
66
+ # data: list or array
67
+ # return: max value @ index
68
+ def get_maxValue_Index(data):
69
+ data = np.array(data)
70
+ maxValue = np.max(data)
71
+ index = np.argwhere(data == maxValue)
72
+
73
+ return maxValue, index
74
+
75
+
76
+ def crop_2d_array(inData, start_row, end_row, start_col, end_col):
77
+ inData = np.array(inData)
78
+ cropData = inData[start_row:end_row, start_col:end_col]
79
+ return cropData
80
+
81
+ def scale_2d_array(data, new_width, new_height):
82
+
83
+ original_height, original_width = data.shape
84
+
85
+ # 計算縮放因子
86
+ zoom_factor_height = new_height / original_height
87
+ zoom_factor_width = new_width / original_width
88
+
89
+ # 使用 scipy 的 zoom 函數縮放 order=0~5
90
+ scaled_array = zoom(data, (zoom_factor_height, zoom_factor_width), order=5)
91
+
92
+ return scaled_array
MxTools/fileMg.py ADDED
@@ -0,0 +1,119 @@
1
+ import os
2
+ import logging
3
+
4
+
5
+ def checkFileOrDir(path):
6
+ if os.path.isdir(path):
7
+ return 0
8
+ elif os.path.isfile(path):
9
+ return 1
10
+
11
+ # return "Result output" path
12
+ # ex: /data (data in this folder)
13
+ # /data/out (output result here)
14
+ def get_outFilePath(path):
15
+ outPath = path + r"/out"
16
+ if not os.path.isdir(outPath):
17
+ os.mkdir(outPath)
18
+ return outPath
19
+
20
+
21
+ def generate_output_path(path, dirName:str):
22
+
23
+ if os.path.isdir(path) == True:
24
+ outPath = path + r"/"+dirName
25
+ else:
26
+ os.mkdir(path)
27
+ # sp = os.path.split(path)
28
+ outPath = path + r"/"+dirName
29
+
30
+ if not os.path.isdir(outPath):
31
+ os.mkdir(outPath)
32
+ logging.info(f"output path:{outPath}")
33
+ return outPath
34
+
35
+ def replace_extFileName(fn: str, orgExt: str, newExt: str):
36
+ newFileName = fn.split(orgExt)[0] + newExt
37
+ return newFileName
38
+
39
+
40
+ # input PATH & extensions(mutiple is ok)
41
+ # output file path & file name w/o ext
42
+ # list_of_paths, list_of_files = fileMg.find_files_with_extensions(
43
+ # path, [".dat", ".txt"]
44
+ # )
45
+ def find_files_with_extensions(inPath, extensions):
46
+ list_of_files = []
47
+ fileNames = []
48
+
49
+ logging.info(f"inPath: {inPath}")
50
+ if os.path.isdir(inPath) == True:
51
+ for dirPaths, dirNames, files in os.walk(inPath, topdown=True):
52
+ for fn in files:
53
+ if any(fn.endswith(ext) for ext in extensions):
54
+ list_of_files.append(os.path.join(dirPaths, fn))
55
+ fileNames.append( os.path.splitext(fn)[0] ) # remove extension
56
+ break
57
+ else :
58
+ list_of_files.append(inPath)
59
+ sp = os.path.split(inPath) # split path & filename
60
+ fileNames.append( os.path.splitext(sp[1])[0] ) # remove extension
61
+
62
+ logging.info(list_of_files)
63
+ logging.info(fileNames)
64
+
65
+ return list_of_files, fileNames
66
+
67
+ # fileName = "test_E_-90_605.txt"
68
+ # name, phase, deg = extractFileNameInfo(fileName, partNumber=(0, 1, 2))
69
+ def extractFileNameInfo(fileName: str, partNumber: tuple = (0, 1), sp: str = '_'):
70
+ """
71
+ Dynamically extracts specific parts of a file name based on a given delimiter and range.
72
+
73
+ Parameters:
74
+ fileName (str): The full file name to process.
75
+ partNumber (tuple): A tuple specifying the indices of parts to extract (can be of any length).
76
+ Defaults to (0, 1).
77
+ sp (str): The delimiter used to split the file name. Defaults to '_'.
78
+
79
+ Returns:
80
+ tuple: A tuple containing the extracted parts in the order specified by partNumber.
81
+
82
+ Raises:
83
+ ValueError: If the fileName is empty.
84
+ IndexError: If any index in partNumber is out of range.
85
+ """
86
+ if not fileName:
87
+ raise ValueError("fileName cannot be empty.")
88
+
89
+ # Split the file name by the delimiter
90
+ parts = fileName.split(sp)
91
+
92
+ # Validate partNumber indices
93
+ if not all(0 <= idx < len(parts) for idx in partNumber):
94
+ raise IndexError("Index in partNumber is out of range.")
95
+
96
+ # Extract and return the specified parts as a tuple
97
+ return tuple(parts[idx] for idx in partNumber)
98
+
99
+
100
+ import os
101
+
102
+ def get_folder_from_path(path: str) -> str:
103
+ """
104
+ Determines if the given path is a file or a folder.
105
+ - If it's a file, return the folder containing the file.
106
+ - If it's already a folder, return the path as is.
107
+
108
+ Parameters:
109
+ path (str): The input file or folder path.
110
+
111
+ Returns:
112
+ str: The folder path.
113
+ """
114
+ if os.path.isfile(path):
115
+ return os.path.dirname(path) # 回傳資料夾路徑
116
+ elif os.path.isdir(path):
117
+ return path # 直接回傳資料夾
118
+ else:
119
+ raise ValueError(f"Invalid path: {path} does not exist.")
MxTools/lsf.py ADDED
@@ -0,0 +1,183 @@
1
+ import numpy as np
2
+ import logging
3
+ from PIL import Image
4
+ from scipy.ndimage import zoom
5
+
6
+
7
+ def lut_filter(inData):
8
+ row, col = inData.shape
9
+ logging.info(f"row,col:{row},{col}")
10
+ col_L = int(col/2)
11
+ col_End = col
12
+ # filter from row
13
+ for i in range(row):
14
+ checkData = inData[i,0:col_L]
15
+ min_value = np.min(checkData)
16
+ min_positions = np.argwhere(checkData == min_value)
17
+ # logging.info(f"min value={min_value} pos:{min_positions}")
18
+ if min_value == 0:
19
+ max_pos = np.max(min_positions)
20
+ # logging.info(f"posL:{max_pos}")
21
+ inData[i,0:max_pos] = 0
22
+ checkData = inData[i,col_L:col_End]
23
+ min_value = np.min(checkData)
24
+ min_positions = np.argwhere(checkData == min_value)
25
+ if min_value == 0:
26
+ min_pos = np.min(min_positions)
27
+ # logging.info(f"posR:{col_L+min_pos}")
28
+ inData[i,col_L+min_pos:col_End] = 0
29
+ row_U = int(row/2)
30
+ row_End = row
31
+ for i in range(col):
32
+ checkData = inData[0:row_U,i]
33
+ min_value = np.min(checkData)
34
+ min_positions = np.argwhere(checkData == min_value)
35
+ if min_value == 0:
36
+ max_pos = np.max(min_positions)
37
+ # logging.info(f"posU:{max_pos}")
38
+ inData[0:max_pos,i] = 0
39
+ checkData = inData[row_U:row_End,i]
40
+ min_value = np.min(checkData)
41
+ min_positions = np.argwhere(checkData == min_value)
42
+ if min_value == 0:
43
+ min_pos = np.min(min_positions)
44
+ # logging.info(f"posB:{max_pos}")
45
+ inData[row_U+min_pos:row_End,i] = 0
46
+ return inData
47
+
48
+ def crop_2d_array(inData, start_row, end_row, start_col, end_col):
49
+ inData = np.array(inData)
50
+ cropData = inData[start_row:end_row, start_col:end_col]
51
+ return cropData
52
+
53
+ def scale_2d_array(data, new_width, new_height):
54
+
55
+ original_height, original_width = data.shape
56
+
57
+ # 計算縮放因子
58
+ zoom_factor_height = new_height / original_height
59
+ zoom_factor_width = new_width / original_width
60
+
61
+ # 使用 scipy 的 zoom 函數縮放 order=0~5
62
+ scaled_array = zoom(data, (zoom_factor_height, zoom_factor_width), order=5)
63
+
64
+ return scaled_array
65
+
66
+
67
+ def scaling_down_image_to_array(fp, width, height):
68
+ img = Image.open(fp)
69
+ img_data = np.array(img).astype(np.float32)
70
+ logging.info(f"input data max:{np.max(img_data)} pos:{np.argwhere(img_data == np.max(img_data))}")
71
+ img_scaled = Image.fromarray(img_data).resize((width, height), Image.Resampling.LANCZOS)
72
+ scaled_data = np.array(img_scaled).astype(np.uint16)
73
+ logging.info(f"scaled_data max:{np.max(scaled_data)} pos:{np.argwhere(scaled_data == np.max(scaled_data))}")
74
+ return scaled_data
75
+
76
+
77
+ def scaling_down_image(fp, width, height):
78
+ img = Image.open(fp)
79
+ scaled_down_img = img.resize((width, height), Image.Resampling.LANCZOS)
80
+ return scaled_down_img
81
+
82
+
83
+ def scale_down_2d_array(array, new_row, new_col):
84
+ m, n = array.shape
85
+
86
+ block_m = m // new_row
87
+ block_n = n // new_col
88
+
89
+ # 創建縮小後的新array
90
+ small_array = np.zeros((new_row, new_col))
91
+
92
+ # 對每個區塊取平均值
93
+ for i in range(new_row):
94
+ for j in range(new_col):
95
+ block = array[i * block_m : (i + 1) * block_m, j * block_n : (j + 1) * block_n]
96
+ small_array[i, j] = np.mean(block)
97
+
98
+ return small_array
99
+
100
+
101
+ def lsfNormalize(data, nValue):
102
+
103
+ max_value = np.max(data)
104
+ max_positions = np.argwhere(data == max_value)
105
+ logging.info(f"max value={max_value} pos:{max_positions}")
106
+ # data = np.round(data * float(nValue/max_value)).astype(int)
107
+ # data = np.round(data * float(nValue/max_value))
108
+ data = np.round(data * float(nValue / max_value)).astype(np.uint16)
109
+ logging.info(f"data[{max_positions[0,0]},{max_positions[0,1]}]={data[max_positions[0,0],max_positions[0,1]]}")
110
+
111
+ max_posRow = np.mean(max_positions[:, 0]).astype(int)
112
+ max_posCol = np.mean(max_positions[:, 1]).astype(int)
113
+ max_pos = [max_posRow, max_posCol]
114
+
115
+ return data, max_pos
116
+
117
+
118
+ def get_search_idx(pos, range, length):
119
+ st = pos - range
120
+ if st < 0:
121
+ st = 0
122
+ end = pos + range
123
+ if end >= length:
124
+ end = length - 1
125
+ return st, end
126
+
127
+
128
+ def search_max_rowN(st, end, data):
129
+ dataS = []
130
+ for i in range(st, end):
131
+ dataS.append(np.mean(data[i][:]))
132
+
133
+ max_value = max(dataS)
134
+ max_idx = dataS.index(max_value)
135
+ max_idx = max_idx + st
136
+ return max_idx
137
+
138
+
139
+ def search_max_colN(st, end, data):
140
+ dataS = []
141
+ for i in range(st, end):
142
+ dataS.append(np.mean(data[:, i]))
143
+
144
+ max_value = max(dataS)
145
+ max_idx = dataS.index(max_value)
146
+ max_idx = max_idx + st
147
+ return max_idx
148
+
149
+
150
+ def search_peak_line(data, pos):
151
+ # print(data[1][:])
152
+ rng = 50
153
+ row_length = len(data)
154
+ col_length = len(data[0])
155
+ # search row
156
+ start_row, end_row = get_search_idx(pos[0], rng, row_length)
157
+ logging.info(f"search from row:{start_row} to row:{end_row}")
158
+ max_rowN = search_max_rowN(start_row, end_row, data)
159
+ # search col
160
+ start_col, end_col = get_search_idx(pos[1], rng, col_length)
161
+ logging.info(f"search from col:{start_col} to col:{end_col}")
162
+ max_colN = search_max_colN(start_col, end_col, data)
163
+
164
+ return max_rowN, max_colN
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+