parameter_generator.py 12.4 KB
Newer Older
1
# coding: utf-8
2
3
4
"""Helper script for generating config file and parameters list.

This script generates LightGBM/src/io/config_auto.cpp file
5
6
7
8
with list of all parameters, aliases table and other routines
along with parameters description in LightGBM/docs/Parameters.rst file
from the information in LightGBM/include/LightGBM/config.h file.
"""
Guolin Ke's avatar
Guolin Ke committed
9
10
11
import os


12
13
14
15
16
17
18
19
20
21
22
23
24
def get_parameter_infos(config_hpp):
    """Parse config header file.

    Parameters
    ----------
    config_hpp : string
        Path to the config header file.

    Returns
    -------
    infos : tuple
        Tuple with names and content of sections.
    """
Guolin Ke's avatar
Guolin Ke committed
25
26
    is_inparameter = False
    cur_key = None
27
    key_lvl = 0
Guolin Ke's avatar
Guolin Ke committed
28
29
30
31
32
33
34
35
    cur_info = {}
    keys = []
    member_infos = []
    with open(config_hpp) as config_hpp_file:
        for line in config_hpp_file:
            if "#pragma region Parameters" in line:
                is_inparameter = True
            elif "#pragma region" in line and "Parameters" in line:
36
                key_lvl += 1
Guolin Ke's avatar
Guolin Ke committed
37
                cur_key = line.split("region")[1].strip()
38
                keys.append((cur_key, key_lvl))
Guolin Ke's avatar
Guolin Ke committed
39
40
                member_infos.append([])
            elif '#pragma endregion' in line:
41
                key_lvl -= 1
Guolin Ke's avatar
Guolin Ke committed
42
43
44
45
46
47
48
                if cur_key is not None:
                    cur_key = None
                elif is_inparameter:
                    is_inparameter = False
            elif cur_key is not None:
                line = line.strip()
                if line.startswith("//"):
49
50
51
                    key, _, val = line[2:].partition("=")
                    key = key.strip()
                    val = val.strip()
Guolin Ke's avatar
Guolin Ke committed
52
                    if key not in cur_info:
53
                        if key == "descl2" and "desc" not in cur_info:
Guolin Ke's avatar
Guolin Ke committed
54
                            cur_info["desc"] = []
55
                        elif key != "descl2":
Guolin Ke's avatar
Guolin Ke committed
56
57
                            cur_info[key] = []
                    if key == "desc":
58
                        cur_info["desc"].append(("l1", val))
Guolin Ke's avatar
Guolin Ke committed
59
                    elif key == "descl2":
60
                        cur_info["desc"].append(("l2", val))
Guolin Ke's avatar
Guolin Ke committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
                    else:
                        cur_info[key].append(val)
                elif line:
                    has_eqsgn = False
                    tokens = line.split("=")
                    if len(tokens) == 2:
                        if "default" not in cur_info:
                            cur_info["default"] = [tokens[1][:-1].strip()]
                        has_eqsgn = True
                    tokens = line.split()
                    cur_info["inner_type"] = [tokens[0].strip()]
                    if "name" not in cur_info:
                        if has_eqsgn:
                            cur_info["name"] = [tokens[1].strip()]
                        else:
                            cur_info["name"] = [tokens[1][:-1].strip()]
                    member_infos[-1].append(cur_info)
                    cur_info = {}
79
    return keys, member_infos
Guolin Ke's avatar
Guolin Ke committed
80
81


82
83
84
85
86
87
88
89
90
91
92
93
94
def get_names(infos):
    """Get names of all parameters.

    Parameters
    ----------
    infos : list
        Content of the config header file.

    Returns
    -------
    names : list
        Names of all parameters.
    """
Guolin Ke's avatar
Guolin Ke committed
95
96
97
98
99
100
101
    names = []
    for x in infos:
        for y in x:
            names.append(y["name"][0])
    return names


102
103
104
105
106
107
108
109
110
111
112
113
114
def get_alias(infos):
    """Get aliases of all parameters.

    Parameters
    ----------
    infos : list
        Content of the config header file.

    Returns
    -------
    pairs : list
        List of tuples (param alias, param name).
    """
Guolin Ke's avatar
Guolin Ke committed
115
116
117
118
119
120
121
    pairs = []
    for x in infos:
        for y in x:
            if "alias" in y:
                name = y["name"][0]
                alias = y["alias"][0].split(',')
                for name2 in alias:
122
                    pairs.append((name2.strip(), name))
Guolin Ke's avatar
Guolin Ke committed
123
124
125
    return pairs


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
def parse_check(check, reverse=False):
    """Parse the constraint.

    Parameters
    ----------
    check : string
        String representation of the constraint.
    reverse : bool, optional (default=False)
        Whether to reverse the sign of the constraint.

    Returns
    -------
    pair : tuple
        Parsed constraint in the form of tuple (value, sign).
    """
    try:
        idx = 1
        float(check[idx:])
    except ValueError:
        idx = 2
        float(check[idx:])
    if reverse:
        reversed_sign = {'<': '>', '>': '<', '<=': '>=', '>=': '<='}
        return check[idx:], reversed_sign[check[:idx]]
    else:
        return check[idx:], check[:idx]


