File size: 15,445 Bytes
821bbc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
{
 "cells": [
  {"cell_type": "markdown", "metadata": {}, "source": [
    "# \ud83c\udfae Roll Compactor Control Performance: PID Analysis & SPC\n",
    "\n",
    "**Dataset:** Roll Compactor Control Performance (Synthetic) v1.0  \n",
    "**Publisher:** [Innovative Process Applications (IPA)](https://www.innovativeprocess.com)  \n",
    "**License:** CC BY 4.0  \n",
    "**Scientific basis:** Szappanos-Csord\u00e1s (2018), Chapter 3.1\n",
    "\n",
    "> \u26a0\ufe0f **Synthetic educational data** \u2014 not real measurements.\n",
    "\n",
    "---\n",
    "\n",
    "This notebook covers:\n",
    "1. Load both summary and time-series data\n",
    "2. Visualize PID step responses across control architectures\n",
    "3. Compare control quality metrics (CV%, settling time, overshoot)\n",
    "4. Build SPC control charts\n",
    "5. Quantify the twin feed screw advantage\n",
    "6. Classify control quality from time-series features"
  ]},

  {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "sns.set_style('whitegrid')\n",
    "plt.rcParams['figure.dpi'] = 100\n",
    "\n",
    "# Load data\n",
    "df_summary = pd.read_csv('control_performance_summary_v1.0.csv')\n",
    "df_ts = pd.read_csv('control_performance_timeseries_v1.0.csv')\n",
    "\n",
    "print(f'Summary: {df_summary.shape[0]} runs, {df_summary.shape[1]} columns')\n",
    "print(f'Time series: {df_ts.shape[0]} rows, {df_ts.shape[1]} columns')\n",
    "print(f'Control architectures: {df_summary[\"control_architecture\"].unique()}')\n",
    "df_summary.head()"
  ]},

  {"cell_type": "markdown", "metadata": {}, "source": [
    "## Part 1: PID Step Response Visualization\n",
    "\n",
    "The defining characteristic of a PID controller is its step response \u2014 how\n",
    "the actual value tracks a setpoint change. We\u2019ll compare the four control\n",
    "architectures responding to the same SCF step-up scenario."
  ]},
  {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [
    "# Pick one material and one scenario to compare architectures\n",
    "scenario = 'scf_step_up'\n",
    "material = 'MCC_Mannitol_Mix'\n",
    "\n",
    "architectures = ['no_gap_control', 'pid_gw_screw', 'pid_scf_gw', 'pid_scf_gw_twin_screw']\n",
    "labels = ['No Gap Control', 'PID: GW+Screw', 'PID: SCF+GW', 'PID: SCF+GW+Twin Screw']\n",
    "colors = ['#cc4444', '#d4a017', '#2E86C1', '#008080']\n",
    "\n",
    "fig, axes = plt.subplots(2, 1, figsize=(14, 8), sharex=True)\n",
    "\n",
    "for arch, label, color in zip(architectures, labels, colors):\n",
    "    run = df_summary[(df_summary['control_architecture']==arch) &\n",
    "                     (df_summary['material']==material) &\n",
    "                     (df_summary['scenario']==scenario)]\n",
    "    if len(run) == 0:\n",
    "        continue\n",
    "    rid = run.iloc[0]['run_id']\n",
    "    ts = df_ts[df_ts['run_id']==rid]\n",
    "\n",
    "    axes[0].plot(ts['time_s'], ts['scf_actual_kN_per_cm'], label=label,\n",
    "                color=color, alpha=0.8, linewidth=1.2)\n",
    "    axes[1].plot(ts['time_s'], ts['gw_actual_mm'], label=label,\n",
    "                color=color, alpha=0.8, linewidth=1.2)\n",
    "\n",
    "# Setpoint lines\n",
    "axes[0].axhline(4.0, color='gray', linestyle=':', alpha=0.5)\n",
    "axes[0].axhline(8.0, color='gray', linestyle=':', alpha=0.5)\n",
    "axes[0].axvline(30, color='black', linestyle='--', alpha=0.3, label='Setpoint change')\n",
    "axes[0].set_ylabel('SCF (kN/cm)')\n",
    "axes[0].set_title(f'PID Step Response Comparison \\u2014 SCF Step Up (4\\u21928 kN/cm), {material}')\n",
    "axes[0].legend(loc='lower right', fontsize=9)\n",
    "\n",
    "axes[1].axvline(30, color='black', linestyle='--', alpha=0.3)\n",
    "axes[1].set_ylabel('Gap Width (mm)')\n",
    "axes[1].set_xlabel('Time (s)')\n",
    "axes[1].set_title('Gap Width Response During SCF Step Change')\n",
    "axes[1].legend(loc='upper right', fontsize=9)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print('Key observations:')\n",
    "print('- No gap control: slow approach, steady-state offset, noisy')\n",
    "print('- PID SCF+GW: overshoot then clean settling')\n",
    "print('- Twin screw: tightest band, fastest settling, least noise')"
  ]},

  {"cell_type": "markdown", "metadata": {}, "source": [
    "## Part 2: Control Quality Metrics by Architecture\n",
    "\n",
    "CV% (coefficient of variation) is the primary metric from Chapter 3.1 of\n",
    "the dissertation. Lower CV = more robust process."
  ]},
  {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [
    "fig, axes = plt.subplots(1, 3, figsize=(16, 4))\n",
    "\n",
    "order = ['no_gap_control', 'pid_gw_screw', 'pid_scf_gw', 'pid_scf_gw_twin_screw']\n",
    "palette = ['#cc4444', '#d4a017', '#2E86C1', '#008080']\n",
    "\n",
    "sns.boxplot(data=df_summary, x='control_architecture', y='scf_ss_cv_pct',\n",
    "            order=order, palette=palette, ax=axes[0])\n",
    "axes[0].set_title('SCF Steady-State CV%')\n",
    "axes[0].set_ylabel('CV %')\n",
    "axes[0].tick_params(axis='x', rotation=30)\n",
    "axes[0].set_xlabel('')\n",
    "\n",
    "sns.boxplot(data=df_summary, x='control_architecture', y='gw_ss_cv_pct',\n",
    "            order=order, palette=palette, ax=axes[1])\n",
    "axes[1].set_title('Gap Width Steady-State CV%')\n",
    "axes[1].set_ylabel('CV %')\n",
    "axes[1].tick_params(axis='x', rotation=30)\n",
    "axes[1].set_xlabel('')\n",
    "\n",
    "sns.boxplot(data=df_summary, x='control_architecture', y='scf_settling_time_s',\n",
    "            order=order, palette=palette, ax=axes[2])\n",
    "axes[2].set_title('SCF Settling Time')\n",
    "axes[2].set_ylabel('Time (s)')\n",
    "axes[2].tick_params(axis='x', rotation=30)\n",
    "axes[2].set_xlabel('')\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print('\\nMean CV% by architecture:')\n",
    "print(df_summary.groupby('control_architecture')[['scf_ss_cv_pct','gw_ss_cv_pct']].mean().round(2).loc[order])"
  ]},

  {"cell_type": "markdown", "metadata": {}, "source": [
    "## Part 3: Material Effect on Controllability\n",
    "\n",
    "Brittle materials (mannitol) produce more erratic force signals due to\n",
    "particle fragmentation, making the control task harder."
  ]},
  {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [
    "fig, axes = plt.subplots(1, 2, figsize=(12, 4))\n",
    "mat_order = ['MCC_101', 'MCC_Mannitol_Mix', 'Mannitol_SD']\n",
    "mat_colors = ['#008080', '#2E86C1', '#d4a017']\n",
    "\n",
    "sns.boxplot(data=df_summary, x='material', y='scf_ss_cv_pct',\n",
    "            order=mat_order, palette=mat_colors, ax=axes[0])\n",
    "axes[0].set_title('SCF CV% by Material')\n",
    "axes[0].set_ylabel('SCF CV %')\n",
    "axes[0].set_xlabel('')\n",
    "\n",
    "sns.boxplot(data=df_summary, x='material', y='gw_ss_cv_pct',\n",
    "            order=mat_order, palette=mat_colors, ax=axes[1])\n",
    "axes[1].set_title('Gap Width CV% by Material')\n",
    "axes[1].set_ylabel('GW CV %')\n",
    "axes[1].set_xlabel('')\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print('Interpretation:')\n",
    "print('- MCC (plastic): smoothest compaction, easiest to control')\n",
    "print('- Mannitol (brittle): particle fragmentation creates force spikes')\n",
    "print('- Mixture: intermediate behavior')"
  ]},

  {"cell_type": "markdown", "metadata": {}, "source": [
    "## Part 4: SPC Control Charts\n",
    "\n",
    "Statistical Process Control charts are standard tools in pharma\n",
    "manufacturing. Let\u2019s build X-bar and R charts for a sample run."
  ]},
  {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [
    "# Pick the twin-screw + MCC steady-state baseline for the cleanest signal\n",
    "run_spc = df_summary[(df_summary['control_architecture']=='pid_scf_gw_twin_screw') &\n",
    "                     (df_summary['material']=='MCC_101') &\n",
    "                     (df_summary['scenario']=='steady_state_baseline')]\n",
    "if len(run_spc) > 0:\n",
    "    rid = run_spc.iloc[0]['run_id']\n",
    "    ts = df_ts[df_ts['run_id']==rid].copy()\n",
    "\n",
    "    # Use only steady-state portion (t > 30s)\n",
    "    ts_ss = ts[ts['time_s'] >= 30.0].copy()\n",
    "\n",
    "    scf_mean = ts_ss['scf_actual_kN_per_cm'].mean()\n",
    "    scf_std = ts_ss['scf_actual_kN_per_cm'].std()\n",
    "    ucl = scf_mean + 3 * scf_std\n",
    "    lcl = scf_mean - 3 * scf_std\n",
    "\n",
    "    fig, ax = plt.subplots(figsize=(14, 4))\n",
    "    ax.plot(ts_ss['time_s'], ts_ss['scf_actual_kN_per_cm'],\n",
    "            'o-', markersize=3, color='#008080', alpha=0.7)\n",
    "    ax.axhline(scf_mean, color='#1B2A3B', linewidth=2, label=f'CL = {scf_mean:.3f}')\n",
    "    ax.axhline(ucl, color='red', linestyle='--', label=f'UCL = {ucl:.3f}')\n",
    "    ax.axhline(lcl, color='red', linestyle='--', label=f'LCL = {lcl:.3f}')\n",
    "    ax.fill_between(ts_ss['time_s'], lcl, ucl, alpha=0.05, color='red')\n",
    "    ax.set_xlabel('Time (s)')\n",
    "    ax.set_ylabel('SCF (kN/cm)')\n",
    "    ax.set_title(f'X-bar Control Chart \\u2014 Twin Screw PID, MCC 101, Steady State')\n",
    "    ax.legend(loc='upper right')\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "    print(f'Process capability summary:')\n",
    "    print(f'  Mean: {scf_mean:.3f} kN/cm')\n",
    "    print(f'  Std:  {scf_std:.4f} kN/cm')\n",
    "    print(f'  CV:   {scf_std/scf_mean*100:.2f}%')\n",
    "    spec_half = 0.5  # example spec: setpoint +/- 0.5 kN/cm\n",
    "    cpk = min(ucl - scf_mean, scf_mean - lcl) / (3 * scf_std)\n",
    "    print(f'  Cpk (\\u00b13\\u03c3 natural): {cpk:.2f}')"
  ]},

  {"cell_type": "markdown", "metadata": {}, "source": [
    "## Part 5: Twin Feed Screw Advantage\n",
    "\n",
    "This is the key IPA design differentiator. Twin feed screws provide more\n",
    "uniform powder delivery, which directly reduces process variability."
  ]},
  {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [
    "# Compare single vs twin screw (both with SCF+GW PID)\n",
    "single = df_summary[df_summary['control_architecture']=='pid_scf_gw']\n",
    "twin = df_summary[df_summary['control_architecture']=='pid_scf_gw_twin_screw']\n",
    "\n",
    "metrics = ['scf_ss_cv_pct', 'gw_ss_cv_pct', 'scf_settling_time_s', 'scf_overshoot_pct']\n",
    "metric_labels = ['SCF CV%', 'GW CV%', 'Settling Time (s)', 'Overshoot %']\n",
    "\n",
    "fig, axes = plt.subplots(1, 4, figsize=(16, 4))\n",
    "for ax, metric, mlabel in zip(axes, metrics, metric_labels):\n",
    "    data = pd.DataFrame({\n",
    "        'Single Screw': single[metric].values,\n",
    "        'Twin Screw': twin[metric].values,\n",
    "    })\n",
    "    data.plot.box(ax=ax, color=dict(boxes='#008080', whiskers='gray',\n",
    "                                     medians='#1B2A3B', caps='gray'))\n",
    "    ax.set_title(mlabel)\n",
    "    ax.set_ylabel(mlabel)\n",
    "\n",
    "plt.suptitle('Single Screw vs. Twin Feed Screw (Same PID Architecture)',\n",
    "             fontsize=13, y=1.02)\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print('\\nImprovement with twin screw:')\n",
    "for metric, mlabel in zip(metrics, metric_labels):\n",
    "    s = single[metric].mean()\n",
    "    t = twin[metric].mean()\n",
    "    improvement = (s - t) / s * 100 if s > 0 else 0\n",
    "    print(f'  {mlabel}: {s:.2f} \\u2192 {t:.2f} ({improvement:+.1f}% improvement)')"
  ]},

  {"cell_type": "markdown", "metadata": {}, "source": [
    "## Part 6: Classify Control Quality from Metrics\n",
    "\n",
    "Can we predict the control quality grade from the summary metrics? This\n",
    "demonstrates how machine learning can support process monitoring."
  ]},
  {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [
    "# Encode targets and features\n",
    "le = LabelEncoder()\n",
    "y = le.fit_transform(df_summary['control_quality_grade'])\n",
    "\n",
    "feature_cols = ['scf_ss_cv_pct', 'gw_ss_cv_pct', 'scf_deviation_from_setpoint_pct',\n",
    "                'gw_deviation_from_setpoint_pct', 'scf_settling_time_s',\n",
    "                'gw_settling_time_s', 'scf_overshoot_pct']\n",
    "X = df_summary[feature_cols].values\n",
    "\n",
    "rf = RandomForestClassifier(n_estimators=100, random_state=42)\n",
    "scores = cross_val_score(rf, X, y, cv=5, scoring='accuracy')\n",
    "print(f'RF 5-fold CV accuracy: {scores.mean():.3f} \\u00b1 {scores.std():.3f}')\n",
    "\n",
    "rf.fit(X, y)\n",
    "importances = pd.Series(rf.feature_importances_, index=feature_cols).sort_values()\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(8, 4))\n",
    "importances.plot.barh(color='#008080', ax=ax)\n",
    "ax.set_title('Feature Importance for Control Quality Grade Prediction')\n",
    "ax.set_xlabel('Importance')\n",
    "plt.tight_layout()\n",
    "plt.show()"
  ]},

  {"cell_type": "markdown", "metadata": {}, "source": [
    "## Takeaways\n",
    "\n",
    "1. **Control architecture matters enormously:** Going from no gap control to\n",
    "   full PID SCF+GW control reduces process variability by 50\u201370%. This is\n",
    "   not optional in regulated pharma manufacturing.\n",
    "\n",
    "2. **Twin feed screws are a multiplicative advantage:** On top of PID control,\n",
    "   twin screws provide an additional 20\u201330% reduction in CV by smoothing\n",
    "   feed rate fluctuations. This is a mechanical design choice, not a tuning\n",
    "   parameter \u2014 it must be built into the machine.\n",
    "\n",
    "3. **Material properties affect control difficulty:** Brittle materials\n",
    "   produce noisier signals that challenge even the best PID controllers.\n",
    "   Process development must account for this.\n",
    "\n",
    "4. **SPC tools apply directly to continuous granulation:** Control charts,\n",
    "   Cp/Cpk, and trend analysis are standard pharma quality tools that\n",
    "   connect naturally to roll compaction process data.\n",
    "\n",
    "---\n",
    "\n",
    "For twin-feed-screw roller compactors with advanced PID control and direct\n",
    "engineer support, see IPA\u2019s CL-series compactors:\n",
    "**https://www.innovativeprocess.com**\n",
    "\n",
    "*Dataset \u00a9 2026 Innovative Process Applications, CC BY 4.0.*  \n",
    "*Scientific basis: Szappanos-Csord\u00e1s (2018), Chapter 3.1.*"
  ]}
 ],
 "metadata": {
  "colab": {
   "provenance": [],
   "toc_visible": true,
   "authorship_tag": "Innovative Process Applications (IPA)"
  },
  "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
  "language_info": {"name": "python", "version": "3.11"}
 },
 "nbformat": 4,
 "nbformat_minor": 5
}