import json,tempfile,pickle
from pathlib import Path
import numpy as np,networkx as nx
from scipy.sparse import coo_matrix,diags,vstack
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
root=Path(tempfile.gettempdir())/'oryon-graph-datasets'/'cora'
raw=root/'Cora'/'raw'
def read(name):
    with open(raw/f'ind.cora.{name}','rb') as f: return pickle.load(f,encoding='latin1')
allx,tx,ally,ty,graph=map(read,('allx','tx','ally','ty','graph'))
test_order=np.loadtxt(raw/'ind.cora.test.index',dtype=int); test_sorted=np.sort(test_order)
features=vstack((allx,tx)).tolil(); features[test_order]=features[test_sorted]; features=features.tocsr()
labels=np.vstack((ally,ty)); labels[test_order]=labels[test_sorted]; labels=labels.argmax(1)
rng=np.random.default_rng(2718)
train=np.arange(140)
edges=np.array(sorted({(int(u),int(v)) for u,vs in graph.items() for v in vs if u!=v}|{(int(v),int(u)) for u,vs in graph.items() for v in vs if u!=v}),dtype=int)
neighbors=np.unique(edges[np.isin(edges[:,0],train),1]); val=rng.choice(np.intersect1d(neighbors,np.arange(140,640)),70,replace=False); test=rng.choice(np.intersect1d(neighbors,test_sorted),70,replace=False)
chosen=set(np.r_[train,val,test].tolist()); candidates=[int(i) for i in rng.permutation(neighbors) if int(i) not in chosen]; extra=candidates[:100]; nodes=np.r_[train,val,test,extra]; loc={int(v):i for i,v in enumerate(nodes)}
edge=np.array([(loc[int(u)],loc[int(v)]) for u,v in edges if int(u) in loc and int(v) in loc],dtype=int); N=len(nodes)
print('Cora subset',N,'directed edges',len(edge),'train/val/test',len(train),len(val),len(test),flush=True)
# Características de 16 dimensiones por SVD ajustada sin etiquetas sobre Cora completo.
svd=TruncatedSVD(n_components=16,random_state=42,n_iter=5); projection=svd.fit_transform(features); X=projection[nodes]; scaler=StandardScaler().fit(X); X=scaler.transform(X).astype(np.float64)
y=labels[nodes]; train_i=np.arange(140); val_i=np.arange(140,210); test_i=np.arange(210,280)
A=coo_matrix((np.ones(len(edge)),(edge[:,0],edge[:,1])),shape=(N,N)).tocsr(); A.data[:]=1; A=A+diags(np.ones(N)); D=np.asarray(A.sum(1)).ravel(); S=diags(D**-.5)@A@diags(D**-.5)
eig=np.linalg.eigvalsh(S.toarray()); eig=np.sort(1-eig)
H=X.copy(); results=[]; signals=[]
for k in range(21):
    scale=StandardScaler().fit(H[train_i]); fit=LogisticRegression(C=1,max_iter=1000,random_state=42).fit(scale.transform(H[train_i]),y[train_i]); score=fit.score(scale.transform(H[val_i]),y[val_i]); results.append(float(score)); signals.append(H[:,0].round(6).tolist()); H=S@H
G=nx.Graph();G.add_nodes_from(range(N));G.add_edges_from((int(u),int(v)) for u,v in edge if u!=v); pos=nx.spring_layout(G,seed=42,iterations=50)
mx=max(np.max(np.abs(np.array(list(pos.values())))),1e-9); coords=[[round(float(v[0]/mx),5),round(float(v[1]/mx),5)] for _,v in sorted(pos.items())]
obj={'n':N,'edges':edge.tolist(),'x':X.round(5).tolist(),'y':y.tolist(),'train':train_i.tolist(),'val':val_i.tolist(),'test':test_i.tolist(),'eigen':eig.round(6).tolist(),'val_accuracy':results,'signals':signals,'coords':coords}
Path('cora-subgraph.json').write_text(json.dumps(obj,ensure_ascii=False,separators=(',',':')),encoding='utf-8')
print('accuracy validation k0,1,2,5,10,20',[round(results[k],4) for k in (0,1,2,5,10,20)],flush=True)
print('components',nx.number_connected_components(G),'SVD variance',sum(svd.explained_variance_ratio_),flush=True)
