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

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.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 87d44c7 was 463e7ffc, checked in by Ricardo Ferraz Leal <ricleal@…>, 8 years ago

getLogger with module name

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