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

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 1cdbcd8 was 65f3930, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

move models.py to sascalc/fit

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