PhD With Me 🔬

thickness

The code:

Takes user-input thickness values. Computes basic statistics (min, max, mean, variance). Plots a histogram of the data alongside an ideal uniform PDF. Performs a Kolmogorov-Smirnov (KS) test to check if the data fits a uniform distribution. Displays results and a conclusion.

Thickness Widget

Including: Roughness Widget

Remake in Matlab as .m file.

Python

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

def main():
    print("Enter thickness values (separated by spaces or commas):")
    user_input = input("> ")
    
    # Parse input with error handling
    try:
        data = np.array([float(x) for x in user_input.replace(',', ' ').split()])
    except ValueError:
        print("Invalid input. Please enter numeric values.")
        return
    
    if len(data) < 2:
        print("Please enter at least 2 values.")
        return
    
    a, b = np.min(data), np.max(data)
    ttv = b - a
    mean = np.mean(data)
    variance = np.var(data)
    uniform_variance = (b - a)**2 / 12

    # Print summary statistics
    print(f"\nSummary Statistics:")
    print(f"Min (a): {a}")
    print(f"Max (b): {b}")
    print(f"TTV: {ttv}")
    print(f"Mean: {mean}")
    print(f"Sample Variance: {variance}")
    print(f"Theoretical Uniform Variance: {uniform_variance}")

    # Plot histogram and uniform PDF
    if ttv == 0:
        print("All values are identical; no variation to plot.")
        return
    plt.figure(figsize=(10, 5))
    plt.hist(data, bins='auto', color='skyblue', edgecolor='black', density=True, alpha=0.7, label='Observed')
    x = np.linspace(a, b, 100)
    plt.plot(x, [1 / ttv] * len(x), 'r--', label='Ideal Uniform PDF')
    plt.title("Histogram of Thickness Measurements")
    plt.xlabel("Thickness")
    plt.ylabel("Density")
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()

    # Kolmogorov-Smirnov test
    ks_stat, p_value = stats.kstest(data, 'uniform', args=(a, ttv))
    print("\nKolmogorov–Smirnov Test for Uniformity:")
    print(f"KS Statistic: {ks_stat:.4f}")
    print(f"P-Value: {p_value:.4f}")
    print("✅ Data likely uniform (p > 0.05)" if p_value > 0.05 else "❌ Data likely not uniform (p ≤ 0.05)")
if __name__ == "__main__":
    main()

TSX

import React, { useState } from 'react';
import * as d3 from 'd3';

