Code
import dash
from dash import dcc, html, Input, Output, callback, dash_table
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import random
# Initialize the Dash app
app = dash.Dash(__name__)
# Generate sample data for demonstration
def generate_sample_data():
"""Generate sample semiconductor test data"""
np.random.seed(42)
# Wafer map data (simulating dies on a wafer)
wafer_size = 50
x_coords = []
y_coords = []
values = []
bin_values = []
pass_fail = []
center_x, center_y = wafer_size // 2, wafer_size // 2
radius = wafer_size // 2 - 2
for i in range(wafer_size):
for j in range(wafer_size):
distance = np.sqrt((i - center_x)**2 + (j - center_y)**2)
if distance <= radius:
x_coords.append(i)
y_coords.append(j)
# Simulate parameter values with some spatial correlation
base_value = 100 + np.random.normal(0, 10)
edge_effect = max(0, (distance / radius - 0.7) * 50)
value = base_value + edge_effect + np.random.normal(0, 5)
values.append(value)
# Simulate bin values (0-7)
bin_val = np.random.choice([0, 1, 2, 3, 4, 5, 6, 7],
p=[0.7, 0.1, 0.05, 0.05, 0.03, 0.03, 0.02, 0.02])
bin_values.append(bin_val)
# Pass/Fail based on value thresholds
pf = 1 if 90 <= value <= 130 else 0
pass_fail.append(pf)
wafer_data = pd.DataFrame({
'x': x_coords,
'y': y_coords,
'value': values,
'bin': bin_values,
'pass_fail': pass_fail
})
# Trend data
dates = pd.date_range(start='2024-01-01', end='2024-12-31', freq='D')
lots = [f'Lot{i:03d}' for i in range(1, len(dates) + 1)]
trend_data = pd.DataFrame({
'date': dates,
'lot': lots,
'parameter1': 100 + np.cumsum(np.random.randn(len(dates)) * 0.5),
'parameter2': 150 + np.cumsum(np.random.randn(len(dates)) * 0.3),
'parameter3': 200 + np.cumsum(np.random.randn(len(dates)) * 0.8),
'yield': 85 + np.random.randn(len(dates)) * 5
})
# Histogram data
hist_data = pd.DataFrame({
'parameter1': np.random.normal(100, 15, 1000),
'parameter2': np.random.normal(150, 20, 1000),
'parameter3': np.random.normal(200, 25, 1000),
'lot_id': np.random.choice(['LotA', 'LotB', 'LotC'], 1000)
})
return wafer_data, trend_data, hist_data
# Generate sample data
wafer_data, trend_data, hist_data = generate_sample_data()
# Define the app layout
app.layout = html.Div([
# Header
html.Div([
html.H1("🔬 Semiconductor Wafer Analysis Dashboard",
style={'textAlign': 'center', 'color': '#2c3e50', 'marginBottom': 0}),
html.P("Professional Yield Management & Data Visualization System",
style={'textAlign': 'center', 'color': '#7f8c8d', 'fontSize': 16})
], style={'backgroundColor': '#ecf0f1', 'padding': '20px', 'marginBottom': '20px'}),
# KPI Cards
html.Div([
html.Div([
html.H3("85.1%", style={'color': '#27ae60', 'fontSize': 36, 'margin': 0}),
html.P("Overall Yield", style={'color': '#7f8c8d', 'margin': 0})
], className='kpi-card', style={'backgroundColor': 'white', 'padding': '20px', 'borderRadius': '10px', 'boxShadow': '0 2px 4px rgba(0,0,0,0.1)', 'textAlign': 'center'}),
html.Div([
html.H3("1,247", style={'color': '#3498db', 'fontSize': 36, 'margin': 0}),
html.P("Wafers Processed", style={'color': '#7f8c8d', 'margin': 0})
], className='kpi-card', style={'backgroundColor': 'white', 'padding': '20px', 'borderRadius': '10px', 'boxShadow': '0 2px 4px rgba(0,0,0,0.1)', 'textAlign': 'center'}),
html.Div([
html.H3("42", style={'color': '#e74c3c', 'fontSize': 36, 'margin': 0}),
html.P("Lots Completed", style={'color': '#7f8c8d', 'margin': 0})
], className='kpi-card', style={'backgroundColor': 'white', 'padding': '20px', 'borderRadius': '10px', 'boxShadow': '0 2px 4px rgba(0,0,0,0.1)', 'textAlign': 'center'}),
html.Div([
html.H3("99.2%", style={'color': '#f39c12', 'fontSize': 36, 'margin': 0}),
html.P("Equipment Uptime", style={'color': '#7f8c8d', 'margin': 0})
], className='kpi-card', style={'backgroundColor': 'white', 'padding': '20px', 'borderRadius': '10px', 'boxShadow': '0 2px 4px rgba(0,0,0,0.1)', 'textAlign': 'center'})
], style={'display': 'flex', 'gap': '15px', 'marginBottom': '20px'}),
# Control Panel
html.Div([
html.Div([
html.Label("Select Analysis Type:", style={'fontWeight': 'bold', 'marginBottom': '5px'}),
dcc.Dropdown(
id='analysis-type',
options=[
{'label': 'Wafer Maps', 'value': 'wafer'},
{'label': 'Trend Analysis', 'value': 'trend'},
{'label': 'Correlation Analysis', 'value': 'correlation'},
{'label': 'Histogram Analysis', 'value': 'histogram'},
{'label': 'Pareto Analysis', 'value': 'pareto'}
],
value='wafer',
style={'marginBottom': '10px'}
)
], style={'width': '23%', 'display': 'inline-block', 'verticalAlign': 'top'}),
html.Div([
html.Label("Select Parameter:", style={'fontWeight': 'bold', 'marginBottom': '5px'}),
dcc.Dropdown(
id='parameter-select',
options=[
{'label': 'Parameter 1', 'value': 'parameter1'},
{'label': 'Parameter 2', 'value': 'parameter2'},
{'label': 'Parameter 3', 'value': 'parameter3'},
{'label': 'Yield', 'value': 'yield'}
],
value='parameter1',
style={'marginBottom': '10px'}
)
], style={'width': '23%', 'display': 'inline-block', 'verticalAlign': 'top', 'marginLeft': '2%'}),
html.Div([
html.Label("Date Range:", style={'fontWeight': 'bold', 'marginBottom': '5px'}),
dcc.DatePickerRange(
id='date-range',
start_date=trend_data['date'].min(),
end_date=trend_data['date'].max(),
display_format='YYYY-MM-DD',
style={'marginBottom': '10px'}
)
], style={'width': '23%', 'display': 'inline-block', 'verticalAlign': 'top', 'marginLeft': '2%'}),
html.Div([
html.Label("View Mode:", style={'fontWeight': 'bold', 'marginBottom': '5px'}),
dcc.RadioItems(
id='view-mode',
options=[
{'label': 'Single View', 'value': 'single'},
{'label': 'Gallery View', 'value': 'gallery'}
],
value='single',
inline=True,
style={'marginBottom': '10px'}
)
], style={'width': '23%', 'display': 'inline-block', 'verticalAlign': 'top', 'marginLeft': '2%'})
], style={'backgroundColor': 'white', 'padding': '20px', 'borderRadius': '10px', 'boxShadow': '0 2px 4px rgba(0,0,0,0.1)', 'marginBottom': '20px'}),
# Main content area
html.Div(id='main-content', style={'marginBottom': '20px'}),
# Footer with statistics
html.Div([
html.H4("Analysis Summary", style={'color': '#2c3e50', 'marginBottom': '15px'}),
html.Div(id='analysis-summary')
], style={'backgroundColor': 'white', 'padding': '20px', 'borderRadius': '10px', 'boxShadow': '0 2px 4px rgba(0,0,0,0.1)'})
])
# Callback for main content
@app.callback(
[Output('main-content', 'children'),
Output('analysis-summary', 'children')],
[Input('analysis-type', 'value'),
Input('parameter-select', 'value'),
Input('view-mode', 'value'),
Input('date-range', 'start_date'),
Input('date-range', 'end_date')]
)
def update_main_content(analysis_type, parameter, view_mode, start_date, end_date):
"""Update main content based on selections"""
if analysis_type == 'wafer':
return create_wafer_maps(view_mode), create_wafer_summary()
elif analysis_type == 'trend':
return create_trend_analysis(parameter, start_date, end_date), create_trend_summary(parameter)
elif analysis_type == 'correlation':
return create_correlation_analysis(), create_correlation_summary()
elif analysis_type == 'histogram':
return create_histogram_analysis(parameter), create_histogram_summary(parameter)
elif analysis_type == 'pareto':
return create_pareto_analysis(), create_pareto_summary()
return html.Div(), html.Div()
def create_wafer_maps(view_mode):
"""Create wafer map visualizations"""
if view_mode == 'single':
# Single wafer map
fig = go.Figure(data=go.Scatter(
x=wafer_data['x'],
y=wafer_data['y'],
mode='markers',
marker=dict(
size=8,
color=wafer_data['value'],
colorscale='RdYlGn_r',
showscale=True,
colorbar=dict(title="Parameter Value")
),
text=[f"Die ({x},{y})<br>Value: {v:.1f}<br>Bin: {b}"
for x, y, v, b in zip(wafer_data['x'], wafer_data['y'],
wafer_data['value'], wafer_data['bin'])],
hovertemplate="%{text}<extra></extra>"
))
fig.update_layout(
title="Wafer Map - Parameter Distribution",
xaxis_title="X Position",
yaxis_title="Y Position",
width=600,
height=600,
plot_bgcolor='white'
)
return dcc.Graph(figure=fig)
else:
# Gallery view with multiple wafer maps
fig = make_subplots(
rows=2, cols=3,
subplot_titles=['Wafer 1', 'Wafer 2', 'Wafer 3',
'Wafer 4', 'Wafer 5', 'Wafer 6'],
specs=[[{"type": "scatter"}, {"type": "scatter"}, {"type": "scatter"}],
[{"type": "scatter"}, {"type": "scatter"}, {"type": "scatter"}]]
)
for i in range(6):
row = i // 3 + 1
col = i % 3 + 1
# Add some variation to each wafer
variation = np.random.normal(0, 5, len(wafer_data))
values_varied = wafer_data['value'] + variation
fig.add_trace(
go.Scatter(
x=wafer_data['x'],
y=wafer_data['y'],
mode='markers',
marker=dict(
size=4,
color=values_varied,
colorscale='RdYlGn_r',
showscale=False
),
showlegend=False
),
row=row, col=col
)
fig.update_layout(
title="Wafer Maps Gallery - Recent Production",
height=800,
plot_bgcolor='white'
)
return dcc.Graph(figure=fig)
def create_trend_analysis(parameter, start_date, end_date):
"""Create trend analysis charts"""
# Filter data by date range
filtered_data = trend_data[
(trend_data['date'] >= start_date) &
(trend_data['date'] <= end_date)
]
fig = make_subplots(
rows=2, cols=1,
subplot_titles=[f'{parameter.title()} Trend Over Time', 'Statistical Process Control Chart'],
vertical_spacing=0.1
)
# Main trend line
fig.add_trace(
go.Scatter(
x=filtered_data['date'],
y=filtered_data[parameter],
mode='lines+markers',
name=parameter.title(),
line=dict(color='#3498db', width=2)
),
row=1, col=1
)
# SPC chart with control limits
mean_val = filtered_data[parameter].mean()
std_val = filtered_data[parameter].std()
ucl = mean_val + 3 * std_val
lcl = mean_val - 3 * std_val
fig.add_trace(
go.Scatter(
x=filtered_data['date'],
y=filtered_data[parameter],
mode='markers',
name='Data Points',
marker=dict(color='#e74c3c')
),
row=2, col=1
)
# Control limits
fig.add_hline(y=ucl, line_dash="dash", line_color="red",
annotation_text="UCL", row=2, col=1)
fig.add_hline(y=mean_val, line_dash="solid", line_color="green",
annotation_text="Mean", row=2, col=1)
fig.add_hline(y=lcl, line_dash="dash", line_color="red",
annotation_text="LCL", row=2, col=1)
fig.update_layout(
height=800,
title_text="Parameter Trend Analysis",
plot_bgcolor='white'
)
return dcc.Graph(figure=fig)
def create_correlation_analysis():
"""Create correlation matrix and scatter plots"""
# Correlation matrix
corr_matrix = hist_data[['parameter1', 'parameter2', 'parameter3']].corr()
fig = make_subplots(
rows=2, cols=2,
subplot_titles=['Correlation Matrix', 'Parameter 1 vs Parameter 2',
'Parameter 1 vs Parameter 3', 'Parameter 2 vs Parameter 3'],
specs=[[{"type": "heatmap"}, {"type": "scatter"}],
[{"type": "scatter"}, {"type": "scatter"}]]
)
# Correlation heatmap
fig.add_trace(
go.Heatmap(
z=corr_matrix.values,
x=corr_matrix.columns,
y=corr_matrix.columns,
colorscale='RdBu',
zmid=0,
text=corr_matrix.round(3).values,
texttemplate="%{text}",
textfont={"size": 12}
),
row=1, col=1
)
# Scatter plots
correlations = [
('parameter1', 'parameter2', 1, 2),
('parameter1', 'parameter3', 2, 1),
('parameter2', 'parameter3', 2, 2)
]
for param1, param2, row, col in correlations:
fig.add_trace(
go.Scatter(
x=hist_data[param1],
y=hist_data[param2],
mode='markers',
marker=dict(
color=hist_data['lot_id'].map({'LotA': 'red', 'LotB': 'blue', 'LotC': 'green'}),
size=5,
opacity=0.6
),
name=f'{param1} vs {param2}',
showlegend=False
),
row=row, col=col
)
fig.update_layout(
height=800,
title_text="Parameter Correlation Analysis",
plot_bgcolor='white'
)
return dcc.Graph(figure=fig)
def create_histogram_analysis(parameter):
"""Create histogram analysis"""
fig = make_subplots(
rows=2, cols=2,
subplot_titles=['Overall Distribution', 'Distribution by Lot',
'Box Plot Analysis', 'Cumulative Distribution'],
specs=[[{"type": "histogram"}, {"type": "histogram"}],
[{"type": "box"}, {"type": "scatter"}]]
)
# Overall histogram
fig.add_trace(
go.Histogram(
x=hist_data[parameter],
nbinsx=30,
name='Overall',
marker_color='#3498db'
),
row=1, col=1
)
# Histogram by lot
for lot in hist_data['lot_id'].unique():
lot_data = hist_data[hist_data['lot_id'] == lot]
fig.add_trace(
go.Histogram(
x=lot_data[parameter],
nbinsx=20,
name=lot,
opacity=0.7
),
row=1, col=2
)
# Box plot
for lot in hist_data['lot_id'].unique():
lot_data = hist_data[hist_data['lot_id'] == lot]
fig.add_trace(
go.Box(
y=lot_data[parameter],
name=lot,
boxpoints='outliers'
),
row=2, col=1
)
# Cumulative distribution
sorted_data = np.sort(hist_data[parameter])
cumulative = np.arange(1, len(sorted_data) + 1) / len(sorted_data)
fig.add_trace(
go.Scatter(
x=sorted_data,
y=cumulative,
mode='lines',
name='CDF',
line=dict(color='#e74c3c', width=2)
),
row=2, col=2
)
fig.update_layout(
height=800,
title_text=f"{parameter.title()} Distribution Analysis",
plot_bgcolor='white'
)
return dcc.Graph(figure=fig)
def create_pareto_analysis():
"""Create Pareto analysis chart"""
# Simulate defect data
defect_types = ['Scratches', 'Particles', 'Etch Issues', 'Litho Defects',
'Metal Issues', 'Via Problems', 'Others']
defect_counts = [45, 38, 22, 15, 12, 8, 5]
# Sort in descending order
sorted_data = sorted(zip(defect_types, defect_counts), key=lambda x: x[1], reverse=True)
defect_types_sorted, defect_counts_sorted = zip(*sorted_data)
# Calculate cumulative percentage
total_defects = sum(defect_counts_sorted)
cumulative_pct = [sum(defect_counts_sorted[:i+1])/total_defects*100
for i in range(len(defect_counts_sorted))]
fig = go.Figure()
# Bar chart
fig.add_trace(
go.Bar(
x=defect_types_sorted,
y=defect_counts_sorted,
name='Defect Count',
yaxis='y',
marker_color='#3498db'
)
)
# Line chart for cumulative percentage
fig.add_trace(
go.Scatter(
x=defect_types_sorted,
y=cumulative_pct,
mode='lines+markers',
name='Cumulative %',
yaxis='y2',
line=dict(color='#e74c3c', width=3),
marker=dict(size=8)
)
)
# Add 80% line
fig.add_hline(y=80, line_dash="dash", line_color="green",
annotation_text="80% Line")
fig.update_layout(
title='Pareto Analysis - Defect Types',
xaxis_title='Defect Types',
yaxis=dict(title='Count', side='left'),
yaxis2=dict(title='Cumulative Percentage (%)', side='right', overlaying='y'),
height=600,
plot_bgcolor='white'
)
return dcc.Graph(figure=fig)
# Summary functions
def create_wafer_summary():
total_dies = len(wafer_data)
passing_dies = len(wafer_data[wafer_data['pass_fail'] == 1])
yield_pct = (passing_dies / total_dies) * 100
return html.Div([
html.P(f"Total Dies Analyzed: {total_dies:,}"),
html.P(f"Passing Dies: {passing_dies:,}"),
html.P(f"Die Yield: {yield_pct:.1f}%"),
html.P(f"Average Parameter Value: {wafer_data['value'].mean():.1f}")
])
def create_trend_summary(parameter):
recent_data = trend_data.tail(30)
trend_direction = "↗️" if recent_data[parameter].iloc[-1] > recent_data[parameter].iloc[0] else "↘️"
return html.Div([
html.P(f"Parameter Trend (30 days): {trend_direction}"),
html.P(f"Current Value: {recent_data[parameter].iloc[-1]:.1f}"),
html.P(f"Average: {recent_data[parameter].mean():.1f}"),
html.P(f"Standard Deviation: {recent_data[parameter].std():.1f}")
])
def create_correlation_summary():
corr_matrix = hist_data[['parameter1', 'parameter2', 'parameter3']].corr()
max_corr = corr_matrix.abs().values[np.triu_indices_from(corr_matrix.values, k=1)].max()
return html.Div([
html.P(f"Strongest Correlation: {max_corr:.3f}"),
html.P(f"Parameters Analyzed: 3"),
html.P(f"Sample Size: {len(hist_data):,}"),
html.P("Strong correlations may indicate process dependencies")
])
def create_histogram_summary(parameter):
data = hist_data[parameter]
return html.Div([
html.P(f"Mean: {data.mean():.1f}"),
html.P(f"Median: {data.median():.1f}"),
html.P(f"Standard Deviation: {data.std():.1f}"),
html.P(f"Sample Size: {len(data):,}")
])
def create_pareto_summary():
return html.Div([
html.P("Top 3 defect types account for 72% of all defects"),
html.P("Focus areas: Scratches, Particles, Etch Issues"),
html.P("Recommended: Implement contamination control"),
html.P("Next review: Weekly defect analysis")
])
# Add custom CSS
app.index_string = '''
<!DOCTYPE html>
<html>
<head>
{%metas%}
<title>{%title%}</title>
{%favicon%}
{%css%}
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f8f9fa;
margin: 0;
padding: 20px;
}
.kpi-card {
transition: transform 0.2s;
}
.kpi-card:hover {
transform: translateY(-2px);
}
</style>
</head>
<body>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
{%renderer%}
</footer>
</body>
</html>
'''
if __name__ == '__main__':
app.run(debug=True, port=8050) # Changed app.run_server to app.run