File: apps.py

package info (click to toggle)
xraylarch 0.9.58%2Bds1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 74,640 kB
  • sloc: python: 63,075; fortran: 6,978; makefile: 1,877; ansic: 1,562; sh: 185; javascript: 104
file content (318 lines) | stat: -rw-r--r-- 10,028 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import os
import sys
import locale
import numpy
import time
from argparse import ArgumentParser
import pkg_resources
from subprocess import check_call
import shutil

from .site_config import icondir, home_dir, uname
from .site_config import (extras_wxgraph, extras_qtgraph,
                          extras_epics, extras_xrd, extras_doc)
from .shell import shell
from .xmlrpc_server import larch_server_cli
from .version import __date__, make_banner, check_larchversion

HAS_CONDA = os.path.exists(os.path.join(sys.prefix, 'conda-meta'))

HAS_WXPYTHON = False
try:
    import wx
    HAS_WXPYTHON = True
except ImportError:
    pass

def install_extras(package_set):
    all_packages = set([pkg.key for pkg in pkg_resources.working_set])
    missing = package_set - all_packages - {"pyshortcuts"}
    if missing:
        raise RuntimeError("%s missing", missing)
        # command = [sys.executable, '-m', 'pip', 'install', *missing]
        # check_call(command)

def update_larch():
    check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'xraylarch'])

def use_mpl_wxagg():
    """import matplotlib, set backend to wxAgg"""
    if HAS_WXPYTHON:
        try:
            import matplotlib
            matplotlib.use('WXAgg', force=True)
            return True
        except ImportError:
            pass
    return False

def set_locale():
    """set locale to 'C' for these applications, 
    may need some improvement!!"""
    locale.setlocale(locale.LC_ALL, 'C')

def fix_darwin_shebang(script):
    """
    fix anaconda python apps on MacOs to launch with pythonw
    """
    pyapp = os.path.join(sys.prefix, 'python.app', 'Contents', 'MacOS', 'python')
    # strip off any arguments:
    script = script.split(' ', 1)[0]
    if not os.path.exists(script):
        script = os.path.join(sys.exec_prefix, 'bin', script)

    if uname == 'darwin' and os.path.exists(pyapp) and os.path.exists(script):
        with open(script, 'r') as fh:
            try:
                lines = fh.readlines()
            except IOError:
                lines = ['-']

        if len(lines) > 1:
            text = ["#!%s\n" % pyapp]
            text.extend(lines[1:])
            time.sleep(.05)
            with open(script, 'w') as fh:
                fh.write("".join(text))

class LarchApp:
    """
    wrapper for Larch Application
    """
    def __init__(self, name, script, icon='larch', terminal=False):
        self.name = name
        self.script = script
        self.terminal = terminal
        self.icon = icon
        bindir = 'Scripts' if uname == 'win' else 'bin'
        self.bindir = os.path.join(sys.prefix, bindir)

    def create_shortcut(self):
        script = os.path.join(self.bindir, self.script)
        icon = os.path.join(icondir, self.icon)
        if HAS_CONDA and uname == 'darwin':
            try:
                fix_darwin_shebang(script)
            except:
                print("Warning: could not fix Mac exe for ", script)

APPS = (LarchApp('Larch CLI', 'larch', terminal=True),
        LarchApp('Larch GUI', 'larch --wxgui'),
        LarchApp('XAS Viewer',  'xas_viewer',  icon='onecone'),
        LarchApp('GSE MapViewer', 'gse_mapviewer',  icon='gse_xrfmap'),
        LarchApp('XRF Display',  'xrfdisplay',  icon='ptable'),
        # LarchApp('GSE DTCorrect', 'gse_dtcorrect'),
        # LarchApp('Dioptas', 'dioptas_larch', icon='dioptas'),
        # LarchApp('2D XRD Viewer', 'xrd2d_viewer'),
        # LarchApp('1D XRD Viewer', 'xrd1d_viewer')
        )


def make_desktop_shortcuts():
    """make desktop shortcuts for Larch apps,
    first clearing any existing shortcuts"""
    pass

def make_cli(description='run larch program', filedesc='data file'):
    usage = "usage: %prog [options] file"
    parser = ArgumentParser(description=description)
    parser.add_argument('filename', nargs='?',  help=filedesc)
    args = parser.parse_args()
    return dict(filename=args.filename)

# entry points:
def run_gse_mapviewer():
    """Mapviewer"""
    set_locale()
    use_mpl_wxagg()
    install_extras(extras_wxgraph)
    install_extras(extras_epics)
    install_extras(extras_xrd)
    vinfo = check_larchversion()
    from larch.wxmap import MapViewer
    kwargs = make_cli(description="Larch's XRM Map Viewer and Analysis Program",
                      filedesc='XRM Map File (.h5)')
    MapViewer(version_info=vinfo, **kwargs).MainLoop()

def run_gse_dtcorrect():
    """GSE DT Correct """
    set_locale()
    use_mpl_wxagg()
    install_extras(extras_wxgraph)
    install_extras(extras_epics)
    from larch.wxmap import DTViewer
    DTViewer().MainLoop()

