source: sasview/src/sas/sasgui/guiframe/CategoryInstaller.py @ d3b0c77

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since d3b0c77 was d3b0c77, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

Merge branch 'ticket-887-reorg' into ticket-853-fit-gui-to-calc

  • Property mode set to 100644
File size: 6.1 KB
Line 
1"""
2Class for making sure all category stuff is installed
3and works fine.
4
5Copyright (c) Institut Laue-Langevin 2012
6
7@author kieranrcampbell@gmail.com
8@modified by NIST/MD sasview team
9"""
10
11import os
12import sys
13import json
14import logging
15from collections import defaultdict, OrderedDict
16
17from sas.sasgui import get_user_dir
18
19USER_FILE = 'categories.json'
20
21logger = logging.getLogger(__name__)
22
23class CategoryInstaller(object):
24    """
25    Class for making sure all category stuff is installed
26
27    Note - class is entirely static!
28    """
29
30    @staticmethod
31    def _get_installed_model_dir():
32        """
33        returns the dir where installed_models.txt should be
34        """
35        from sas.sascalc.dataloader.readers import get_data_path
36        return get_data_path()
37
38    @staticmethod
39    def _get_default_cat_file_dir():
40        """
41        returns the dir where default_cat.j should be
42        """
43        # The default categories file is usually found with the code, except
44        # when deploying using py2app (it will be in Contents/Resources), or
45        # py2exe (it will be in the exec dir).
46        import sas.sasview
47        cat_file = "default_categories.json"
48
49        possible_cat_file_paths = [
50            os.path.join(os.path.split(sas.sasview.__file__)[0], cat_file),           # Source
51            os.path.join(os.path.dirname(sys.executable), '..', 'Resources', cat_file), # Mac
52            os.path.join(os.path.dirname(sys.executable), cat_file)                     # Windows
53        ]
54
55        for path in possible_cat_file_paths:
56            if os.path.isfile(path):
57                return os.path.dirname(path)
58
59        raise RuntimeError('CategoryInstaller: Could not find folder containing default categories')
60
61    @staticmethod
62    def _get_home_dir():
63        """
64        returns the users sasview config dir
65        """
66        return os.path.join(os.path.expanduser("~"), ".sasview")
67
68    @staticmethod
69    def _regenerate_model_dict(master_category_dict):
70        """
71        regenerates self.by_model_dict which has each model name as the key
72        and the list of categories belonging to that model
73        along with the enabled mapping
74        returns tuplet (by_model_dict, model_enabled_dict)
75        """
76        by_model_dict = defaultdict(list)
77        model_enabled_dict = defaultdict(bool)
78
79        for category in master_category_dict:
80            for (model, enabled) in master_category_dict[category]:
81                by_model_dict[model].append(category)
82                model_enabled_dict[model] = enabled
83
84        return (by_model_dict, model_enabled_dict)
85
86    @staticmethod
87    def _regenerate_master_dict(by_model_dict, model_enabled_dict):
88        """
89        regenerates master_category_dict from by_model_dict
90        and model_enabled_dict
91        returns the master category dictionary
92        """
93        master_category_dict = defaultdict(list)
94        for model in by_model_dict:
95            for category in by_model_dict[model]:
96                master_category_dict[category].append(\
97                    (model, model_enabled_dict[model]))
98        return OrderedDict(sorted(master_category_dict.items(), key=lambda t: t[0]))
99
100    @staticmethod
101    def get_user_file():
102        """
103        returns the user data file, eg .sasview/categories.json.json
104        """
105        return os.path.join(get_user_dir(), USER_FILE)
106
107    @staticmethod
108    def get_default_file():
109        logger.warning("CategoryInstaller.get_default_file is deprecated.")
110
111    @staticmethod
112    def check_install(homedir = None, model_list=None):
113        """
114        the main method of this class
115        makes sure categories.json exists and if not
116        compile it and install
117        :param homefile: Override the default home directory
118        :param model_list: List of model names except those in Plugin Models
119               which are user supplied.
120        """
121        _model_dict = {model.name: model for model in model_list}
122        _model_list = _model_dict.keys()
123
124        serialized_file = None
125        if homedir is None:
126            serialized_file = CategoryInstaller.get_user_file()
127        else:
128            serialized_file = os.path.join(homedir, USER_FILE)
129        if os.path.isfile(serialized_file):
130            with open(serialized_file, 'rb') as f:
131                master_category_dict = json.load(f)
132        else:
133            master_category_dict = defaultdict(list)
134
135        (by_model_dict, model_enabled_dict) = \
136                CategoryInstaller._regenerate_model_dict(master_category_dict)
137        add_list = _model_list
138        del_name = False
139        for cat in master_category_dict.keys():
140            for ind in range(len(master_category_dict[cat])):
141                model_name, enabled = master_category_dict[cat][ind]
142                if model_name not in _model_list:
143                    del_name = True
144                    try:
145                        by_model_dict.pop(model_name)
146                        model_enabled_dict.pop(model_name)
147                    except Exception:
148                        logger.error("CategoryInstaller: %s", sys.exc_value)
149                else:
150                    add_list.remove(model_name)
151        if del_name or (len(add_list) > 0):
152            for model in add_list:
153                model_enabled_dict[model] = True
154                # TODO: should be:  not _model_dict[model].category
155                if (_model_dict[model].category is None
156                        or len(str(_model_dict[model].category.capitalize())) == 0):
157                    by_model_dict[model].append('Uncategorized')
158                else:
159                    category = _model_dict[model].category
160                    toks = category.split(':')
161                    category = toks[-1]
162                    toks = category.split('-')
163                    capitalized_words = [t.capitalize() for t in toks]
164                    category = ' '.join(capitalized_words)
165
166                    by_model_dict[model].append(category)
167
168            master_category_dict = \
169                CategoryInstaller._regenerate_master_dict(by_model_dict,
170                                                          model_enabled_dict)
171
172            json.dump(master_category_dict, open(serialized_file, 'wb'))
Note: See TracBrowser for help on using the repository browser.