const ThicknessAnalyzer = () => {
  const [input, setInput] = useState('');
  const [results, setResults] = useState(null);
  const [error, setError] = useState('');

  const analyzeData = () => {
    try {
      // Parse input
      const data = input
        .replace(/,/g, ' ')
        .split(/\s+/)
        .filter(x => x.trim() !== '')
        .map(x => parseFloat(x));

      // Validate data
      if (data.some(isNaN)) {
        throw new Error("Invalid input. Please enter numeric values.");
      }
      
      if (data.length < 2) {
        throw new Error("Please enter at least 2 values.");
      }

      // Calculate statistics
      const min = Math.min(...data);
      const max = Math.max(...data);
      const ttv = max - min;
      
      // Calculate mean
      const mean = data.reduce((sum, val) => sum + val, 0) / data.length;
      
      // Calculate variance
      const variance = data.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / data.length;
      
      // Calculate theoretical uniform variance
      const uniformVariance = Math.pow(max - min, 2) / 12;

      // Kolmogorov-Smirnov test approximation
      // This is a simplified approximation as we don't have the exact implementation
      const sortedData = [...data].sort((a, b) => a - b);
      const n = sortedData.length;
      
      // Calculate empirical CDF values
      const ecdf = sortedData.map((_, i) => (i + 1) / n);
      
      // Calculate theoretical CDF values for uniform distribution
      const tcdf = sortedData.map(val => (val - min) / ttv);
      
      // Calculate maximum difference
      const differences = ecdf.map((val, i) => Math.abs(val - tcdf[i]));
      const ksStat = Math.max(...differences);
      
      // Approximate p-value using Kolmogorov distribution
      // This is a very simplified approximation
      const criticalValue = 1.36 / Math.sqrt(n);  // 0.05 significance level
      const pValue = ksStat < criticalValue ? 0.99 : 0.01;  // Simplified

      // Generate histogram data
      let histogramData = [];
      if (ttv > 0) {
        // Create bins
        const binCount = Math.min(10, Math.ceil(Math.sqrt(data.length)));
        const binWidth = ttv / binCount;
        
        // Initialize bins
        const bins = Array(binCount).fill(0);
        
        // Fill bins
        data.forEach(val => {
          const binIndex = Math.min(Math.floor((val - min) / binWidth), binCount - 1);
          bins[binIndex]++;
        });
        
        // Convert to density
        const density = bins.map(count => count / (data.length * binWidth));
        
        // Create histogram data
        histogramData = bins.map((count, i) => ({
          x0: min + i * binWidth,
          x1: min + (i + 1) * binWidth,
          y: density[i]
        }));
      }

      setResults({
        min,
        max,
        ttv,
        mean,
        variance,
        uniformVariance,
        ksStat,
        pValue,
        histogramData,
        uniformY: ttv > 0 ? 1 / ttv : 0
      });
      
      setError('');
    } catch (err) {
      setError(err.message);
      setResults(null);
    }
  };

  const renderHistogram = () => {
    if (!results || results.ttv === 0) return null;
    
    const margin = { top: 20, right: 30, bottom: 40, left: 40 };
    const width = 500 - margin.left - margin.right;
    const height = 300 - margin.top - margin.bottom;
    
    // Set up scales
    const x = d3.scaleLinear()
      .domain([results.min, results.max])
      .range([0, width]);
    
    const y = d3.scaleLinear()
      .domain([0, Math.max(d3.max(results.histogramData, d => d.y) * 1.1, results.uniformY * 1.1)])
      .range([height, 0]);

    return (
      <svg width={width + margin.left + margin.right} height={height + margin.top + margin.bottom}>
        <g transform={`translate(${margin.left},${margin.top})`}>
          {/* X axis */}
          <g transform={`translate(0,${height})`}>
            <line x1={0} y1={0} x2={width} y2={0} stroke="black" />
            {x.ticks(5).map(tick => (
              <g key={tick} transform={`translate(${x(tick)},0)`}>
                <line y2={5} stroke="black" />
                <text y={15} textAnchor="middle" fontSize="10px">{tick}</text>
              </g>
            ))}
            <text x={width / 2} y={30} textAnchor="middle">Thickness</text>
          </g>
          
          {/* Y axis */}
          <g>
            <line x1={0} y1={0} x2={0} y2={height} stroke="black" />
            {y.ticks(5).map(tick => (
              <g key={tick} transform={`translate(0,${y(tick)})`}>
                <line x2={-5} stroke="black" />
                <text x={-8} dy="0.32em" textAnchor="end" fontSize="10px">{tick.toFixed(2)}</text>
              </g>
            ))}
            <text transform={`translate(-30,${height/2}) rotate(-90)`} textAnchor="middle">Density</text>
          </g>
          
          {/* Histogram bars */}
          {results.histogramData.map((d, i) => (
            <rect
              key={i}
              x={x(d.x0)}
              y={y(d.y)}
              width={x(d.x1) - x(d.x0)}
              height={height - y(d.y)}
              fill="skyblue"
              stroke="black"
              fillOpacity={0.7}
            />
          ))}
          
          {/* Uniform PDF line */}
          <line
            x1={0}
            y1={y(results.uniformY)}
            x2={width}
            y2={y(results.uniformY)}
            stroke="red"
            strokeDasharray="5,5"
            strokeWidth={2}
          />
          
          {/* Legend */}
          <g transform={`translate(${width - 150}, 10)`}>
            <rect width={12} height={12} fill="skyblue" fillOpacity={0.7} stroke="black" />
            <text x={16} y={10} fontSize="10px">Observed</text>
            <line x1={0} y1={30} x2={12} y2={30} stroke="red" strokeDasharray="5,5" strokeWidth={2} />
            <text x={16} y={33} fontSize="10px">Ideal Uniform PDF</text>
          </g>
        </g>
      </svg>
    );
  };

  return (
    <div className="p-4 max-w-4xl mx-auto">
      <h2 className="text-xl font-bold mb-4">Thickness Measurement Analyzer</h2>
      
      <div className="mb-4">
        <label className="block mb-2">
          Enter thickness values (separated by spaces or commas):
        </label>
        <div className="flex">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            className="flex-grow p-2 border rounded mr-2"
            placeholder="e.g. 4.2, 5.1, 4.8, 5.2"
          />
          <button
            onClick={analyzeData}
            className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
          >
            Analyze
          </button>
        </div>
        {error && <p className="text-red-500 mt-2">{error}</p>}
      </div>
      
      {results && (
        <div className="border rounded p-4 bg-gray-50">
          <h3 className="font-bold mb-2">Summary Statistics:</h3>
          <div className="grid grid-cols-2 gap-4 mb-4">
            <div>
              <p><strong>Min (a):</strong> {results.min.toFixed(4)}</p>
              <p><strong>Max (b):</strong> {results.max.toFixed(4)}</p>
              <p><strong>TTV:</strong> {results.ttv.toFixed(4)}</p>
            </div>
            <div>
              <p><strong>Mean:</strong> {results.mean.toFixed(4)}</p>
              <p><strong>Sample Variance:</strong> {results.variance.toFixed(4)}</p>
              <p><strong>Theoretical Uniform Variance:</strong> {results.uniformVariance.toFixed(4)}</p>
            </div>
          </div>
          
          {results.ttv > 0 ? (
            <div className="mb-4">
              <h3 className="font-bold mb-2">Histogram of Thickness Measurements:</h3>
              <div className="bg-white border rounded p-2">
                {renderHistogram()}
              </div>
            </div>
          ) : (
            <p className="mb-4">All values are identical; no variation to plot.</p>
          )}
          
          <div>
            <h3 className="font-bold mb-2">Kolmogorov–Smirnov Test for Uniformity:</h3>
            <p><strong>KS Statistic:</strong> {results.ksStat.toFixed(4)}</p>
            <p><strong>P-Value:</strong> {results.pValue.toFixed(4)}</p>
            <p>
              {results.pValue > 0.05 ? (
                <span className="text-green-600">✅ Data likely uniform (p &gt; 0.05)</span>
              ) : (
                <span className="text-red-600">❌ Data likely not uniform (p ≤ 0.05)</span>
              )}
            </p>
          </div>
        </div>
      )}
    </div>
  );
};

export default ThicknessAnalyzer;