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

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 899e084 was efe730d, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

move sasview to src/sas/sasview and refactor bundled apps for easier debugging

  • Property mode set to 100644
File size: 6.0 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
14from collections import defaultdict
15
16from sas.sasgui import get_user_dir
17
18USER_FILE = 'categories.json'
19
20class CategoryInstaller:
21    """
22    Class for making sure all category stuff is installed
23
24    Note - class is entirely static!
25    """
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        import sas.sascalc.dataloader.readers
37        return sas.sascalc.dataloader.readers.get_data_path()
38
39    @staticmethod
40    def _get_models_py_dir():
41        """
42        returns the dir where models.py should be
43        """
44        import sas.sasgui.perspectives.fitting.models
45        return sas.sasgui.perspectives.fitting.models.get_model_python_path()
46   
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"
57       
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)
67           
68        raise RuntimeError('CategoryInstaller: Could not find folder containing default categories')
69
70    @staticmethod
71    def _regenerate_model_dict(master_category_dict):
72        """
73        regenerates self.by_model_dict which has each model name as the key
74        and the list of categories belonging to that model
75        along with the enabled mapping
76        returns tuplet (by_model_dict, model_enabled_dict)
77        """
78        by_model_dict = defaultdict(list)
79        model_enabled_dict = defaultdict(bool)
80       
81        for category in master_category_dict:
82            for (model, enabled) in master_category_dict[category]:
83                by_model_dict[model].append(category)
84                model_enabled_dict[model] = enabled
85   
86        return (by_model_dict, model_enabled_dict)
87
88
89    @staticmethod
90    def _regenerate_master_dict(by_model_dict, model_enabled_dict):
91        """
92        regenerates master_category_dict from by_model_dict
93        and model_enabled_dict
94        returns the master category dictionary
95        """
96        master_category_dict = defaultdict(list)
97        for model in by_model_dict:
98            for category in by_model_dict[model]:
99                master_category_dict[category].append(\
100                    (model, model_enabled_dict[model]))
101       
102        return master_category_dict
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        """
114        returns the path of the default file
115        e.g. blahblah/default_categories.json
116        """
117        return os.path.join(\
118            CategoryInstaller._get_default_cat_file_dir(), "default_categories.json")
119       
120    @staticmethod
121    def check_install(homedir = None, model_list=None):
122        """
123        the main method of this class
124        makes sure categories.json exists and if not
125        compile it and install
126        :param homefile: Override the default home directory
127        :param model_list: List of model names except customized models
128        """
129        #model_list = []
130        default_file = CategoryInstaller.get_default_file()
131        serialized_file = None
132        master_category_dict = defaultdict(list)
133        if homedir == None:
134            serialized_file = CategoryInstaller.get_user_file()
135        else:
136            serialized_file = os.path.join(homedir, USER_FILE)
137        if os.path.isfile(serialized_file):
138            cat_file = open(serialized_file, 'rb')
139        else:
140            cat_file = open(default_file, 'rb')
141        master_category_dict = json.load(cat_file)
142#        master_category_dict = pickle.Unpickler(cat_file).load()
143        (by_model_dict, model_enabled_dict) = \
144                CategoryInstaller._regenerate_model_dict(master_category_dict)
145        cat_file.close()
146        add_list = model_list
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]
151                if model_name not in model_list:
152                    del_name = True 
153                    try:
154                        by_model_dict.pop(model_name)
155                        model_enabled_dict.pop(model_name)
156                    except:
157                        pass
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
163                by_model_dict[model].append('Uncategorized')
164   
165            master_category_dict = \
166                CategoryInstaller._regenerate_master_dict(by_model_dict,
167                                                          model_enabled_dict)
168           
169            json.dump( master_category_dict,
170                         open(serialized_file, 'wb') )
Note: See TracBrowser for help on using the repository browser.