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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since ddbac66 was ddbac66, checked in by butler, 7 years ago

Fix remaining custom/customized to plugin conversion

  • Property mode set to 100644
File size: 6.5 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 those in Plugin Models
126               which are user supplied.
127        """
128        _model_dict = { model.name: model for model in model_list}
129        _model_list = _model_dict.keys()
130
131        serialized_file = None
132        if homedir == None:
133            serialized_file = CategoryInstaller.get_user_file()
134        else:
135            serialized_file = os.path.join(homedir, USER_FILE)
136        if os.path.isfile(serialized_file):
137            with open(serialized_file, 'rb') as f:
138                master_category_dict = json.load(f)
139        else:
140            master_category_dict = defaultdict(list)
141
142        (by_model_dict, model_enabled_dict) = \
143                CategoryInstaller._regenerate_model_dict(master_category_dict)
144        add_list = _model_list
145        del_name = False
146        for cat in master_category_dict.keys():
147            for ind in range(len(master_category_dict[cat])):
148                model_name, enabled = master_category_dict[cat][ind]
149                if model_name not in _model_list:
150                    del_name = True 
151                    try:
152                        by_model_dict.pop(model_name)
153                        model_enabled_dict.pop(model_name)
154                    except:
155                        logging.error("CategoryInstaller: %s", sys.exc_value)
156                else:
157                    add_list.remove(model_name)
158        if del_name or (len(add_list) > 0):
159            for model in add_list:
160                model_enabled_dict[model]= True
161                if _model_dict[model].category is None or len(str(_model_dict[model].category.capitalize())) == 0:
162                    by_model_dict[model].append('Uncategorized')
163                else:
164                    category = _model_dict[model].category
165                    toks = category.split(':')
166                    category = toks[-1]
167                    toks = category.split('-')
168                    capitalized_words = [t.capitalize() for t in toks]
169                    category = ' '.join(capitalized_words)
170
171                    by_model_dict[model].append(category)
172
173            master_category_dict = \
174                CategoryInstaller._regenerate_master_dict(by_model_dict,
175                                                          model_enabled_dict)
176
177            json.dump(master_category_dict, open(serialized_file, 'wb'))
Note: See TracBrowser for help on using the repository browser.