import sys,os,json,re,collections,datetime as dtm;sys.path.insert(0,'/home/claude/pkg') from pkgkit import * os.chdir('/home/claude/sca') src=open('/home/claude/sca/build_scagn_orig.py').read();ns={'__name__':'bs'} exec(compile(src[:src.index('E=dict(t=[]')],'build_scagn_head','exec'),ns) P=ns['P'];ids=ns['ids'];places=ns['places'];pos=ns['pos'];cellof=ns['cellof'];rows=ns['rows'];g2r=ns['g2r'];G2key=ns['G2key'];g2lab=ns['g2lab'];S=ns['S'];items=ns['items'];lab=ns['lab'];T=ns['T'] FL=json.load(open('/home/claude/val/final_labels.json'));LBL={tuple(k.split('|')):v for k,v in FL.items()} seedid={k:v['seed']['paperId'] for k,v in S.items()};paperlab={items[int(i)]['p']:v for i,v in lab.items()};flagged={(k,p) for key in ('A','B') for k,p,*_ in T[key]} os.chdir('/home/claude/pkg') GR=re.compile(r'^(ieee|acm|proceedings|eurographics|computer graphics forum|human factors|international (conference|symposium|journal)|symposium|journal|transactions|conference)',re.I) strong=re.compile(r'scagnostic|pargnostic',re.I) def yr0(p): q=P[p];y=q.get('year') if y: return int(y) d=q.get('publicationDate');return int(d[:4]) if d else None year={p:yr0(p) for p in ids};imp={} earliest=collections.defaultdict(lambda:9999) for (s,p) in list(rows)+list(g2r): if s in P and p in P and year.get(p): earliest[s]=min(earliest[s],year[p]) for p in ids: if year[p]: continue m=re.search(r'\b(19[89]\d|20[0-2]\d)\b',P[p].get('title') or '') if m: year[p]=int(m.group(1));imp[p]='title' elif earliest[p]<9999: year[p]=earliest[p];imp[p]='earliest_citer' else: year[p]=2010;imp[p]='default' print('imputed',collections.Counter(imp.values())) seeds_meta=json.load(open('/home/claude/sca/seeds.json'));seedpids={v['seed']['paperId'] for v in S.values()} expanded=seedpids|set(json.load(open('/home/claude/sca/gen2_sca.json'))) import difflib def nt(t): return re.sub(r'[^a-z0-9]','',(t or '').lower()) canon={p:p for p in ids};bykey=collections.defaultdict(list) for p in ids: bykey[nt(P[p].get('title'))[:22]].append(p) def score(x): return (bool((P[x].get('externalIds') or {}).get('DOI')),P[x].get('citationCount') or 0) for kk,g in bykey.items(): for i in range(len(g)): for j in range(i+1,len(g)): a,b=g[i],g[j] if canon[a]!=a or canon[b]!=b: continue ta,tb=nt(P[a].get('title')),nt(P[b].get('title')) import os as _os rr=difflib.SequenceMatcher(None,ta,tb).ratio();cp=len(_os.path.commonprefix([ta,tb]));sh=min(ta,tb,key=len);lo=max(ta,tb,key=len) if len(ta)>=20 and len(tb)>=20 and (rr>=0.92 or (rr>=0.88 and cp>=30) or (len(sh)>=30 and lo.startswith(sh))) and abs(year[a]-year[b])<=2: keep,drop=(a,b) if score(a)>=score(b) else (b,a);canon[drop]=keep merged=collections.defaultdict(list) for p,c in canon.items(): if p!=c: merged[c].append(p) print('merged duplicate records',sum(len(v) for v in merged.values()),[ (P[c]['title'][:40],len(v)) for c,v in merged.items()]) events=[] for p in [x for x in ids if canon[x]==x]: q=P[p];doi=(q.get('externalIds') or {}).get('DOI');title=(q.get('title') or '').strip() or f'Untitled record {p}' fl=['time_coarse']+(['time_imputed'] if p in imp else [])+(['title_garbled'] if (GR.search(title) or title.lower().startswith('of ')) else [])+(['duplicate_merged'] if p in merged else []) a=dict(venue=(q.get('venue') or '')[:80],citation_count=q.get('citationCount') or 0,coords=dict(space='scagnostics_topic_map_tsne_unit',x=round(pos[p][0],4),y=round(pos[p][1],4))) if doi: a['doi']=doi if p in seedpids: a['seed']=True if p in imp: a['year_imputed_by']=imp[p] if title.startswith('ClustML'): a['pdf_check']='Journal version: Information Visualization 2024, 23(2); the year of the first appearance is kept' ev=dict(id=p,kind='paper',title=title,time=dict(start=f'{year[p]}-01-01T00:00:00Z',precision='year',basis='imputed' if p in imp else 'recorded'),refs=[dict(entity=f'topic:{cellof[p]}',role='anchor')],attrs=a, provenance=dict(source_ids=[dict(source='semantic_scholar',id=p)]+[dict(source='semantic_scholar',id=d) for d in merged.get(p,[])],extraction=dict(method='seed paper, or paper citing a seed and judged relevant to scagnostics or visual quality metrics',rule_ids=['R_SNOWBALL']),confidence=None,**({'merged_from':merged[p]} if p in merged else {})),flags=fl,link_coverage='partial' if p in expanded else 'none') if doi: ev['url']='https://doi.org/'+doi events.append(ev) ents=[dict(id=f'topic:{i}',type='topic_region',label=pl['label'],attrs=dict(coords=dict(space='scagnostics_topic_map_tsne_unit',x=pl['x'],y=pl['y']),papers=pl['n']),provenance=dict(source_ids=[],derived=True,method='k-means (k=12, 10 restarts, seed 0) on TF-IDF (sublinear tf, min_df 2, max_df 0.35) reduced by SVD to 40 dimensions of title plus the first 600 characters of the abstract (scikit-learn); regions named by their top title terms')) for i,pl in enumerate(places)] def best(r): cs=[c for c in (r.get('contexts') or []) if c] if r else [] return max(cs,key=lambda c:(bool(strong.search(c)),len(c))) if cs else '' def words(s,n=14): s=re.sub(r'\s+',' ',s).strip();return ' '.join(s.split(' ')[:n]) RAT={'D':'The citing paper develops a new or extended measure, technique or concept from the cited idea','A':'The citing paper uses scagnostics or a quality metric from the cited work in a system or study','M':'The citing paper cites the cited work as general background'} REL={'D':'develops','A':'applies','M':'background'} links=[];om=[];oc=collections.Counter();seen=set() def add(s,p,r,label,unit,review,basis=None): if s not in P or p not in P or s==p or (s,p) in seen: return seen.add((s,p));dy=year[p]-year[s];lid=f'{s}>{p}' if dy<0: oc['backward_in_time']+=1;om.append(dict(item_type='link',reason='backward_in_time',id=lid,**{'from':s,'to':p},detail=f'citing paper dated {year[p]}, cited paper dated {year[s]}'));return L=dict(id=lid,**{'from':s,'to':p},kind='reference',propagates=False,direction='evidence' if dy==0 else 'time',gap_seconds=0 if dy==0 else int((dtm.date(year[p],1,1)-dtm.date(year[s],1,1)).total_seconds()), evidence=dict(existence=dict(level='given',basis='citation_record',source_ref=dict(source='semantic_scholar',id=f'{s}>{p}')))) if label: L['relation']=REL[label];L['propagates']=label in 'DA' if basis=='full_text': ctx='';sent=False;how='. Read from the full text of the citing paper';bs='full_text' elif basis=='title_and_abstract': ctx='';sent=False;how='. Read from the title and abstract of the citing paper';bs='title_and_abstract' else: ctx=best(r);sent=bool(ctx);how='. Read from the citing sentence' if sent else '. Read from the title and abstract of the citing paper';bs='citing_sentence' if sent else 'title_and_abstract' txt=RAT[label]+how+(f'. Excerpt: “{words(ctx)}”' if sent else '') L['evidence']['relation']=dict(level='judged',basis=bs,text=txt,judge=dict(type='model',id='claude_reader',date='2026-10',unit=unit));L['attrs']=dict(review_set=review) else: L['flags']=['unassessed'] links.append(L) cand={} def cadd(s,p,r,label,unit,review,basis=None): s=canon.get(s,s);p=canon.get(p,p);rank={'D':3,'A':2,'M':1,None:0}[label] if (s,p) not in cand or rank>cand[(s,p)][0]: cand[(s,p)]=(rank,(s,p,r,label,unit,review,basis)) for (k,p),r in rows.items(): s=seedid[k];v=LBL.get((s,p)) if v and v[0]: cadd(s,p,r,v[0],'link','first_generation_selection',v[1]) else: cadd(s,p,r,None,'link','') for (cited,p),r in g2r.items(): cadd(cited,p,r,g2lab[str(G2key[(cited,p)])],'link','second_generation') for key in sorted(cand): add(*cand[key][1]) print('links',len(links),collections.Counter(l.get('relation','-') for l in links),dict(oc)) omc=collections.Counter(oc);om=sorted(om,key=lambda o:o['id'])[:10000] M=dict(spec_version='0.1',package_id='scagnostics-0.2',created_at=CREATED, adapter=dict(name='bibliometric_scagnostics_adapter',version='0.2',domain='bibliometrics',code_ref=None,produced_by='Claude, from the scagnostics pilot data (Semantic Scholar) and the judgements of the scagnostics study'), domain=dict(event_definition='A paper that cites scagnostics, an extension of it to other graphics, or a related visual quality metric, dated by publication year',entity_description='Topic regions derived by clustering the words of titles and abstracts'), sources=[dict(id='semantic_scholar',name='Semantic Scholar Academic Graph (papers, citation lists, citing sentences)',url='https://api.semanticscholar.org',accessed_at='2026-10',license='Semantic Scholar API licence; to be confirmed before sharing, citing sentences are not stored in full in this package')], observation_window=dict(start=f'{min(year.values())}-01-01',end='2026-10-21',collected_at='2026-10',right_censored=True), coverage=dict(procedure='snowball',description='Seeds are 22 papers: ten on scagnostics and its extensions (scatterplots, parallel coordinates, time series) and twelve on related visual quality metrics. First generation: papers citing a seed that cite a scagnostics seed or deal with scatterplots, visual quality measures or view selection. Second generation: papers citing the papers that develop an idea',seeds=[s['short'] for s in seeds_meta],depth_limit=2,selection_rules=['R_SNOWBALL'], known_gaps=['The seeds were chosen by the analyst; papers on scagnostics that cite none of them are missing; Tukey and Tukey (1985) is not in the data','Only a selection of links was judged: links of papers flagged by a keyword rule (cue words, influential citations, mentions of scagnostics in title or abstract) were read one by one, 570 links in all (500 from the citing sentence or the title and abstract, 70 from the full text of 12 papers); 11 of them have no citing sentence and stay unassessed; all other links carry the flag unassessed','The first version typed each citing paper once and applied the type to its links. A check against the full text of 12 papers showed that only 16 of 41 develops or applies links were supported, so all flagged first-generation links were judged again one by one in this version','Second-generation links were collected only for the papers that develop an idea and judged for 332 links (cue-selected after the first 70)','The 2020s are incomplete because recent papers have had little time to be cited','Dates are reduced to the publication year; records without a year were given a year by rule and carry the flag time_imputed','Only Semantic Scholar was used for the citation lists; OpenCitations lists fewer citing papers']), event_kinds=[dict(id='paper',label='Paper',description='A publication')], entity_types=[dict(id='topic_region',label='Topic region',description='Cluster of papers with similar title and abstract words; derived')],entity_relation_types=[],roles=[], link_kinds=[dict(id='reference',core_kind='reference',description='The citing paper cites the cited paper',relations=[dict(id='develops',description='The citing paper develops a new or extended measure, technique or concept from the cited idea',propagates_default=True),dict(id='applies',description='The citing paper uses scagnostics or a quality metric in a system or study',propagates_default=True),dict(id='background',description='The citing paper cites the cited work as background',propagates_default=False)],propagates_default=False,default_window_seconds=None,max_gap_seconds=None,direction_rule='From the cited paper to the citing paper; papers of the same year use evidence',levels=['given'])], evidence_bases=[dict(id='full_text',label='Full text',description='Full text (PDF) of the citing paper, read by the judge'),dict(id='citation_record',label='Citation record',description='Citation listed by Semantic Scholar'),dict(id='citing_sentence',label='Citing sentence',description='The sentence of the citing paper that cites the cited paper'),dict(id='title_and_abstract',label='Title and abstract',description='Title and abstract of the citing paper, used where no citing sentence exists')], rules=[dict(id='R_SNOWBALL',description='Paper is a seed, or cites a seed and cites scagnostics or deals with scatterplots, visual quality measures or view selection',parameters={},applies_to='event')], judges=[dict(id='claude_reader',type='model',description='Claude (an Anthropic language model) read the citing sentence, or the title and abstract where none exists, and typed the citing paper as develops, applies or background; one reader, no second reader',agreement=dict(measured=False))], flags=[],parameters=dict(time_precision=dict(value='year',description='All papers are dated to the first instant of their publication year; papers of one year are simultaneous'),coords_space=dict(value='scagnostics_topic_map_tsne_unit',description='attrs.coords hold a t-SNE layout of title and abstract words in the unit square; layout hint only')), limitations=['One reader judged the papers and agreement was not measured; the reader is a language model','Evidence texts hold a rationale and an excerpt of at most 14 words, not the full citing sentence; the full sentence can be retrieved through source_ref','First-generation links are judged one by one; a link is develops only if the citing paper builds on the cited work itself, and applies only if it uses the cited measure, tool or data (a baseline comparison counts as applies); related-work mentions are background','Cascades overlap because a paper citing several seeds belongs to each of their cascades','The seeds were chosen by the analyst and include related quality-metric work, so the set is wider than scagnostics proper','Year precision hides the order of papers within a year'], notes='Hand check: take a develops link; open the citing paper and find the sentence that cites the earlier paper.') od='/home/claude/pkg/out/scagnostics';st=write_package(od,M,events,ents,[],links,om,omc);print(json.dumps(st)[:600]);print(finalize(od))