import dash
from dash import dcc, html, Input, Output, State, callback, dash_table
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np
import requests
import json
import base64
import io
from datetime import datetime
import math
from packaging import version
# Initialize Dash app
app = dash.Dash(__name__)
app.title = "Resonance Chart Visualization"
# Flask API base URL
API_BASE_URL = "http://localhost:5000/api"
# Define CSS styles
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# Define the layout
app.layout = html.Div([
html.Div([
html.H1("Resonance Chart Visualization",
style={'textAlign': 'center', 'color': '#2c3e50', 'marginBottom': '10px'}),
html.P("Interactive parameter correlation visualization for semiconductor manufacturing",
style={'textAlign': 'center', 'color': '#7f8c8d', 'marginBottom': '30px'})
]),
# File Upload Section
html.Div([
html.Div([
html.H3("Upload CSV File", style={'color': '#34495e'}),
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px',
'backgroundColor': '#ecf0f1'
},
multiple=False
),
html.Div(id='upload-status'),
], className='six columns'),
html.Div([
html.H3("Analysis Controls", style={'color': '#34495e'}),
html.Div([
html.Label("Visualization Type:", style={'fontWeight': 'bold'}),
dcc.Dropdown(
id='viz-type-dropdown',
options=[
{'label': 'Network Graph', 'value': 'network'},
{'label': 'Correlation Heatmap', 'value': 'heatmap'},
{'label': 'Statistical Summary', 'value': 'statistics'}
],
value='network',
style={'marginBottom': '15px'}
),
html.Label("Correlation Threshold:", style={'fontWeight': 'bold'}),
dcc.Slider(
id='correlation-threshold',
min=0,
max=1,
step=0.05,
value=0.3,
marks={i/10: str(i/10) for i in range(0, 11, 2)},
tooltip={"placement": "bottom", "always_visible": True}
),
html.Div([
dcc.Checklist(
id='significance-filter',
options=[{'label': ' Show only significant (p<0.05)', 'value': 'significant'}],
value=[],
style={'marginTop': '15px'}
)
])
])
], className='six columns')
], className='row', style={'marginBottom': '30px'}),
# Main visualization area
html.Div([
dcc.Graph(id='main-visualization', style={'height': '600px'})
], style={'marginBottom': '30px'}),
# Statistics and Information Panel
html.Div([
html.Div([
html.H4("Dataset Information", style={'color': '#2c3e50'}),
html.Div(id='dataset-info')
], className='four columns'),
html.Div([
html.H4("Correlation Statistics", style={'color': '#2c3e50'}),
html.Div(id='correlation-stats')
], className='four columns'),
html.Div([
html.H4("Top Correlations", style={'color': '#2c3e50'}),
html.Div(id='top-correlations')
], className='four columns')
], className='row', style={'marginBottom': '30px'}),
# Hidden divs to store data
html.Div(id='analysis-data', style={'display': 'none'}),
html.Div(id='current-filename', style={'display': 'none'})
])
# Callback for file upload
@app.callback(
[Output('upload-status', 'children'),
Output('current-filename', 'children')],
[Input('upload-data', 'contents')],
[State('upload-data', 'filename')]
)
def upload_file(contents, filename):
if contents is None:
return "", ""
try:
# Parse the uploaded file
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
# Send to Flask API
files = {'file': (filename, io.BytesIO(decoded), 'text/csv')}
response = requests.post(f"{API_BASE_URL}/upload", files=files)
if response.status_code == 200:
result = response.json()
status_message = html.Div([
html.P(f"✓ File uploaded successfully!", style={'color': 'green', 'fontWeight': 'bold'}),
html.P(f"Rows: {result['rows']}, Columns: {result['columns']}")
])
return status_message, filename
else:
error_msg = response.json().get('error', 'Unknown error')
return html.P(f"✗ Upload failed: {error_msg}", style={'color': 'red'}), ""
except Exception as e:
return html.P(f"✗ Error: {str(e)}", style={'color': 'red'}), ""
# Callback for analysis
@app.callback(
Output('analysis-data', 'children'),
[Input('current-filename', 'children')]
)
def analyze_data(filename):
if not filename:
return ""
try:
response = requests.get(f"{API_BASE_URL}/analyze/{filename}")
if response.status_code == 200:
return json.dumps(response.json())
else:
return ""
except Exception as e:
return ""
# Callback for visualization
@app.callback(
Output('main-visualization', 'figure'),
[Input('analysis-data', 'children'),
Input('viz-type-dropdown', 'value'),
Input('correlation-threshold', 'value'),
Input('significance-filter', 'value')]
)
def update_visualization(analysis_data, viz_type, threshold, significance_filter):
if not analysis_data:
return go.Figure().add_annotation(text="Upload a CSV file to begin analysis",
xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False)
try:
data = json.loads(analysis_data)
parameters = data['parameters']
correlations = data['correlations']
category_colors = data['categoryColors']
# Filter correlations based on threshold and significance
filtered_correlations = {}
for key, corr_data in correlations.items():
meets_threshold = abs(corr_data['value']) >= threshold
meets_significance = 'significant' not in significance_filter or corr_data['pValue'] < 0.05
if meets_threshold and meets_significance:
filtered_correlations[key] = corr_data
if viz_type == 'network':
return create_network_graph(parameters, filtered_correlations, category_colors)
elif viz_type == 'heatmap':
return create_heatmap(parameters, correlations, threshold, significance_filter)
elif viz_type == 'statistics':
return create_statistics_chart(data['statistics'])
except Exception as e:
return go.Figure().add_annotation(text=f"Error creating visualization: {str(e)}",
xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False)
def create_network_graph(parameters, correlations, category_colors):
"""Create network graph visualization"""
# Create node positions in a circle
n_params = len(parameters)
positions = {}
for i, param in enumerate(parameters):
angle = (i / n_params) * 2 * math.pi
positions[param['id']] = {
'x': math.cos(angle),
'y': math.sin(angle)
}
# Create edges
edge_x = []
edge_y = []
edge_colors = []
edge_widths = []
for key, corr_data in correlations.items():
param1_id, param2_id = key.split('-')
if param1_id in positions and param2_id in positions:
pos1 = positions[param1_id]
pos2 = positions[param2_id]
edge_x.extend([pos1['x'], pos2['x'], None])
edge_y.extend([pos1['y'], pos2['y'], None])
color = 'green' if corr_data['type'] == 'positive' else 'red'
edge_colors.append(color)
edge_widths.append(abs(corr_data['value']) * 10)
# Create nodes
node_x = []
node_y = []
node_colors = []
node_sizes = []
node_text = []
for param in parameters:
pos = positions[param['id']]
node_x.append(pos['x'])
node_y.append(pos['y'])
node_colors.append(category_colors.get(param['category'], '#95a5a6'))
node_sizes.append(10 + param['importance'] * 20)
node_text.append(param['name'])
fig = go.Figure()
# Add edges
for i in range(0, len(edge_x), 3):
if i + 1 < len(edge_x):
fig.add_trace(go.Scatter(
x=edge_x[i:i+3],
y=edge_y[i:i+3],
mode='lines',
line=dict(width=edge_widths[i//3] if i//3 < len(edge_widths) else 2,
color=edge_colors[i//3] if i//3 < len(edge_colors) else 'gray'),
hoverinfo='none',
showlegend=False
))
# Add nodes
fig.add_trace(go.Scatter(
x=node_x,
y=node_y,
mode='markers+text',
marker=dict(
size=node_sizes,
color=node_colors,
line=dict(width=2, color='black')
),
text=node_text,
textposition="top center",
hoverinfo='text',
showlegend=False
))
fig.update_layout(
title="Parameter Correlation Network",
showlegend=False,
hovermode='closest',
margin=dict(b=20,l=5,r=5,t=40),
annotations=[ dict(
text="Node size represents parameter importance<br>Edge thickness represents correlation strength",
showarrow=False,
xref="paper", yref="paper",
x=0.005, y=-0.002,
xanchor='left', yanchor='bottom',
font=dict(size=12)
)],
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)
)
return fig
def create_heatmap(parameters, correlations, threshold, significance_filter):
"""Create correlation heatmap"""
param_names = [p['name'] for p in parameters]
n_params = len(param_names)
# Create correlation matrix
corr_matrix = np.zeros((n_params, n_params))
p_value_matrix = np.ones((n_params, n_params))
for i in range(n_params):
corr_matrix[i, i] = 1.0
p_value_matrix[i, i] = 0.0
param_id_to_name = {p['id']: p['name'] for p in parameters}
for key, corr_data in correlations.items():
param1_id, param2_id = key.split('-')
param1_name = param_id_to_name.get(param1_id)
param2_name = param_id_to_name.get(param2_id)
if param1_name in param_names and param2_name in param_names:
i = param_names.index(param1_name)
j = param_names.index(param2_name)
corr_matrix[i, j] = corr_data['value']
corr_matrix[j, i] = corr_data['value']
p_value_matrix[i, j] = corr_data['pValue']
p_value_matrix[j, i] = corr_data['pValue']
# Apply significance filter
if 'significant' in significance_filter:
mask = p_value_matrix >= 0.05
corr_matrix[mask] = 0
fig = go.Figure(data=go.Heatmap(
z=corr_matrix,
x=param_names,
y=param_names,
colorscale='RdBu',
zmid=0,
colorbar=dict(title="Correlation")
))
fig.update_layout(
title="Parameter Correlation Heatmap",
xaxis_title="Parameters",
yaxis_title="Parameters"
)
return fig
def create_statistics_chart(stats):
"""Create statistics visualization"""
categories = ['Total Parameters', 'Numerical', 'Categorical', 'Total Correlations',
'Significant', 'Positive', 'Negative']
values = [stats['total_parameters'], stats['numerical_parameters'],
stats['categorical_parameters'], stats['total_correlations'],
stats['significant_correlations'], stats['positive_correlations'],
stats['negative_correlations']]
fig = go.Figure([go.Bar(x=categories, y=values,
marker_color=['#3498db', '#2ecc71', '#f39c12', '#9b59b6',
'#e74c3c', '#1abc9c', '#e67e22'])])
fig.update_layout(
title="Dataset Statistics",
xaxis_title="Categories",
yaxis_title="Count"
)
return fig
# Callback for dataset info
@app.callback(
Output('dataset-info', 'children'),
[Input('analysis-data', 'children')]
)
def update_dataset_info(analysis_data):
if not analysis_data:
return "No data loaded"
try:
data = json.loads(analysis_data)
info = data['dataInfo']
return html.Div([
html.P(f"File: {info['filename']}"),
html.P(f"Rows: {info['rows']}"),
html.P(f"Columns: {info['columns']}")
])
except:
return "Error loading data info"
# Callback for correlation stats
@app.callback(
Output('correlation-stats', 'children'),
[Input('analysis-data', 'children')]
)
def update_correlation_stats(analysis_data):
if not analysis_data:
return "No data loaded"
try:
data = json.loads(analysis_data)
stats = data['statistics']
return html.Div([
html.P(f"Total: {stats['total_correlations']}"),
html.P(f"Significant: {stats['significant_correlations']}"),
html.P(f"Positive: {stats['positive_correlations']}"),
html.P(f"Negative: {stats['negative_correlations']}")
])
except:
return "Error loading correlation stats"
# Callback for top correlations
@app.callback(
Output('top-correlations', 'children'),
[Input('analysis-data', 'children')]
)
def update_top_correlations(analysis_data):
if not analysis_data:
return "No data loaded"
try:
data = json.loads(analysis_data)
correlations = data['correlations']
parameters = data['parameters']
# Get parameter names mapping
param_id_to_name = {p['id']: p['name'] for p in parameters}
# Sort correlations by absolute value
sorted_corrs = sorted(correlations.items(),
key=lambda x: abs(x[1]['value']), reverse=True)
top_corrs = []
for key, corr_data in sorted_corrs[:5]:
param1_id, param2_id = key.split('-')
param1_name = param_id_to_name.get(param1_id, param1_id)
param2_name = param_id_to_name.get(param2_id, param2_id)
color = 'green' if corr_data['value'] > 0 else 'red'
top_corrs.append(
html.P(f"{param1_name} - {param2_name}: {corr_data['value']:.3f}",
style={'color': color, 'fontSize': '12px'})
)
return html.Div(top_corrs)
except:
return "Error loading top correlations"
if __name__ == '__main__':
if version.parse(dash.__version__) >= version.parse("2.14.0"):
app.run(debug=True, host='0.0.0.0', port=8050,use_reloader=False)
else:
app.run_server(debug=True, host='0.0.0.0', port=8050,use_reloader=False)app.py
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import pandas as pd
import numpy as np
from scipy.stats import pearsonr
import os
import json
from werkzeug.utils import secure_filename
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__)
CORS(app)
# Configuration
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'csv'}
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB max file size
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def detect_parameter_type(series):
"""Detect if a parameter is numerical or categorical"""
# Check if it's numeric
try:
pd.to_numeric(series, errors='raise')
return 'numerical'
except (ValueError, TypeError):
return 'categorical'
def categorize_parameter(param_name):
"""Categorize parameter based on name patterns"""
param_lower = param_name.lower()
if any(word in param_lower for word in ['temp', 'temperature', 'thermal']):
return 'thermal'
elif any(word in param_lower for word in ['pressure', 'vacuum', 'torr']):
return 'process'
elif any(word in param_lower for word in ['flow', 'gas', 'ar', 'o2', 'n2', 'he']):
return 'gas'
elif any(word in param_lower for word in ['power', 'rf', 'voltage', 'current']):
return 'power'
elif any(word in param_lower for word in ['time', 'duration', 'rate']):
return 'temporal'
elif any(word in param_lower for word in ['chamber', 'tool', 'equipment', 'recipe']):
return 'equipment'
else:
return 'process'
def calculate_importance(series):
"""Calculate parameter importance based on variance and distribution"""
if series.dtype in ['object', 'category']:
# For categorical data, use entropy-based importance
value_counts = series.value_counts(normalize=True)
entropy = -sum(p * np.log2(p) for p in value_counts if p > 0)
max_entropy = np.log2(len(value_counts))
return entropy / max_entropy if max_entropy > 0 else 0.5
else:
# For numerical data, use coefficient of variation
if series.std() == 0:
return 0.1
cv = series.std() / abs(series.mean()) if series.mean() != 0 else 1
return min(cv, 1.0)
def calculate_correlations(df):
"""Calculate correlation matrix with p-values"""
correlations = {}
numeric_columns = df.select_dtypes(include=[np.number]).columns
for i, col1 in enumerate(numeric_columns):
for j, col2 in enumerate(numeric_columns):
if i < j: # Avoid duplicates and self-correlation
try:
# Remove NaN values
data1 = df[col1].dropna()
data2 = df[col2].dropna()
# Find common indices
common_idx = data1.index.intersection(data2.index)
if len(common_idx) > 3: # Need at least 4 points for correlation
corr_coef, p_value = pearsonr(data1[common_idx], data2[common_idx])
if not np.isnan(corr_coef):
key = f"{col1}-{col2}"
correlations[key] = {
'value': float(corr_coef),
'pValue': float(p_value),
'type': 'positive' if corr_coef > 0 else 'negative'
}
except Exception as e:
logger.warning(f"Error calculating correlation between {col1} and {col2}: {e}")
return correlations
@app.route('/')
def index():
return jsonify({
'message': 'Resonance Chart API',
'version': '1.0.0',
'endpoints': {
'upload': '/api/upload',
'analyze': '/api/analyze/<filename>',
'health': '/api/health'
}
})
@app.route('/api/health')
def health():
return jsonify({'status': 'healthy', 'service': 'resonance-chart-api'})
@app.route('/api/upload', methods=['POST'])
def upload_file():
try:
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
if not allowed_file(file.filename):
return jsonify({'error': 'File type not allowed. Please upload a CSV file.'}), 400
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Basic validation of the CSV file
try:
df = pd.read_csv(filepath)
if df.empty:
os.remove(filepath)
return jsonify({'error': 'Uploaded CSV file is empty'}), 400
return jsonify({
'message': 'File uploaded successfully',
'filename': filename,
'rows': len(df),
'columns': len(df.columns),
'column_names': df.columns.tolist()
})
except Exception as e:
if os.path.exists(filepath):
os.remove(filepath)
return jsonify({'error': f'Error reading CSV file: {str(e)}'}), 400
except Exception as e:
logger.error(f"Upload error: {e}")
return jsonify({'error': 'Internal server error during upload'}), 500
@app.route('/api/analyze/<filename>')
def analyze_file(filename):
try:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(filename))
if not os.path.exists(filepath):
return jsonify({'error': 'File not found'}), 404
# Read and analyze the CSV file
df = pd.read_csv(filepath)
# Extract parameters information
parameters = []
for col in df.columns:
param_type = detect_parameter_type(df[col])
category = categorize_parameter(col)
importance = calculate_importance(df[col])
parameters.append({
'id': col.lower().replace(' ', '_').replace('-', '_'),
'name': col,
'type': param_type,
'category': category,
'importance': float(importance)
})
# Calculate correlations
correlations = calculate_correlations(df)
# Generate category colors
categories = list(set(p['category'] for p in parameters))
category_colors = {
'thermal': '#FF6B6B',
'process': '#4ECDC4',
'gas': '#45B7D1',
'power': '#FFA07A',
'temporal': '#98D8C8',
'equipment': '#F7DC6F'
}
# Add default colors for new categories
default_colors = ['#9B59B6', '#E67E22', '#16A085', '#F39C12', '#8E44AD', '#27AE60']
for i, cat in enumerate(categories):
if cat not in category_colors:
category_colors[cat] = default_colors[i % len(default_colors)]
# Basic statistics
stats = {
'total_parameters': len(parameters),
'numerical_parameters': len([p for p in parameters if p['type'] == 'numerical']),
'categorical_parameters': len([p for p in parameters if p['type'] == 'categorical']),
'total_correlations': len(correlations),
'significant_correlations': len([c for c in correlations.values() if c['pValue'] < 0.05]),
'positive_correlations': len([c for c in correlations.values() if c['value'] > 0]),
'negative_correlations': len([c for c in correlations.values() if c['value'] < 0])
}
return jsonify({
'parameters': parameters,
'correlations': correlations,
'categoryColors': category_colors,
'statistics': stats,
'dataInfo': {
'filename': filename,
'rows': len(df),
'columns': len(df.columns)
}
})
except Exception as e:
logger.error(f"Analysis error: {e}")
return jsonify({'error': f'Error analyzing file: {str(e)}'}), 500
@app.route('/api/files')
def list_files():
try:
files = []
for filename in os.listdir(app.config['UPLOAD_FOLDER']):
if filename.endswith('.csv'):
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
stat = os.stat(filepath)
files.append({
'filename': filename,
'size': stat.st_size,
'modified': stat.st_mtime
})
return jsonify({'files': files})
except Exception as e:
logger.error(f"List files error: {e}")
return jsonify({'error': 'Error listing files'}), 500
@app.route('/api/delete/<filename>', methods=['DELETE'])
def delete_file(filename):
try:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(filename))
if os.path.exists(filepath):
os.remove(filepath)
return jsonify({'message': 'File deleted successfully'})
else:
return jsonify({'error': 'File not found'}), 404
except Exception as e:
logger.error(f"Delete error: {e}")
return jsonify({'error': 'Error deleting file'}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)