import sys,os,json,re,collections;sys.path.insert(0,'/home/claude/pkg') from pkgkit import * os.chdir('/home/claude/sch');sys.path.insert(0,'/home/claude/sch') src=open('/home/claude/sch/build_scholar_orig.py').read();ns={'__name__':'bs'} exec(compile(src[:src.index('rows={}')],'build_scholar_head','exec'),ns) corpus=ns['corpus'];ids=ns['ids'];places=ns['places'];pos=ns['pos'];cellof=ns['cellof'];rev=ns['rev'];c=ns['c'];ROLE=ns['E']['role'];ROLES=['technique','application','study','synthesis'] os.chdir('/home/claude/pkg') SURV='e684fc96a0bff8e79594ed8ce4a1830d86c03c65' G=re.compile(r'^(ieee|acm|proceedings|eurographics|computer graphics forum|human factors|international (conference|symposium|journal)|symposium|journal|transactions|conference)',re.I) def source_of(p): return 'openalex' if p.startswith('oa:') else 'semantic_scholar' def sid_of(p): return p[3:] if p.startswith('oa:') else p # links first (needed for imputed years) C=json.load(open('/home/claude/sch/corpus2.json')) rows={} for s,rs in c.items(): for r in rs: a=(r['citingPaper'] or {}).get('paperId') if a in corpus: rows[(s,a)]=r for a,b in C['links']: rows.setdefault((a,b),None) def yr0(p): q=corpus[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 rows: if s in corpus and p in corpus and year.get(p): earliest[s]=min(earliest[s],year[p]) for p in ids: if year[p]: continue t=corpus[p].get('title') or '';m=re.search(r'\b(19[89]\d|20[0-2]\d)\b',t) 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]=2000;imp[p]='default' print('imputed years',collections.Counter(imp.values())) # merged duplicates among survey citers merged=collections.defaultdict(list) doi2id={((q.get('externalIds') or {}).get('DOI') or '').lower():p for p,q in corpus.items() if (q.get('externalIds') or {}).get('DOI')} t2id={(q.get('title') or '').lower()[:60]:p for p,q in corpus.items()} for r in json.load(open('/home/claude/sch/survey_citers.json')): ident=r['s2'] or ('oa:'+(r.get('oa') or '').split('/')[-1]) if r['s2'] in corpus: continue pid=doi2id.get((r.get('doi') or '').lower()) or t2id.get((r['title'] or '').lower()[:60]) if pid and pid!=ident and ident not in merged[pid]: merged[pid].append(ident) expanded=set(json.load(open('/home/claude/sch/gen2_citations.json')))|{SURV}|set(c) events=[] for p in ids: q=corpus[p];doi=(q.get('externalIds') or {}).get('DOI') title=(q.get('title') or '').strip() or f'Untitled record {sid_of(p)}' fl=['time_coarse'] if p in imp: fl.append('time_imputed') if G.search(title) or not (q.get('title') or '').strip(): fl.append('title_garbled') if p in merged: fl.append('duplicate_merged') a=dict(role=ROLES[ROLE[ids.index(p)]] if False else None);a={} a['venue']=(q.get('venue') or '')[:80];a['citation_count']=q.get('citationCount') or 0;a['coords']=dict(space='lens_topic_map_tsne_unit',x=round(pos[p][0],4),y=round(pos[p][1],4)) if doi: a['doi']=doi if p in imp: a['year_imputed_by']=imp[p] pv=dict(source_ids=[dict(source=source_of(p),id=sid_of(p))],extraction=dict(method='paper in the citation neighbourhood of the survey reference list',rule_ids=['R_SNOWBALL']),confidence=None) if p in merged: pv['merged_from']=merged[p] 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=pv,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='lens_topic_map_tsne_unit',x=pl['x'],y=pl['y']),papers=pl['n']),provenance=dict(source_ids=[],derived=True,method='k-means (k=14, 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 words(s,n=14): s=re.sub(r'\s+',' ',s.replace('[abstract]','')).strip().strip('…').strip();w=s.split(' ');return ' '.join(w[:n]) RAT={'D':'The citing paper develops a new or extended technique or concept from the cited idea','A':'The citing paper uses the cited idea in a system or study','M':'The citing paper cites the cited paper as general background'} REL={'D':'develops','A':'applies','M':'background'} links=[];om=[];oc=collections.Counter() for (s,p),r in rows.items(): if s not in corpus or p not in corpus or s==p: continue dy=year[p]-year[s];kindid='reference';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]}'));continue srcname='openalex' if (s.startswith('oa:') or p.startswith('oa:')) else 'semantic_scholar' ex=dict(level='given',basis='citation_record',source_ref=dict(source=srcname,id=f'{sid_of(s)}>{sid_of(p)}')) L=dict(id=lid,**{'from':s,'to':p},kind=kindid,propagates=False,direction='evidence' if dy==0 else 'time',gap_seconds=0 if dy==0 else int((__import__('datetime').date(year[p],1,1)-__import__('datetime').date(year[s],1,1)).total_seconds()),evidence=dict(existence=ex)) if p==SURV: L['relation']='described_in_survey';L['evidence']['relation']=dict(level='given',basis='citation_record',text='The survey cites this earlier paper in its reference list',source_ref=dict(source=srcname,id=f'{sid_of(s)}>{sid_of(p)}')) elif (s,p) in rev: lab,ctx,sr=rev[(s,p)];L['relation']=REL[lab];L['propagates']=lab in 'DA' sent=bool(ctx) and not ctx.startswith('[abstract]');w=words(ctx) if sent else '' txt=RAT[lab]+('. Read from the citing sentence' if sent else '. Read from the title and abstract of the citing paper')+(f'. Excerpt: “{w}”' if w else '') L['evidence']['relation']=dict(level='judged',basis='citing_sentence' if sent else 'title_and_abstract',text=txt,judge=dict(type='model',id='claude_reader',date='2026-10',unit='link')) L.setdefault('attrs',{})['review_set']=sr else: L['flags']=['unassessed'] links.append(L) 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='lens-survey-0.1',created_at=CREATED, adapter=dict(name='bibliometric_lens_adapter',version='0.1',domain='bibliometrics',code_ref=None,produced_by='Claude, from the lens pilot data (Semantic Scholar and OpenAlex records) and the judgements of the lens study'), domain=dict(event_definition='A paper in the citation neighbourhood of the references of the interactive-lenses survey by Tominski et al., 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'), dict(id='openalex',name='OpenAlex works (records of papers not found in Semantic Scholar, publication dates)',url='https://openalex.org',accessed_at='2026-10',license='CC0 (OpenAlex data)')], 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 the 92 papers on lenses and focus+context cited by the survey. First generation: papers citing a seed (Semantic Scholar, lens-related by title or abstract). The survey itself and the papers citing it were added, then the papers citing the survey papers that develop or apply a lens idea (second generation)',seeds=[s['title'] for s in json.load(open('/home/claude/sch/seeds.json'))],depth_limit=2,selection_rules=['R_SNOWBALL'], known_gaps=['Starts from the references of one survey; lens papers that cite none of them are missing','Second generation collected only for the 69 papers that develop or apply a survey idea','The 2020s are incomplete because recent papers have had little time to be cited','Only a selection of links was judged: 358 links selected by a keyword rule (strict), 140 random other links to estimate the precision of the rule, 175 links from the survey to its citing papers and 156 second-generation links; all other links carry the flag unassessed','Dates are reduced to the publication year; 31 records without a year or date were given a year by rule and carry the flag time_imputed','About 11 records have a garbled title in the source and carry the flag title_garbled','Merging of duplicate records in the first collection stage used DOI and title matching and is not listed; only merges of the survey citers are listed in merged_from','Citation lists of Semantic Scholar and OpenAlex differ; the union was used for the survey']), 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 technique or concept from the cited idea',propagates_default=True),dict(id='applies',description='The citing paper uses the idea in a system or study',propagates_default=True),dict(id='background',description='The citing paper cites the idea as background',propagates_default=False),dict(id='described_in_survey',description='The survey cites and describes the earlier paper',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='citation_record',label='Citation record',description='Citation listed by Semantic Scholar or OpenAlex'),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 cites a seed or a paper already in the set, or is cited by the survey, and deals with lenses, magnification or focus+context',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 link 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='lens_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 links 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','Links are typed only for a selection; the keyword selection favours papers with cue words','The survey is the root of a cascade because the links into it are non-propagating; switch them on to see it as a hub','Citation counts are those of Semantic Scholar at collection time','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/lens-survey';st=write_package(od,M,events,ents,[],links,om,omc);print(json.dumps(st)[:600]);print(finalize(od))