154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def set_one_var_from_string(name, param_type, checks):
    """Construct code for auto config file for one param value.

    Parameters
    ----------
    name : string
        Name of the parameter.
    param_type : string
        Type of the parameter.
    checks : list
        Constraints of the parameter.

    Returns
    -------
    ret : string
        Lines of auto config file with getting and checks of one parameter value.
    """
Guolin Ke's avatar
Guolin Ke committed
171
172
    ret = ""
    univar_mapper = {"int": "GetInt", "double": "GetDouble", "bool": "GetBool", "std::string": "GetString"}
173
174
    if "vector" not in param_type:
        ret += "  %s(params, \"%s\", &%s);\n" % (univar_mapper[param_type], name, name)
Guolin Ke's avatar
Guolin Ke committed
175
        if len(checks) > 0:
176
            check_mapper = {"<": "LT", ">": "GT", "<=": "LE", ">=": "GE"}
Guolin Ke's avatar
Guolin Ke committed
177
            for check in checks:
178
179
                value, sign = parse_check(check)
                ret += "  CHECK_%s(%s, %s);\n" % (check_mapper[sign], name, value)
Guolin Ke's avatar
Guolin Ke committed
180
181
182
        ret += "\n"
    else:
        ret += "  if (GetString(params, \"%s\", &tmp_str)) {\n" % (name)
183
        type2 = param_type.split("<")[1][:-1]
Guolin Ke's avatar
Guolin Ke committed
184
185
186
187
188
189
190
191
        if type2 == "std::string":
            ret += "    %s = Common::Split(tmp_str.c_str(), ',');\n" % (name)
        else:
            ret += "    %s = Common::StringToArray<%s>(tmp_str, ',');\n" % (name, type2)
        ret += "  }\n\n"
    return ret


192
193
def gen_parameter_description(sections, descriptions, params_rst):
    """Write descriptions of parameters to the documentation file.
194

195
196
197
198
199
200
201
202
203
    Parameters
    ----------
    sections : list
        Names of parameters sections.
    descriptions : list
        Structured descriptions of parameters.
    params_rst : string
        Path to the file with parameters documentation.
    """
204
    params_to_write = []
205
206
207
208
    lvl_mapper = {1: '-', 2: '~'}
    for (section_name, section_lvl), section_params in zip(sections, descriptions):
        heading_sign = lvl_mapper[section_lvl]
        params_to_write.append('{0}\n{1}'.format(section_name, heading_sign * len(section_name)))
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
        for param_desc in section_params:
            name = param_desc['name'][0]
            default_raw = param_desc['default'][0]
            default = default_raw.strip('"') if len(default_raw.strip('"')) > 0 else default_raw
            param_type = param_desc.get('type', param_desc['inner_type'])[0].split(':')[-1].split('<')[-1].strip('>')
            options = param_desc.get('options', [])
            if len(options) > 0:
                options_str = ', options: ``{0}``'.format('``, ``'.join([x.strip() for x in options[0].split(',')]))
            else:
                options_str = ''
            aliases = param_desc.get('alias', [])
            if len(aliases) > 0:
                aliases_str = ', aliases: ``{0}``'.format('``, ``'.join([x.strip() for x in aliases[0].split(',')]))
            else:
                aliases_str = ''
            checks = sorted(param_desc.get('check', []))
            checks_len = len(checks)
            if checks_len > 1:
                number1, sign1 = parse_check(checks[0])
                number2, sign2 = parse_check(checks[1], reverse=True)
229
                checks_str = ', constraints: ``{0} {1} {2} {3} {4}``'.format(number2, sign2, name, sign1, number1)
230
231
            elif checks_len == 1:
                number, sign = parse_check(checks[0])
232
                checks_str = ', constraints: ``{0} {1} {2}``'.format(name, sign, number)
233
234
            else:
                checks_str = ''
235
            main_desc = '-  ``{0}`` :raw-html:`<a id="{0}" title="Permalink to this parameter" href="#{0}">&#x1F517;&#xFE0E;</a>`, default = ``{1}``, type = {2}{3}{4}{5}'.format(name, default, param_type, options_str, aliases_str, checks_str)
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
            params_to_write.append(main_desc)
            params_to_write.extend([' ' * 3 * int(desc[0][-1]) + '-  ' + desc[1] for desc in param_desc['desc']])

    with open(params_rst) as original_params_file:
        all_lines = original_params_file.read()
        before, start_sep, _ = all_lines.partition('.. start params list\n\n')
        _, end_sep, after = all_lines.partition('\n\n.. end params list')

    with open(params_rst, "w") as new_params_file:
        new_params_file.write(before)
        new_params_file.write(start_sep)
        new_params_file.write('\n\n'.join(params_to_write))
        new_params_file.write(end_sep)
        new_params_file.write(after)


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def gen_parameter_code(config_hpp, config_out_cpp):
    """Generate auto config file.

    Parameters
    ----------
    config_hpp : string
        Path to the config header file.
    config_out_cpp : string
        Path to the auto config file.

    Returns
    -------
    infos : tuple
        Tuple with names and content of sections.
    """
    keys, infos = get_parameter_infos(config_hpp)
    names = get_names(infos)
    alias = get_alias(infos)
