Skip to content

Commit 7e3912f

Browse files
committed
style: Fix ruff linting errors in PR
1 parent abc4f33 commit 7e3912f

2 files changed

Lines changed: 103 additions & 64 deletions

File tree

cnsd/datasets/xjtusy.py

Lines changed: 63 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,117 +1,132 @@
1-
import os
21
import glob
2+
import os
3+
34
import numpy as np
45
import pandas as pd
6+
57
from cnsd.datasets.contract import Dataset
68
from cnsd.physics.configs import XJTUSY_PHYSICS
79

810
# Known fault mappings per XJTU-SY paper
911
# We map Bearing ID to CNSD fault class: 1=Outer, 2=Inner, 3=Cage
1012
XJTUSY_FAULTS = {
1113
'35Hz12kN': {
12-
'Bearing1_1': 1, # Outer
13-
'Bearing1_2': 1, # Outer
14-
'Bearing1_3': 1, # Outer
14+
'Bearing1_1': 1, # Outer
15+
'Bearing1_2': 1, # Outer
16+
'Bearing1_3': 1, # Outer
1517
},
1618
'37.5Hz11kN': {
17-
'Bearing2_1': 2, # Inner
18-
'Bearing2_2': 1, # Outer
19-
'Bearing2_4': 1, # Outer
20-
'Bearing2_5': 1, # Outer
19+
'Bearing2_1': 2, # Inner
20+
'Bearing2_2': 1, # Outer
21+
'Bearing2_4': 1, # Outer
22+
'Bearing2_5': 1, # Outer
2123
},
2224
'40Hz10kN': {
23-
'Bearing3_1': 1, # Outer
24-
'Bearing3_2': 2, # Inner
25-
'Bearing3_3': 2, # Inner
26-
'Bearing3_4': 2, # Inner
27-
'Bearing3_5': 1, # Outer
28-
}
25+
'Bearing3_1': 1, # Outer
26+
'Bearing3_2': 2, # Inner
27+
'Bearing3_3': 2, # Inner
28+
'Bearing3_4': 2, # Inner
29+
'Bearing3_5': 1, # Outer
30+
},
2931
}
3032

31-
def load_xjtusy_domain_split(data_dir=r'E:\301\CNSD\data\XJTU-SY\XJTU-SY_Bearing_Datasets', window_size=32768, train_cond='35Hz12kN', test_cond='37.5Hz11kN'):
33+
34+
def load_xjtusy_domain_split(
35+
data_dir=r'E:\301\CNSD\data\XJTU-SY\XJTU-SY_Bearing_Datasets',
36+
window_size=32768,
37+
train_cond='35Hz12kN',
38+
test_cond='37.5Hz11kN',
39+
):
3240
"""
3341
Loads authentic XJTU-SY dataset and strictly splits by condition (Domain Shift).
34-
Uses the run-to-failure nature to grab the first 15% as Healthy (0) and the
42+
Uses the run-to-failure nature to grab the first 15% as Healthy (0) and the
3543
last 15% as the Fault label.
3644
"""
45+
3746
def _load_condition(cond_folder, rpm_val):
3847
X, y, cond = [], [], []
3948
cond_path = os.path.join(data_dir, cond_folder)
40-
49+
4150
if not os.path.exists(cond_path):
4251
return [], [], []
4352

4453
for bearing_folder in os.listdir(cond_path):
4554
bearing_path = os.path.join(cond_path, bearing_folder)
4655
if not os.path.isdir(bearing_path):
4756
continue
48-
57+
4958
fault_label = XJTUSY_FAULTS.get(cond_folder, {}).get(bearing_folder, None)
50-
if fault_label is None or bearing_folder == 'Bearing1_5': # skip 1_5 to avoid mixed labels
59+
if (
60+
fault_label is None or bearing_folder == 'Bearing1_5'
61+
): # skip 1_5 to avoid mixed labels
5162
continue
52-
53-
csv_files = sorted(glob.glob(os.path.join(bearing_path, '*.csv')),
54-
key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
55-
63+
64+
csv_files = sorted(
65+
glob.glob(os.path.join(bearing_path, '*.csv')),
66+
key=lambda x: int(os.path.splitext(os.path.basename(x))[0]),
67+
)
68+
5669
total_files = len(csv_files)
5770
if total_files < 10:
58-
continue # ignore wildly corrupted directories
59-
71+
continue # ignore wildly corrupted directories
72+
6073
healthy_count = max(1, int(total_files * 0.20))
6174
fault_count = max(1, int(total_files * 0.20))
62-
75+
6376
# Sliding window parameters
6477
step_size = 1024
65-
78+
6679
# Extract Healthy
6780
for fpath in csv_files[:healthy_count]:
6881
df = pd.read_csv(fpath)
69-
sig = df.iloc[:, 0].values # Horizontal acceleration
82+
sig = df.iloc[:, 0].values # Horizontal acceleration
7083
sig = (sig - np.mean(sig)) / (np.std(sig) + 1e-8)
71-
84+
7285
# Slicing the 32768 array into overlapping 4096 windows
7386
for start_idx in range(0, len(sig) - window_size + 1, step_size):
7487
X.append(sig[start_idx : start_idx + window_size])
7588
y.append(0)
7689
cond.append(rpm_val)
77-
90+
7891
# Extract Fault
7992
for fpath in csv_files[-fault_count:]:
8093
df = pd.read_csv(fpath)
8194
sig = df.iloc[:, 0].values
8295
sig = (sig - np.mean(sig)) / (np.std(sig) + 1e-8)
83-
96+
8497
for start_idx in range(0, len(sig) - window_size + 1, step_size):
8598
X.append(sig[start_idx : start_idx + window_size])
8699
y.append(fault_label)
87100
cond.append(rpm_val)
88-
101+
89102
return X, y, cond
90103

91104
X_train, y_train, c_train = _load_condition(train_cond, 2100.0)
92105
X_test, y_test, c_test = _load_condition(test_cond, 2250.0)
93-
106+
94107
if not X_train or not X_test:
95-
raise FileNotFoundError(f"Could not load data. Ensure {data_dir} contains extracted {train_cond} and {test_cond} folders.")
108+
raise FileNotFoundError(
109+
f'Could not load data. Ensure {data_dir} contains extracted {train_cond} and {test_cond} folders.'
110+
)
96111

97112
ds_train = Dataset.from_arrays(
98-
X=np.array(X_train, dtype=np.float32),
99-
y=np.array(y_train, dtype=np.int32),
100-
cond=np.array(c_train, dtype=np.float32),
101-
fs=25600,
102-
physics=XJTUSY_PHYSICS,
113+
X=np.array(X_train, dtype=np.float32),
114+
y=np.array(y_train, dtype=np.int32),
115+
cond=np.array(c_train, dtype=np.float32),
116+
fs=25600,
117+
physics=XJTUSY_PHYSICS,
103118
taxonomy={0: ('Normal', 'None'), 1: ('Outer Race', 'Medium'), 2: ('Inner Race', 'High')},
104-
name='XJTUSY_Train'
119+
name='XJTUSY_Train',
105120
)
106-
121+
107122
ds_test = Dataset.from_arrays(
108-
X=np.array(X_test, dtype=np.float32),
109-
y=np.array(y_test, dtype=np.int32),
110-
cond=np.array(c_test, dtype=np.float32),
111-
fs=25600,
112-
physics=XJTUSY_PHYSICS,
123+
X=np.array(X_test, dtype=np.float32),
124+
y=np.array(y_test, dtype=np.int32),
125+
cond=np.array(c_test, dtype=np.float32),
126+
fs=25600,
127+
physics=XJTUSY_PHYSICS,
113128
taxonomy={0: ('Normal', 'None'), 1: ('Outer Race', 'Medium'), 2: ('Inner Race', 'High')},
114-
name='XJTUSY_Test'
129+
name='XJTUSY_Test',
115130
)
116-
131+
117132
return ds_train, ds_test

validate_xjtusy.py

Lines changed: 40 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
import tensorflow as tf
33

44
from cnsd import Dataset
5-
from cnsd.diagnosis.system import CNSD
65
from cnsd.datasets.xjtusy import load_xjtusy_domain_split
6+
from cnsd.diagnosis.system import CNSD
7+
78

89
def headline_accuracy_by_verdict(report, y_true):
910
pred = np.array([r['predicted_class'] for r in report.records])
@@ -16,6 +17,7 @@ def headline_accuracy_by_verdict(report, y_true):
1617
out[v] = {'n': int(m.sum()), 'cnn_accuracy': float(correct[m].mean())}
1718
return out
1819

20+
1921
if __name__ == '__main__':
2022
np.random.seed(42)
2123
tf.random.set_seed(42)
@@ -31,23 +33,39 @@ def headline_accuracy_by_verdict(report, y_true):
3133
calib_idx = indices[:calib_size]
3234
test_idx = indices[calib_size:]
3335

34-
X_calib, y_calib, cond_calib = target_data.X[calib_idx], target_data.y[calib_idx], target_data.cond[calib_idx]
35-
X_test, y_test, cond_test = target_data.X[test_idx], target_data.y[test_idx], target_data.cond[test_idx]
36+
X_calib, y_calib, cond_calib = (
37+
target_data.X[calib_idx],
38+
target_data.y[calib_idx],
39+
target_data.cond[calib_idx],
40+
)
41+
X_test, y_test, cond_test = (
42+
target_data.X[test_idx],
43+
target_data.y[test_idx],
44+
target_data.cond[test_idx],
45+
)
3646

3747
calib_data = Dataset.from_arrays(
38-
X_calib, y_calib, cond_calib,
39-
fs=target_data.fs, physics=target_data.physics,
48+
X_calib,
49+
y_calib,
50+
cond_calib,
51+
fs=target_data.fs,
52+
physics=target_data.physics,
4053
taxonomy=target_data.taxonomy,
41-
name='XJTUSY_Calib'
54+
name='XJTUSY_Calib',
4255
)
4356
test_data = Dataset.from_arrays(
44-
X_test, y_test, cond_test,
45-
fs=target_data.fs, physics=target_data.physics,
57+
X_test,
58+
y_test,
59+
cond_test,
60+
fs=target_data.fs,
61+
physics=target_data.physics,
4662
taxonomy=target_data.taxonomy,
47-
name='XJTUSY_Test'
63+
name='XJTUSY_Test',
4864
)
4965

50-
print(f'Train (2100 RPM)={len(train_data.y)} | Calib (2250 RPM)={len(y_calib)} | Test (2250 RPM)={len(y_test)}')
66+
print(
67+
f'Train (2100 RPM)={len(train_data.y)} | Calib (2250 RPM)={len(y_calib)} | Test (2250 RPM)={len(y_test)}'
68+
)
5169

5270
model = CNSD()
5371

@@ -81,21 +99,27 @@ def headline_accuracy_by_verdict(report, y_true):
8199
report = model.diagnose(test_data)
82100
pred = np.array([r['predicted_class'] for r in report.records])
83101
baseline_acc = float((pred == np.asarray(y_test)).mean())
84-
102+
85103
print('\n--- FINAL TEST RESULTS (CROSS-DOMAIN XJTU-SY) ---')
86104
print(f'Baseline CNN Acc: {baseline_acc:.3f}')
87105
print('--------------------------------------------')
88-
106+
89107
hb = headline_accuracy_by_verdict(report, y_test)
90108
if 'CONFIRMED' in hb:
91-
print(f' Physics-Confirmed Acc: {hb["CONFIRMED"]["cnn_accuracy"]:.3f} (n={hb["CONFIRMED"]["n"]})')
109+
print(
110+
f' Physics-Confirmed Acc: {hb["CONFIRMED"]["cnn_accuracy"]:.3f} (n={hb["CONFIRMED"]["n"]})'
111+
)
92112
if 'CONFLICT' in hb:
93-
print(f' Physics-Conflict Acc: {hb["CONFLICT"]["cnn_accuracy"]:.3f} (n={hb["CONFLICT"]["n"]})')
113+
print(
114+
f' Physics-Conflict Acc: {hb["CONFLICT"]["cnn_accuracy"]:.3f} (n={hb["CONFLICT"]["n"]})'
115+
)
94116
if 'INCONCLUSIVE' in hb:
95117
inc_n = hb['INCONCLUSIVE']['n']
96118
inc_pct = (inc_n / len(y_test)) * 100
97-
print(f' Physics-Inconclusive Acc:{hb["INCONCLUSIVE"]["cnn_accuracy"]:.3f} (n={inc_n}, {inc_pct:.1f}%)')
98-
119+
print(
120+
f' Physics-Inconclusive Acc:{hb["INCONCLUSIVE"]["cnn_accuracy"]:.3f} (n={inc_n}, {inc_pct:.1f}%)'
121+
)
122+
99123
if 'CONFIRMED' in hb and 'CONFLICT' in hb:
100124
gap = hb['CONFIRMED']['cnn_accuracy'] - hb['CONFLICT']['cnn_accuracy']
101125
print(f' GAP (CONF - CNFL): {gap:+.3f}')

0 commit comments

Comments
 (0)