forked from yamins81/govdata-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bea.py
2046 lines (1607 loc) · 101 KB
/
bea.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import urllib
import re
import cPickle as pickle
import numpy as np
import tabular as tb
import pymongo as pm
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, NavigableString
from mechanize import Browser
from starflow.utils import activate, MakeDir, Contents, listdir, IsDir, uniqify, PathExists,RecursiveFileList, ListUnion, MakeDirs,delete,strongcopy
import govdata.core
import utils.htools as htools
from utils.basic import wget
#=-=-=-=-=-=-=-=-=-Utilities
def SafeContents(x):
return ' '.join(Contents(x).strip().split())
def filldown(x):
y = np.array([xx.strip() for xx in x])
nz = np.append((y != '').nonzero()[0],[len(y)])
return y[nz[:-1]].repeat(nz[1:] - nz[:-1])
def gethierarchy(x,f,postprocessor = None):
hl = np.array([f(xx) for xx in x])
# normalize
ind = np.concatenate([(hl == min(hl)).nonzero()[0], np.array([len(hl)])])
if ind[0] != 0:
ind = np.concatenate([np.array([0]), ind])
hl2 = []
for i in range(len(ind)-1):
hls = hl[ind[i]:ind[i+1]].copy()
hls.sort()
hls = tb.utils.uniqify(hls)
D = dict(zip(hls, range(len(hls))))
hl2 += [D[h] for h in hl[ind[i]:ind[i+1]]]
hl = np.array(hl2)
m = max(hl)
cols = []
for v in range(m+1):
vxo = hl < v
vx = hl == v
if vx.any():
nzv = np.append(vx.nonzero()[0],[len(x)])
col = np.append(['']*nzv[0],x[nzv[:-1]].repeat(nzv[1:] - nzv[:-1]))
col[vxo] = ''
cols.append(col)
else:
cols.append(np.array(['']*len(x)))
if postprocessor:
for i in range(len(cols)):
cols[i] = np.array([postprocessor(y) for y in cols[i]])
return [cols,hl]
def getzip(url,zippath,dirpath=None):
assert zippath.endswith('.zip')
if dirpath == None:
dirpath = zippath[:-4]
print url, zippath
os.system('wget ' + url + ' -O ' + zippath)
os.system('unzip -d ' + dirpath + ' ' + zippath)
def WgetMultiple(link,fname,opstring='', maxtries=5):
for i in range(maxtries):
wget(link, fname, opstring)
F = open(fname,'r').read().strip()
if not (F.lower().startswith('<!doctype') or F == '' or 'servlet error' in F.lower()):
return
else:
print 'download of ' + link + ' failed'
print 'download of ' + link + ' failed after ' + str(maxtries) + ' attempts'
return
def hr(x):
return len(x) - len(x.lstrip(' '))
def hr2(x):
return len(x.split('\xc2\xa0')) - 1
def hr3(x):
return len(x) - len(x.lstrip('\t'))
def GetFootnotes(line, FootnoteSplitter='/'):
newline = ' '*(len(line)-len(line.lstrip())) + ' '.join([' '.join(x.split()[:-1]) for x in line.split(FootnoteSplitter)[:-1]])
footnotes = ', '.join([x.split()[-1] for x in line.split(FootnoteSplitter)[:-1]])
return (newline, footnotes)
def GetFootnotes2(line, FootnoteSplitter='\\'):
newline = ' '.join(line.split(FootnoteSplitter)[:-1])
footnotes = ', '.join([x.split()[0] for x in line.split(FootnoteSplitter)[1:]])
return (newline, footnotes)
def GetFootnotesLazy(line, FootnoteSplitter='\\'):
newline = line.split(FootnoteSplitter)[0]
footnotes = line.split(FootnoteSplitter)[1]
return (newline, footnotes)
def CleanLinesForMetadata(x):
x = [line.strip('"').strip() for line in x]
line = x[0]
while line == '':
x = x[1:]
line = x[0]
line = x[-1]
while line == '':
x = x[:-1]
line = x[-1]
return x
def ExpandString(S):
ind2 = [i for i in range(1,len(S)-1) if S[i].lower() != S[i] and S[i+1].lower() == S[i+1]] + [len(S)]
ind1 = [0] + ind2[:-1]
return ' '.join([S[i:j] for (i,j) in zip(ind1,ind2)])
def nea_dateparse(x):
mmap = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
d = x.split('-')
if len(d) == 1:
return d[0] + 'X' + 'XX'
elif set(d[1].lower()) <= set(['i','v']):
D = {'i':'1','ii':'2','iii':'3','iv':'4'}
return d[0] + D[d[1].lower()] + 'XX'
elif d[1].lower() in mmap:
ind = str(mmap.index(d[1].lower())+1)
ind = ind if len(ind) == 2 else '0' + ind
return d[0] + 'X' + ind
def NEA_Parser(page, headerlines=None, FootnoteSplitter = '/', FootnotesFunction = GetFootnotes, CategoryColumn=None,FormulaColumn=None):
[Y, header, footer, keywords] = BEA_Parser(page, headerlines=headerlines, FootnoteSplitter = FootnoteSplitter, FootnotesFunction = FootnotesFunction, CategoryColumn=CategoryColumn, NEA=True, FormulaColumn=FormulaColumn)
levelnames = [n for n in Y.dtype.names if n.startswith('Level_')]
displaylevels = np.array([np.where(Y[n] != '', i,0) for (i,n) in enumerate(levelnames)]).T.max(axis=1)
Y = Y.addcols(displaylevels,names=['DisplayLevel'])
labels = [x.strip() for x in Y['Category']]
for k in range(0,Y['DisplayLevel'].max()):
badcounts = [i for i in range(len(labels)) if labels.count(labels[i]) > 1]
for i in badcounts:
if Y['DisplayLevel'][i] - k >= 1:
labels[i] = (labels[i] + ' - ' + Y['Level_' + str(Y['DisplayLevel'][i] - k)][i]).strip()
Y = Y.addcols(labels,names=['Label'])
Y.metadata = {'labelcollist':['Label']}
return [Y, header, footer, keywords]
def BEA_Parser(page, headerlines=None, FootnoteSplitter = '/', FootnotesFunction = GetFootnotes, CategoryColumn=None, NEA=False, FormulaColumn=None):
if NEA:
G = [line.strip() for line in open(page, 'rU').read().strip('\n').split('\n')]
# get header
keepon = 1
i = 0
header = []
while keepon:
line = G[i]
if not line.startswith('Line'):
header += [line]
i = i + 1
else:
keepon = 0
[F, meta] = tb.io.loadSVrecs(page, headerlines=i+1,delimiter = ',')
else:
[F, meta] = tb.io.loadSVrecs(page, headerlines=headerlines)
header = None
names = [n.strip() for n in meta['names']]
if not NEA:
names = names[:len(F[0])]
F = [f[:len(names)] for f in F]
if names[1] == '':
names[1] = 'Category'
# get footer
keepon = 1
i = len(F)-1
footer = []
while keepon:
rec = F[i]
if len(rec) != len(names):
footer = [','.join(rec)] + footer
i = i - 1
else:
keepon = 0
F = F[:i+1]
F = [line + ['']*(len(names)-len(line)) for line in F ]
if CategoryColumn:
i = [i for i in range(len(names)) if names[i].strip() == CategoryColumn][0]
CatCol = np.array([row[i] for row in F])
F = [tuple([col.strip() for col in row]) for row in F]
ind = [i for i in range(len(names)) if names[i][:4].isdigit()][0]
X = tb.tabarray(records=F, names=names, coloring={'Info': names[:ind], 'Data': names[ind:]})
FootnoteColumns = []
FootnoteNames = []
for cname in X.coloring['Info']:
L = [len(c.split(FootnoteSplitter)) > 1 for c in X[cname]]
if any(L):
#Column_Footnote = [FootnotesFunction(X[cname][i]) if L[i] else (col[i], '') for i in range(len(X))]
Column_Footnote = [FootnotesFunction(c) if l else (c, '') for (c, l) in zip(X[cname], L)]
X[cname] = [c for (c,n) in Column_Footnote]
FootnoteColumns += [[n for (c,n) in Column_Footnote]]
FootnoteNames += [cname + ' Footnotes']
if cname == CategoryColumn:
Column_Footnote = np.array([FootnotesFunction(c) if l else (c, '') for (c, l) in zip(CatCol, L)])
CatCol = np.array([c for (c,n) in Column_Footnote])
if FootnoteColumns:
Footnotes = tb.tabarray(columns = FootnoteColumns, names = FootnoteNames, coloring = {'Footnotes': FootnoteNames})
else:
Footnotes = None
if FormulaColumn:
L = [len(c.split('(')) > 1 and any([x.isdigit() and x<1000 for x in c.split('(')[1]]) for c in X[FormulaColumn]]
if any(L):
Formula = [X[FormulaColumn][i].split('(')[1].split(')')[0] if L[i] else '' for i in range(len(X))]
X[FormulaColumn] = [X[FormulaColumn][i].split('(')[0].rstrip() if L[i] else X[FormulaColumn][i] for i in range(len(X))]
X = X['Info'].colstack(tb.tabarray(columns = [Formula], names = ['Formula'])).colstack(X['Data'])
X.coloring['Info'] += ['Formula']
if CategoryColumn:
[cols, hl] = gethierarchy(CatCol, hr, postprocessor = lambda x : x.strip())
columns = [c for c in cols if not (c == '').all()]
if len(columns) > 1:
categorynames = ['Level_' + str(i) for i in range(1, len(columns)+1)]
Categories = tb.tabarray(columns = columns, names = categorynames, coloring = {'Categories': categorynames})
else:
Categories = None
else:
Categories = None
Y = X['Info']
if Footnotes != None:
Y = Y.colstack(Footnotes)
if Categories != None:
Y = Y.colstack(Categories)
if NEA:
X.replace('---','')
Y = Y.colstack(tb.tabarray(columns=[tb.utils.DEFAULT_TYPEINFERER(X[c]) for c in X.coloring['Data']], names=X.coloring['Data'], coloring={'Data': X.coloring['Data']}))
else:
Y = Y.colstack(X['Data'])
if CategoryColumn:
keywords = [y for y in tb.utils.uniqify([x.replace(',', '').replace('.', '').replace(',', '') for x in X[CategoryColumn]]) if y]
else:
keywords = []
if footer:
footer = CleanLinesForMetadata(footer)
if header:
header = CleanLinesForMetadata(header)
return [Y, header, footer, keywords]
def NEA_preparser2(inpath,filepath,metadatapath,L = None):
MakeDir(filepath)
if L == None:
L = [inpath + x for x in listdir(inpath) if x.endswith('.tsv')]
T = [x.split('/')[-1].split('_')[0].strip('.') for x in L]
R = tb.tabarray(columns=[L,T],names = ['Path','Table']).aggregate(On=['Table'],AggFunc=lambda x : '|'.join(x))
ColGroups = {}
Metadict = {}
for (j,r) in enumerate(R):
ps = r['Path'].split('|')
t = r['Table']
print t
assert t != ''
X = [tb.tabarray(SVfile = p) for p in ps]
X1 = [x[x['Line'] != ''].deletecols(['Category','Label','DisplayLevel']) for x in X]
for i in range(len(X)):
X1[i].metadata = X[i].metadata
X1[i].coloring['Topics'] = X1[i].coloring.pop('Categories')
X1[i].coloring['timeColNames'] = X1[i].coloring['Data']
X1[i].coloring.pop('Data')
for k in range(len(X1[i].coloring['timeColNames'])):
name = X1[i].coloring['timeColNames'][k]
X1[i].renamecol(name,nea_dateparse(name))
if len(X1) > 1:
keycols = [x for x in X1[0].dtype.names if x not in X1[0].coloring['timeColNames']]
Z = tb.tab_join(X1,keycols=keycols)
else:
Z = X1[0]
topics = sorted(uniqify(Z.coloring['Topics']))
Z.coloring['Topics'] = topics
for topic in topics:
Z.renamecol(topic,'Topic ' + topic)
K = ['Category','Section','units','notes','downloadedOn','lastRevised','Table','footer','description']
Z.metadata = {}
for k in K:
h = [x.metadata[k] for x in X if k in x.metadata.keys()]
if h:
if isinstance(h[0],str):
Z.metadata[k] = ', '.join(uniqify(h))
elif isinstance(h[0],list) or isinstance(h[0],tuple):
Z.metadata[k] = uniqify(ListUnion(h))
else:
print 'metadata type for key', k , 'in table', t, 'not recognized.'
Section = Z.metadata.pop('Section')
Table = Z.metadata.pop('Table').strip().split('.')[-1].strip()
for k in Z.coloring.keys():
if k in ColGroups.keys():
ColGroups[k] = uniqify(ColGroups[k] + Z.coloring[k])
else:
ColGroups[k] = Z.coloring[k]
Metadict[t] = Z.metadata
Metadict[t]['title'] = Table
Z = Z.addcols([[t]*len(Z),[Table]*len(Z),[Section]*len(Z),[t]*len(Z)],names=['TableNo','Table','Section','subcollections'])
Z.saveSV(filepath + str(j) + '.tsv',metadata=['dialect','formats','names'])
AllKeys = uniqify(ListUnion([k.keys() for k in Metadict.values()]))
AllMeta = {}
for k in AllKeys:
if all([k in Metadict[l].keys() for l in Metadict.keys()]) and len(uniqify([Metadict[l][k] for l in Metadict.keys()])) == 1:
AllMeta[k] = Metadict[Metadict.keys()[0]][k]
for l in Metadict.keys():
Metadict[l].pop(k)
Category = AllMeta.pop('Category')
AllMeta['topicHierarchy'] = ('agency','subagency','program','dataset','Section','Table')
AllMeta['uniqueIndexes'] = ['TableNo','Line']
ColGroups['Topics'].sort()
ColGroups['labelColumns'] = ['Table','Topics']
AllMeta['columnGroups'] = ColGroups
AllMeta['description'] = 'National Income and Product Accounts (NIPA) data from the <a href="http://www.bea.gov/national/nipaweb/SelectTable.asp?Selected=N">All NIPA Tables</a> data set under the <a href="http://www.bea.gov/national/index.htm">National Economic Accounts</a> section of the <a href="http://www.bea.gov/">Bureau of Economic Accounts (BEA)</a> website. For additional information on the NIPAs, see: <a href="http://www.bea.gov/scb/pdf/misc/nipaguid.pdf">A Guide to the National Income and Product Accounts of the United States (PDF)</a>, <a href="http://www.bea.gov/scb/pdf/2009/11%20November/1109_nipa_method.pdf">Updated Summary of NIPA Methodologies (PDF)</a>, and <a href="http://www.bea.gov/scb/pdf/2003/08August/0803NIPA-Preview.pdf#page=9">Guide to the Numbering of the NIPA Tables (PDF)</a>.'
AllMeta['dateFormat'] = 'YYYYqmm'
AllMeta['keywords'] = ['NIPA','GDP','income']
AllMeta['sliceCols'] = [['Section','Table','Topic Level_0','Topic Level_1','Topic Level_2'] + [tuple(ColGroups['Topics'][:i]) for i in range(4,len(ColGroups['Topics']) + 1)]]
AllMeta['phraseCols'] = ['Section','Table','Topic','Line','TableNo']
Subcollections = Metadict
Subcollections[''] = AllMeta
F = open(metadatapath,'w')
pickle.dump(Subcollections,F)
F.close()
#=-=-=-=-=-=-=-=-=-=-=-=-=-=FAT
FAT_NAME = 'BEA_FAT'
@activate(lambda x : 'http://www.bea.gov/national/FA2004/SelectTable.asp',lambda x : x[0])
def FAT_downloader(maindir):
MakeDirs(maindir)
get_FAT_manifest(maindir)
connection = pm.Connection()
incremental = FAT_NAME in connection['govdata'].collection_names()
MakeDir(maindir + 'raw/')
URLBase = 'http://www.bea.gov/national/FA2004/csv/NIPATable.csv?'
X = tb.tabarray(SVfile = maindir + 'manifest.tsv')
for x in X:
NC = x['NumCode']
Freq = x['Freq']
if incremental:
Vars = ['TableName','FirstYear','LastYear','Freq']
FY = x['FirstYear']
LY = x['LastYear']
url = URLBase + '&'.join([v + '=' + str(val) for (v,val) in zip(Vars,[NC,FY,LY,Freq])])
else:
Vars = ['TableName','AllYearChk','FirstYear','LastYear','Freq']
FY = 1800
LY = 2200
url = URLBase + '&'.join([v + '=' + str(val) for (v,val) in zip(Vars,[NC,'YES',FY,LY,Freq])])
topath = maindir + 'raw/' + x['Section'] + '_' + x['Table'] + '.csv'
WgetMultiple(url,topath)
def get_FAT_manifest(download_dir,depends_on = 'http://www.bea.gov/national/FA2004/SelectTable.asp'):
wget(depends_on,download_dir + 'manifest.html')
nc = re.compile('SelectedTable=[\d]+')
fy = re.compile('FirstYear=[\d]+')
ly = re.compile('LastYear=[\d]+')
fr = re.compile('Freq=[a-zA-Z]+')
L = lambda reg , x : int(reg.search(str(dict(x.findAll('a')[0].attrs)['href'])).group().split('=')[-1])
L2 = lambda reg , x : reg.search(str(dict(x.findAll('a')[0].attrs)['href'])).group().split('=')[-1]
path = download_dir + 'manifest.html'
Soup = BeautifulSoup(open(path),convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
c1 = lambda x : x.name == 'a' and 'name' in dict(x.attrs).keys() and dict(x.attrs)['name'].startswith('S')
c2 = lambda x : x.name == 'tr' and 'class' in dict(x.attrs).keys() and dict(x.attrs)['class'] == 'TR' and x.findAll('a') and 'href' in dict(x.findAll('a')[0].attrs).keys() and dict(x.findAll('a')[0].attrs)['href'].startswith('Table')
p1 = lambda x : Contents(x).strip().strip('\xc2\xa0').strip()
p2 = lambda x : (p1(x),'http://www.bea.gov/national/FA2004/' + str(dict(x.findAll('a')[0].attrs)['href']),L(nc,x),L(fy,x),L(ly,x),L2(fr,x))
X = htools.MakeTable(Soup,[c1,c2],[p1,p2],['Section',['Table','URL','NumCode','FirstYear','LastYear','Freq']])
secnums = [x['Section'].split(' ')[1].strip() for x in X]
secnames = [x['Section'].split('-')[1].strip() for x in X]
tablenums = [x['Table'].split(' ')[1].split('.')[-2].strip() for x in X]
tablenames = [' '.join(x['Table'].split(' ')[2:]).strip() for x in X]
X = X.addcols([secnums,secnames,tablenums,tablenames],names=['Section','SectionName','Table','TableName'])
X.saveSV(download_dir + 'manifest.tsv',metadata=True)
@activate(lambda x : (x[0] + 'raw/',x[0] + 'manifest.tsv'), lambda x : x[0] + 'preparsed/')
def FAT_preparser1(maindir):
targetdir = maindir + 'preparsed/'
sourcedir = maindir + 'raw/'
MakeDir(targetdir)
M = tb.tabarray(SVfile = maindir + 'manifest.tsv')
for x in M:
f = sourcedir + x['Section'].strip('.') + '_' + x['Table'] + '.csv'
print f
savepath = targetdir + x['Section'].strip('.') + '_' + x['Table'] + '.tsv'
[X, header, footer, keywords] = NEA_Parser(f, FootnoteSplitter='\\', FootnotesFunction=GetFootnotesLazy, CategoryColumn='Category',FormulaColumn='Category')
metadata = {}
metadata['Header'] = '\n'.join(header)
(title, units, bea) = header
metadata['title'] = title
metadata['description'] = 'Fixed Asset "' + title + '" from the <a href="http://www.bea.gov/national/FA2004/SelectTable.asp">Standard Fixed Asset Tables</a> data set under the <a href="http://www.bea.gov/national/index.htm">National Economic Accounts</a> section of the <a href="http://www.bea.gov/">Bureau of Economic Accounts (BEA)</a> website. For additional information on the Fixed Asset Tables, see: <a href="http://www.bea.gov/national/pdf/Fixed_Assets_1925_97.pdf"> Methodology, Fixed Assets and Consumer Durable Goods in the United States, 1925-97 | September 2003 (PDF)</a>, <a href="http://www.bea.gov/scb/pdf/national/niparel/1997/0797fr.pdf">The Measurement of Depreciation in the NIPA\'s | SCB, July 1997 (PDF) </a>, and <a href="http://www.bea.gov/national/FA2004/Tablecandtext.pdf">BEA Rates of Depreciation, Service Lives, Declining-Balance Rates, and Hulten-Wykoff categories | February 2008 (PDF)</a>.'
metadata['Agency'] = 'DOC'
metadata['Subagency'] = 'BEA'
metadata['Type'] = 'National'
metadata['Category'] = 'Fixed Asset Tables'
metadata['Table'] = ' '.join(title.split()[1:])
metadata['SectionNo'] = x['Section']
metadata['Section'] = x['SectionName']
metadata['Categories'] = ', '.join(['Agency', 'Subagency', 'Type', 'Category', 'Section', 'Table'])
metadata['units'] = units.strip('[]')
if footer:
metadata['footer'] = '\n'.join(footer)
metadata['keywords'] = 'National Economic Accounts,' + ','.join(keywords)
X.metadata.update(metadata)
X.saveSV(savepath, metadata=True, comments='#', delimiter='\t')
@activate(lambda x: (x[0] + 'preparsed/',x[0]+'manifest.tsv'),lambda x : (x[0] + '__PARSE__/',x[0] + '__metadata.pickle'))
def FAT_preparser2(maindir):
sourcedir = maindir + 'preparsed/'
filedir = maindir + '__PARSE__/'
metadatapath = maindir + '__metadata.pickle'
MakeDir(filedir)
GoodKeys = ['Category', 'Section', 'units', 'Table', 'footer','description']
Metadict = {}
ColGroups = {}
M = tb.tabarray(SVfile = maindir + 'manifest.tsv')
for (i,x) in enumerate(M):
l = sourcedir + x['Section'].strip('.') + '_' + x['Table'] + '.tsv'
print l
t = x['Section'] + '.' + x['Table']
print t
X = tb.tabarray(SVfile = l)
topics = sorted(uniqify(X.coloring.pop('Categories')))
X.coloring['Topics'] = topics
for topic in topics:
X.renamecol(topic,'Topic ' + topic)
X1 = X[X['Line'] != ''].deletecols(['Category','Label','DisplayLevel'])
X1.metadata = X.metadata
X = X1
X.coloring['timeColNames'] = X.coloring.pop('Data')
for j in range(len(X.coloring['timeColNames'])):
name = X.coloring['timeColNames'][j]
X.renamecol(name,nea_dateparse(name))
SectionNo = X.metadata.pop('SectionNo').split('-')[-1].strip()
Section = X.metadata.pop('Section')
Table = X.metadata.pop('Table')
for k in X.coloring.keys():
if k in ColGroups.keys():
ColGroups[k] = uniqify(ColGroups[k] + X.coloring[k])
else:
ColGroups[k] = uniqify(X.coloring[k])
Metadict[t] = dict([(k,X.metadata[k]) for k in GoodKeys if k in X.metadata.keys()])
Metadict[t]['title'] = Table
X = X.addcols([[t]*len(X),[Table]*len(X),[SectionNo]*len(X),[Section]*len(X),[t]*len(X)],names=['TableNo','Table','SectionNo','Section','subcollections'])
X.saveSV(filedir + str(i) + '.tsv',metadata=['dialect','names','formats'])
AllKeys = uniqify(ListUnion([k.keys() for k in Metadict.values()]))
AllMeta = {}
for k in AllKeys:
if all([k in Metadict[l].keys() for l in Metadict.keys()]) and len(uniqify([Metadict[l][k] for l in Metadict.keys()])) == 1:
AllMeta[k] = Metadict[Metadict.keys()[0]][k]
for l in Metadict.keys():
Metadict[l].pop(k)
Category = AllMeta['Category']
AllMeta.pop('Category')
AllMeta['topicHierarchy'] = ('agency','subagency','program','dataset','Section','Table')
AllMeta['uniqueIndexes'] = ['TableNo','Line']
ColGroups['Topics'].sort()
ColGroups['labelColumns'] = ['Table','Topics']
AllMeta['description'] = 'The <a href="http://www.bea.gov/national/FA2004/SelectTable.asp">Standard Fixed Asset Tables</a> data set under the <a href="http://www.bea.gov/national/index.htm">National Economic Accounts</a> section of the <a href="http://www.bea.gov/">Bureau of Economic Accounts (BEA)</a> website. For additional information on the Fixed Asset Tables, see: <a href="http://www.bea.gov/national/pdf/Fixed_Assets_1925_97.pdf"> Methodology, Fixed Assets and Consumer Durable Goods in the United States, 1925-97 | September 2003 (PDF)</a>, <a href="http://www.bea.gov/scb/pdf/national/niparel/1997/0797fr.pdf">The Measurement of Depreciation in the NIPA\'s | SCB, July 1997 (PDF) </a>, and <a href="http://www.bea.gov/national/FA2004/Tablecandtext.pdf">BEA Rates of Depreciation, Service Lives, Declining-Balance Rates, and Hulten-Wykoff categories | February 2008 (PDF)</a>.'
AllMeta['columnGroups'] = ColGroups
AllMeta['dateFormat'] = 'YYYYqmm'
AllMeta['sliceCols'] = [['Section','Table'] + [tuple(ColGroups['Topics'][:i]) for i in range(1,len(ColGroups['Topics']) +1)]]
AllMeta['keywords'] = ['fixed assets','equipment','software','structures' ,'durable goods']
Subcollections = Metadict
Subcollections[''] = AllMeta
F = open(metadatapath ,'w')
pickle.dump(Subcollections,F)
F.close()
def fat_trigger():
connection = pm.Connection()
incremental = FAT_NAME in connection['govdata'].collection_names()
if incremental:
return 'increment'
else:
return 'overall'
FAT_PARSER = govdata.core.GovParser(FAT_NAME,
govdata.core.CsvParser,
downloader = [(FAT_downloader,'raw'),
(FAT_preparser1,'preparse1'),
(FAT_preparser2,'preparse2')],
trigger = fat_trigger,
incremental=True)
#=-=-=-=-=-=-=-=-=-=-=-=-=-=NIPA
NIPA_NAME = 'BEA_NIPA'
@activate(lambda x : 'http://www.bea.gov/national/nipaweb/csv/NIPATable.csv',lambda x : x[0])
def NIPA_downloader(maindir):
MakeDirs(maindir)
get_manifest(maindir)
connection = pm.Connection()
incremental = NIPA_NAME in connection['govdata'].collection_names()
MakeDir(maindir + 'raw/')
URLBase = 'http://www.bea.gov/national/nipaweb/csv/NIPATable.csv?'
Vars = ['TableName','FirstYear','LastYear','Freq']
X = tb.tabarray(SVfile = maindir + 'manifest.tsv')
for x in X:
NC = x['NumCode']
Freq = x['Freq']
if incremental:
FY = x['FirstYear']
LY = x['LastYear']
else:
FY = 1800
LY = 2200
ystr = ''
url = URLBase + '&'.join([v + '=' + str(val) for (v,val) in zip(Vars,[NC,FY,LY,Freq])])
topath = maindir + 'raw/' + x['Number'].strip('.') + '_' + Freq + '.csv'
WgetMultiple(url,topath)
@activate(lambda x : (x[0] + 'raw/',x[0] + 'manifest.tsv'), lambda x : x[0] + 'preparsed/')
def NIPA_preparser1(maindir):
targetdir = maindir + 'preparsed/'
sourcedir = maindir + 'raw/'
MakeDir(targetdir)
M = tb.tabarray(SVfile = maindir + 'manifest.tsv')
for x in M:
f = sourcedir + x['Number'].strip('.') + '_' + x['Freq'] + '.csv'
print f
savepath = targetdir + x['Number'].strip('.') + '_' + x['Freq'] + '.tsv'
[X, header, footer, keywords] = NEA_Parser(f, FootnoteSplitter='\\', FootnotesFunction=GetFootnotesLazy, CategoryColumn='Category',FormulaColumn='Category')
metadata = {}
metadata['Header'] = '\n'.join(header)
[title, units] = header[:2]
notes = '\n'.join(header[2:-2])
[owner, info] = header[-2:]
metadata['title'] = title
metadata['description'] = 'National Income and Product Accounts (NIPA) "' + title + '" from the <a href="http://www.bea.gov/national/nipaweb/SelectTable.asp?Selected=N">All NIPA Tables</a> data set under the <a href="http://www.bea.gov/national/index.htm">National Economic Accounts</a> section of the <a href="http://www.bea.gov/">Bureau of Economic Accounts (BEA)</a> website. For additional information on the NIPAs, see: <a href="http://www.bea.gov/scb/pdf/misc/nipaguid.pdf">A Guide to the National Income and Product Accounts of the United States (PDF)</a>, <a href="http://www.bea.gov/scb/pdf/2009/11%20November/1109_nipa_method.pdf">Updated Summary of NIPA Methodologies (PDF)</a>, and <a href="http://www.bea.gov/scb/pdf/2003/08August/0803NIPA-Preview.pdf#page=9">Guide to the Numbering of the NIPA Tables (PDF)</a>.'
metadata['Agency'] = 'DOC'
metadata['Subagency'] = 'BEA'
metadata['Type'] = 'National'
metadata['Category'] = 'NIPA Tables'
metadata['Section'] = x['Section']
metadata['Table'] = ' '.join(title.split()[1:])
metadata['Categories'] = ', '.join(['Agency', 'Subagency', 'Type', 'Category', 'Section', 'Table'])
metadata['units'] = units.strip('[]')
metadata['notes'] = notes
metadata['Owner'] = owner
metadata['downloadedOn'] = info.split('Last')[0]
metadata['lastRevised'] = info.split('Revised')[1].strip()
if footer:
metadata['Footer'] = '\n'.join(footer)
table = title.split()[1].strip('.')
metadata['keywords'] = ['National Economic Accounts'] + keywords
X.metadata.update(metadata)
X.saveSV(savepath, metadata=True, comments='#', delimiter='\t')
@activate(lambda x: x[0] + 'preparsed/',lambda x : (x[0] + '__PARSE__/',x[0] + '__metadata.pickle'))
def NIPA_preparser2(maindir):
inpath = maindir + 'preparsed/'
filedir = maindir + '__PARSE__/'
metapath = maindir + '__metadata.pickle'
NEA_preparser2(inpath,filedir,metapath)
@activate(lambda x : 'http://www.bea.gov/national/nipaweb/Index.asp',lambda x : (x[0] + 'additional_info.html',x[0] + 'additional_info.csv',x[0] + '__FILES__/'))
def get_additional_info(download_dir):
wget('http://www.bea.gov/national/nipaweb/Index.asp',download_dir + 'additional_info.html')
page = download_dir + 'additional_info.html'
Soup = BeautifulSoup(open(page,'r'),convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
PA = [(SafeContents(p), str(dict(p.findAll('a')[0].attrs)['href'])) for p in Soup.findAll('blockquote')[0].findAll('p')]
Recs = [(p, 'http://www.bea.gov' + a) for (p,a) in PA]
X = tb.tabarray(records = Recs, names = ['Name', 'URL'])
X.saveSV(download_dir + 'additional_info.csv',metadata=True)
MakeDir(download_dir + '__FILES__')
for x in X:
name = download_dir + '__FILES__/' + x['Name'].replace(' ','_')
wget(x['URL'],name)
def get_manifest(download_dir,depends_on = 'http://www.bea.gov/national/nipaweb/SelectTable.asp?'):
wget(depends_on,download_dir + 'manifest.html')
nc = re.compile('SelectedTable=[\d]+')
fy = re.compile('FirstYear=[\d]+')
ly = re.compile('LastYear=[\d]+')
page = download_dir + 'manifest.html'
S = [s.strip() for s in open(page, 'r').read().split('Section')[1:]]
Section_SplitSoup = [(s.split('-')[1].split('<')[0].strip(), BeautifulSoup(s,convertEntities=BeautifulStoneSoup.HTML_ENTITIES)) for s in S]
D = {'(A)': 'Year', '(Q)': 'Qtr', '(M)': 'Month'}
Recs = []
for (Section, Soup) in Section_SplitSoup:
alist = [tr.findAll('a')[0] for tr in Soup.findAll('tr') if tr.findAll('a')]
Table_URL = [(SafeContents(a), 'http://www.bea.gov/national/nipaweb/' + str(dict(a.attrs)['href'])) for a in alist if 'href' in dict(a.attrs).keys()]
Number_Name_URL = [(t.split()[1], ' '.join(t.split()[2:]), url) for (t, url) in Table_URL]
XYZ = [tuple(n[0].strip('.').split('.')) if len(n[0].strip('.').split('.'))==3 else tuple(n[0].strip('.').split('.')) + ('',) for n in Number_Name_URL]
for i in range(len(XYZ)):
(Section_Number, Subsection_Number, Table_Number) = XYZ[i]
(Number, Name, u) = Number_Name_URL[i]
Dlist = [d for d in D.keys() if d in Name]
for d in Dlist:
Freq = D[d]
URL = u.split('Freq=')[0] + 'Freq=' + Freq + '&' + '&'.join(u.split('Freq=')[1].split('&')[1:])
NumCode = int(nc.search(URL).group().split('=')[-1])
FirstYear = int(fy.search(URL).group().split('=')[-1])
LastYear = int(ly.search(URL).group().split('=')[-1])
Recs += [(Section, Section_Number, Subsection_Number, Table_Number, Number, Freq, Name, URL,NumCode,FirstYear,LastYear)]
M = tb.tabarray(records = Recs, names = ['Section', 'Section_Number', 'Subsection_Number', 'Table_Number', 'Number', 'Freq', 'Name', 'URL','NumCode','FirstYear','LastYear'])
M.saveSV(download_dir + 'manifest.tsv',metadata=True)
def trigger():
connection = pm.Connection()
incremental = NIPA_NAME in connection['govdata'].collection_names()
if incremental:
return 'increment'
else:
return 'overall'
NIPA_PARSER = govdata.core.GovParser(NIPA_NAME,govdata.core.CsvParser,downloader = [(NIPA_downloader,'raw'),(NIPA_preparser1,'preparse1'),(NIPA_preparser2,'preparse2'),(get_additional_info,'additional_info')],trigger = trigger,incremental=True)
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
@activate(lambda x : (x[0] + 'State_Preparsed/',x[0] + 'State_Manifest_1.tsv',x[0] + 'Metro_Preparsed.tsv'),lambda x : (x[0] + '__PARSE__/',x[0] + '__metadata.pickle'))
def RegionalGDP_Preparse2(maindir):
inpath = maindir + 'State_Preparsed/'
outpath = maindir + '__PARSE__/'
MakeDir(outpath)
R = tb.tabarray(SVfile = maindir + 'State_Manifest_1.tsv')[['Region','IC','File']].aggregate(On=['Region','IC'],AggFunc = lambda x : '|'.join(x))
GoodKeys = ['Category', 'description','footer', 'LastRevised']
Metadict = {}
LenR = len(R)
ColGroups = {}
for (i,r) in enumerate(R):
state = r['Region']
indclass = r['IC']
ps = r['File'].split('|')
print state,indclass
X = [tb.tabarray(SVfile = inpath + p[:-4] + '.tsv') for p in ps]
for (j,x) in enumerate(X):
x1 = x.deletecols(['Component'])
x1.renamecol('Component Code','ComponentCode')
x1.renamecol('Industry Code','IndustryCode')
x1.renamecol('ParsedComponent','Component')
x1.metadata = x.metadata
x1.metadata['description'] = '.'.join(x1.metadata['description'].split('.')[1:]).strip()
X[j] = x1
if len(X) > 1:
Z = tb.tab_join(X)
else:
Z = X[0]
inds = sorted(uniqify(Z.coloring.pop('Categories')))
Z.coloring['IndustryHierarchy'] = inds
for ind in inds:
Z.renamecol(ind,'Industry ' + ind)
Z.renamecol('State','Location')
Z = Z.addcols(['{"s":' + repr(z['Location']) + ',"f":{"s":' + repr(z['FIPS']) + '}}' for z in Z],names = ['Location'])
Z = Z.deletecols(['FIPS'])
Z.coloring['timeColNames'] = Z.coloring['Data']
Z.coloring.pop('Data')
for j in range(len(Z.coloring['timeColNames'])):
name = Z.coloring['timeColNames'][j]
Z.renamecol(name,nea_dateparse(name))
Z.metadata = {}
for k in GoodKeys:
h = [x.metadata[k] for x in X if k in x.metadata.keys()]
if h:
if isinstance(h[0],str):
Z.metadata[k] = ' '.join(uniqify(h))
elif isinstance(h[0],list) or isinstance(h[0],tuple):
Z.metadata[k] = ' '.join(uniqify(ListUnion(h)))
else:
print 'metadata type for key', k , 'in table', t, 'not recognized.'
Z.coloring['labelColumns'] = ['Location','Industry','Component']
for k in Z.coloring.keys():
if k in ColGroups.keys():
ColGroups[k] = uniqify(ColGroups[k] + Z.coloring[k])
else:
ColGroups[k] = Z.coloring[k]
Metadict[state] = Z.metadata
Z = Z.addcols([len(Z)*[indclass], len(Z)*['S']],names=['IndClass','subcollections'])
Z.saveSV(outpath + str(i) + '.tsv',metadata=['dialect','names','formats'])
AllKeys = uniqify(ListUnion([k.keys() for k in Metadict.values()]))
AllMeta = {}
for k in AllKeys:
if all([k in Metadict[l].keys() for l in Metadict.keys()]) and len(uniqify([Metadict[l][k] for l in Metadict.keys()])) == 1:
AllMeta[k] = Metadict[Metadict.keys()[0]][k]
Subcollections = {'S':AllMeta}
Subcollections['S']['Title'] = 'GDP by State'
del(Z)
L = ['Metro_Preparsed.tsv']
Metadict = {}
for (i,l) in enumerate(L):
print l
X = tb.tabarray(SVfile = maindir + l)
X.renamecol('industry_id','IndustryCode')
X.renamecol('component_id','ComponentCode')
X.renamecol('area_name','Metropolitan Area')
X.renamecol('ParsedComponent','Component')
X.renamecol('industry_name','Industry')
if 'Categories' in X.coloring.keys():
inds = sorted(uniqify(X.coloring.pop('Categories')))
X.coloring['IndustryHierarchy'] = inds
for ind in inds:
X.renamecol(ind,'Industry ' + ind)
X1 = X.deletecols('component_name')
X1 = X1.addcols(['{"m":' + repr(x['Metropolitan Area']) + ',"f":{"m":' + repr(x['FIPS']) + '}}' for x in X],names=['Location'])
X1 = X1.deletecols(['FIPS','Metropolitan Area'])
X1.metadata = X.metadata
X = X1
X.metadata['description'] = '--'.join(X.metadata['description'].split('--')[2:]).strip()
for k in X.metadata.keys():
if k not in GoodKeys:
X.metadata.pop(k)
X.coloring['timeColNames'] = X.coloring['Data']
X.coloring.pop('Data')
for j in range(len(X.coloring['timeColNames'])):
name = X.coloring['timeColNames'][j]
X.renamecol(name,nea_dateparse(name))
X.coloring['labelColumns'] = ['Location','Industry','Component']
for k in X.coloring.keys():
if k in ColGroups.keys():
ColGroups[k] = uniqify(ColGroups[k] + X.coloring[k])
else:
ColGroups[k] = X.coloring[k]
Metadict[l] = X.metadata
X = X.addcols([['NAICS']*len(X),['M']*len(X)],names=['IndClass','subcollections'])
X.saveSV(outpath + str(i+LenR) + '.tsv',metadata=['dialect','names','formats'])
AllKeys = uniqify(ListUnion([k.keys() for k in Metadict.values()]))
AllMeta = {}
for k in AllKeys:
if all([k in Metadict[l].keys() for l in Metadict.keys()]) and len(uniqify([Metadict[l][k] for l in Metadict.keys()])) == 1:
AllMeta[k] = Metadict[Metadict.keys()[0]][k]
Subcollections['M'] = AllMeta
Subcollections['M']['Title'] = 'GDP by Metropolitan Area'
ColGroups['IndustryHierarchy'].sort()
IH = [tuple(ColGroups['IndustryHierarchy'][:i]) for i in range(1,len(ColGroups['IndustryHierarchy']) + 1)]
AllMeta = {}
AllMeta['topicHierarchy'] = ('agency','subagency','program','dataset','Category')
AllMeta['uniqueIndexes'] = ['Location','IndustryCode','ComponentCode','IndClass']
ColGroups['spaceColumns'] = ['Location']
AllMeta['columnGroups'] = ColGroups
AllMeta['dateFormat'] = 'YYYYqmm'
AllMeta['sliceCols'] = [['Location'] + IH ,['Location','Component'],['Component'] + IH]
AllMeta['phraseCols'] = ['Component', 'IndClass','IndustryHiearchy','Units']
Subcollections[''] = AllMeta
F = open(maindir+'__metadata.pickle','w')
pickle.dump(Subcollections,F)
F.close()
@activate(lambda x : x[0] + 'Metro_Raw/allgmp.csv',lambda x : x[0] + 'Metro_Preparsed.tsv')
def Metro_PreParse1(maindir):
f = maindir + 'Metro_Raw/allgmp.csv'
savepath = maindir + 'Metro_Preparsed.tsv'
[X, header, footer, keywords] = BEA_Parser(f, headerlines=1, CategoryColumn='industry_name')
X = X[(X['component_name'] != '') & (X['component_name'] != 'component_name')]
p = re.compile('\(.*\)')
ParsedComp = [p.sub('',x).strip() for x in X['component_name']]
Units = [x[p.search(x).start()+1:p.search(x).end()-1] for x in X['component_name']]
X = X.addcols([ParsedComp,Units],names=['ParsedComponent','Units'])
metadata = {}
metadata['keywords'] = ['Regional Economic Accounts']
metadata['title'] = 'GDP by Metropolitan Area'
metadata['description'] = 'Gross domestic product (GDP) for individual metropolitan statistical areas -- from the <a href="http://www.bea.gov/regional/gdpmetro/">GDP by Metropolitan Areas</a> data set under the <a href="http://www.bea.gov/regional/index.htm">Regional Economic Accounts</a> section of the <a href="http://www.bea.gov/">Bureau of Economic Accounts (BEA)</a> website. Note that NAICS industry detail is based on the 1997 NAICS. For more information on Metropolitan Statistical Areas, see the BEA website on <a href="http://www.bea.gov/regional/docs/msalist.cfm?mlist=45">Statistical Areas</a>. Component units are as follows: GDP by Metropolitan Area (millions of current dollars), Quantity Indexes for Real GDP by Metropolitan Area (2001=100.000), Real GDP by Metropolitan Area (millions of chained 2001 dollars), Per capita real GDP by Metropolitan Area (chained 2001 dollars).'
metadata['Agency'] = 'DOC'
metadata['Subagency'] = 'BEA'
metadata['Type'] = 'Regional'
metadata['Category'] = 'GDP by Metropolitan Area'
metadata['Categories'] = ', '.join(['Agency', 'Subagency', 'Type', 'Category', 'Region'])
if footer:
footer = [ff for ff in footer if ff.strip('\x1a')]
metadata['footer'] = '\n'.join(footer)
metadata['Notes'] = '\n'.join([x.split('Note:')[1].strip() for x in footer[:-1]])
metadata['Source'] = footer[-1].split('Source:')[1].strip()
metadata['LastRevised'] = metadata['Source'].split('--')[-1].strip()
X.metadata = metadata
X.metadata['unitcol'] = ['Units']
X.metadata['labelcollist'] = ['industry_name','ParsedComponent']
X.saveSV(savepath, metadata=True, comments='#', delimiter='\t')
@activate(lambda x : ( x[0] + 'State_Manifest_1.tsv', x[0] + 'State_Raw/'),lambda x : x[0] + 'State_Preparsed/')
def State_PreParse1(maindir):
target = maindir + 'State_Preparsed/'
sourcedir = maindir + 'State_Raw/'
manifest = maindir + 'State_Manifest_1.tsv'
MakeDir(target)
M = tb.tabarray(SVfile=manifest)
for mm in M:
FIPS,Region,IC,file = mm['FIPS'],mm['Region'],mm['IC'],mm['File']
f = sourcedir + file
savepath = target + file[:-4] + '.tsv'
[X, header, footer, keywords] = BEA_Parser(f, headerlines=1, FootnoteSplitter='\\', FootnotesFunction=GetFootnotes2, CategoryColumn='Industry')
p = re.compile('\(.*\)')
ParsedComp = [p.sub('',x).strip() for x in X['Component']]
Units = [x[p.search(x).start()+1:p.search(x).end()-1] for x in X['Component']]
X = X.addcols([ParsedComp,Units],names=['ParsedComponent','Units'])
metadata = {}
Years = [int(y[:4]) for y in X.coloring['Data'] if y[:4].isdigit()]
metadata['keywords'] = ['Regional Economic Accounts']
metadata['description'] = 'Gross domestic product (GDP) for a single state or larger region, ' + Region + ' using the ' + IC + ' industry classification. This data comes from the <a href="http://www.bea.gov/regional/gsp/">GDP by State</a> data set under the <a href="http://www.bea.gov/regional/index.htm">Regional Economic Accounts</a> section of the <a href="http://www.bea.gov/">Bureau of Economic Accounts (BEA)</a> website. For more information on the industry classifications, see the BEA web pages on <a href="http://www.bea.gov/regional/definitions/nextpage.cfm?key=NAICS">NAICS (1997-2008)</a> and <a href="http://www.bea.gov/regional/definitions/nextpage.cfm?key=SIC">SIC (1963-1997)</a>. Component units are as follows: Gross Domestic Product by State (millions of current dollars), Compensation of Employees (millions of current dollars), Taxes on Production and Imports less Subsidies (millions of current dollars), Gross Operating Surplus (millions of current dollars), Real GDP by state (millions of chained 2000 dollars), Quantity Indexes for Real GDP by State (2000=100.000), Subsidies (millions of current dollars), Taxes on Production and Imports (millions of current dollars), Per capita real GDP by state (chained 2000 dollars).'
metadata['Agency'] = 'DOC'
metadata['Subagency'] = 'BEA'
metadata['Type'] = 'Regional'
metadata['Category'] = 'GDP by State'
metadata['IndustryClassification'] = IC
metadata['Region'] = Region
metadata['FIPS'] = X['FIPS'][0]
metadata['Categories'] = ', '.join(['Agency', 'Subagency', 'Type', 'Category', 'IndustryClassification', 'Region', 'TimePeriod'])
if footer:
footer = CleanLinesForMetadata(footer)
metadata['footer'] = '\n'.join(footer)
[source] = footer
metadata['Source'] = source.split('Source:')[1].strip()
X.metadata = metadata
X.metadata['unitcol'] = ['Units']
X.metadata['labelcollist'] = ['Industry','ParsedComponent']
X.saveSV(savepath, metadata=True, comments='#', delimiter='\t')
def GetStateManifest(maindir):
wget('http://www.bea.gov/regional/gsp/',maindir + 'State_Index.html')
page = maindir + 'State_Index.html'
Soup = BeautifulSoup(open(page),convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
O = Soup.findAll('select',{'name':'selFips'})[0].findAll('option')
L = [(str(dict(o.attrs)['value']),Contents(o).strip()) for o in O]
tb.tabarray(records = L,names = ['FIPS','Region']).saveSV(maindir + 'State_Manifest.tsv',metadata=True)
@activate(lambda x : 'http://www.bea.gov/national/nipaweb/csv/NIPATable.csv',lambda x : x[0])
def RegionalGDP_initialize(maindir):
MakeDirs(maindir)
GetStateManifest(maindir)
@activate(lambda x : x[0] + 'State_Manifest.tsv',lambda x : (x[0] + 'State_Raw/',x[0] + 'State_Manifest_1.tsv'))
def DownloadStateFiles(maindir):
connection = pm.Connection()
incremental = REG_NAME in connection['govdata'].collection_names()
X = tb.tabarray(SVfile = maindir + 'State_Manifest.tsv')
rawdir = maindir + 'State_Raw/'
MakeDir(rawdir)
Recs = []
for x in X: