source: framspy/evolalg/utils.py @ 1219

Last change on this file since 1219 was 1190, checked in by Maciej Komosinski, 2 years ago

Added the "evolalg" module for evolutionary optimization

File size: 1.9 KB
Line 
1import argparse
2import os
3
4
5def ensureDir(string):
6    if os.path.isdir(string):
7        return string
8    else:
9        raise NotADirectoryError(string)
10
11def merge_two_parsers(p1,p2):
12    """
13    This function is a modification of  argparse _ActionsContainer._add_container_actions
14    that allows for merging duplicates
15    """
16    # collect groups by titles
17    title_group_map = {}
18    for group in p1._action_groups:
19        if group.title in title_group_map:
20            msg = ('cannot merge actions - two groups are named %r')
21            raise ValueError(msg % (group.title))
22        title_group_map[group.title] = group
23
24    # map each action to its group
25    group_map = {}
26    for group in p2._action_groups:
27
28        # if a group with the title exists, use that, otherwise
29        # create a new group matching the p2's group
30        if group.title not in title_group_map:
31            title_group_map[group.title] = p1.add_argument_group(
32                title=group.title,
33                description=group.description,
34                conflict_handler=group.conflict_handler)
35
36        # map the actions to their new group
37        for action in group._group_actions:
38            group_map[action] = title_group_map[group.title]
39
40    # add p2's mutually exclusive groups
41    # NOTE: if add_mutually_exclusive_group ever gains title= and
42    # description= then this code will need to be expanded as above
43    for group in p2._mutually_exclusive_groups:
44        mutex_group = p1.add_mutually_exclusive_group(
45            required=group.required)
46
47        # map the actions to their new mutex group
48        for action in group._group_actions:
49            group_map[action] = mutex_group
50    # add all actions to this p2 or their group
51    for action in p2._actions:
52        try:
53            group_map.get(action, p1)._add_action(action)
54        except:
55            print("Warning:",action.option_strings, "is a duplicate" )
56    return p1
Note: See TracBrowser for help on using the repository browser.