def run_xas_viewer():
    """XAS Viewer """
    set_locale()
    use_mpl_wxagg()
    install_extras(extras_wxgraph)
    vinfo = check_larchversion()
    from larch.wxxas import XASViewer
    kwargs = make_cli(description="Larch's XAS Viewer and Analysis Program")
    XASViewer(version_info=vinfo, **kwargs).MainLoop()

def run_xrfdisplay():
    """ XRF Display"""
    set_locale()
    use_mpl_wxagg()
    install_extras(extras_wxgraph)
    install_extras(extras_epics)
    from larch.wxlib.xrfdisplay import XRFApp
    kwargs = make_cli(description="Larch's XRF Viewer and Analysis Program",
                    filedesc='MCA File (.mca)')
    XRFApp(**kwargs).MainLoop()

def run_xrfdisplay_epics():
    """XRF Display for Epics Detectors"""
    set_locale()
    use_mpl_wxagg()
    install_extras(extras_wxgraph)
    install_extras(extras_epics)
    from larch.epics import EpicsXRFApp
    EpicsXRFApp().MainLoop()

def run_xrd1d_viewer():
    """XRD Display for 1D patternss"""
    set_locale()
    use_mpl_wxagg()
    from larch.wxxrd import XRD1DViewer
    XRD1DViewer().MainLoop()

def run_xrd2d_viewer():
    """XRD Display for 2D patternss"""
    set_locale()
    use_mpl_wxagg()
    install_extras(extras_wxgraph)
    install_extras(extras_epics)
    install_extras(extras_xrd)
    from larch.wxxrd import XRD2DViewer
    XRD2DViewer().MainLoop()

def run_dioptas_larch():
    """XRD Display for 2D patternss"""
    from dioptas import main
    main()

def run_feff6l():
    "run feff6l"
    from larch.xafs.feffrunner import feff6l_cli
    feff6l_cli()

def run_feff8l():
    "run feff8l"
    from larch.xafs.feffrunner import feff8l_cli
    feff8l_cli()

def run_larch_server():
    "run larch XMLRPC server"
    larch_server_cli()

## main larch cli or wxgui
def run_larch():
    """
    main larch application launcher, running either
    commandline repl program or wxgui
    """
    usage = "usage: %prog [options] file(s)"
    parser = ArgumentParser(description='run main larch program')

    parser.add_argument('-v', '--version', dest='version', action='store_true',
                        default=False, help='show version')

    parser.add_argument("-e", "--exec", dest="noshell", action="store_true",
                        default=False, help="execute script only, default = False")

    parser.add_argument("-q", "--quiet", dest="quiet", action="store_true",
                        default=False, help="set quiet mode, default = False")

    parser.add_argument("-x", "--nowx", dest="nowx", action="store_true",
                        default=False, help="set no wx graphics mode, default = False")

    parser.add_argument("-w", "--wxgui", dest="wxgui", default=False,
                        action='store_true', help="run Larch GUI")

    parser.add_argument("-m", "--makeicons", dest="makeicons", action="store_true",
                        default=False, help="create desktop icons")

    parser.add_argument('-u', '--update', dest='update', action='store_true',
                        default=False, help='update larch to the latest version')

    parser.add_argument("-r", "--remote", dest="server_mode", action="store_true",
                        default=False, help="run in remote server mode")

    parser.add_argument("-p", "--port", dest="port", default='4966',
                        help="port number for remote server")

    parser.add_argument('scripts', nargs='*',
                        help='larch or python scripts to run on startup')

    args = parser.parse_args()
    if args.version:
        print(make_banner())
        vinfo = check_larchversion()
        if vinfo.update_available:
            print(vinfo.message)
        return

    with_wx = HAS_WXPYTHON and (not args.nowx)

    # create desktop icons
    if args.makeicons:
        return

    # run updates
    if args.update:
        update_larch()
        return

    # run in server mode
    if args.server_mode:
        if with_wx:
            use_mpl_wxagg()
        vinfo = check_larchversion()
        if vinfo.update_available:
            print(vinfo.message)

        from larch.xmlrpc_server import LarchServer
        server = LarchServer(host='localhost', port=int(args.port))
        server.run()

    # run wx Larch GUI
    elif args.wxgui:
        set_locale()        
        use_mpl_wxagg()
        install_extras(extras_wxgraph)
        install_extras(extras_epics)
        install_extras(extras_xrd)
        from larch.wxlib.larchframe import LarchApp
        LarchApp().MainLoop()

    # run wx Larch CLI
    else:
        if with_wx:
            set_locale()            
            use_mpl_wxagg()
            install_extras(extras_wxgraph)
        install_extras(extras_epics)
        install_extras(extras_xrd)
        vinfo = check_larchversion()
        if vinfo.update_available:
            print(vinfo.message)

        cli = shell(quiet=args.quiet, with_wx=with_wx)
        # execute scripts listed on command-line
        if args.scripts is not None:
            for script in args.scripts:
                if script.endswith('.py'):
                    cmd = "import %s" %  script[:-3]
                else:
                    cmd = "run('%s')" % script
                cli.default(cmd)
        # if interactive, start command loop
        if not args.noshell:
            try:
                cli.cmdloop()
            except ValueError:
                pass