summaryrefslogtreecommitdiffstats
path: root/tryprune.py
blob: 41a45e9c11341577f88efd3a34598732c149843d (plain)
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
#!/usr/bin/python3
import os
import os.path
import shutil
import sys
from subprocess import Popen, PIPE
from argparse import ArgumentParser
from myconfig import MyConfig
import utils


config = MyConfig()

#change cwd to the libpinyin utils/training directory
libpinyin_dir = config.getToolsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'utils', 'training')
os.chdir(libpinyin_sub_dir)
#chdir done

def validateModel(modelfile):
    #begin processing
    cmdline = ['./validate_k_mixture_model', \
                   modelfile]

    subprocess = Popen(cmdline, shell=False, close_fds=True)

    (pid, status) = os.waitpid(subprocess.pid, 0)
    if status != 0:
        sys.exit('Corrupted model found when validating:' + modelfile)
    #end processing

def exportModel(modelfile, textmodel):
    #begin processing
    cmdline = ['./export_k_mixture_model', \
                   '--k-mixture-model-file', \
                   modelfile]

    subprocess = Popen(cmdline, shell=False, stdout=PIPE, \
                           close_fds=True)

    with open(textmodel, 'wb') as f:
        f.writelines(subprocess.stdout.readlines())
    f.close()

    (pid, status) = os.waitpid(subprocess.pid, 0)
    if status != 0:
        sys.exit('Corrupted model found when exporting:' + modelfile)
    #end processing

def convertModel(kmm_model, inter_model):
    #begin processing
    cmdline = ['./k_mixture_model_to_interpolation']

    subprocess = Popen(cmdline, shell=False, stdin=PIPE, \
                           stdout=PIPE, close_fds=True)
    with open(kmm_model, 'rb') as f:
        subprocess.stdin.writelines(f.readlines())
    f.close()

    with open(inter_model, 'wb') as f:
        f.writelines(subprocess.stdout.readlines())
    f.close()

    (pid, status) = os.waitpid(subprocess.pid, 0)
    if status != 0:
        sys.exit('Corrupted model found when converting:' + kmm_model)
    #end processing

def mergeOneModel(mergedmodel, onemodel, score):
    #validate first
    validateModel(onemodel)

    onemodelstatuspath = onemodel + config.getStatusPostfix()
    onemodelstatus = utils.load_status(onemodelstatuspath)
    if not utils.check_epoch(onemodelstatus, 'Estimate'):
        raise utils.Epoch('Please estimate first.\n')
    if score != onemodelstatus['EstimateScore']:
        raise AssertionError('estimate scores mis-match.\n')

    #begin processing
    cmdline = ['./merge_k_mixture_model', \
                   '--result-file', \
                   mergedmodel, \
                   onemodel]

    subprocess = Popen(cmdline, shell=False, close_fds=True)

    (pid, status) = os.waitpid(subprocess.pid, 0)
    if status != 0:
        sys.exit('Corrupted model found when merging:' + onemodel)
    #end processing

def mergeSomeModels(mergedmodel, sortedindexname, mergenum):
    last_score = 1.
    #begin processing
    indexfile = open(sortedindexname, 'r')
    for i in range(mergenum):
        line = indexfile.readline()
        if not line:
            raise AssertionError('No more models.\n')
        line = line.rstrip(os.linesep)
        (subdir, modelname, score) = line.split('#', 2)
        score = float(score)
        if score > last_score:
            raise AssertionError('scores must be descending.\n')

        onemodel = os.path.join(config.getModelDir(), subdir, modelname)
        mergeOneModel(mergedmodel, onemodel, score)
        last_score = score
    indexfile.close()
    #end processing

    #validate merged model
    validateModel(mergedmodel)

def pruneModel(prunedmodel, k, CDF):
    #begin processing
    cmdline = ['./prune_k_mixture_model', \
               '-k', k, '--CDF', CDF,
               prunedmodel]

    subprocess = Popen(cmdline, shell=False, close_fds=True)

    (pid, status) = os.waitpid(subprocess.pid, 0)
    if (status != 0):
        sys.exit('Corrupted model found when pruning:' + modelfile)
    #end processing

    #validate pruned model
    validateModel(prunedmodel)

if __name__ == '__main__':
    parser = ArgumentParser(description='Try prune models.')
    parser.add_argument('--modeldir', action='store', \
                            help='model directory', \
                            default=config.getModelDir())

    parser.add_argument('--mergenumber', action='store', \
                            help='number of documents to be merged', \
                            default=10, type=int)

    parser.add_argument('-k', action='store', \
                            help='k parameter of k mixture model prune', \
                            default=3, type=int)

    parser.add_argument('--CDF', action='store', \
                            help='CDF parameter of k mixture model prune', \
                            default=0.99, type=float)

    parser.add_argument('tryname', action='store', \
                            help='the storage directory')

    args = parser.parse_args()
    print(args)
    tryname = 'try' + args.tryname

    trydir = os.path.join(config.getFinalDir(), tryname)

    #check try<name> directory
    if os.access(trydir, os.F_OK):
        sys.exit(tryname + ' exists.')

    os.makedirs(trydir)
    cwdstatuspath = os.path.join(trydir, config.getFinalStatusFileName())
    cwdstatus = {}
    cwdstatus['PruneMergeNumber'] = args.mergenumber
    cwdstatus['PruneK'] = args.k
    cwdstatus['PruneCDF'] = args.CDF
    utils.store_status(cwdstatuspath, cwdstatus)

    #merge model candidates
    print('merging')
    mergedmodel = os.path.join(trydir, 'merged.db')
    sortedindexname = os.path.join(args.modeldir, \
                                       config.getSortedEstimateIndex())
    mergeSomeModels(mergedmodel, sortedindexname, args.mergenumber)

    #export textual format
    print('exporting')
    exportfile = os.path.join(trydir, 'kmm_merged.text')
    exportModel(mergedmodel, exportfile)

    #prune merged model
    print('pruning')
    prunedmodel = os.path.join(trydir, 'pruned.db')
    #backup merged model
    shutil.copyfile(mergedmodel, prunedmodel)
    pruneModel(prunedmodel, args.k, args.CDF)

    #export textual format
    print('exporting')
    exportfile = os.path.join(trydir, 'kmm_pruned.text')
    exportModel(prunedmodel, exportfile)

    #convert to interpolation
    print('converting')
    kmm_model = exportfile
    inter_model = os.path.join(trydir, config.getFinalModelFileName())
    convertModel(kmm_model, inter_model)

    #sign status epoch
    utils.sign_epoch(cwdstatus, 'Prune')
    utils.store_status(cwdstatuspath, cwdstatus)
    print('done')