forked from joonspk-research/generative_agents
-
Notifications
You must be signed in to change notification settings - Fork 17
/
global_methods.py
245 lines (201 loc) · 6.08 KB
/
global_methods.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""
Author: Joon Sung Park (joonspk@stanford.edu)
File: global_methods.py
Description: Contains functions used throughout my projects.
"""
import random
import string
import csv
import time
import datetime as dt
import pathlib
import os
import sys
import numpy
import math
import shutil, errno
from os import listdir
def create_folder_if_not_there(curr_path):
"""
Checks if a folder in the curr_path exists. If it does not exist, creates
the folder.
Note that if the curr_path designates a file location, it will operate on
the folder that contains the file. But the function also works even if the
path designates to just a folder.
Args:
curr_list: list to write. The list comes in the following form:
[['key1', 'val1-1', 'val1-2'...],
['key2', 'val2-1', 'val2-2'...],]
outfile: name of the csv file to write
RETURNS:
True: if a new folder is created
False: if a new folder is not created
"""
outfolder_name = curr_path.split("/")
if len(outfolder_name) != 1:
# This checks if the curr path is a file or a folder.
if "." in outfolder_name[-1]:
outfolder_name = outfolder_name[:-1]
outfolder_name = "/".join(outfolder_name)
if not os.path.exists(outfolder_name):
os.makedirs(outfolder_name)
return True
return False
def write_list_of_list_to_csv(curr_list_of_list, outfile):
"""
Writes a list of list to csv.
Unlike write_list_to_csv_line, it writes the entire csv in one shot.
ARGS:
curr_list_of_list: list to write. The list comes in the following form:
[['key1', 'val1-1', 'val1-2'...],
['key2', 'val2-1', 'val2-2'...],]
outfile: name of the csv file to write
RETURNS:
None
"""
create_folder_if_not_there(outfile)
with open(outfile, "w") as f:
writer = csv.writer(f)
writer.writerows(curr_list_of_list)
def write_list_to_csv_line(line_list, outfile):
"""
Writes one line to a csv file.
Unlike write_list_of_list_to_csv, this opens an existing outfile and then
appends a line to that file.
This also works if the file does not exist already.
ARGS:
curr_list: list to write. The list comes in the following form:
['key1', 'val1-1', 'val1-2'...]
Importantly, this is NOT a list of list.
outfile: name of the csv file to write
RETURNS:
None
"""
create_folder_if_not_there(outfile)
# Opening the file first so we can write incrementally as we progress
curr_file = open(outfile, 'a',)
csvfile_1 = csv.writer(curr_file)
csvfile_1.writerow(line_list)
curr_file.close()
def read_file_to_list(curr_file, header=False, strip_trail=True):
"""
Reads in a csv file to a list of list. If header is True, it returns a
tuple with (header row, all rows)
ARGS:
curr_file: path to the current csv file.
RETURNS:
List of list where the component lists are the rows of the file.
"""
if not header:
analysis_list = []
with open(curr_file) as f_analysis_file:
data_reader = csv.reader(f_analysis_file, delimiter=",")
for count, row in enumerate(data_reader):
if strip_trail:
row = [i.strip() for i in row]
analysis_list += [row]
return analysis_list
else:
analysis_list = []
with open(curr_file) as f_analysis_file:
data_reader = csv.reader(f_analysis_file, delimiter=",")
for count, row in enumerate(data_reader):
if strip_trail:
row = [i.strip() for i in row]
analysis_list += [row]
return analysis_list[0], analysis_list[1:]
def read_file_to_set(curr_file, col=0):
"""
Reads in a "single column" of a csv file to a set.
ARGS:
curr_file: path to the current csv file.
RETURNS:
Set with all items in a single column of a csv file.
"""
analysis_set = set()
with open(curr_file) as f_analysis_file:
data_reader = csv.reader(f_analysis_file, delimiter=",")
for count, row in enumerate(data_reader):
analysis_set.add(row[col])
return analysis_set
def get_row_len(curr_file):
"""
Get the number of rows in a csv file
ARGS:
curr_file: path to the current csv file.
RETURNS:
The number of rows
False if the file does not exist
"""
try:
analysis_set = set()
with open(curr_file) as f_analysis_file:
data_reader = csv.reader(f_analysis_file, delimiter=",")
for count, row in enumerate(data_reader):
analysis_set.add(row[0])
return len(analysis_set)
except:
return False
def check_if_file_exists(curr_file):
"""
Checks if a file exists
ARGS:
curr_file: path to the current csv file.
RETURNS:
True if the file exists
False if the file does not exist
"""
try:
with open(curr_file) as f_analysis_file: pass
return True
except:
return False
def find_filenames(path_to_dir, suffix=".csv"):
"""
Given a directory, find all files that ends with the provided suffix and
returns their paths.
ARGS:
path_to_dir: Path to the current directory
suffix: The target suffix.
RETURNS:
A list of paths to all files in the directory.
"""
filenames = listdir(path_to_dir)
return [ path_to_dir+"/"+filename
for filename in filenames if filename.endswith( suffix ) ]
def average(list_of_val):
"""
Finds the average of the numbers in a list.
ARGS:
list_of_val: a list of numeric values
RETURNS:
The average of the values
"""
return sum(list_of_val)/float(len(list_of_val))
def std(list_of_val):
"""
Finds the std of the numbers in a list.
ARGS:
list_of_val: a list of numeric values
RETURNS:
The std of the values
"""
std = numpy.std(list_of_val)
return std
def copyanything(src, dst):
"""
Copy over everything in the src folder to dst folder.
ARGS:
src: address of the source folder
dst: address of the destination folder
RETURNS:
None
"""
try:
shutil.copytree(src, dst)
except OSError as exc: # python >2.5
if exc.errno in (errno.ENOTDIR, errno.EINVAL):
shutil.copy(src, dst)
else: raise
if __name__ == '__main__':
pass