source: sasview/src/sas/qtgui/Utilities/CategoryInstaller.py @ e958531

Last change on this file since e958531 was 125c4be, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Allow rebuilding of the categories file and plugin_models dir

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