1 from pyspark.sql import functions as f
2 from pyspark.sql import SparkSession
3 from pyspark.sql import Window
6 import pyarrow.dataset as ds
9 from itertools import islice, chain
10 from pathlib import Path
11 from similarities_helper import *
12 from multiprocessing import Pool, cpu_count
13 from functools import partial
16 def _week_similarities(week, simfunc, tfidf_path, term_colname, min_df, max_df, included_subreddits, topN, outdir:Path):
18 term_id = term + '_id'
19 term_id_new = term + '_id_new'
20 print(f"loading matrix: {week}")
21 entries, subreddit_names = reindex_tfidf(infile = tfidf_path,
22 term_colname=term_colname,
25 included_subreddits=included_subreddits,
28 mat = csr_matrix((entries[tfidf_colname],(entries[term_id_new], entries.subreddit_id_new)))
29 print('computing similarities')
30 sims = column_similarities(mat)
32 sims = pd.DataFrame(sims.todense())
33 sims = sims.rename({i: sr for i, sr in enumerate(subreddit_names.subreddit.values)}, axis=1)
34 sims['_subreddit'] = names.subreddit.values
35 outfile = str(Path(outdir) / str(week))
36 write_weekly_similarities(outfile, sims, week, names)
38 def pull_weeks(batch):
39 return set(batch.to_pandas()['week'])
41 #tfidf = spark.read.parquet('/gscratch/comdata/users/nathante/subreddit_tfidf_weekly.parquet')
42 def cosine_similarities_weekly(tfidf_path, outfile, term_colname, min_df = None, max_df=None, included_subreddits = None, topN = 500):
44 tfidf_ds = ds.dataset(tfidf_path)
45 tfidf_ds = tfidf_ds.to_table(columns=["week"])
46 batches = tfidf_ds.to_batches()
48 with Pool(cpu_count()) as pool:
49 weeks = set(chain( * pool.imap_unordered(pull_weeks,batches)))
52 # do this step in parallel if we have the memory for it.
53 # should be doable with pool.map
55 print(f"computing weekly similarities")
56 week_similarities_helper = partial(_week_similarities,simfunc=column_similarities, tfidf_path=tfidf_path, term_colname=term_colname, outdir=outfile, min_df=min_df,max_df=max_df,included_subreddits=included_subreddits,topN=topN)
58 with Pool(cpu_count()) as pool: # maybe it can be done with 40 cores on the huge machine?
59 list(pool.map(week_similarities_helper,weeks))
61 def author_cosine_similarities_weekly(outfile, min_df=2, max_df=None, included_subreddits=None, topN=500):
62 return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_authors.parquet',
70 def term_cosine_similarities_weekly(outfile, min_df=None, max_df=None, included_subreddits=None, topN=500):
71 return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_terms.parquet',
79 if __name__ == "__main__":
80 fire.Fire({'authors':author_cosine_similarities_weekly,
81 'terms':term_cosine_similarities_weekly})