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

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 60a7820 was 914ba0a, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

merge with master

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