270
271
272
273
274
275
276
277
    str_to_write = r"""/*!
 * Copyright (c) 2018 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 *
 * \note
 * This file is auto generated by LightGBM\helpers\parameter_generator.py from LightGBM\include\LightGBM\config.h file.
 */
"""
Guolin Ke's avatar
Guolin Ke committed
278
279
    str_to_write += "#include<LightGBM/config.h>\nnamespace LightGBM {\n"
    # alias table
jcipar's avatar
jcipar committed
280
281
282
    str_to_write += "const std::unordered_map<std::string, std::string>& Config::alias_table() {\n"
    str_to_write += "  static std::unordered_map<std::string, std::string> aliases({\n"

Guolin Ke's avatar
Guolin Ke committed
283
    for pair in alias:
284
        str_to_write += "  {\"%s\", \"%s\"},\n" % (pair[0], pair[1])
jcipar's avatar
jcipar committed
285
286
287
288
    str_to_write += "  });\n"
    str_to_write += "  return aliases;\n"
    str_to_write += "}\n\n"

Guolin Ke's avatar
Guolin Ke committed
289
    # names
jcipar's avatar
jcipar committed
290
291
292
    str_to_write += "const std::unordered_set<std::string>& Config::parameter_set() {\n"
    str_to_write += "  static std::unordered_set<std::string> params({\n"

Guolin Ke's avatar
Guolin Ke committed
293
    for name in names:
294
        str_to_write += "  \"%s\",\n" % (name)
jcipar's avatar
jcipar committed
295
296
297
    str_to_write += "  });\n"
    str_to_write += "  return params;\n"
    str_to_write += "}\n\n"
Guolin Ke's avatar
Guolin Ke committed
298
299
300
301
302
303
304
    # from strings
    str_to_write += "void Config::GetMembersFromString(const std::unordered_map<std::string, std::string>& params) {\n"
    str_to_write += "  std::string tmp_str = \"\";\n"
    for x in infos:
        for y in x:
            if "[doc-only]" in y:
                continue
305
            param_type = y["inner_type"][0]
Guolin Ke's avatar
Guolin Ke committed
306
307
308
309
            name = y["name"][0]
            checks = []
            if "check" in y:
                checks = y["check"]
310
            tmp = set_one_var_from_string(name, param_type, checks)
Guolin Ke's avatar
Guolin Ke committed
311
312
            str_to_write += tmp
    # tails
313
    str_to_write = str_to_write.strip() + "\n}\n\n"
Guolin Ke's avatar
Guolin Ke committed
314
315
316
317
318
319
    str_to_write += "std::string Config::SaveMembersToString() const {\n"
    str_to_write += "  std::stringstream str_buf;\n"
    for x in infos:
        for y in x:
            if "[doc-only]" in y:
                continue
320
            param_type = y["inner_type"][0]
Guolin Ke's avatar
Guolin Ke committed
321
            name = y["name"][0]
322
323
            if "vector" in param_type:
                if "int8" in param_type:
324
                    str_to_write += "  str_buf << \"[%s: \" << Common::Join(Common::ArrayCast<int8_t, int>(%s), \",\") << \"]\\n\";\n" % (name, name)
Guolin Ke's avatar
Guolin Ke committed
325
                else:
326
                    str_to_write += "  str_buf << \"[%s: \" << Common::Join(%s, \",\") << \"]\\n\";\n" % (name, name)
Guolin Ke's avatar
Guolin Ke committed
327
328
329
330
331
            else:
                str_to_write += "  str_buf << \"[%s: \" << %s << \"]\\n\";\n" % (name, name)
    # tails
    str_to_write += "  return str_buf.str();\n"
    str_to_write += "}\n\n"
332
    str_to_write += "}  // namespace LightGBM\n"
Guolin Ke's avatar
Guolin Ke committed
333
334
335
    with open(config_out_cpp, "w") as config_out_cpp_file:
        config_out_cpp_file.write(str_to_write)

336
337
    return keys, infos

Guolin Ke's avatar
Guolin Ke committed
338
339

if __name__ == "__main__":
340
341
342
343
    current_dir = os.path.abspath(os.path.dirname(__file__))
    config_hpp = os.path.join(current_dir, os.path.pardir, 'include', 'LightGBM', 'config.h')
    config_out_cpp = os.path.join(current_dir, os.path.pardir, 'src', 'io', 'config_auto.cpp')
    params_rst = os.path.join(current_dir, os.path.pardir, 'docs', 'Parameters.rst')
344
345
    sections, descriptions = gen_parameter_code(config_hpp, config_out_cpp)
    gen_parameter_description(sections, descriptions, params_rst)