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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 821c330 was 50008e3, checked in by butler, 9 years ago

Fix so 4.0 uses categories.json instead of serialized_cat.json. Thus
this last won't be overwritten and both old SasView? with old model names
and new SasView? with new model names can co-exist.

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