1#!/usr/bin/env python
2"""
3LDfeatureselect.py -
4LD (Lang-Domain) feature extractor
5Marco Lui November 2011
6
7Based on research by Marco Lui and Tim Baldwin.
8
9Copyright 2011 Marco Lui <saffsd@gmail.com>. All rights reserved.
10
11Redistribution and use in source and binary forms, with or without modification, are
12permitted provided that the following conditions are met:
13
14   1. Redistributions of source code must retain the above copyright notice, this list of
15      conditions and the following disclaimer.
16
17   2. Redistributions in binary form must reproduce the above copyright notice, this list
18      of conditions and the following disclaimer in the documentation and/or other materials
19      provided with the distribution.
20
21THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY EXPRESS OR IMPLIED
22WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
23FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
24CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
27ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31The views and conclusions contained in the software and documentation are those of the
32authors and should not be interpreted as representing official policies, either expressed
33or implied, of the copyright holder.
34"""
35
36######
37# Default values
38# Can be overriden with command-line options
39######
40FEATURES_PER_LANG = 300 # number of features to select for each language
41
42import os, sys, argparse
43import csv
44import marshal
45import numpy
46import multiprocessing as mp
47from collections import defaultdict
48
49from common import read_weights, Enumerator, write_features
50
51def select_LD_features(ig_lang, ig_domain, feats_per_lang, ignore_domain=False):
52  """
53  @param ignore_domain boolean to indicate whether to use domain weights
54  """
55  assert (ig_domain is None) or (len(ig_lang) == len(ig_domain))
56  num_lang = len(ig_lang.values()[0])
57  num_term = len(ig_lang)
58
59  term_index = defaultdict(Enumerator())
60
61
62  ld = numpy.empty((num_lang, num_term), dtype=float)
63
64  for term in ig_lang:
65    term_id = term_index[term]
66    if ignore_domain:
67      ld[:, term_id] = ig_lang[term]
68    else:
69      ld[:, term_id] = ig_lang[term] - ig_domain[term]
70
71  terms = sorted(term_index, key=term_index.get)
72  # compile the final feature set
73  selected_features = dict()
74  for lang_id, lang_w in enumerate(ld):
75    term_inds = numpy.argsort(lang_w)[-feats_per_lang:]
76    selected_features[lang_id] = [terms[t] for t in term_inds]
77
78  return selected_features
79
80if __name__ == "__main__":
81  parser = argparse.ArgumentParser()
82  parser.add_argument("-o","--output", metavar="OUTPUT_PATH", help = "write selected features to OUTPUT_PATH")
83  parser.add_argument("--feats_per_lang", type=int, metavar='N', help="select top N features for each language", default=FEATURES_PER_LANG)
84  parser.add_argument("--per_lang", action="store_true", default=False, help="produce a list of features selecter per-language")
85  parser.add_argument("--no_domain_ig", action="store_true", default=False, help="use only per-langugage IG in LD calculation")
86  parser.add_argument("model", metavar='MODEL_DIR', help="read index and produce output in MODEL_DIR")
87  args = parser.parse_args()
88
89  lang_w_path = os.path.join(args.model, 'IGweights.lang.bin')
90  domain_w_path = os.path.join(args.model, 'IGweights.domain')
91  feature_path = args.output if args.output else os.path.join(args.model, 'LDfeats')
92
93  # display paths
94  print "model path:", args.model
95  print "lang weights path:", lang_w_path
96  print "domain weights path:", domain_w_path
97  print "feature output path:", feature_path
98
99  lang_w = read_weights(lang_w_path)
100  domain_w = read_weights(domain_w_path) if not args.no_domain_ig else None
101
102  features_per_lang = select_LD_features(lang_w, domain_w, args.feats_per_lang, ignore_domain=args.no_domain_ig)
103  if args.per_lang:
104    with open(feature_path + '.perlang', 'w') as f:
105      writer = csv.writer(f)
106      for i in range(len(features_per_lang)):
107        writer.writerow(map(repr,features_per_lang[i]))
108
109
110  final_feature_set = reduce(set.union, map(set, features_per_lang.values()))
111  print 'selected %d features' % len(final_feature_set)
112
113  write_features(sorted(final_feature_set), feature_path)
114  print 'wrote features to "%s"' % feature_path
115
116