source: sasview/src/sans/guiframe/CategoryInstaller.py @ e090c624

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.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since e090c624 was 16bd5ca, checked in by Mathieu Doucet <doucetm@…>, 11 years ago

Find default categories with p2app

  • Property mode set to 100644
File size: 6.1 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 cPickle as pickle
15from collections import defaultdict
16
17USER_FILE = 'serialized_cat.p'
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 sans.dataloader.readers
36        return sans.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 sans.perspectives.fitting.models
44        return sans.perspectives.fitting.models.get_model_python_path()
45   
46    @staticmethod
47    def _get_default_cat_p_dir():
48        """
49        returns the dir where default_cat.p should be
50        """
51        # The default categories file is usually found with the code
52        import sans.sansview
53        cat_file = "default_categories.p"
54        dir, file_name = os.path.split(sans.sansview.__file__)
55        cat_file_path = os.path.join(dir, cat_file)
56        if os.path.isfile(cat_file_path):
57            cat_file_dir = os.path.dirname(cat_file_path)
58            return cat_file_dir
59       
60        # When deploying using py2app, the default categories file
61        # can be found in Contents/Resources
62        cat_file_path = os.path.join(os.path.dirname(sys.executable), '..', 'Resources', 'default_categories.p')
63        if os.path.isfile(cat_file_path):
64            cat_file_dir = os.path.dirname(cat_file_path)
65            return cat_file_dir
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 sansview 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/serialized_cat.p
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.p
123        """
124        return os.path.join(\
125            CategoryInstaller._get_default_cat_p_dir(), "default_categories.p")
126       
127    @staticmethod
128    def check_install(homedir = None, model_list=None):
129        """
130        the main method of this class
131        makes sure serialized_cat.p 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 = pickle.Unpickler(cat_file).load()
149        (by_model_dict, model_enabled_dict) = \
150                CategoryInstaller._regenerate_model_dict(master_category_dict)
151        cat_file.close()
152        add_list = model_list
153        del_name = False
154        for cat in master_category_dict.keys():
155            for ind in range(len(master_category_dict[cat])):
156                model_name, enabled = master_category_dict[cat][ind]
157                if model_name not in model_list:
158                    del_name = True 
159                    try:
160                        by_model_dict.pop(model_name)
161                        model_enabled_dict.pop(model_name)
162                    except:
163                        pass
164                else:
165                    add_list.remove(model_name)
166        if del_name or (len(add_list) > 0):
167            for model in add_list:
168                model_enabled_dict[model]= True
169                by_model_dict[model].append('Uncategorized')
170   
171            master_category_dict = \
172                CategoryInstaller._regenerate_master_dict(by_model_dict,
173                                                          model_enabled_dict)
174           
175            pickle.dump( master_category_dict,
176                         open(serialized_file, 'wb') )
177           
178            try:
179                #It happens only in source environment
180                shutil.copyfile(serialized_file, default_file)
181            except:
182                pass
183       
Note: See TracBrowser for help on using the repository browser.