{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee96cb15",
   "metadata": {},
   "outputs": [],
   "source": [
    "import glob\n",
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy.signal import spectrogram\n",
    "\n",
    "folder_path = r'G:\\Fault_Diagnosis\\APS-New-Test\\Data-in-brief\\Processed-Data\\6314\\Korrosion\\12,8kHz\\DatenKorrosion_6314_323Nm_2000U_min_20260929'\n",
    "fs = 12800 # Sampling frequency in Hz\n",
    "dt = 1 / fs\n",
    "time_ticks = [0, 30, 60, 90, 120] # Time ticks for the time-domain\n",
    "#time_ticks = [0, 20, 40, 60]\n",
    "#freq_ticks = [0, 1000, 2000, 3000, 4000, 5000]\n",
    "freq_ticks = [0, 1000, 2000, 3000, 4000, 5000, 6000] # Frequency ticks for the FFT and spectrogram as per fs\n",
    "#freq_ticks = [0, 2000, 4000, 6000, 8000, 10000, 12000]\n",
    "#freq_ticks = [0, 5000, 10000, 15000, 20000, 25000]\n",
    "label_size = 14\n",
    "tick_size = 14\n",
    "\n",
    "files = sorted(glob.glob(os.path.join(folder_path, '*.csv')))\n",
    "\n",
    "if files:\n",
    "  all_data, ffts = [], []\n",
    "  for f in files:\n",
    "    try:\n",
    "      df = pd.read_csv(f, header=None)\n",
    "      sig = (\n",
    "          df.iloc[:, 0].values.astype(float)\n",
    "          if df.iloc[0, 0].dtype != object\n",
    "          else pd.read_csv(f, header=0).iloc[:, 0].values.astype(float)\n",
    "      )\n",
    "    except Exception:\n",
    "      try:\n",
    "        sig = pd.read_csv(f, header=0).iloc[:, 0].values.astype(float)\n",
    "      except Exception:\n",
    "        continue\n",
    "    all_data.append(sig)\n",
    "    ffts.append(np.abs(np.fft.rfft(sig)) / len(sig) * 2)\n",
    "\n",
    "  combined = np.concatenate(all_data)\n",
    "  time = np.arange(len(combined)) * dt\n",
    "  mean_fft = np.mean(ffts, axis=0)\n",
    "  mean_fft /= np.max(mean_fft) if np.max(mean_fft) > 0 else 1\n",
    "  xf = np.fft.rfftfreq(len(all_data[0]), dt)\n",
    "\n",
    "  f_spec, t_spec, Sxx = spectrogram(\n",
    "      combined,\n",
    "      fs,\n",
    "      window='hann',\n",
    "      nperseg=1024,\n",
    "      noverlap=512,\n",
    "      scaling='spectrum',\n",
    "      mode='magnitude',\n",
    "  )\n",
    "  Sxx_log = 20 * np.log10(Sxx + 1e-12)\n",
    "\n",
    "  fig = plt.figure(figsize=(8, 12))\n",
    "  gs = fig.add_gridspec(\n",
    "      3,\n",
    "      2,\n",
    "      width_ratios=[1, 0.04],\n",
    "      height_ratios=[1, 1, 1],\n",
    "      wspace=0.06,\n",
    "      hspace=0.35,\n",
    "  )\n",
    "\n",
    "  ax_time = fig.add_subplot(gs[0, 0])\n",
    "  ax_fft = fig.add_subplot(gs[1, 0])\n",
    "  ax_spec = fig.add_subplot(gs[2, 0])\n",
    "  cax = fig.add_subplot(gs[2, 1])\n",
    "\n",
    "  ax_time.plot(time, combined, lw=0.4, color='b')\n",
    "  ax_time.set_ylabel('Amplitude [g] →', fontsize=label_size)\n",
    "  ax_time.set_xlabel('Time [s] →', fontsize=label_size)\n",
    "  ax_time.grid(True)\n",
    "  ax_time.set_xlim(0, 40)\n",
    "  ax_time.set_ylim(-50, 50)\n",
    "  ax_time.set_xticks(time_ticks)\n",
    "  ax_time.tick_params(axis='both', labelsize=tick_size)\n",
    "\n",
    "  ax_fft.plot(xf, mean_fft, color='blue', lw=1)\n",
    "  ax_fft.set_ylabel('Norm. Magnitude [g] →', fontsize=label_size)\n",
    "  ax_fft.set_xlabel('Frequency [Hz] →', fontsize=label_size)\n",
    "  ax_fft.grid(True)\n",
    "  ax_fft.set_xlim(0, fs / 2)\n",
    "  ax_fft.set_ylim(0, 1.05)\n",
    "  ax_fft.set_xticks(freq_ticks)\n",
    "  ax_fft.tick_params(axis='both', labelsize=tick_size)\n",
    "\n",
    "  pcm = ax_spec.pcolormesh(\n",
    "      f_spec,\n",
    "      t_spec,\n",
    "      Sxx_log.T,\n",
    "      shading='gouraud',\n",
    "      cmap='viridis',\n",
    "      vmin=-40,\n",
    "      vmax=-10,\n",
    "  )\n",
    "  ax_spec.set_xlabel('Frequency [Hz] →', fontsize=label_size)\n",
    "  ax_spec.set_ylabel('Time [s] →', fontsize=label_size)\n",
    "  ax_spec.set_xlim(0, fs / 2)\n",
    "  ax_spec.set_yticks(time_ticks)\n",
    "  ax_spec.set_xticks(freq_ticks)\n",
    "  ax_spec.tick_params(axis='both', labelsize=tick_size)\n",
    "\n",
    "  cbar = fig.colorbar(pcm, cax=cax)\n",
    "  cbar.set_label('Intensity [dB] →', fontsize=label_size)\n",
    "  cbar.ax.tick_params(labelsize=tick_size)\n",
    "\n",
    "  plt.tight_layout()\n",
    "  plt.show()\n",
    "else:\n",
    "  print('No files found.')"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
