-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlatexRegressions.py
5994 lines (5263 loc) · 312 KB
/
latexRegressions.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
#from pystata import *
import re, os
from pystata import defaults # Do not import from pystata_config; that should only be done in one place, and globally once.
paths = defaults['paths']
WP = paths['working']
from pylab import array, flatten, arange
import pandas as pd
import pylab as plt
from copy import deepcopy
from pystata_core import * # Should I be removing this line for style reasons??
from .pystata_core import standardSubstitutions, substitutedNames, readStataRegressionLogFile, texheader, defaultVariableOrder # Or import it as stata??
from .pystata_core import *
from codecs import open # I need to do this just to get encoding= option in open() ?.
if 'stata' not in defaults[
'paths']: # This is actually for sprawl's analysis.py, feb2014
defaults['paths']['stata'] = defaults['paths']
from cpblUtilities import debugprint, uniqueInOrder, doSystemLatex
from cpblUtilities.textables import chooseSFormat, tableToTSV, cpblTable_to_PDF
from cpblUtilities import transLegend, dfPlotWithEnvelope, str2pathname, flattenList, dgetget, NaN, dsetset
from cpblUtilities.cpblunicode import str2latex
from cpblUtilities.color import getIndexedColormap
from pystata.codebooks import stataCodebookClass
"""
To do:
revise generate_postEstimate_sums_by_condition(rollingX,ifs) to give DataFrame return value
revise semiRolling to build dataframes only.
"""
###########################################################################################
###
class latexRegressionFile(): # # # # # # MAJOR CLASS # # # # # #
###
#######################################################################################
""" Open a file and write some headers. The file will act as a .tex file with a regression table in it.
As a class, it's a wrapper for some of my python-stata-latex programs that convert Stata output to latex.
It also compiles the file when it is closed..
April 2008: the "suppressSE" argument throughout this class and etc just became obselete: LaTeX now uses a facultative \useSEs{}{} to choose between showing standard errors or not.
Dec 2009:
Allow specification of a "main survey" and a "main data file". This makes it easier to do a half-decent guess job at constructing the right descriptive statistics tables. That is, if we know a survey to use, we can look up the PDF codebook to find descriptions/questions. If we know the the right data file, we can calculate stats using the right/final/regression-ready data. Because these ideas do not always make sense (multiple surveys or files.), one can also call descriptive stats tables along the way with these things specified.
"""
# Caution: If you define variables here, before __init__, you can access them with latexinstance.avar , but those are common to the entire class, not to an instance.
def __init__(self,
filename,
margins='default',
allow_underscore=True,
colour=True,
modelVersion=None,
regressionVersion=None,
compactPreview=True,
codebook=None,
mainSurvey=None,
mainDataFile=None,
recreateCodebook=None,
substitutions=None,
texNameSuffix=None):
"""
codebook can be either a string (name of DTA file) or a codebook object. It's appropriate when there is one dataset for the whole file.. Nov 2009. I suppose I could add this functionality of making descriptive stats tables somehow at the table-level....
"""
self.lfile = None
self.lfileTeXbody = ''
self.fname = None
self.fpathname = None
self.modelVersion = None
self.regressionVersion = None
self.compactPreview = True
self.codebook = None # Not implemented yet? Added only Dec 2009.. does this conflict with some other functionality?
self.mainSurvey = None
self.mainDataFile = None
self.recreateCodebook = None #This tells the codebook class whether to recreate the codebook of mainDataFile...
self.captureNoObservations = None # Dec 2010: update. This should really be default true, as there's no harm now. I use Stata's "capture noisily" to test whether we need to introduce a dummy regression when a regression fails with no samples.
self.skipStataForCompletedTables = False # This sets all regTable calls not to call Stata for any tables which have been completed, even if they are old. That is, either DO NOT TURN THIS ON or actually delete the Stata .log files in the texPath that you wish to update/overwrite. So this is also a debugging tool, basically, to focus on tables that are causing trouble when you may be doing many tables all in one program. The trick, then, if you're using large data files, is to make sure that the data files are loaded as part of the first model's "code" element, in order that it doesn't get called if the table is to be skipped... So there's a tradeoff if you're making many tables from the same data.
self.skipSavingExistingFigures = None # If not set, this will follow skipStataForCompletedTables. Otherwise, it can separately choose whether to update figures or not (saving is often the slowest part, and is often done through a call to this class).
self.usingDisclosedData = False # This means never run stata, since only log files are available, not data. (ie we're analysiing RDC disclosures). So this can just be used as a double check to enforce no stata. Not fully implemented yet. (2010 July)
self.skipAllDerivedTables = False # ie if True, ignore all table calls (or just output) whenevr "skipStata=True" flag is used. So this is for making a more compact PDF for exporting results from RDC. Conversely, when set to True it also ignores any skipLaTeX=True calls, since those might be the original/main regression call. Also, it does not produce CRC tables unless forced to with "onlyCRC" or etc.
self.variableOrder = None # This is a default variable order to override what's in pystata module. This simplifies things so one doesn't need to specify it for every single table, though it can also be done per table.
self.txtNamesUsed = []
self.variablesUsed = '' # Collect all variables from regressions, useful for choosing what to display as desc stats at end.
if not modelVersion:
modelVersion = ''
if not regressionVersion:
regressionVersion = ''
self.modelVersion = modelVersion
self.regressionVersion = regressionVersion
self.compactPreview = compactPreview # This just means not to show/use sections (function names) and subsections (table/figure names?) in output PDF?
self.substitutions = standardSubstitutions
if substitutions is not None: # Can set default set of variable name translations for the entire latex instance.
self.substitutions = substitutions
self.txtNamesUsed = []
self.updateSettings(
codebook=codebook,
mainSurvey=mainSurvey,
mainDataFile=mainDataFile,
recreateCodebook=recreateCodebook)
if filename.endswith('.tex'):
filename = filename[:-5]
self.fname = filename + ('-' + self.modelVersion) * (
not not self.modelVersion) + ('-' + self.regressionVersion) * (
not not self.regressionVersion)
if texNameSuffix is None:
texNameSuffix = ''
self.fname += texNameSuffix
self.fpathname = defaults['native']['paths'][
'tex'] + self.fname # Native: since we just want to run stata on windows, not tex
#print ' Initiating a latex file %s.tex with margins: %s'%(self.fpathname,margins)
#lfile=open(self.fpathname+'.partial.tex','wt')
thead = texheader(
margins=margins, allow_underscore=allow_underscore).replace(
'%LOT:', '').replace('%LOF:', '')
if not self.compactPreview:
thead = thead.replace('%TOC:', '')
#lfile.write(thead)
#lfile.close()
self.lfileTeXwrapper = [
thead, '\n' + r'\clearpage\newpage\end{landscape}' +
' End\n\\end{document}\n'
]
#self.lfileTeX_original=self.lfileTeXbody+'' # Maybe obselete now, since I have body separate
def updateSettings(self,
codebook=None,
mainSurvey=None,
mainDataFile=None,
recreateCodebook=None):
self.mainSurvey = mainSurvey
self.mainDataFile = mainDataFile
self.codebook = codebook # eithe filename or codebook object...
self.recreateCodebook = recreateCodebook
def append(self, string):
self.lfileTeXbody += string
#lfile=open(self.fpathname+'.partial.tex','at')
#lfile.write(string)
#lfile.close()
###########################################################################################
###
def appendRegressionTable(
self,
models,
suppressSE=False,
substitutions=None,
transposed=None,
tableFilePath=None,
tableFormat=None,
sourceLogfile=None
): # tableCaption=None, tableComments=None,modelTeXformat=None,extrarows,
###
#######################################################################################
"""
This takes estimation results (data) and makes a LaTeX output, adding it to the self.
Aug 2009: Rewrote this function to use list of model dicts, rather than vectors of various attributes plus a "pairedrows".
eliminated: colnames,colnums,coefrows, hiderows and landscape,... rowmodelNams
sourceLogfile: Nov 2010: Now it also accepts (should demand?) the filename of the source stata log file. This entire logfile is duplicated, commented out, inside any latex file created.
June 2011: Needs to be altered to use new two-formats-in-one-tex-file ability of cpblTableC style. For instance, I could have it so that the automated choice of transposed or not still here still uses the cpblTableC files as untransposed as first (default) option, and simple changes the wrapper.
"""
if sourceLogfile is not None:
assert all([sourceLogfile == mm['logFilename'] for mm in models])
if substitutions == None:
substitutions = self.substitutions
if 'version' == 'priorToJune2011': # you can now pass "both" as value for transposed to appendRegressionTable, so that it doesn't duplicate the cpbltablec tex file.
if isinstance(transposed, str) and transposed.lower() == 'both':
self.appendRegressionTable(
models,
suppressSE=suppressSE,
substitutions=substitutions, #modelTeXformat=modelTeXformat,
tableFilePath=tableFilePath,
tableFormat=tableFormat,
sourceLogfile=sourceLogfile, #tableCaption=tableCaption, tableComments=tableComments,
transposed=True, ) #,hideRows=hideRows)
if 1:
self.appendRegressionTable(
models,
suppressSE=suppressSE,
substitutions=substitutions, #modelTeXformat=modelTeXformat,
tableFilePath=tableFilePath,
tableFormat=tableFormat,
sourceLogfile=sourceLogfile, #tableCaption=tableCaption, tableComments=tableComments,
transposed=False) #,hideRows=hideRows)
return
if tableFilePath == None:
tableFilePath = defaults['paths']['tex'] + 'tmpMissingTableName.tex'
if 0:
if tableCaption == None:
tableCaption = '(missing table caption)'
tableCaption += ' ' + tableFilePath.split('/')[-1]
if tableFilePath.endswith('.tex'):
tableFilePath = tableFilePath[:-4]
# Add either the whole logfile, if specified, or a concatenated version of each model output, if no logfile was specified.
# Add all caution comments for this table to the table Caption.?
if sourceLogfile is None:
sourceLogfile = [
LL + '\n'
for LL in sum(
[mm['rawLogfileOutput'].split('\n') for mm in models], [])
]
else:
sourceLogfile = open(sourceLogfile, 'rt').readlines()
twarnings = [
r'\framebox{' + str2latex(LL) + '}' for LL in sourceLogfile
if 'Warning' in LL or 'Caution' in LL or ("CAUTION" in LL and 'di '
not in LL)
]
tableFormat['comments'] += r' ' + r' '.join(twarnings) if len(
twarnings
) < 10 else r' \framebox{Warning!! More than TEN Cautions or Warnings were reported by Stata code for this estimate}'
# Write the tabular or longtable latex file that the master LaTeX will include.
#if not colnums:
# colnums=['' for cn in colnames]
if transposed is None: transposed = 'both'
assert transposed in ['both', True, False]
includedTex, wrapperTex, transposedChoice = composeLaTeXregressionTable(
models,
suppressSE=suppressSE,
substitutions=substitutions,
tableFormat=tableFormat,
transposed=transposed
) #,hideRows=hideRows),modelTeXformat=modelTeXformat,
# {'comments':tableComments,'caption':tableCaption,}
if {
True: 'true',
False: 'false'
}.get(transposedChoice, transposedChoice).lower() in ['true', 'both']:
assert 'BEGIN TRANSPOSED VERSION' in includedTex # File must have two versions of the table if we're to include the second.
if 'version' == "no... i'm changing things june 2011 to always use the same file, and fit both normal andtransposed in it.":
if transposedChoice: # NB: this "transposed" is reset by the call to composeLaTeXtable
tableFilePath = tableFilePath + '-transposed'
fout = open(tableFilePath + '.tex', 'wt', encoding='utf-8')
fout.write(
includedTex + '\n\n%' + '% '.join(sourceLogfile)
) # Append entire Stata log file to end of each LaTeX table file.
fout.close()
# 2010 Jan: Also create a .csv file *from* the .tex.
###from cpblUtilities import cpblTableToCSV
fout = open(tableFilePath + '-tex.csv', 'wt')
fout.write(tableToTSV(includedTex))
fout.close()
print ' Appended table: ' + tableFilePath
###################################################################################
# Add this table as in include in a master LaTeX file that includes all the tables...
# Do landscape, if desired. Decide this separately for each table.
# Following lscape stuff should be moved to texopening/closing.: trash me/it
#lscapeb,lscapee='',''
#if landscape==True or (len(models)>9): # Choose it automatically. if not forced
# lscapeb,lscapee=r'\begin{landscape}',r'\end{landscape}'
self.append(r'\newpage ' + wrapperTex.replace(
'PUT-TABLETEX-FILEPATH-HERE',
tableFilePath.replace(defaults['paths']['tex'], r'\texdocs ')) +
'\n\n')
# Also create a standalone PDF of this table
cpblTable_to_PDF(tableFilePath, aftertabulartex = r' {\footnotesize\cpblColourLegend} ')
if transposed in ['both', True]:
cpblTable_to_PDF(tableFilePath, aftertabulartex = r' {\footnotesize\cpblColourLegend} ', transposed=True)
return
###########################################################################################
###
def old_forPairedRows_appendRegressionTable(
self,
colnames,
colnums,
coefrows,
extrarows,
greycols=None,
suppressSE=False,
substitutions=None,
modelTeXformat=None,
transposed=None,
tableFilePath=None,
tableCaption=None,
tableComments=None,
landscape=False,
rowModelNames=None,
hideRows=None
): # landscape is deprecated: it's chosen automatically.
###
#######################################################################################
# Add this table as in include in a master LaTeX file that includes all the tables...
# Do landscape, if desired. Decide this separately for each table.
# Create the actual latex file that is to be included, as well, through a call to composeLaTeXtable
"""
If rowModelNames is specified, use them for transposed tables only.
"""
if isinstance(transposed, str) and transposed == 'both':
self.old_forPairedRows_appendRegressionTable(
colnames,
colnums,
coefrows,
extrarows,
suppressSE=suppressSE,
substitutions=substitutions,
modelTeXformat=modelTeXformat,
tableFilePath=tableFilePath,
tableCaption=tableCaption,
tableComments=tableComments,
landscape=landscape,
transposed=True,
rowModelNames=rowModelNames,
hideRows=hideRows)
self.old_forPairedRows_appendRegressionTable(
colnames,
colnums,
coefrows,
extrarows,
suppressSE=suppressSE,
substitutions=substitutions,
modelTeXformat=modelTeXformat,
tableFilePath=tableFilePath,
tableCaption=tableCaption,
tableComments=tableComments,
greycols=greycols,
landscape=landscape,
transposed=False,
rowModelNames=rowModelNames,
hideRows=hideRows)
return
if tableFilePath == None:
tableFilePath = defaults['paths']['tex'] + 'tmpMissingTableName.tex'
if tableCaption == None:
tableCaption = '(missing table caption)'
tableCaption += ' ' + tableFilePath.split('/')[-1]
if tableFilePath[-4:] == '.tex':
tableFilePath = tableFilePath[:-4]
# Write the tabular or longtable latex file that the master LaTeX will include.
if not colnums:
colnums = ['' for cn in colnames]
#includedTex,texOpening,texClosing,transposedChoice =
includedTex, wrapperTex, transposedChoice = old_uses_pairedRows_composeLaTeXtable(
colnames,
colnums,
coefrows,
extrarows,
suppressSE=suppressSE,
substitutions=substitutions,
modelTeXformat=modelTeXformat,
caption=tableCaption,
greycols=greycols,
comments=tableComments,
transposed=transposed,
rowModelNames=rowModelNames,
hideRows=hideRows,
landscape=landscape)
if transposedChoice: # NB: this "transposed" is reset by the call to composeLaTeXtable
tableFilePath = tableFilePath + '-transposed'
fout = open(tableFilePath + '.tex', 'wt', encoding='utf-8')
fout.write(includedTex)
fout.close()
debugprint('AppendTable: ', tableFilePath)
###################################################################################
# Add this table as in include in a master LaTeX file that includes all the tables...
# Do landscape, if desired. Decide this separately for each table.
# Following lscape stuff should be moved to texopening/closing.: trash me/it
#lscapeb,lscapee='',''
#if landscape==True or (len(models)>9): # Choose it automatically. if not forced
# lscapeb,lscapee=r'\begin{landscape}',r'\end{landscape}'
self.append(r'\newpage ' + wrapperTex.replace(
'PUT-TABLETEX-FILEPATH-HERE',
tableFilePath.replace(defaults['paths']['tex'], r'\texdocs ')) +
'\n\n')
## if 1: # 18 Marc 2008: seems to be a bug in my use of include, so I am eliminating it for now. #:(
## self.append(wrapperTex''.join([ texOpening, tableFilePath , texClosing]))
## else:
## self.append('\n'.join([ texOpening, includedTex , texClosing]))
return
###########################################################################################
###
def toDict(self,
line,
depvar=None,
regoptions=None,
method=None,
defaultValues=None): # Used to be called regDict
###
#######################################################################################
""" This is a utility to convert from old string list form of a regression model to the newer dict format.
defaultValues is an alternative form for setting fields that are explicitly listed as the other optional parameters.
nov 2009: this is completely obselete, since the old format is no longer allowed. there are new methods and conversions for "do file format" (string) and for "defaultModel" in other... See regTable()...
may 2010: Actually, not quite obselete. bySurvey() still uses it ...
"""
# It might be easily identifiable as a list of old-format models:
if isinstance(line, list) and isinstance(line[0], list):
return ([self.toDict(LL) for LL in line])
#if defaultValues==None:
# defaultValues={}
defaultValues = [deepcopy(defaultValues), {}][defaultValues == None]
# Incorporate other keywords into the defaultValues dict:
for optparam, kk in [[depvar, 'depvar'], [regoptions, 'regoptions'],
[method, 'method']]:
if optparam:
defaultValues[kk] = depvar
# And some fields may be considered mandatory:
if 'flags' not in defaultValues:
defaultValues['flags'] = []
## if ....depvar:
## dd['depvar']=depvar
## if 'regoptions' not in dd and regoptions:
## dd['regoptions']=regoptions
## if method and 'method' not in dd:
## dd['method']=method
if isinstance(line, dict): # It might not need converting:
dd = deepcopy(line)
#if 'flags' not in line:
# line['flags']=[]
else: # It does need converting from old list of strings,etc format:
dd = dict()
# It could be just a string, the really simplest format:
if isinstance(line, str):
line = ['', line]
dd['name'] = line[0]
dd['model'] = line[1]
if len(line) > 2:
# line+=[[]]
dd['flags'] = line[2]
if len(line) > 3:
dd['format'] = line[3]
if len(line) > 4:
dd['code'] = {'before': line[4], 'after': line[5]}
if len(line) > 6:
dd['regoptions'] = line[6]
if len(line) > 7:
dd['feGroup'] = line[7]
# Now fill in any missing values that were specified separately
for kk in defaultValues:
if not kk in dd:
dd[kk] = defaultValues[kk]
return (dd)
###########################################################################################
###
def withCellDummies(self,
lines,
cellVariables,
cellName=None,
nCounts=None,
clusterCells=True,
dropvars=None,
minSampleSize=300,
defaultModel=None): #depvar=None,regoptions=None):
###
#######################################################################################
"""
To test this:
import pystata
L=pystata.latexRegressionFile('tmp1234')
mmm=L.withCellDummies([['','lsatis da_stuff etc if 1',[['survey','EDS']]], ['','lsatis da_stuff etcother if 1',[['survey','GSS17']]]],['DAuid'])
That is, I want to split data up into cells based on certain
variables, for instance, geographic identifiers.
I want to make sure there are at least a certain number of samples in
each cell which have good values for all the regressors in the model,
and eliminate the small cells.
I want to possibly cluster on those cells...
Let this function work on just one line of a model. Then the byCR function can use it (it needs also to drop higher CR level vars), specifying just one CRuid as the cell var...
Algorithm: look for "survey" attribute of the line (model),
which must be in 3 or more element format, so that the third
element is a list of attributes.
Unless specified otherwise, clustering is turned on at the cell level, using the options-specification feature of regseries.
16 April 2008: Adding a Stata "if" statement to condition the regression on successful generation of cell dummies.
[2010: Really?? It looks like this comment is for withCR, not withCell] Ah, what the real problem is is that if the model includes
other conditions ("if"s), they reduce the group size of some,
so I am getting completely determined samples. (see notes for
19 March 2008). Or, some variables may not be available for
all samples, also reducing the number in a CR group. When
forming CR/survey cells, must make sure that all regressors
exist for those samples included. Well... no: only those variables which *ought* to exist for the given survey. This is very kludgey and specific now, but look to see if a survey is selected and if so, restrict the variables used for cell counts to those that we expect should be there.
If surveys are specified as attributes, the cells will be only within those surveys; the surveys restriction can also exist in the if clause of the model description, though.
Oh dear IO have to create a 5th element in model lines. this will be stata code which gets written before the regression is done...
ugh.
Aug 2008: I am adding "depvar" as an option: you can specify a default depvar to fill in unfilled field depvar for each model.
Oct 2008: I am adding "regoptions" as an option. Specify it here as a default. Note how valuable this is: since you cannot specify it as a default later, in regtable, since "regoptions" will already be populated by this function, ie with a cluster option (for stata).
OCt 2008: Eliminated "depvar" and "regoptions" in favour of defaultModel, which can have the former two fields.
"""
if cellName == None:
cellName = 'cells'
from copy import deepcopy
if nCounts == None:
nCounts = 5
modelsout = []
from pprint import pprint
# Check for format of passed lines, and possibly recursively iterate. lines should really be called models, since it now can be a list of models/lists of models.
if not lines or lines == [[]]:
return ([])
if isinstance(lines, dict):
debugprint('Found dict')
lines = [lines]
elif isinstance(lines, list) and all([
isinstance(onee, dict) or
(isinstance(onee, list) and isinstance(onee[0], str))
for onee in lines
]):
debugprint(
'Found list of nothing but ',
len(lines),
' models (in dict or old format); so proceed with standard loop that will treat them as one group'
)
for mm in lines:
mm = self.toDict(mm)
#mm=self.convertMtoDict(mm)
else:
debugprint(
'so must have a list of ',
len(lines),
' lists/modelslists, or else the models are not in dict format?'
)
for lineOrGroup in lines:
debugprint(
'For a linegroup ',
lineOrGroup,
' generated ',
self.withCellDummies(
lineOrGroup,
cellVariables,
cellName=cellName,
nCounts=nCounts,
clusterCells=clusterCells,
dropvars=dropvars,
minSampleSize=minSampleSize,
defaultModel=defaultModel)
) #depvar=depvar,regoptions=regoptions))
modelsout += self.withCellDummies(
lineOrGroup,
cellVariables,
cellName=cellName,
nCounts=nCounts,
clusterCells=clusterCells,
dropvars=dropvars,
minSampleSize=minSampleSize,
defaultModel=defaultModel
) #,depvar=depvar,regoptions=regoptions)
debugprint(' Ended with ', modelsout)
return (modelsout)
# So now we are sure that we have just a list of models (in dict or old form), though the list could be length one.
if not cellVariables: # Facility for degenerate use of this function: e.g. a loop might have a case without any cell variables. Then just return what we got.
return (lines)
oneGroupModels = []
for model in deepcopy(lines):
if 'isManualEntry' in model:
continue
# Option to supply depvar in the function call: Do not override ones already specified.
#if 'depvar' not in model and depvar:
# model['depvar']=depvar
# Option to supply regoptions in the function call: Do not override ones already specified.
#if 'regoptions' not in model and regoptions:
# model['regoptions']=regoptions
if defaultModel:
for field in defaultModel:
if field not in model:
model[field] = deepcopy(defaultModel[field])
stataBeforeOut, stataAfterOut = '', ''
# Find surveys, if there is one. Ignore "all~n" entries for "survey" attribute.
if isinstance(model.get('flags', ''), dict):
surv = dgetget(model, 'flags', 'survey', '')
else:
surv = [
aaa[1] for aaa in model.get('flags', [])
if aaa and isinstance(aaa, list) and aaa[0] == 'survey'
]
surveys, dsurveys = [], ' 1 ' # ie "true" in an if condition
if surv:
surveys = [
sss for sss in surv[0].replace(' ', ',').split(',')
if not 'all~' in sss
]
if len(surveys) > 0:
dsurveys = ' (' + ' | '.join(
['d%s==1' % ss for ss in surveys]) + ') '
# Surely the above is redundant. if the survey selection is already in the if clause. Why do this here?
# Find regressors; find if conditions:
if ' if ' not in model['model']:
model['model'] += ' if 1'
parts = model['model'].split(' if ')
assert len(parts) < 3
regressors = [pp for pp in parts[0].split(' ') if pp]
# Construct appropriate dummy: for this specified set of variables ("cellVariables") and for this survey or these surveys:
# Does not apply to this function.:
# Also, remove any regressors which look like they are at this (or higher...) CR level:
# useRegressors=[rr for rr in regressors if not rr[0:3].lower() in higherLevels[aCR] and not rr[0:4].lower() in higherLevels[aCR]]
useRegressors = regressors
if dropvars == None:
dropvars = ''
dropvars += ' ' + cellVariables
if not dropvars == None:
for dv in uniqueInOrder([
dvv for dvv in dropvars.split(' ')
if dvv and dvv in useRegressors
]):
useRegressors.remove(
dv) #=useRegressors.replace(' '+dv+' ',' ')
# Also, just for the dummy selection, remove any other variables which we do not think exist for any of the chosen surveys:
expectedExistRegressors = ['1'] + [
rr for rr in useRegressors if inanyCodebook(rr, surveys)
]
droppedList = set(expectedExistRegressors) - set(
useRegressors) - set(['1'])
if droppedList:
print('Ignoring existence of ', droppedList, ' for ', surveys)
# Count how many people in each bin for the coming regression:
stataBeforeOut+="""
capture drop ttt_*
capture drop tttvvv_*
capture drop dummyOne
gen dummyOne=1
""" # Safely clear old counters (Could have used "capture" instead)
if isinstance(cellVariables, list):
cellVariables = ' '.join(cellVariables)
# Following command is equivalent to use egen with group() and then counting??
stataBeforeOut += '\n bysort ' + cellVariables + ': egen ttt_' + cellName + '=count(dummyOne) if ' + parts[
1] + ' & ' + dsurveys + ' & ' + ' & '.join(
['%s<.' % rr for rr in useRegressors])
# Also ensure (if depvar is known) that there is at least some variation in depvar within each cell
if 'depvar' in model:
stataBeforeOut += '\n bysort ' + cellVariables + ': egen tttvvv_' + cellName + '=sd(' + model[
'depvar'] + ') if ' + parts[
1] + ' & ' + dsurveys + ' & ' + ' & '.join(
['%s<.' % rr for rr in useRegressors])
else:
stataBeforeOut += '\n gen tttvvv_' + cellName + '=1'
# 2013 Feb: btw, is it a simpler method to say: by year wp5:egen nSample =total(dummyOne)
# Also must make some dummies myself here for these regions and this survey.
#stataBeforeOut+='\n gen ddd_null=. \n drop ddd_* ' # Safely clear old dummies
stataBeforeOut += """
capture drop ddd_*
egen dcelltmp= group( """ + cellVariables + """)
quietly: tab dcelltmp if ttt_""" + cellName + """ >= """ + str(
nCounts
) + """ & tttvvv_""" + cellName + """>0 & ttt_""" + cellName + """ <. & """ + parts[
1] + """, gen(ddd_""" + cellName + """)
drop dcelltmp
"""
# Condition doing the regressions on success of this dummy generation.
stataBeforeOut += "\n capture noisily confirm numeric variable ddd_" + cellName + "1, exact\n if _rc==0 & r(N)>" + '%d' % minSampleSize + " & r(r)>1 { * Condition on number of respondents, number of clusters, and existence of some " + cellName + " dummies\n"
# If there are not enough samples, create a blank line in eventual output, showing number of samples. (In fact, the line below is safe to the possibility that ddd_cellname could not even be created.: in that case, the number of samples will be all-encompassoing)
stataAfterOut += '\n }\n else { \n reg dummyOne dummyOne \n capture reg dummyOne dummyOne ddd_' + cellName + '* \n } \n matrix est=e(b) \n est\n'
# Wrap up:
# Aghhh. so far must be one survey exactly..
model['model'] = ' ' + ' '.join(
useRegressors) + ' ddd_' + cellName + '* if ' + parts[1]
if isinstance(model.get('flags', ''), dict):
model['flags'][cellName + '~f.e.'] = True
else:
model['flags'] = model.get('flags', []) + [cellName + '~f.e.']
if 'code' not in model:
model['code'] = dict(before='', after='')
assert 'cellDummiesBefore' not in model['code']
model['code']['cellDummiesBefore'] = stataBeforeOut
model['code']['cellDummiesAfter'] = stataAfterOut
if clusterCells:
if 'regoptions' not in model and method not in ['rreg']:
model[
'regoptions'] = ', robust' # Need to have comma, at least here...
if 'cluster(' in model['regoptions']:
print "Warning!! I am not putting the cell variable in as cluster because you already have a cluster variable! ", model[
'regoptions']
else:
model['regoptions'] += ' cluster(%s) ' % cellVariables
if isinstance(model.get('flags', ''), dict):
model['flags'][
'clustering'] = '{\smaller \smaller %s}' % cellName
else:
model['flags'] += [[
'clustering', r'{\smaller \smaller %s}' % cellName
]]
#print ' Revised model: ',model
oneGroupModels += [model]
#modelsout+=[oneGroupModels]
return (oneGroupModels)
###########################################################################################
###
def withCRdummies(self,
models,
CRs,
each=False,
nCounts=None,
clusterCRs=True,
minSampleSize=800,
defaultModel=None,
manualDrops=None): # aka "byCR"
###
#######################################################################################
"""
What does this do? It replicates the given sets of models so that each is run with a series of sets of CR values / dummies included/excluded in order to isolate effects at each level.
This makes use of withCellDummies, above. The only thing that should still be done here is dropping higher CR level vars. and iterating over CRs. [done]
to test this: same as prev function, except:
import pystata
L=pystata.latexRegressionFile('tmp1234')
mmm=L.withCRdummies([convertMtoDict(['','lsatis da_stuff pr_this csd_that if 1',[['survey','EDS']]]), convertMtoDict( ['','lsatis da_stuff pr_this csd_that if 1',[['survey','GSS17']]]), ],['PR','CSD'])
or maybe: (two surveys, three CRs, and four regression models)
mmm=L.withCRdummies([
[convertMtoDict(['','lsatis da_stuff pr_this csd_that if 1',[['survey','EDS']]]), convertMtoDict(['','lsatis da_stuff pr_this csd_that if 1',[['survey','GSS17']]]),],
[convertMtoDict(['','lsatis modelTwothings da_stuff pr_this csd_that if 1',[['survey','EDS']]]), convertMtoDict(['','lsatis otherThings da_stuff pr_this csd_that if 1',[['survey','GSS17']]])],
[convertMtoDict(['','lsatis modelThreethings da_stuff pr_this csd_that if 1',[['survey','EDS']]]), convertMtoDict(['','lsatis otherThings da_stuff pr_this csd_that if 1',[['survey','GSS17']]])],
[convertMtoDict(['','lsatis modelFourthings da_stuff pr_this csd_that if 1',[['survey','EDS']]]), convertMtoDict(['','lsatis otherThings da_stuff pr_this csd_that if 1',[['survey','GSS17']]])],
],['PR','CSD','CT'])
"""
""" This function removes any regressors that look like they
are determined at the same CR level that is being controlled
for, since Stata will randomly choose one of the available
variables at the CR level to leave in, and we want it to be
the dummy.
This is rather specific and therefore probably finicky.
If each=True, the idea is to keep collections of the CR
dummies together, so we see the coefficients grouped by the
rest of the model.
Consider a set of modeles passed as: [1,[2,3,4],[5,6]]. ie there are two sets of grouped ones (which regTable will takes means of) and one ungrouped one.
How do I preserve this ordering?
I want the result for, say, two CRs to be: [1,1',[2,3,4],[2',3',4'],[5,6],[5',6']]
if any of the top level list members is another list of lists (ie list of models), then do a recursive loop to parse them.
Otherwise, parse as a group.
So: this function can now take complex nested sets of models.
Examples: 1 (not allowed); [1]; [1,2,3]; [[1,2,3]]
May 2008: Adding a note of group names for each group of CR models...
Aug 2008: [Obselete] I am adding "depvar" as an option: you can specify a default depvar to fill in unfilled field depvar for each model. This is passed on to celldummies.
Oct2 008: I am replacing "depvar" option with "defaultModel" option!
Aug 2010: Generalising so that if CR doesn't look like a CR, it may be a Gallup geographic level. (or USA, in future?)
manualDrops = ??
"""
from copy import deepcopy
if nCounts == None:
nCounts = 5
if manualDrops is None:
manualDrops = {}
##assert(isinstance(models[0],list))
modelsout = []
from pprint import pprint
###print len(models),len(models[0])#,len(models[1])
#if any([isinstance(model,list) and isinstance(model[0],list) for model in models]):
debugprint('-------------werwerwe', models)
# What object do we have?
if isinstance(models, str):
models = self.str2models(models, defaultModel=defaultModel)
if isinstance(models, dict):
debugprint('Found dict')
elif isinstance(models, list) and all(
[isinstance(onee, dict) for onee in models]):
debugprint('Found list of nothing but dicts')
#elif any([isinstance(model,list) and (isinstance(model[0],list) or isinstance(model[0],dict)) for model in models]):
# debugprint('Found list of lists that are not models')
else:
debugprint(
'so must have a list of lists, or else the models are not in dict format?'
)
# This will fail if models are passed not in dict form.!
if not isinstance(models, dict) and not isinstance(models[0], dict):
debugprint(
'withCRdummies is recursively looping over %d elements\n' %
len(models))
for modelOrGroup in models:
if isinstance(
modelOrGroup,
dict): # or not isinstance(modelOrGroup[0],list):
debugprint(' withCRdummies entry: a single model!\n',
modelOrGroup)
modelOrGroup = [modelOrGroup]
else:
debugprint(' withCRdummies entry: length %d \n' %
len(modelOrGroup))
pass
modelsout += self.withCRdummies(
modelOrGroup,
CRs,
each=each,
nCounts=nCounts,
clusterCRs=clusterCRs,
minSampleSize=minSampleSize,
defaultModel=defaultModel,
manualDrops=manualDrops)
return (modelsout)
"""
if not isinstance(models,dict) and (\
(isinstance(models,list) and isinstance(models[0],dict)) \
or any([isinstance(model,list) and isinstance(model[0],list) for model in models])):
debugprint ('withCRdummies is recursively looping over %d elements\n'%len(models))
for modelOrGroup in models:
if isinstance(modelOrGroup,dict) or not isinstance(modelOrGroup[0],list):
debugprint( ' withCRdummies entry: a single model!\n',modelOrGroup)
modelOrGroup=[modelOrGroup]
else:
debugprint (' withCRdummies entry: length %d \n'%len(modelOrGroup))
pass
modelsout+=self.withCRdummies(modelOrGroup,CRs,each=each,nCounts=nCounts)
return(modelsout)
"""
# Note: HR cannot be ranked this way, so including HR in below is a kludge for testing.this is a kludge for testing.
higherLevels = {
'CT': ['CT', 'A15', 'CSD', 'HR', 'CMA', 'PR'],
'CSD': ['CSD', 'HR', 'CMA', 'PR'],
'HR': ['HR', 'CMA', 'PR'],
'CMA': ['CMA', 'PR'],
'PR': ['PR'],
'wp5': ['wp5'],
'subregion': ['subregion', 'wp5'],
}
for aCR in higherLevels: # Add underscores to these; I use them for variable prefixes.
higherLevels[aCR] = [cc.lower() + '_' for cc in higherLevels[aCR]]
if each == True: #(...? huh?)
#assert 0 # This assert added Setp2009 since it looks like this is a not-implemented feature?. Well, actually I'll leave it for now. Do not understand.
return
# Ensure all models are in the modern format:
models = deepcopy(models)
assert all([isinstance(model, dict)
for model in models]) # Otherwise out of date / impossible
# Treat models as a group; cycle through each of them together before moving on to next CR:
# By this point, single-model sets come looking like a group (ie as [[list]])
dums = {}
global globalGroupCounter
""" This counter / CRgroups label will be the same for a group of models run over different surveys and also with different CR controls. Later on, the *averaged over surveys* version of these can be grouped based on this CRgroups marker to find how to collect coefficients from the means. Note that there is always one model (the first in a group) run without any CR fixed effects. This should also get the CRgroup marker.
"""
globalGroupCounter += 1
if isinstance(CRs, str):
CRs = [CRs]
# Following is a lookup that tells which CR coef is isolated by a given CR dummies set: ie it's one smaller than the set of dummies.
topCoefficient = dict(
[[CRs[iCR], (CRs[1:] + [''])[iCR]] for iCR in range(len(CRs))])
for aCR in CRs:
dummyStr = '%s~f.e.' % aCR
## if aCR=='': # Make one copy with no dummies
## amodel=deepcopy(models)
## amodel['CRgroup']={'CR%03d'%globalGroupCounter:aCR}#+parts[1].replace(' ','')}
## modelsout+=[amodel]
## debugprint ('No change for this model\n')
## continue
debugprint(' byCR: for %s, looping over the %d models.\n' %
(aCR, len(models)))
oneGroupModels = []
# Call the more general function to do most of the work:
#models=self.withCellDummies(deepcopy(models),aCR,cellName=aCR.replace('uid',''),nCounts=nCounts,clusterCells=clusterCRs)
for model in deepcopy(models):
#!stataBeforeOut,stataAfterOut='',''
#print ' byCR: Original model: ',model
# Find surveys, if there is one. Ignore "all~n" entries for "survey" attribute.
#!surv=[aaa[1] for aaa in model[2] if isinstance(aaa,list) and aaa[0]=='survey'][0]
#!surveys=[sss for sss in surv.replace(' ',',').split(',') if not 'all~' in sss]
#print 'Found survey: ',surveys
#if ',' in surv or ' ' in surv:
# print "Multiple surveys in this model"
#!dsurveys=' 1 ' # ie "true" in an if condition
#!if len(surveys)>0:
#! dsurveys=' ('+ ' | '.join(['d%s==1'%ss for ss in surveys]) + ') '
#dums= ' td%s_%s* '%(aCR,surv[0])
# Find regressors; find if conditions:
######model['CRgroup']={'CR%03d'%globalGroupCounter:aCR}#+parts[1].replace(' ','')}
model['CRgroup'] = {
'id': 'CR%03d' % globalGroupCounter,
'fixedeffects': aCR,
'takeCoef': topCoefficient[aCR],
'addend': len(models) > 1
} #,'isaddend':''}}
if aCR == '': # Make one copy with no dummies
if defaultModel:
for field in defaultModel:
if field not in model:
model[field] = deepcopy(defaultModel[field])
debugprint('No change for this model\n')
modelC = deepcopy(model)
else:
if ' if ' not in model['model']:
model['model'] += ' if 1'
parts = model['model'].split(' if ')
assert len(parts) < 3
regressors = [pp for pp in parts[0].split(' ') if pp]
# Also, remove any regressors which look like they are at this (or higher...) CR level:
useRegressors = [
rr for rr in regressors
if not rr[0:3].lower() in higherLevels[aCR] and
not rr[0:4].lower() in higherLevels[aCR] and rr not in
manualDrops.get(aCR, [])
]
model['model'] = ' '.join(
useRegressors) + ' if ' + parts[1]
if aCR in crlist:
acrsuffix = 'uid'
else:
acrsuffix = ''
modelC = self.withCellDummies(
[model],
aCR + acrsuffix,
cellName=aCR,
nCounts=nCounts,
clusterCells=clusterCRs,
minSampleSize=minSampleSize,
defaultModel=defaultModel)[0]
oneGroupModels += [modelC]
modelsout += [oneGroupModels]
#pprint(modelsout)