source: sasview/sansguiframe/src/sans/guiframe/CategoryInstaller.py @ df7a7e3

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 df7a7e3 was df7a7e3, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

merging category branch

  • Property mode set to 100644
File size: 6.8 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
9"""
10
11import os
12import shutil
13import cPickle as pickle
14from collections import defaultdict
15
16user_file = 'serialized_cat.p'
17
18class CategoryInstaller:
19    """
20    Class for making sure all category stuff is installed
21
22    Note - class is entirely static!
23    """
24
25
26    def __init__(self):
27        """ initialization """
28
29    @staticmethod
30    def _get_installed_model_dir():
31        """
32        returns the dir where installed_models.txt should be
33        """
34        import sans.dataloader.readers
35        return sans.dataloader.readers.get_data_path()
36
37    @staticmethod
38    def _get_models_py_dir():
39        """
40        returns the dir where models.py should be
41        """
42        import sans.perspectives.fitting.models
43        return sans.perspectives.fitting.models.get_model_python_path()
44    @staticmethod
45    def _get_default_cat_p_dir():
46        """
47        returns the dir where default_cat.p should be
48        """
49        import sans.dataloader.readers
50        return sans.dataloader.readers.get_data_path()
51
52    @staticmethod
53    def _get_home_dir():
54        """
55        returns the users sansview config dir
56        """
57        return os.path.join(os.path.expanduser("~"),
58                            ".sansview")
59
60    @staticmethod
61    def _regenerate_model_dict(master_category_dict):
62        """
63        regenerates self.by_model_dict which has each model name as the key
64        and the list of categories belonging to that model
65        along with the enabled mapping
66        returns tuplet (by_model_dict, model_enabled_dict)
67        """
68        by_model_dict = defaultdict(list)
69        model_enabled_dict = defaultdict(bool)
70       
71        for category in master_category_dict:
72            for (model, enabled) in master_category_dict[category]:
73                by_model_dict[model].append(category)
74                model_enabled_dict[model] = enabled
75   
76        return (by_model_dict, model_enabled_dict)
77
78
79    @staticmethod
80    def _regenerate_master_dict(by_model_dict, model_enabled_dict):
81        """
82        regenerates master_category_dict from by_model_dict
83        and model_enabled_dict
84        returns the master category dictionary
85        """
86        master_category_dict = defaultdict(list)
87        for model in by_model_dict:
88            for category in by_model_dict[model]:
89                master_category_dict[category].append(\
90                    (model, model_enabled_dict[model]))
91       
92        return master_category_dict
93
94    @staticmethod
95    def get_user_file():
96        """
97        returns the user data file, eg .sansview/serialized_cat.p
98        """
99        return os.path.join(CategoryInstaller._get_home_dir(),
100                            user_file)
101
102    @staticmethod
103    def get_default_file():
104        """
105        returns the path of the default file
106        e.g. blahblah/default_categories.p
107        """
108        return os.path.join(\
109            CategoryInstaller._get_default_cat_p_dir, 
110            "default_categories.p")
111       
112    @staticmethod
113    def check_install(homedir = None, defaultfile = None,
114                      modelsdir = None, installed_models_dir = None):
115        """
116        the main method of this class
117        makes sure serialized_cat.p exists and if not
118        compile it and install
119        :param homefile: Override the default home directory
120        :param defaultfile: Override the default file location
121        :param modelsfile: The file where models.py lives. This
122        MUST be overwritten in setup.py
123        :param installed_models_dir: Where installed_models.txt is to go:
124        """
125        model_list = []
126        serialized_file = None
127        if homedir == None:
128            serialized_file = CategoryInstaller.get_user_file()
129        else:
130            serialized_file = os.path.join(homedir, user_file)
131
132        if os.path.exists(serialized_file):
133            return
134
135        if installed_models_dir == None:
136            installed_models_dir = \
137                CategoryInstaller._get_installed_model_dir() 
138       
139        installed_model_file = open(
140            os.path.join(installed_models_dir,
141                         "installed_models.txt"), 'w')
142
143        if modelsdir == None:
144            modelsdir = CategoryInstaller._get_models_py_dir()
145        python_model_file = open(os.path.join(modelsdir, 
146                                              "models.py"),
147                                 'r')
148
149        python_models = python_model_file.read()
150       
151        # we remove models that appear in the installed
152        # model folder but not in models.py . the excess
153        # hard coded ones on the end come from them being
154        # present in models.py but not actual models, eg
155        # TwoLorenzianModel contains the string 'Lorenzian'
156        # but we don't actually want to include Lorenzian
157        model_list = [mod for mod in model_list if \
158                          mod in python_models and \
159                          not 'init' in mod and \
160                          not 'BaseComponent' in mod \
161                          and not 'MultiplicationModel' in mod \
162                          and not 'pluginmodel' in mod \
163                          and mod != 'PowerLawModel' \
164                          and mod != 'Lorentzian']
165
166       
167        for mod in model_list:
168            installed_model_file.write(mod + '\n')
169       
170        installed_model_file.close()
171
172        # start sorting category stuff
173        default_file = None
174        if defaultfile == None:
175            default_file = CategoryInstaller.get_default_file()
176        else:
177            default_file = defaultfile
178
179        master_category_dict = pickle.load(open(default_file, 'rb'))
180       
181        (by_model_dict, model_enabled_dict) = \
182            CategoryInstaller._regenerate_model_dict(master_category_dict)
183           
184           
185        for found_model in model_list:
186            if not found_model in by_model_dict:
187                print found_model + ' : ' + str(by_model_dict[found_model]) 
188                by_model_dict[found_model].append("Uncategorized")
189                model_enabled_dict[found_model] = True
190
191                # remove any stray models from categorization
192                # that aren't stored anymore
193
194        models_to_delete = []
195        for model in by_model_dict:
196            if not model in model_list:
197                models_to_delete.append(model)
198
199        for model in models_to_delete:
200            by_model_dict.pop(model)
201
202        master_category_dict = \
203            CategoryInstaller._regenerate_master_dict(by_model_dict,
204                                                      model_enabled_dict)
205       
206        pickle.dump( master_category_dict,
207                     open(default_file, 'wb') )
208
209        #shutil.copyfile(default_file, serialized_file)
Note: See TracBrowser for help on using the repository browser.