source: sasview/src/sas/sasview/sasview.py @ 20fa5fe

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 20fa5fe was 20fa5fe, checked in by Stuart Prescott <stuart@…>, 21 months ago

Fix lots more typos in comments and docs

  • Property mode set to 100644
File size: 9.0 KB
Line 
1# -*- coding: utf-8 -*-
2"""
3Base module for loading and running the main SasView application.
4"""
5################################################################################
6# This software was developed by the University of Tennessee as part of the
7# Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
8# project funded by the US National Science Foundation.
9#
10# See the license text in license.txt
11#
12# copyright 2009, University of Tennessee
13################################################################################
14import os
15import os.path
16import sys
17import traceback
18import logging
19
20try:
21    reload(sys)
22    sys.setdefaultencoding("iso-8859-1")
23except NameError:
24    # On python 3 sys.setdefaultencoding does nothing, so pass.
25    # We know we are in python 3 at this point since reload is no longer in
26    # builtins, but instead has been moved to importlib, hence the NameError.
27    pass
28
29import sas
30
31APP_NAME = 'SasView'
32PLUGIN_MODEL_DIR = 'plugin_models'
33
34class SasView(object):
35    """
36    Main class for running the SasView application
37    """
38    def __init__(self):
39        """
40        """
41        logger = logging.getLogger(__name__)
42
43        from sas.sasgui.guiframe.gui_manager import SasViewApp
44        self.gui = SasViewApp(0)
45        # Set the application manager for the GUI
46        self.gui.set_manager(self)
47        # Add perspectives to the basic application
48        # Additional perspectives can still be loaded
49        # dynamically
50        # Note: py2exe can't find dynamically loaded
51        # modules. We load the fitting module here
52        # to ensure a complete Windows executable build.
53
54        # Rebuild .sasview/categories.json.  This triggers a load of sasmodels
55        # and all the plugins.
56        try:
57            from sas.sascalc.fit.models import ModelManager
58            from sas.sasgui.guiframe.CategoryInstaller import CategoryInstaller
59            model_list = ModelManager().cat_model_list()
60            CategoryInstaller.check_install(model_list=model_list)
61        except Exception:
62            logger.error("%s: could not load SasView models")
63            logger.error(traceback.format_exc())
64
65        # Fitting perspective
66        try:
67            import sas.sasgui.perspectives.fitting as module
68            fitting_plug = module.Plugin()
69            self.gui.add_perspective(fitting_plug)
70        except Exception:
71            logger.error("%s: could not find Fitting plug-in module", APP_NAME)
72            logger.error(traceback.format_exc())
73
74        # P(r) perspective
75        try:
76            import sas.sasgui.perspectives.pr as module
77            pr_plug = module.Plugin()
78            self.gui.add_perspective(pr_plug)
79        except Exception:
80            logger.error("%s: could not find P(r) plug-in module", APP_NAME)
81            logger.error(traceback.format_exc())
82
83        # Invariant perspective
84        try:
85            import sas.sasgui.perspectives.invariant as module
86            invariant_plug = module.Plugin()
87            self.gui.add_perspective(invariant_plug)
88        except Exception:
89            logger.error("%s: could not find Invariant plug-in module",
90                         APP_NAME)
91            logger.error(traceback.format_exc())
92
93        # Corfunc perspective
94        try:
95            import sas.sasgui.perspectives.corfunc as module
96            corfunc_plug = module.Plugin()
97            self.gui.add_perspective(corfunc_plug)
98        except Exception:
99            logger.error("Unable to load corfunc module")
100
101        # Calculator perspective
102        try:
103            import sas.sasgui.perspectives.calculator as module
104            calculator_plug = module.Plugin()
105            self.gui.add_perspective(calculator_plug)
106        except Exception:
107            logger.error("%s: could not find Calculator plug-in module",
108                         APP_NAME)
109            logger.error(traceback.format_exc())
110
111        # File converter tool
112        try:
113            import sas.sasgui.perspectives.file_converter as module
114            converter_plug = module.Plugin()
115            self.gui.add_perspective(converter_plug)
116        except Exception:
117            logger.error("%s: could not find File Converter plug-in module",
118                         APP_NAME)
119            logger.error(traceback.format_exc())
120
121        # Add welcome page
122        from .welcome_panel import WelcomePanel
123        self.gui.set_welcome_panel(WelcomePanel)
124
125        # Build the GUI
126        self.gui.build_gui()
127        # delete unused model folder
128        self.gui.clean_plugin_models(PLUGIN_MODEL_DIR)
129        # Start the main loop
130        self.gui.MainLoop()
131
132
133def setup_logging():
134    from sas.logger_config import SetupLogger
135
136    logger = SetupLogger(__name__).config_production()
137    # Log the start of the session
138    logger.info(" --- SasView session started ---")
139    # Log the python version
140    logger.info("Python: %s" % sys.version)
141    return logger
142
143
144def setup_wx():
145    # Allow the dynamic selection of wxPython via an environment variable, when devs
146    # who have multiple versions of the module installed want to pick between them.
147    # This variable does not have to be set of course, and through normal usage will
148    # probably not be, but this can make things a little easier when upgrading to a
149    # new version of wx.
150    logger = logging.getLogger(__name__)
151    WX_ENV_VAR = "SASVIEW_WX_VERSION"
152    if WX_ENV_VAR in os.environ:
153        logger.info("You have set the %s environment variable to %s.",
154                    WX_ENV_VAR, os.environ[WX_ENV_VAR])
155        import wxversion
156        if wxversion.checkInstalled(os.environ[WX_ENV_VAR]):
157            logger.info("Version %s of wxPython is installed, so using that version.",
158                        os.environ[WX_ENV_VAR])
159            wxversion.select(os.environ[WX_ENV_VAR])
160        else:
161            logger.error("Version %s of wxPython is not installed, so using default version.",
162                         os.environ[WX_ENV_VAR])
163    else:
164        logger.info("You have not set the %s environment variable, so using default version of wxPython.",
165                    WX_ENV_VAR)
166
167    import wx
168
169    try:
170        logger.info("Wx version: %s", wx.__version__)
171    except AttributeError:
172        logger.error("Wx version: error reading version")
173
174    from . import wxcruft
175    wxcruft.call_later_fix()
176    #wxcruft.trace_new_id()
177    #Always use private .matplotlib setup to avoid conflicts with other
178    #uses of matplotlib
179
180
181def setup_mpl(backend=None):
182    # Always use private .matplotlib setup to avoid conflicts with other
183    mplconfigdir = os.path.join(sas.get_user_dir(), '.matplotlib')
184    if not os.path.exists(mplconfigdir):
185        os.mkdir(mplconfigdir)
186    os.environ['MPLCONFIGDIR'] = mplconfigdir
187    # Set backend to WXAgg; this overrides matplotlibrc, but shouldn't override
188    # mpl.use().  Note: Don't import matplotlib here since the script that
189    # we are running may not actually need it; also, putting as little on the
190    # path as we can
191    if backend:
192        os.environ['MPLBACKEND'] = backend
193
194    # TODO: ... so much for not importing matplotlib unless we need it...
195    from matplotlib import backend_bases
196    backend_bases.FigureCanvasBase.filetypes.pop('pgf', None)
197
198def setup_sasmodels():
199    """
200    Prepare sasmodels for running within sasview.
201    """
202    # Set SAS_MODELPATH so sasmodels can find our custom models
203    plugin_dir = os.path.join(sas.get_user_dir(), PLUGIN_MODEL_DIR)
204    os.environ['SAS_MODELPATH'] = plugin_dir
205    #Initialize environment variable with custom setting but only if variable not set
206    SAS_OPENCL = sas.get_custom_config().SAS_OPENCL
207    if SAS_OPENCL and "SAS_OPENCL" not in os.environ:
208        os.environ["SAS_OPENCL"] = SAS_OPENCL
209
210def run_gui():
211    """
212    __main__ method for loading and running SasView
213    """
214    from multiprocessing import freeze_support
215    freeze_support()
216    setup_logging()
217    setup_mpl(backend='WXAgg')
218    setup_sasmodels()
219    setup_wx()
220    SasView()
221
222
223def run_cli():
224    from multiprocessing import freeze_support
225    freeze_support()
226    setup_logging()
227    # Use default matplotlib backend on mac/linux, but wx on windows.
228    # The problem on mac is that the wx backend requires pythonw.  On windows
229    # we are sure to wx since it is the shipped with the app.
230    setup_mpl(backend='WXAgg' if os.name == 'nt' else None)
231    setup_sasmodels()
232    if len(sys.argv) == 1 or sys.argv[1] == '-i':
233        # Run sasview as an interactive python interpreter
234        try:
235            from IPython import start_ipython
236            sys.argv = ["ipython", "--pylab"]
237            sys.exit(start_ipython())
238        except ImportError:
239            import code
240            code.interact(local={'exit': sys.exit})
241    elif sys.argv[1] == '-c':
242        exec(sys.argv[2])
243    else:
244        thing_to_run = sys.argv[1]
245        sys.argv = sys.argv[1:]
246        import runpy
247        if os.path.exists(thing_to_run):
248            runpy.run_path(thing_to_run, run_name="__main__")
249        else:
250            runpy.run_module(thing_to_run, run_name="__main__")
251
252
253if __name__ == "__main__":
254    run_gui()
Note: See TracBrowser for help on using the repository browser.