-
Notifications
You must be signed in to change notification settings - Fork 1
/
dlatkInterface.py
1973 lines (1728 loc) · 125 KB
/
dlatkInterface.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
#!/usr/bin/env python3
"""
Interface Module to DLATK
"""
import os, getpass
import sys
import pdb
import argparse
import time
from pprint import pprint
from numpy import isnan, sqrt, log
from configparser import SafeConfigParser
import gzip
import dlatk.dlaWorker as dlaWorker
import dlatk.dlaConstants as dlac
from dlatk import DDLA
from dlatk.classifyPredictor import ClassifyPredictor
from dlatk.dimensionReducer import DimensionReducer, CCA
from dlatk.dlaWorker import DLAWorker
from dlatk.featureExtractor import FeatureExtractor
from dlatk.featureGetter import FeatureGetter
from dlatk.featureRefiner import FeatureRefiner
from dlatk.lexicainterface import lexInterface
from dlatk.mediation import MediationAnalysis
from dlatk.messageAnnotator import MessageAnnotator
from dlatk.messageTransformer import MessageTransformer
from dlatk.outcomeGetter import OutcomeGetter
from dlatk.outcomeAnalyzer import OutcomeAnalyzer
from dlatk.regressionPredictor import RegressionPredictor, CombinedRegressionPredictor, ClassifyToRegressionPredictor
from dlatk.semanticsExtractor import SemanticsExtractor
from dlatk.topicExtractor import TopicExtractor
try:
from dlatk.lib import wordcloud
except ImportError:
print('warning: wordcloud not found.')
from dlatk.lexicainterface.lexInterface import LexInterfaceParser
def getInitVar(variable, parser, default, varList=False):
if parser:
if varList:
return [o.strip() for o in parser.get('constants',variable).split(",")] if parser.has_option('constants',variable) else default
else:
return parser.get('constants',variable) if parser.has_option('constants',variable) else default
else:
return default
#################################################################
### Main / Command-Line Processing:
##
#
def main(fn_args = None):
"""
:param fn_args: string - ex "-d testing -t msgs -c user_id --add_ngrams -n 1 "
"""
strTime = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
dlac.warn("\n%s\n--\nDLATK Interface Initiated\n--" % strTime)
start_time = time.time()
##Argument Parser:
init_parser = argparse.ArgumentParser(prefix_chars='-+', formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
# Meta variables
group = init_parser.add_argument_group('Meta Variables', '')
group.add_argument('--lex_interface', dest='lexinterface', action='store_true', default=False,
help='Send arguments to lexInterface.py')
group.add_argument('--to_file', dest='toinitfile', nargs='?', const=dlac.DEF_INIT_FILE, default=None,
help='write flag values to text file')
group.add_argument('--from_file', type=str, dest='frominitfile', default='',
help='reads flag values from file')
init_args, remaining_argv = init_parser.parse_known_args()
if init_args.lexinterface:
lex_parser = LexInterfaceParser(parents=[init_parser])
lex_parser.processArgs(args=remaining_argv, parents=True)
sys.exit()
elif init_args.frominitfile:
conf_parser = SafeConfigParser()
conf_parser.read(init_args.frominitfile)
else:
conf_parser = None
# Inherit options from init_parser
parser = argparse.ArgumentParser(description='Extract and Manage Language Feature Data.',
parents=[init_parser])
group = parser.add_argument_group('Corpus Variables', 'Defining the data from which features are extracted.')
group.add_argument('-d', '--corpdb', metavar='DB', dest='corpdb', default=getInitVar('corpdb', conf_parser, dlac.DEF_CORPDB),
help='Corpus Database Name.')
group.add_argument('-t', '--corptable', metavar='TABLE', dest='corptable', default=getInitVar('corptable', conf_parser, dlac.DEF_CORPTABLE),
help='Corpus Table.')
group.add_argument('-c', '--correl_field', metavar='FIELD', dest='correl_field', default=getInitVar('correl_field', conf_parser, dlac.DEF_CORREL_FIELD),
help='Correlation Field (AKA Group Field): The field which features are aggregated over.')
group.add_argument('-H', '--host', metavar='HOST', dest='mysql_host', default=getInitVar('mysql_host', conf_parser, dlac.MYSQL_HOST),
help='Host that the mysql server runs on (default: %s)' % dlac.MYSQL_HOST)
group.add_argument('--message_field', metavar='FIELD', dest='message_field', default=getInitVar('message_field', conf_parser, dlac.DEF_MESSAGE_FIELD),
help='The field where the text to be analyzed is located.')
group.add_argument('--messageid_field', metavar='FIELD', dest='messageid_field', default=getInitVar('messageid_field', conf_parser, dlac.DEF_MESSAGEID_FIELD),
help='The unique identifier for the message.')
group.add_argument('--date_field', metavar='FIELD', dest='date_field', default=getInitVar('date_field', conf_parser, dlac.DEF_DATE_FIELD),
help='Date a message was sent (if avail, for timex processing).')
group.add_argument('--lexicondb', metavar='DB', dest='lexicondb', default=getInitVar('lexicondb', conf_parser, dlac.DEF_LEXICON_DB),
help='The database which stores all lexicons.')
group.add_argument('--encoding', metavar='DB', dest='encoding', default=getInitVar('encoding', conf_parser, ''),
help='MySQL encoding')
group.add_argument('--no_unicode', action='store_false', dest='useunicode', default=dlac.DEF_UNICODE_SWITCH,
help='Turn off unicode for reading/writing mysql and text processing.')
group = parser.add_argument_group('Feature Variables', 'Use of these is dependent on the action.')
group.add_argument('-f', '--feat_table', metavar='TABLE', dest='feattable', type=str, nargs='+', default=getInitVar('feattable', conf_parser, None, varList=True),
help='Table containing feature information to work with')
group.add_argument('-n', '--set_n', metavar='N', dest='n', type=int, nargs='+', default=[dlac.DEF_N],
help='The n value used for n-grams or co-occurence features')
group.add_argument('--no_metafeats', action='store_false', dest='metafeats', default=True,
help='indicate not to extract meta features (word, message length) with ngrams')
group.add_argument('-l', '--lex_table', metavar='TABLE', dest='lextable', default=getInitVar('lextable', conf_parser, ''),
help='Lexicon Table Name: used for extracting category features from 1grams'+
'(or use --word_table to extract from other than 1gram)')
group.add_argument('--word_table', metavar='WORDTABLE', dest='wordTable', default=getInitVar('wordTable', conf_parser, None),
help='Table that contains the list of words to give for lex extraction/group_freq_thresh')
group.add_argument('--colloc_table', metavar='TABLE', dest='colloc_table', default=dlac.DEF_COLLOCTABLE,
help='Table that holds a list of collocations to be used as features.')
group.add_argument('--colloc_column', metavar='COLUMN', dest='colloc_column', default=dlac.DEF_COLUMN_COLLOC,
help='Column giving collocations to be used as features.')
group.add_argument('--create_collocation_scores', dest='createcollocscores', const=True, nargs='?', default=False,
help='Create ufeat table and annotate with pocc and npmi.')
group.add_argument('--feature_type_name', metavar='STRING', dest='feature_type_name',
help='Customize the name of output features.')
group.add_argument('--gzip_csv', metavar='filename', dest='gzipcsv', default='',
help='gz-csv filename used for extracting ngrams')
group.add_argument('--categories', type=str, metavar='CATEGORY(IES)', dest='categories', nargs='+', default='',
help='Specify particular categories.')
group.add_argument('--feat_blacklist', type=str, metavar='FEAT(S)', dest='feat_blacklist', nargs='+', default='',
help='Features to ban when correlating with outcomes.')
group.add_argument('--feat_whitelist', type=str, metavar='FEAT(S)', dest='feat_whitelist', nargs='+', default='',
help='Only permit these features when correlating with outcomes (specify feature names or if feature table then read distinct features).')
group.add_argument('--sqrt', action='store_const', dest='valuefunc', const=lambda d: sqrt(d),
help='square-roots normalized group_norm freq information.')
group.add_argument('--log', action='store_const', dest='valuefunc', const=lambda d: log(d+1),
help='logs the normalized group_norm freq information.')
group.add_argument('--anscombe', action='store_const', dest='valuefunc', const=lambda d: 2*sqrt(d+3/float(8)),
help='anscombe transforms normalized group_norm freq information.')
group.add_argument('--boolean', action='store_const', dest='valuefunc', const=lambda d: float(1.0),
help='boolean transforms normalized group_norm freq information (1 if true).')
group.add_argument('--lex_sqrt', action='store_const', dest='lexvaluefunc', const=lambda d: sqrt(d),
help='square-roots normalized group_norm lexicon freq information.')
group.add_argument('--lex_log', action='store_const', dest='lexvaluefunc', const=lambda d: log(d+1),
help='logs the normalized group_norm lexicon freq information.')
group.add_argument('--lex_anscombe', action='store_const', dest='lexvaluefunc', const=lambda d: 2*sqrt(d+3/float(8)),
help='anscombe transforms normalized group_norm lexicon freq information.')
group.add_argument('--lex_boolean', action='store_const', dest='lexvaluefunc', const=lambda d: float(1.0),
help='boolean transforms normalized group_norm freq information (1 if true).')
group.add_argument('--set_p_occ', metavar='P', dest='pocc', type=float, default=dlac.DEF_P_OCC,
help='The probability of occurence of either a feature or group (altnernatively if > 1, then limits to top p_occ features instead).')
group.add_argument('--set_pmi_threshold', metavar='PMI', dest='pmi', type=float, default=dlac.DEF_PMI,
help='The threshold for the feat_colloc_filter.')
group.add_argument('--set_min_feat_sum', metavar='N', dest='minfeatsum', type=int, default=dlac.DEF_MIN_FEAT_SUM,
help='The minimum a feature must occur across all groups, to be kept.')
group.add_argument('--topic_file', type=str, dest='topicfile', default='',
help='Name of topic file to use to build the topic lexicon.')
group.add_argument('--num_topic_words', type=int, dest='numtopicwords', default=dlac.DEF_MAX_TOP_TC_WORDS,
help='Number of topic words to use as labels.')
group.add_argument('--topic_lexicon', '--topic_lex', type=str, dest='topiclexicon', default='',
help='this is the (topic) lexicon name specified as part of --make_feat_labelmap_lex and --add_topiclex_from_topicfile')
group.add_argument('--topic_list', type=str, dest='topiclist', default='', nargs='+',
help='this is the list of topics to group together in a plot for --feat_flexibin')
group.add_argument('--topic_lex_method', type=str, dest='topiclexmethod', default=dlac.DEF_TOPIC_LEX_METHOD,
help='must be one of: "csv_lik", "standard"')
group.add_argument('--weighted_lexicon', action='store_true', dest='weightedlexicon', default=False,
help='use with Extraction Action add_lex_table to make weighted lexicon features')
group.add_argument('--num_bins', type=int, dest='numbins', default=None,
help='number of bins (feature refiner).')
group.add_argument('--flexiplot_file', type=str, dest='flexiplotfile', default='',
help='use with Plot Action --feat_flexibin to specify a file to read for plotting')
group.add_argument('--group_id_range', type=float, dest='groupidrange', nargs=2,
help='range of group id\'s to include in binning.')
group.add_argument('--mask_table', type=str, metavar='TABLE', dest='masktable', default=None,
help='Table containing which groups run in various bins (for ttest).')
group.add_argument('--bert_model', type=str, metavar='NAME', dest='bertmodel', default=dlac.DEF_BERT_MODEL,
help='BERT model to use if extracting bert features.')
group.add_argument('--bert_msg_aggregation', '--bert_aggregations', type=str, metavar='AGG', nargs='+', dest='bertaggs', default=dlac.DEF_BERT_AGGREGATION,
help='Aggregations to use with Bert (e.g. mean, min, max).')
group.add_argument('--bert_layer_aggregation', type=str, metavar='AGG', nargs='+', dest='bertlayeraggs', default=dlac.DEF_BERT_LAYER_AGGREGATION,
help='Aggregations to use with Bert (e.g. mean, min, max).')
group.add_argument('--bert_layers', type=int, metavar='LAYER', nargs='+', dest='bertlayers', default=dlac.DEF_BERT_LAYERS,
help='layers from Bert to keep.')
group.add_argument('--bert_no_context', action='store_true', dest='bertnocontext', default=False,
help='encoded without considering context.')
group = parser.add_argument_group('MySQL Interactoins', '')
group.add_argument('--show_feature_tables', '--show_feat_tables', '--ls', action='store_true', dest='listfeattables', default=False,
help='List all feature tables for given corpdb, corptable and correl_field')
group.add_argument('--show_tables', nargs='?', dest='showtables', default=False, const=True,
help='List all non-feature tables. Optional argument for "like"-style SQL call')
group.add_argument('--describe_tables', '--desc_tables', nargs='*', dest='describetables', default=False,
help='')
group.add_argument('--view_tables', '--view_data', nargs='*', dest='viewtables', default=False,
help='')
group.add_argument('--create_random_sample', '--create_rand_sample', dest='createrandsample', default=None,
nargs='+', help='Given percentage, creates random sample of messages')
group.add_argument('--copy_table', '--create_copied_table', dest='createcopiedtable', default=None,
nargs=2, help='OLD_TABLE NEW_TABLE copies OLD_TABLE to NEW_TABLE')
group.add_argument('--extension', metavar='EXTENSION', dest='extension', default=None,
help='String added to the end of the feature table name')
group.add_argument('--top_messages', type=int, dest='top_messages', nargs='?', const=dlac.DEF_TOP_MESSAGES, default=False,
help='Print top messages with the largest score for a given topic.')
group = parser.add_argument_group('Outcome Variables', '')
group.add_argument('--outcome_table', type=str, metavar='TABLE', dest='outcometable', default=getInitVar('outcometable', conf_parser, dlac.DEF_OUTCOME_TABLE),
help='Table holding outcomes (make sure correl_field type matches corpus\').')
group.add_argument('--outcome_fields', '--outcomes', type=str, metavar='FIELD(S)', dest='outcomefields', nargs='+', default=getInitVar('outcomefields', conf_parser, dlac.DEF_OUTCOME_FIELDS, varList=True),
help='Fields to compare with.')
group.add_argument('--no_outcomes', action='store_const', const=[], dest='outcomefields',
help='Switch to override outcomes listed in init file.')
group.add_argument('--outcome_controls', '--controls', type=str, metavar='FIELD(S)', dest='outcomecontrols', nargs='+', default=getInitVar('outcomecontrols', conf_parser, dlac.DEF_OUTCOME_CONTROLS, varList=True),
help='Fields in outcome table to use as controls for correlation(regression).')
group.add_argument('--no_controls', action='store_const', const=[], dest='outcomecontrols',
help='Switch to override controls listed in init file.')
group.add_argument('--categorical', '--categories_to_binary', '--cat_to_bin', type=str, metavar='FIELD(S)', dest='cattobinfields', nargs='+', default=[],
help='Fields with categorical variables to be transformed into a one hot representation')
group.add_argument('--multiclass', '--categories_to_integer', '--cat_to_int', type=str, metavar='FIELD(S)', dest='cattointfields', nargs='+', default=[],
help='Fields with categorical variables to be transformed into a multiclass representation')
group.add_argument('--outcome_interaction', '--interaction', type=str, metavar='TERM(S)', dest='outcomeinteraction', nargs='+', default=getInitVar('outcomeinteraction', conf_parser, dlac.DEF_OUTCOME_CONTROLS, varList=True),
help='Fields in outcome table to use as controls and interaction terms for correlation(regression).')
group.add_argument('--fold_column', '--fold_labels', type=str, dest='fold_column', default=None,
help='Fields in outcome table to use as labels for prespecified folds in classification/regression cross-validation.')
group.add_argument('--test_folds', type=int, dest='test_folds', nargs='+', default=None,
help='Limit tests of classification/regression cross-validation to these folds.')
group.add_argument('--feat_names', type=str, metavar='FIELD(S)', dest='featnames', nargs='+', default=getInitVar('featnames', conf_parser, dlac.DEF_FEAT_NAMES, varList=True),
help='Limit outputs to the given set of features.')
group.add_argument("--group_freq_thresh", type=int, metavar='N', dest="groupfreqthresh", default=getInitVar('groupfreqthresh', conf_parser, None),
help="minimum WORD frequency per correl_field to include correl_field in results")
group.add_argument('--output_name', '--output', '--output_file', type=str, dest='outputname', default=getInitVar('outputname', conf_parser, ''),
help='overrides the default filename for output')
group.add_argument('--max_wordcloud_words', '--max_tagcloud_words', type=int, metavar='N', dest='maxtcwords', default=dlac.DEF_MAX_TC_WORDS,
help='Max words to appear in a tagcloud')
group.add_argument('--show_feat_freqs', action='store_true', dest='showfeatfreqs', default=dlac.DEF_SHOW_FEAT_FREQS,)
group.add_argument('--not_show_feat_freqs', action='store_false', dest='showfeatfreqs', default=dlac.DEF_SHOW_FEAT_FREQS,
help='show / dont show feature frequencies in output.')
group.add_argument('--tagcloud_filter', '--wordcloud_filter', action='store_true', dest='tcfilter', default=dlac.DEF_TC_FILTER,)
group.add_argument('--no_tagcloud_filter', '--no_wordcloud_filter', action='store_false', dest='tcfilter', default=dlac.DEF_TC_FILTER,
help='filter / dont filter tag clouds for duplicate info in phrases.')
group.add_argument('--feat_labelmap_table', type=str, dest='featlabelmaptable', default=getInitVar('featlabelmaptable', conf_parser, ''),
help='specifies an lda mapping tablename to be used for LDA topic mapping')
group.add_argument('--feat_labelmap_lex', type=str, dest='featlabelmaplex', default=getInitVar('featlabelmaplex', conf_parser, ''),
help='specifies a lexicon tablename to be used for the LDA topic mapping')
group.add_argument('--bracket_labels', action='store_true', dest='bracketlabels', default='',
help='use with: feat_labelmap_lex... if used, the labelmap features will be contained within brackets')
group.add_argument('--comparative_tagcloud', '--comparative_wordcloud', action='store_true', dest='compTagcloud', default=False,
help='used with --sample1 and --sample2, this option uses IDP to compare feature usage')
group.add_argument('--sample1', type=str, nargs='+', dest="compTCsample1", default=[],
help='first sample of group to use in comparison [use with --comparative_tagcloud]'+
"(use * to mean all groups in featuretable)")
group.add_argument('--sample2', type=str, nargs='+', dest="compTCsample2", default=[],
help='second sample of group to use in comparison [use with --comparative_tagcloud]'+
"(use * to mean all groups in featuretable)")
group.add_argument('--csv', action='store_true', dest='csv',
help='generate csv correl matrix output as well')
group.add_argument('--pickle', action='store_true', dest='pickle',
help='generate pickle of the correl matrix output as well')
group.add_argument('--sort', action='store_true', dest='sort',
help='add sorted output for correl matrix')
group.add_argument('--whitelist', action='store_true', dest='whitelist', default=False,
help='Uses feat_whitelist or --lex_table and --categories.')
group.add_argument('--blacklist', action='store_true', dest='blacklist', default=False,
help='Uses feat_blacklist or --lex_table and --categories.')
group.add_argument('--spearman', action='store_true', dest='spearman',
help='Use Spearman R instead of Pearson.')
group.add_argument('--logistic_reg', action='store_true', dest='logisticReg', default=False,
help='Use logistic regression instead of linear regression. This is better for binary outcomes.')
group.add_argument('--cohens_d', action='store_true', dest='cohensd', default=False,
help='Report Cohen\'s D with logistic regression instead coefficients (B\'s).')
group.add_argument('--IDP', '--idp', action='store_true', dest='IDP', default=False,
help='Use IDP instead of linear regression/correlation [only works with binary outcome values]')
group.add_argument('--AUC', '--auc', action='store_true', dest='auc', default=False,
help='Use AUC instead of linear regression/correlation [only works with binary outcome values]')
group.add_argument('--zScoreGroup', action='store_true', dest='zScoreGroup', default=False,
help="Outputs a certain group's zScore for all feats, which group is determined by the boolean outcome value [MUST be boolean outcome]")
group.add_argument('--p_correction', metavar='METHOD', type=str, dest='p_correction_method', default=getInitVar('p_correction_method', conf_parser, dlac.DEF_P_CORR),
help='Specify a p-value correction method: simes, holm, hochberg, hommel, bonferroni, BH, BY, fdr, none',
choices=dlac.DEF_P_MAPPING.keys())
group.add_argument('--no_bonferroni', action='store_false', dest='bonferroni', default=True,
help='Turn off bonferroni correction of p-values.')
group.add_argument('--no_correction', action='store_const', const='', dest='p_correction_method',
help='Turn off BH correction of p-values.')
group.add_argument('--nvalue', type=bool, dest='nvalue', default=True,
help='Report n values.')
group.add_argument('--conf_int', type=bool, dest='confint', default=True,
help='Report confidence intervals.')
group.add_argument('--freq', type=bool, dest='freq', default=True,
help='Report freqs.')
group.add_argument('--tagcloud_colorscheme', '--wordcloud_colorscheme', type=str, dest='tagcloudcolorscheme', default=getInitVar('tagcloudcolorscheme', conf_parser, 'multi'),
help='specify a color scheme to use for tagcloud generation. Default: multi, also accepts red, blue, red-random, redblue, bluered')
group.add_argument('--clean_cloud', action='store_true', dest='cleancloud', default=False,
help='Replaces characters in the middle of explatives/slurs with ***. ex: f**k')
group.add_argument('--weighted_sample', dest='weightedsample', default=dlac.DEF_WEIGHTS,
help='Field in outcome table to use as weights for correlation(regression).')
group.add_argument('--keep_low_variance_outcomes', '--keep_low_variance', dest='low_variance_thresh', action='store_false', default=dlac.DEF_LOW_VARIANCE_THRESHOLD,
help='Does not remove low variance outcomes and controls from analysis')
group.add_argument('--interactions', action='store_true', dest='interactions', default=False,
help='Includes interaction terms in multiple regression.')
group.add_argument('--bootstrapp', '--bootstrap', dest='bootstrapp', type=int, default = 0,
help="Bootstrap p-values (only works for AUCs for now) ")
group.add_argument("--p_value", type=float, metavar='P', dest="maxP", default = getInitVar('maxP', conf_parser, float(dlac.DEF_P)),
help="Significance threshold for returning results. Default = 0.05.")
group.add_argument("--where", type=str, dest="groupswhere", default = '',
help="Filter groups with sql-style call. ")
group = parser.add_argument_group('Mediation Variables', '')
group.add_argument('--mediation', action='store_true', dest='mediation', default=False,
help='Run mediation analysis.')
group.add_argument('--mediation_bootstrap', '--mediation_boot', action='store_true', dest='mediationboot', default=False,
help='Run mediation analysis with bootstrapping. The parametric (non-bootstrapping) method is default.')
group.add_argument("--mediation_boot_num", type=int, metavar='N', dest="mediationbootnum", default = int(dlac.DEF_MEDIATION_BOOTSTRAP),
help="The number of repetitions to run in bootstrapping with mediation analysis. Default = 1000.")
group.add_argument('--outcome_pathstarts', '--path_starts', type=str, metavar='FIELD(S)', dest='outcomepathstarts', nargs='+', default=dlac.DEF_OUTCOME_PATH_STARTS,
help='Fields in outcome table to use as treatment in mediation analysis.')
group.add_argument('--outcome_mediators', '--mediators', type=str, metavar='FIELD(S)', dest='outcomemediators', nargs='+', default=dlac.DEF_OUTCOME_MEDIATORS,
help='Fields in outcome table to use as mediators in mediation analysis.')
group.add_argument('--feat_as_path_start', action='store_true', dest='feat_as_path_start', default=False,
help='Use path start variables located in a feature table. Used in mediation analysis.')
group.add_argument('--feat_as_outcome', action='store_true', dest='feat_as_outcome', default=False,
help='Use outcome variables located in a feature table. Used in mediation analysis.')
group.add_argument('--feat_as_control', action='store_true', dest='feat_as_control', default=False,
help='Use control variables located in a feature table. Used in mediation analysis.')
group.add_argument('--no_features', action='store_true', dest='no_features', default=False,
help='All mediation analysis variables found corptable. No feature table needed.')
group.add_argument('--mediation_csv', action='store_true', dest='mediationcsv', default=False,
help='Print results to a CSV. Default file name is mediation.csv. Use --output_name to specify file name.')
group.add_argument('--mediation_no_summary', action='store_false', dest='mediationsummary', default=True,
help='Print results to a CSV. Default file name is mediation.csv. Use --output_name to specify file name.')
group.add_argument('--mediation_method', metavar='METHOD', type=str, dest='mediation_style', default='baron',
help='Specify a mediation method: baron, imai, both')
group = parser.add_argument_group('Prediction Variables', '')
group.add_argument('--adapt_tables', metavar='TABLE_NUM', dest='adapttable', type=int, nargs='+', default=getInitVar('adapttable', conf_parser, None, varList=True),
help='NOT IMPLEMENTED: Table(s) containing feature information to be adapted')
group.add_argument('--adapt_control_names', metavar='COLUMN', dest='adaptcolumns', type=str, nargs='+', default=None,
help='NOT IMPLEMENTED: Controls to be used for adaptation.')
group.add_argument('--model', type=str, metavar='name', dest='model', default=getInitVar('model', conf_parser, dlac.DEF_MODEL),
help='Model to use when predicting: svc, linear-svc, ridge, linear.')
group.add_argument('--combined_models', type=str, nargs='+', metavar='name', dest='combmodels', default=dlac.DEF_COMB_MODELS,
help='Model to use when predicting: svc, linear-svc, ridge, linear.')
group.add_argument('--sparse', action='store_true', dest='sparse', default=False,
help='use sparse representation for X when training / testing')
group.add_argument('--folds', type=int, metavar='NUM', dest='folds', default=dlac.DEF_FOLDS,
help='Number of folds for functions that run n-fold cross-validation')
group.add_argument('--outlier_to_mean', '--outliers_to_mean', dest='outlier_to_mean', nargs='?', type=float, default=False, const=dlac.DEF_OUTLIER_THRESHOLD,
help='')
group.add_argument('--picklefile', type=str, metavar='filename', dest='picklefile', default='',
help='Name of file to save or load pickle of model')
group.add_argument('--all_controls_only', action='store_true', dest='allcontrolsonly', default=False,
help='Only uses all controls when prediction doing test_combo_regression')
group.add_argument('--no_lang', action='store_true', dest='nolang', default=False,
help='Runs with language features excluded')
group.add_argument('--control_combo_sizes', '--combo_sizes', type=int, metavar="index", nargs='+', dest='controlcombosizes',
default=[], help='specify the sizes of control combos to use')
group.add_argument('--residualized_controls', '--res_controls', action='store_true', dest='res_controls', default=False,
help='Finds residuals for controls and tries to predict beyond them (only for combo test)')
group.add_argument('--prediction_csv', '--pred_csv', action='store_true', dest='pred_csv',
help='write yhats in a separate csv')
group.add_argument('--probability_csv', '--prob_csv', action='store_true', dest='prob_csv',
help='write probabilities for yhats in a separate csv')
group.add_argument('--weighted_eval', type=str, dest='weightedeval', default=None,
help='Column to weight the evaluation.')
group.add_argument('--no_standardize', action='store_false', dest='standardize', default=True,
help='turn off standardizing variables before prediction')
group.add_argument('--feature_selection', '--feat_selection', metavar='NAME', type=str, dest='featureselection', default=getInitVar('featureselection', conf_parser, ''),
help='Specify feature selection pipeline in prediction: magic_sauce, univariateFWE, PCA.')
group.add_argument('--feature_selection_string', metavar='NAME', type=str, dest='featureselectionstring', default=getInitVar('featureselectionstring', conf_parser, ''),
help='Specify any feature selection pipeline in prediction.')
group = parser.add_argument_group('Standard Extraction Actions', '')
group.add_argument('--add_ngrams', action='store_true', dest='addngrams',
help='add an n-gram feature table. (uses: n, can flag: sqrt), gzip_csv'
'can be used with or without --use_collocs')
group.add_argument('--add_ngrams_from_tokenized', action='store_true', dest='addngramsfromtok',
help='add an n-gram feature table from a tokenized table. Table must be JSON list of tokens.'
'(uses: n, can flag: sqrt), gzip_csv.')
group.add_argument('--use_collocs', action='store_true', dest='use_collocs',
help='when extracting ngram features, use a table of collocations to parse text into ngrams'
'by default does not include subcollocs, this can be changed with the --include_sub_collocs option ')
group.add_argument('--include_sub_collocs', action='store_true', dest='include_sub_collocs',
help='count all sub n-grams of collocated n-grams'
'if "happy birthday" is designated as a collocation, when you see "happy birthday" in text'
'count it as an instance of "happy", "birthday", and "happy birthday"')
group.add_argument('--colloc_pmi_thresh', metavar="PMI", dest='colloc_pmi_thresh', type=float, default=dlac.DEF_PMI,
help='The PMI threshold for which multigrams from the colloctable to conscider as valid collocs'
'looks at the feat_colloc_filter column of the specified colloc table')
group.add_argument('--add_char_ngrams', action='store_true', dest='addcharngrams',
help='add a character n-gram feature table. (uses: n, can flag: sqrt), gzip_csv'
'can be used with or without --use_collocs')
group.add_argument('--no_lower', action='store_false', dest='lowercaseonly', default=dlac.LOWERCASE_ONLY,
help='')
group.add_argument('--add_lex_table', action='store_true', dest='addlextable',
help='add a lexicon-based feature table. (uses: l, weighted_lexicon, can flag: anscombe).')
group.add_argument('--add_corp_lex_table', action='store_true', dest='addcorplextable',
help='add a lexicon-based feature table based on corpus. (uses: l, weighted_lexicon, can flag: anscombe).')
group.add_argument('--add_phrase_table', action='store_true', dest='addphrasetable',
help='add constituent and phrase feature tables. (can flag: sqrt, anscombe).')
group.add_argument('--add_pos_table', action='store_true', dest='addpostable',
help='add pos feature tables. (can flag: sqrt, anscombe).')
group.add_argument('--add_pos_ngram_table', action='store_true', dest='pos_ngram',
help='add pos with ngrams feature table. (can flag: sqrt, anscombe).')
group.add_argument('--add_lda_table', metavar='LDA_MSG_TABLE', dest='addldafeattable',
help='add lda feature tables. (can flag: sqrt, anscombe).')
group.add_argument('--print_tokenized_lines', metavar="FILENAME", dest='printtokenizedlines', default = None,
help='prints tokenized version of messages to lines.')
group.add_argument('--print_joined_feature_lines', metavar="FILENAME", dest='printjoinedfeaturelines', default = None,
help='prints feature table with line per group joined by spaces (with MWEs joined by underscores) for import into Mallet.')
group.add_argument('--add_topiclex_from_topicfile', action='store_true', dest='addtopiclexfromtopicfile',
help='creates a lexicon from a topic file, requires --topic_file --topic_lexicon --lex_thresh --topic_lex_method')
group.add_argument('--add_timexdiff', action='store_true', dest='addtimexdiff',
help='extract timeex difference features (mean and std) per group.')
group.add_argument('--add_postimexdiff', action='store_true', dest='addpostimexdiff',
help='extract timeex difference features and POS tags per group.')
group.add_argument('--add_wn_nopos', action='store_true', dest='addwnnopos',
help='extract WordNet concept features (not considering POS) per group.')
group.add_argument('--add_wn_pos', action='store_true', dest='addwnpos',
help='extract WordNet concept features (considering POS) per group.')
group.add_argument('--add_fleschkincaid', '--add_fkscore', action='store_true', dest='addfkscore',
help='add flesch-kincaid scores, averaged per group.')
group.add_argument('--add_pnames', type=str, nargs=2, dest='addpnames',
help='add an people names feature table. (two agrs: NAMES_LEX, ENGLISH_LEX, can flag: sqrt)')
group.add_argument('--add_bert', action='store_true', dest='addbert',
help='add BERT mean features (optionally add min, max, --bert_model large)')
group = parser.add_argument_group('Messages Transformation Actions', '')
group.add_argument('--add_tokenized', action='store_true', dest='addtokenized',
help='adds tokenized version of message table.')
group.add_argument('--add_sent_tokenized', action='store_true', dest='addsenttokenized',
help='adds sentence tokenized version of message table.')
group.add_argument('--add_sent_per_row', action='store_true', dest='addsentperrow',
help='adds sentence tokenized version of message table with each sentence as a row in MySQL table.')
group.add_argument('--add_parses', action='store_true', dest='addparses',
help='adds parsed versions of message table.')
group.add_argument('--add_segmented', action="store_true", dest='addsegmented', default=False,
help='adds segmented versions of message table.')
group.add_argument('--segmentation_model',type=str, dest='segmentationModel', default="ctb",
help='Chooses which model to use for message segmentation (CTB or PKU; Default CTB)')
group.add_argument('--add_tweettok', action='store_true', dest='addtweettok',
help='adds tweetNLP tokenized versions of message table.')
group.add_argument('--add_tweetpos', action='store_true', dest='addtweetpos',
help='adds tweetNLP pos tagged versions of message table.')
group.add_argument('--add_lda_messages', metavar='LDA_States_File', dest='addldamsgs',
help='add lda topic version of message table.')
group.add_argument('--add_outcome_feats', action='store_true', dest='addoutcomefeats',
help='add a feature table from the specified outcome table.')
group = parser.add_argument_group('Message Cleaning Actions', '')
group.add_argument('--language_filter', '--lang_filter', type=str, metavar='FIELD(S)', dest='langfilter', nargs='+', default=[],
help='Filter message table for list of languages.')
group.add_argument('--clean_messages', dest='cleanmessages', action = 'store_true', help="Remove URLs, hashtags and @ mentions from messages")
group.add_argument('--deduplicate', action='store_true', dest='deduplicate',
help='Removes duplicate messages within correl_field grouping, writes to new table corptable_dedup Not to be run at the message level.')
group.add_argument('--spam_filter', dest='spamfilter', metavar="SPAM_THRESHOLD", type=float, nargs='?', const=dlac.DEF_SPAM_FILTER,
help='Removes users (by correl_field grouping) with percentage of spam messages > threshold, writes to new table corptable_nospam '
'with new column is_spam. Defaul threshold = %s'%dlac.DEF_SPAM_FILTER)
group = parser.add_argument_group('LDA Actions', '')
group.add_argument('--add_message_id', type=str, nargs=2, dest='addmessageid',
help='Adds the message IDs to the topic distributions and stores the result in --output_name. Previously addMessageID.py (two agrs: MESSAGE_FILE, STATE_FILE)')
group.add_argument('-m', '--lda_msg_tbl', metavar='TABLE', dest='ldamsgtbl', type=str, default=dlac.DEF_LDA_MSG_TABLE,
help='LDA Message Table')
group.add_argument('--create_dists', action='store_true', dest='createdists',
help='Create conditional prob, and likelihood distributions.')
group = parser.add_argument_group('Semantic Extraction Actions', '')
group.add_argument('--add_ner', action='store_true', dest='addner',
help='extract ner features from xml files (corptable should be directory of xml files).')
group = parser.add_argument_group('Feature Table Aanalyses', '')
group.add_argument('--ttest_feat_tables', action='store_true', dest='ttestfeats',
help='Performs ttest on differences between group norms for 2 tables, within features')
group = parser.add_argument_group('Refinement Actions', '')
group.add_argument('--feat_occ_filter', action='store_true', dest='featoccfilter',
help='remove infrequent features. (uses variables feat_table and p_occ).')
group.add_argument('--combine_feat_tables', '--combine_feats', type=str, dest='combinefeattables', default=None,
help='Given multiple feature table, combines them (provide feature name) ')
group.add_argument('--add_feat_norms', action='store_true', dest='addfeatnorms',
help='calculates and adds the mean normalized (feat_norm) value for each row (uses variable feat_table).')
group.add_argument('--feat_colloc_filter', action='store_true', dest='featcollocfilter',
help='removes featrues that do not pass as collocations. (uses feat_table).')
group.add_argument('--feat_correl_filter', action='store_true', dest='featcorrelfilter',
help='removes features that do not pass correlation sig tests with given outcomes (uses -f --outcome_table --outcomes).')
group.add_argument('--make_topic_labelmap_lex', action='store_true', dest='maketopiclabelmap', default=False,
help='Makes labelmap lexicon from topics. Requires --topic_lexicon, --num_topic_words. Optional: --weighted_lexicon')
group.add_argument('--feat_group_by_outcomes', action='store_true', dest='featgroupoutcomes', default=False,
help='Creates a feature table grouped by a given outcome (requires outcome field, can use controls)')
group.add_argument('--aggregate_feats_by_new_group', action='store_true', dest='aggregategroup', default=False,
help='Aggregate feature table by group field (i.e. message_id features by user_ids).')
group.add_argument('--tf_idf', action='store_true', dest='tfidf', default=False,
help='Given an ngram feature table, creates a new feature table with tf-idf (uses -f).')
group = parser.add_argument_group('Outcome Actions', '')
group.add_argument('--print_csv', metavar="FILENAME", dest='printcsv', default = None,
help='prints group normalized values use for correlation.')
group.add_argument('--print_freq_csv', metavar="FILENAME", dest='printfreqcsv', default = None,
help='prints frequencies instead of group normalized values')
group.add_argument('--print_numgroups', action='store_true', dest='printnumgroups', default = False,
help='prints number of groups per outcome field')
group.add_argument('--densify_table', dest='densifytable', nargs=3, default = None,
help='Create a dense csv given a db, table, and three columns. Three variables needed: ROW COL VALUE')
group = parser.add_argument_group('Correlation Actions', 'Finds one relationship at a time (but can still adjust for others)')
group.add_argument('--correlate', '--dla', action='store_true', dest='correlate',
help='correlate with outcome (uses variable feat_table and all outcome variables).')
group.add_argument('--rmatrix', action='store_true', dest='rmatrix',
help='output a correlation matrix to a file in the output dir.')
group.add_argument('--combo_rmatrix', action='store_true', dest='combormatrix',
help='output a correlation matrix with all combinations of controls.')
group.add_argument('--topic_dupe_filter', action='store_true', dest='topicdupefilter',
help='remove topics not passing a duplicate filter from the correlation matrix')
group.add_argument('--tagcloud', '--wordcloud', action='store_true', dest='tagcloud',
help='produce data for making wordle tag clouds (same variables as correlate).')
group.add_argument('--topic_tagcloud', '--topic_wordcloud', action='store_true', dest='topictc',
help='produce data for making topic wordles (must be used with a topic-based feature table and --topic_lexicon).')
group.add_argument('--corp_topic_tagcloud', '--corp_topic_wordcloud', action='store_true', dest='corptopictc',
help='produce data for making topic wordles (must be used with a topic-based feature table and --topic_lexicon).')
group.add_argument('--make_wordclouds', '--make_tagclouds', action='store_true', dest='makewordclouds',
help="make wordclouds from the output tagcloud file.")
group.add_argument('--make_topic_wordclouds', '--make_topic_tagclouds', action='store_true', dest='maketopicwordclouds',
help="make topic wordclouds, needs an output topic tagcloud file.")
group.add_argument('--make_all_topic_wordclouds', '--make_all_topic_tagclouds', action='store_true', dest='makealltopicwordclouds',
help="make all topic wordclouds for a given topic lexicon.")
group.add_argument('--keep_duplicates', action='store_true', dest='keepduplicates',
help="Create topic wordclouds for duplicate filtered topics.")
group.add_argument('--use_featuretable_feats', action='store_true', dest='useFeatTableFeats',
help='use 1gram table to be used as a whitelist when plotting')
group.add_argument('--outcome_with_outcome', action='store_true', dest='outcomeWithOutcome',
help="correlates all outcomes in --outcomes with each other in addition to the features")
group.add_argument('--outcome_with_outcome_only', action='store_true', dest='outcomeWithOutcomeOnly',
help="correlates all outcomes in --outcomes with each other in WITHOUT the features")
group.add_argument('--output_interaction_terms', action='store_true', dest='outputInteractionTerms',
help='with this flag, outputs the coefficients from the interaction terms as r values '+
'the outcome coefficients. Use with --outcome_interaction FIELD1 [FIELD2 ...]')
group.add_argument('--interaction_ddla', dest='interactionDdla',
help="column name from the outcome table that is going to be used in DDLA:"+
"First, finding terms with significant interaction, then taking correlations for groups with outcome = 1 and = 0 separately")
group.add_argument('--interaction_ddla_pvalue', dest='ddlaSignificance', type=float,default=0.001,
help="Set level of significance to filter ddla features by")
group.add_argument('--DDLA', dest='ddlaFiles', nargs=2, help="Compares two csv's that have come out of DLA. Requires --freq and --nvalue to have been used")
group.add_argument('--DDLATagcloud', '--DDLAWordcloud', dest='ddlaTagcloud', action='store_true',
help="Makes a tagcloud file from the DDLA output. Uses deltaR as size, r_INDEX as color. ")
group = parser.add_argument_group('Multiple Regression Actions', 'Find multiple relationships at once')
group.add_argument('--multir', action='store_true', dest='multir',
help='multivariate regression with outcome (uses variable feat_table and all outcome variables, optionally csv).')
group = parser.add_argument_group('Prediction Actions', '')
group.add_argument('--train_regression', '--train_reg', action='store_true', dest='trainregression', default=False,
help='train a regression model to predict outcomes based on feature table')
group.add_argument('--test_regression', action='store_true', dest='testregression', default=False,
help='train/test a regression model to predict outcomes based on feature table')
group.add_argument('--nfold_regression', '--combo_test_regression', '--combo_test_reg', '--nfold_test_regression', action='store_true', dest='combotestregression', default=False,
help='train/test a regression model with and without all combinations of controls')
group.add_argument('--predict_regression', '--predict_reg', action='store_true', dest='predictregression', default=False,
help='predict outcomes based on loaded or trained regression model')
group.add_argument('--control_adjust_outcomes_regression', '--control_adjust_reg', action='store_true', default=False, dest='controladjustreg',
help='predict outcomes from controls and produce adjusted outcomes')
group.add_argument('--test_combined_regression', type=str, metavar="featuretable", nargs='+', dest='testcombregression', default=[],
help='train and test combined model (must specify at least one addition feature table here)')
group.add_argument('--predict_regression_to_feats', type=str, dest='predictrtofeats', default=None,
help='predict outcomes into a feature file (provide a name)')
group.add_argument('--predict_regression_to_outcome_table', type=str, dest='predictRtoOutcomeTable', default=None,
help='predict outcomes into an outcome table (provide a name)')
group.add_argument('--predict_cv_to_feats', '--predict_combo_to_feats', '--predict_regression_all_to_feats', type=str, dest='predictalltofeats', default=None,
help='predict outcomes into a feature file (provide a name)')
group = parser.add_argument_group('Factor Adaptation Actions', '')
group.add_argument('--fs_params', action='store_true', dest='fsparams', default=False, help = 'send values for feature selection parameters')
group.add_argument('--k_best', type=str, dest='kbest', nargs='+', help='vaiables needed for feature selection .')
group.add_argument('--pca_comp', type=str, dest='pcacomp', nargs='+', help='vaiables needed for feature selection .')
group.add_argument('--adaptation_factors', '--factors', type=str, metavar='FIELD(S)', dest='adaptationfactors', nargs='+', help='Fields in outcome table to use as factors for adaptation in FA or RFA.')
group.add_argument('--factor_selection_type', type=str , dest = 'factorselectiontype', default='rfe', help='chooses the type of factor selection, either pca or rfe.')
group.add_argument('--num_of_factors', type=int, dest='numoffactors', nargs='+',
help='specifies the number of factors for factor selection. 0 means all factor1. ')
group.add_argument('--paired_factors', action='store_true', dest = 'pairedfactors', default=False , help='multiplying factors to themself, to make bigger pool of factors')
group.add_argument('--report', action='store_true', dest='report', default=False, help = 'Indicates if we want to store a report on outputfile+"_.report".')
group.add_argument('--factor_addition', action='store_true', dest='factoraddition', default=False, help = 'Indicates we want to append factors to language.')
group.add_argument('--factor_adaptation', '--fa', action='store_true', dest='factoradaptation', default=False, help = 'Indicates we want to factor_adapt language features.')
group.add_argument('--res_factor_adaptation', '--rfa' , action='store_true', dest='residualizedfactoradaptation', default=False, help = 'Indicates we want to apply residualized factor adaptation.')
group = parser.add_argument_group('Classification Actions', '')
group.add_argument('--train_classifiers', '--train_class', action='store_true', dest='trainclassifiers', default=False,
help='train classification models for each outcome field based on feature table')
group.add_argument('--test_classifiers', action='store_true', dest='testclassifiers', default=False,
help='trains and tests classification for each outcome')
group.add_argument('--nfold_classifiers', '--combo_test_classifiers', '--nfold_test_classifiers', action='store_true', dest='combotestclassifiers', default=False,
help='train/test a regression model with and without all combinations of controls')
group.add_argument('--predict_classifiers', '--predict_class', action='store_true', dest='predictclassifiers', default=False,
help='predict outcomes bases on loaded training')
group.add_argument('--roc', action='store_true', dest='roc',
help="Computes ROC curves and outputs to PDF")
group.add_argument('--predict_classifiers_to_feats', type=str, dest='predictctofeats', default=None,
help='predict outcomes into a feature file (provide a name)')
group.add_argument('--predict_probabilities_to_feats', '--predict_probs_to_feats', type=str, dest='predictprobstofeats', default=None,
help='predict probabilities into a feature file (provide a name)')
group.add_argument('--predict_classifiers_to_outcome_table', type=str, dest='predictCtoOutcomeTable', default=None,
help='predict outcomes into an outcome table (provide a name)')
group.add_argument('--regression_to_lexicon', dest='regrToLex', type=str, default=None,
help='Uses the regression coefficients to create a weighted lexicon.')
group.add_argument('--classification_to_lexicon', dest='classToLex', type=str, default=None,
help='Uses the classification coefficients to create a weighted lexicon.')
group.add_argument('--stratify_folds', action='store_true', dest='stratifyfolds', default=False,
help='stratify folds during combo_test_classifiers')
group.add_argument('--train_c2r', action='store_true', dest='trainclasstoreg', default=False,
help='train a model that goes from classification to prediction')
group.add_argument('--test_c2r', action='store_true', dest='testclasstoreg', default=False,
help='trains and tests classification for each outcome')
group.add_argument('--predict_c2r', action='store_true', dest='predictclasstoreg', default=False,
help='predict w/ classification to regression model')
group = parser.add_argument_group('Clustering Actions', '')
group.add_argument('--reducer_to_lexicon', type=str, dest='reducertolexicon', default=None,
help='writes the reduction model to a specified lexicon')
group.add_argument('--super_topics', type=str, dest='supertopics', default=None,
help='unroll reduced topics to the word level')
group.add_argument('--reduced_lexicon', '--reduced_lex', type=str, dest='reducedlexicon', default=None,
help='use during super topics creation if you have already run --reducer_to_lexicon')
group.add_argument('--fit_reducer', action='store_true', dest='fitreducer', default=False,
help='reduces a feature space to clusters')
group.add_argument('--num_factors', '--n_components', dest='n_components', default=None,
help='Number of factors in clustering method. Used with --fit_reducer.')
group = parser.add_argument_group('CCA Actions', '')
group.add_argument('--cca', type=int, dest='cca', default=0,
help='Performs sparse CCA on a set of features and a set of outcomes.'+
"Argument is number of components to output (Uses R's PMA package)")
group.add_argument('--cca_penalty_feats', '--cca_penaltyx', type=float, dest='penaltyFeats', default = None,
help="Penalty value on the feature matrix (X) [penaltyx argument of PMA.CCA]"+
"must be between 0 and 1, larger means less penalization (i.e. less sparse) ")
group.add_argument('--cca_penalty_outcomes', '--cca_penaltyz', type=float, dest='penaltyOutcomes', default = None,
help="Penalty value on the outcomes matrix (Z) [penaltyz argument of PMA.CCA]"+
"must be between 0 and 1, larger means less penalization (i.e. less sparse) ")
group.add_argument('--cca_outcomes_vs_controls', dest='ccaOutcomesVsControls',action='store_true',
help="performs CCA on outcomes vs controls (no language)")
group.add_argument('--cca_permute', dest='ccaPermute', type=int,default=0,
help='Wrapper for the PMA package CCA.permute function that determines the'+
' ideal L1 Penalties for X and Z matrices'+
'argument: number of permutations')
group.add_argument('--cca_predict_components', dest='predictCcaCompsFromModel',action="store_true",
help='Using --picklefile, predict outcomes from the V matrix (aka Z_comp)')
group.add_argument('--to_sql_table', dest='newSQLtable',type=str,
help='Using --cca_predict_components, predict components to sql table,'+
'the name of which you should provide here')
group.add_argument('--useXFeats', dest='usexfeats',action="store_true", default = False,
help='Use feats stored in X matrix when predicting CCA components to SQL')
group.add_argument('--useXControls', dest='usexcontrols',action="store_true", default = False,
help='Use controls stored in X matrix when predicting CCA components to SQL')
group.add_argument('--save_models', action='store_true', dest='savemodels', default=False,
help='saves predictive models (uses --picklefile)')
group.add_argument('--load_models', action='store_true', dest='loadmodels', default=False,
help='loads predictive models (uses --picklefile)')
group = parser.add_argument_group('Plot Actions', '')
group.add_argument('--barplot', action='store_true', dest='barplot',
help='produce correlation barplots. Requires fg, oa. Uses groupfreqthresh, outputdir')
group.add_argument('--scatterplot', action='store_true', dest='scatterplot',
help='Requires --outcome_table --outcome_fields, optional: -f --feature_names')
group.add_argument('--feat_flexibin', action='store_true', dest='featflexibin', default=False,
help='Plots a binned feature table, uses --num_bins, --group_id_range, --feat_table, --flexiplot_file') # group.add_argument('--hist2d', action='store_true', dest='hist2d',
group.add_argument('--skip_bin_step', action='store_true', dest='skipbinstep', default=False,
help='Skips the binning step for feat_flexibin. For when we want fast plotting and the flexitable has been created.')
group.add_argument('--preserve_bin_table', action='store_true', dest='preservebintable', default=False,
help='Preserves the flexibin table for faster plotting.')
# group.add_argument('--hist
# group.add_argument('--hist2d', action='store_true', dest='hist2d',
# help='Requires -f --feature_names --outcome_table --outcome_value')
group.add_argument('--descplot', action='store_true', dest='descplot',
help='produce histograms and boxplots for specified outcomes. Requires oa. Uses outputdir')
group.add_argument('--loessplot', type=str, metavar='FEAT(S)', dest='loessplot', nargs='+', default='',
help='Output loess plots of the given features.')
if len(sys.argv)==1:
parser.print_help()
sys.exit(1)
if fn_args:
args = parser.parse_args(fn_args.split())
else:
args = parser.parse_args(remaining_argv)
##Warnings
if not args.bonferroni:
print("--no_bonf has been depricated. Default p correction method is now Benjamini, Hochberg. Please use --no_correction instead of --no_bonf.")
sys.exit(1)
##Argument adjustments:
if not args.valuefunc: args.valuefunc = lambda d: d
if not args.lexvaluefunc: args.lexvaluefunc = lambda d: d
if args.outcomeWithOutcomeOnly and not args.feattable:
args.groupfreqthresh = 0
if args.feattable and len(args.feattable) == 1:
args.feattable = args.feattable[0]
if not args.feattable and args.aggregategroup:
args.feattable = aggregategroup[0]
if args.weightedeval:
args.outcomefields.append(args.weightedeval)
if args.weightedsample:
args.outcomefields.append(args.weightedsample)
if args.makewordclouds:
if not args.tagcloud:
print("WARNING: --make_wordclouds used without --tagcloud, setting --tagcloud to True")
args.tagcloud = True
if args.maketopicwordclouds:
if not args.topictc and not args.corptopictc:
print("WARNING: --make_topic_wordcloud used without --topic_tagcloud or --corp_topic_tagcloud, setting --topic_tagcloud to True")
args.topictc = True
if not args.encoding:
if not args.useunicode:
args.encoding = 'latin1'
else:
args.encoding = dlac.DEF_ENCODING
if not args.groupfreqthresh and args.groupfreqthresh != 0:
setGFTWarning = False
args.groupfreqthresh = dlac.getGroupFreqThresh(args.correl_field)
else:
setGFTWarning = True
args.integrationmethod = ''
if args.factoradaptation:
args.integrationmethod = 'fa'
if args.factoraddition:
args.integrationmethod += '_plus'
elif args.residualizedfactoradaptation:
args.integrationmethod = 'rfa'
if args.factoraddition:
args.integrationmethod += '_plus'
elif args.factoraddition:
args.integrationmethod = 'plus'
if args.adaptationfactors:
args.outcomefields = args.outcomefields + args.adaptationfactors
elif args.factoradaptation or args.residualizedfactoradaptation or args.factoraddition:
args.adaptationfactors = args.outcomecontrols
args.outcomefields = args.outcomefields + args.adaptationfactors
if args.fsparams:
args.featureselectionparams = { 'kbest': args.kbest , 'pca': args.pcacomp }
else:
args.featureselectionparams = None
DLAWorker.lexicon_db = args.lexicondb
##Process Arguments
def DLAW():
return DLAWorker(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, wordTable = args.wordTable)
def MA():
return MessageAnnotator(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, wordTable = args.wordTable)
def MT():
return MessageTransformer(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, wordTable = args.wordTable)
def FE():
return FeatureExtractor(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, wordTable = args.wordTable)
def SE():
return SemanticsExtractor(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, args.corpdir, wordTable = args.wordTable)
def OG():
return OutcomeGetter(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, args.outcometable, args.outcomefields, args.outcomecontrols, args.outcomeinteraction, args.cattobinfields, args.cattointfields, args.groupfreqthresh, args.low_variance_thresh, args.featlabelmaptable, args.featlabelmaplex, wordTable = args.wordTable, fold_column = args.fold_column)
def OA():
return OutcomeAnalyzer(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, args.outcometable, args.outcomefields, args.outcomecontrols, args.outcomeinteraction, args.cattobinfields, args.cattointfields, args.groupfreqthresh, args.low_variance_thresh, args.featlabelmaptable, args.featlabelmaplex, wordTable = args.wordTable, output_name = args.outputname)
def FR():
return FeatureRefiner(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, args.feattable, args.featnames, wordTable = args.wordTable)
def FG(featTable = None):
if not featTable:
featTable = args.feattable
return FeatureGetter(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, args.encoding, args.useunicode, args.lexicondb, featTable, args.featnames, wordTable = args.wordTable)
def FGs(featTable = None):
if not featTable:
featTable = args.feattable
if not featTable:
print("Need to specify feature table(s)")
sys.exit(1)
if isinstance(featTable, str):
featTable = [featTable]
return [FeatureGetter(args.corpdb,
args.corptable,
args.correl_field,
args.mysql_host,
args.message_field,
args.messageid_field,
args.encoding,
args.useunicode,
args.lexicondb, featTable,
args.featnames,
wordTable = args.wordTable)
for featTable in featTable]
def TE():
return TopicExtractor(args.corpdb, args.corptable, args.correl_field, args.mysql_host, args.message_field, args.messageid_field, dlac.DEF_ENCODING, dlac.DEF_UNICODE_SWITCH, args.ldamsgtbl)
dlaw = None
ma = None
mt = None
fe = None
se = None
fr = None
og = None
oa = None
fg = None
fgs = None #feature getters
te = None
# if not fe:
# fe = FE()
# fe.addFeatsToLexTable(args.lextable, valueFunc = args.valuefunc, isWeighted=args.weightedlexicon, featValueFunc=args.lexvaluefunc)
# exit()
# SQL interface methods
if args.listfeattables or args.showtables or args.describetables or args.createrandsample or args.viewtables or args.createcopiedtable:
if not dlaw: dlaw = DLAW()
if isinstance(args.describetables, list) and len(args.describetables) == 0:
if not dlaw: dlaw = DLAW()
args.describetables = True
if isinstance(args.viewtables, list) and len(args.viewtables) == 0:
if not dlaw: dlaw = DLAW()
args.viewtables = True
if args.listfeattables or args.showtables:
feat_table = True if args.listfeattables else False
tables = dlaw.getTables(like=args.showtables, feat_table=feat_table)
print('Found %s available tables' % (len(tables)))
for table in tables: print(str(table[0]))
def printTableDesc(description):
header = ['Field', 'Type','Null', 'Key', 'Default', 'Extra']
row_format ="{:>25}{:>25}{:>10}{:>10}{:>10}{:>15}"
print(row_format.format(*header))
for row in description:
print(row_format.format(*[r if r or r == 0 else '' for r in row]))
def printTableData(data):
row_format = "{:>15}" * len(data[0])
for row in data:
print(row_format.format(*[' ' + str(r)[0:14] if r or r == 0 else '' for r in row]))
if args.describetables:
if args.corptable:
printTableDesc(dlaw.describeTable(table_name=args.corptable))
if isinstance(args.feattable, str):
printTableDesc(dlaw.describeTable(table_name=args.feattable))
elif isinstance(args.feattable, list):
for ftable in args.feattable:
printTableDesc(dlaw.describeTable(table_name=ftable))
if args.outcometable:
printTableDesc(dlaw.describeTable(table_name=args.outcometable))
if isinstance(args.describetables, str): args.describetables = [args.describetables]
if isinstance(args.describetables, list):
for tbl in args.describetables: printTableDesc(dlaw.describeTable(table_name=tbl))
if args.viewtables:
if args.corptable:
printTableData(dlaw.viewTable(table_name=args.corptable))
if isinstance(args.feattable, str):
printTableData(dlaw.viewTable(table_name=args.feattable))
elif isinstance(args.feattable, list):
for ftable in args.feattable:
printTableData(dlaw.viewTable(table_name=ftable))
if args.outcometable:
printTableData(dlaw.viewTable(table_name=args.outcometable))
if isinstance(args.viewtables, str): args.viewtables = [args.viewtables]
if isinstance(args.viewtables, list):
for tbl in args.viewtables: printTableData(dlaw.viewTable(table_name=tbl))
if args.createrandsample:
if len(args.createrandsample) > 2:
print("Error: Only two optional arguments for --create_random_sample")
sys.exit(1)
percentage, random_seed = args.createrandsample if len(args.createrandsample) > 1 else (args.createrandsample[0], dlac.DEFAULT_RANDOM_SEED)
rand_table = dlaw.createRandomSample(float(percentage), random_seed, where=args.groupswhere)
if args.createcopiedtable:
if len(args.createcopiedtable) != 2:
print("Error: Need two arguments for --create_copied_table")
sys.exit(1)
new_table = dlaw.createCopiedTable(args.createcopiedtable[0], args.createcopiedtable[1], where=args.groupswhere)
#Feature Extraction:
if args.addngrams:
if not fe: fe = FE()
if args.use_collocs:
pmi_filter_thresh = args.colloc_pmi_thresh if args.colloc_pmi_thresh else dlac.DEF_PMI
collocs_list = fe._getCollocsFromTable(args.colloc_table, pmi_filter_thresh, args.colloc_column, dlac.DEF_COLUMN_PMI_FILTER)
if args.feature_type_name:
feature_type_name = args.feature_type_name
else:
# feature_type_name = "clc" + str(pmi_filter_thresh).replace('.', '_')
feature_type_name = "colloc"
args.feattable = fe.addCollocFeatTable(collocs_list, lowercase_only=args.lowercaseonly, valueFunc = args.valuefunc, includeSubCollocs=args.include_sub_collocs, featureTypeName = feature_type_name)
elif args.gzipcsv:
args.feattable = fe.addNGramTableGzipCsv(args.n, args.gzipcsv, 3, 0, 19, lowercase_only=args.lowercaseonly, valueFunc = args.valuefunc)
else:
ftables = list()
for n in args.n:
ftables.append(fe.addNGramTable(n, lowercase_only=args.lowercaseonly, valueFunc = args.valuefunc, metaFeatures = args.metafeats, extension = args.extension))
if len(ftables) > 1:
args.feattable = ftables;
else:
args.feattable = ftables[0]
if args.addngramsfromtok:
if not fe: fe = FE()
ftables = list()
for n in args.n:
ftables.append(fe.addNGramTableFromTok(n, lowercase_only=args.lowercaseonly, valueFunc = args.valuefunc, metaFeatures = args.metafeats))
if len(ftables) > 1:
args.feattable = ftables;
else:
args.feattable = ftables[0]
if args.addcharngrams:
if not fe: fe = FE()
#elif args.gzipcsv:
# args.feattable = fe.addNGramTableGzipCsv(args.n, args.gzipcsv, 3, 0, 19, lowercase_only=args.lowercaseonly, valueFunc = args.valuefunc)
ftables = list()
for n in args.n:
ftables.append(fe.addCharNGramTable(n, lowercase_only=args.lowercaseonly, valueFunc = args.valuefunc, metaFeatures = args.metafeats))
if len(ftables) > 1:
args.feattable = ftables;
else:
args.feattable = ftables[0]
if args.addlextable:
if not fe: fe = FE()
args.feattable = fe.addLexiconFeat(args.lextable, lowercase_only=args.lowercaseonly, valueFunc = args.valuefunc, isWeighted=args.weightedlexicon, featValueFunc=args.lexvaluefunc, extension=args.extension)
if args.addcorplextable:
if not args.lextable:
print("Need to specify lex table with -l", file=sys.stderr)
sys.exit()
if not fe: fe = FE()
args.feattable = fe.addCorpLexTable(args.lextable, lowercase_only=args.lowercaseonly, valueFunc = args.valuefunc, isWeighted=args.weightedlexicon, featValueFunc=args.lexvaluefunc)
if args.addphrasetable:
if not fe: fe = FE()
args.feattable = fe.addPhraseTable(valueFunc = args.valuefunc)
if args.addpostable or args.pos_ngram:
if not fe: fe = FE()
args.feattable = fe.addPosTable(valueFunc = args.valuefunc, keep_words = args.pos_ngram)
if args.addbert:
if not fe: fe = FE()
args.feattable = fe.addBERTTable(modelName = args.bertmodel, aggregations=args.bertaggs, layersToKeep=args.bertlayers, noContext=args.bertnocontext, layerAggregations = args.bertlayeraggs, valueFunc = args.valuefunc)
if args.addldafeattable:
if not fe: fe = FE()
args.feattable = fe.addLDAFeatTable(args.addldafeattable, valueFunc = args.valuefunc)
if args.addpnames:
if not fe: fe = FE()
namesLex = lexInterface.Lexicon(mysql_host = args.mysql_host)