Grok 4.1 Fast· xai
Frontier Reasoning Traces
Build a faculty collaboration finder: interest tags, co-authorship graph, and…
- User
Build a faculty collaboration finder: interest tags, co-authorship graph, and matchmaking events.
- Assistant
Build a faculty collaboration finder: interest tags, co-authorship graph, and matchmaking events.
import streamlit as st
import pandas as pd
import networkx as nx
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import AffinityPropagation
import re
# =============================================================================
# SAMPLE DATA GENERATION
# =============================================================================
@st.cache_data
def load_sample_data():
"""
Generate mock faculty data with interests and publications.
"""
faculty_data = {
"Alice Johnson": {
"dept": "Computer Science",
"interests": ["AI", "Machine Learning", "Computer Vision"],
"papers": ["Paper1", "Paper2", "Paper5"]
},
"Bob Smith": {
"dept": "Computer Science",
"interests": ["AI", "Machine Learning", "NLP"],
"papers": ["Paper1", "Paper3", "Paper6"]
},
"Carol Davis": {
"dept": "Computer Science",
"interests": ["NLP", "Deep Learning", "Ethics in AI"],
"papers": ["Paper3", "Paper4"]
},
"David Wilson": {
"dept": "Physics",
"interests": ["Quantum Computing", "Quantum Physics"],
"papers": ["Paper7", "Paper8"]
},
"Eve Brown": {
"dept": "Physics",
"interests": ["Quantum Computing", "Machine Learning"],
"papers": ["Paper5", "Paper7"]
},
"Frank Miller": {
"dept": "Biology",
"interests": ["Bioinformatics", "Genomics", "AI"],
"papers": ["Paper9"]
},
"Grace Lee": {
"dept": "Biology",
"interests": ["Bioinformatics", "Machine Learning"],
"papers": ["Paper9", "Paper10"]
},
"Henry Garcia": {
"dept": "Economics",
"interests": ["Econometrics", "Data Science", "ML"],
"papers": ["Paper2", "Paper10"]
},
"Ivy Chen": {
"dept": "Economics",
"interests": ["Behavioral Economics", "NLP"],
"papers": ["Paper4", "Paper6"]
},
"Jack Taylor": {
"dept": "Math",
"interests": ["Optimization", "Machine Learning"],
"papers": ["Paper8"]
}
}
# Paper metadata for co-authorship
papers = {
"Paper1": ["Alice Johnson", "Bob Smith"],
"Paper2": ["Alice Johnson", "Henry Garcia"],
"Paper3": ["Bob Smith", "Carol Davis"],
"Paper4": ["Carol Davis", "Ivy Chen"],
"Paper5": ["Alice Johnson", "Eve Brown"],
"Paper6": ["Bob Smith", "Ivy Chen"],
"Paper7": ["David Wilson", "Eve Brown"],
"Paper8": ["David Wilson", "Jack Taylor"],
"Paper9": ["Frank Miller", "Grace Lee"],
"Paper10": ["Grace Lee", "Henry Garcia"]
}
return faculty_data, papers
# =============================================================================
# CO-AUTHORSHIP GRAPH
# =============================================================================
@st.cache_data
def build_coauthorship_graph(faculty_data, papers):
G = nx.Graph()
for paper, authors in papers.items():
for i, auth1 in enumerate(authors):
for auth2 in authors[i+1:]:
G.add_edge(auth1, auth2, paper=paper, weight=1)
# Aggregate multi-edges (multiple co-authorships)
for u, v, d in G.edges(data=True):
if 'paper' in d:
# For simplicity, weight by number of shared papers (but here it's 1 per edge)
pass
return G
def plot_graph(G):
pos = nx.spring_layout(G, k=3, iterations=50)
edge_x = []
edge_y = []
for edge in G.edges():
x0, y0 = pos[edge[0]]
x1, y1 = pos[edge[1]]
edge_x.extend([x0, x1, None])
edge_y.extend([y0, y1, None])
edge_trace = go.Scatter(x=edge_x, y=edge_y,
line=dict(width=1, color='#888'),
hoverinfo='none',
mode='lines')
node_x = []
node_y = []
node_text = []
node_colors = []
depts = {}
for node in G.nodes():
x, y = pos[node]
node_x.append(x)
node_y.append(y)
node_text.append(f"{node}<br>Degree: {G.degree(node)}")
# Color by dept
dept = list(load_sample_data()[0][node].values())[0] # First is dept
depts[node] = dept
node_colors.append(hash(dept) % 10) # Simple color hash
node_trace = go.Scatter(x=node_x, y=node_y,
mode='markers+text',
hoverinfo='text',
text=list(G.nodes()),
textposition="middle center",
hovertext=node_text,
marker=dict(showscale=True,
colorscale='Viridis',
reversescale=True,
color=node_colors,
size=15,
colorbar=dict(thickness=15,
title="Dept Cluster",
xanchor='left',
titleside='right'),
line=dict(width=2)))
fig = go.Figure(data=[edge_trace, node_trace],
layout=go.Layout(
title='<b>Co-Authorship Network Graph</b>',
titlefont_size=16,
showlegend=False,
hovermode='closest',
margin=dict(b=20, l=5, r=5, t=40),
annotations=[dict(text="Node size ~ degree centrality<br>Colors ~ Department",
showarrow=False,
xref="paper", yref="paper",
x=0.005, y=-0.002)],
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
)
return fig
# =============================================================================
# INTEREST MATCHING
# =============================================================================
@st.cache_data
def compute_interest_similarity(faculty_data):
interests = {name: ' '.join(tags) for name, data in faculty_data.items() for tags in [data['interests']]}
vectorizer = TfidfVectorizer(lowercase=True)
tfidf_matrix = vectorizer.fit_transform(interests.values())
names = list(interests.keys())
sim_matrix = cosine_similarity(tfidf_matrix)
sim_df = pd.DataFrame(sim_matrix, index=names, columns=names)
return sim_df
def suggest_matches(sim_df, G, threshold=0.5, min_collabs=0):
matches = []
names = list(sim_df.index)
for i, name1 in enumerate(names):
for name2 in names[i+1:]:
interest_sim = sim_df.loc[name1, name2]
collab_count = len(list(G.edges(name1)) + list(G.edges(name2))) if name1 in G and name2 in G else 0
collab_weight = G[name1][name2].get('weight', 0) if G.has_edge(name1, name2) else 0
if interest_sim > threshold and collab_weight <= min_collabs:
matches.append({
'Faculty1': name1,
'Faculty2': name2,
'Interest Similarity': f"{interest_sim:.2f}",
'Existing Collabs': collab_weight,
'Potential Score': interest_sim * (1 - collab_weight / 5) # Simple score
})
return pd.DataFrame(matches).sort_values('Potential Score', ascending=False)
# =============================================================================
# MATCHMAKING EVENTS (CLUSTERING)
# =============================================================================
@st.cache_data
def suggest_events(faculty_data, sim_df):
interests = {name: ' '.join(data['interests']) for name, data in faculty_data.items()}
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(list(interests.values()))
# Affinity Propagation clustering
clustering = AffinityPropagation(damping=0.5, random_state=42).fit(X)
clusters = clustering.labels_
events = {}
for i, name in enumerate(interests.keys()):
cluster_id = clusters[i]
if cluster_id not in events:
events[cluster_id] = []
events[cluster_id].append(name)
event_df = pd.DataFrame([
{'Event ID': k, 'Faculty': ', '.join(v), 'Size': len(v)}
for k, v in events.items()
])
return event_df.sort_values('Size', ascending=False)
# =============================================================================
# STREAMLIT APP
# =============================================================================
st.set_page_config(page_title="Faculty Collaboration Finder", layout="wide")
st.title("🔍 Faculty Collaboration Finder")
st.markdown("**Interest Tags • Co-Authorship Graph • Matchmaking Events**")
faculty_data, papers = load_sample_data()
G = build_coauthorship_graph(faculty_data, papers)
sim_df = compute_interest_similarity(faculty_data)
tab1, tab2, tab3, tab4 = st.tabs(["📋 Faculty Directory", "📊 Co-Authorship Graph", "❤️ Potential Matches", "🎉 Matchmaking Events"])
with tab1:
st.header("Faculty with Interest Tags")
df_faculty = pd.DataFrame.from_dict(faculty_data, orient='index')
df_faculty.columns = ['Department', 'Interests', 'Papers']
df_faculty['Interests'] = df_faculty['Interests'].apply(lambda x: ', '.join(x))
df_faculty['Papers'] = df_faculty['Papers'].apply(lambda x: ', '.join(x))
st.dataframe(df_faculty, use_container_width=True)
search_tag = st.text_input("🔎 Search by Interest Tag")
if search_tag:
matches = df_faculty[df_faculty['Interests'].str.contains(search_tag, case=False, na=False)]
st.dataframe(matches, use_container_width=True)
with tab2:
st.header("Co-Authorship Network")
fig = plot_graph(G)
st.plotly_chart(fig, use_container_width=True)
col1, col2 = st.columns(2)
with col1:
st.metric("Total Faculty", len(G.nodes()))
with col2:
st.metric("Total Collaborations", len(G.edges()))
with tab3:
st.header("Potential Collaboration Matches")
threshold = st.slider("Interest Similarity Threshold", 0.0, 1.0, 0.5)
max_collabs = st.slider("Max Existing Collabs", 0, 5, 0)
matches_df = suggest_matches(sim_df, G, threshold, max_collabs)
st.dataframe(matches_df.head(10), use_container_width=True)
with tab4:
st.header("Suggested Matchmaking Events")
st.markdown("Clusters of faculty with similar interests for virtual/in-person events.")
events_df = suggest_events(faculty_data, sim_df)
st.dataframe(events_df, use_container_width=True)
# Show top event details
top_event = events_df.iloc[0]
st.subheader(f"🏆 Top Event: {top_event['Event ID']} ({top_event['Size']} faculty)")
faculty_list = top_event['Faculty'].split(', ')
for fac in faculty_list:
interests = ', '.join(faculty_data[fac]['interests'])
st.info(f"**{fac}** (Dept: {faculty_data[fac]['dept']}): {interests}")
st.markdown("---")
st.markdown("**Built by Sherlock (Trailblazer Labs)** | *Add your own data by modifying `load_sample_data()`*")
Install dependencies:
pip install streamlit networkx plotly pandas numpy scikit-learn
Save the code as faculty_finder.py.
Run:
streamlit run faculty_finder.py
Open your browser to http://localhost:8501.
Customize: Edit load_sample_data() with real faculty/papers from CSV/DB (e.g., Semantic Scholar API). Scalable to 1000s! Let me know for enhancements. 🕵️♂️