aboutsummaryrefslogtreecommitdiff
path: root/trappy/plotter/IPythonConf.py
blob: 05f1a22c19c621557c3bc79bc880b56575f473a6 (plain)
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
#    Copyright 2015-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""IPythonConf provides abstraction for the varying configurations in
different versions of ipython/jupyter packages.
"""
import urllib
import os
import shutil
from distutils.version import StrictVersion as V

D3_PLOTTER_URL = "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"
D3_TIP_URL = "http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"
DYGRAPH_COMBINED_URL = "http://cdnjs.cloudflare.com/ajax/libs/dygraph/1.1.1/dygraph-combined.js"
DYGRAPH_SYNC_URL = "http://dygraphs.com/extras/synchronizer.js"
UNDERSCORE_URL = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"

IPLOT_RESOURCES = {
    "ILinePlot": [
        DYGRAPH_COMBINED_URL,
        "js/ILinePlot.js",
        DYGRAPH_SYNC_URL,
        UNDERSCORE_URL],
    "EventPlot": [
        D3_PLOTTER_URL,
        D3_TIP_URL,
        "js/EventPlot.js",
        "css/EventPlot_help.jpg"]}

"""The location of the IPython webserver in IPython version 4.0+"""
IPYTHON_V4_BASE = "/nbextensions"
"""The webserver base directory for IPython version 4.0+"""
IPYTHON_V3_BASE = "/static"
"""The webserver base directory for IPython version < 4.0"""
PLOTTER_SCRIPTS = "plotter_scripts"
"""The installation directory of plotter JS files in the
IPython webserver"""
PLOTTER_DATA = "plotter_data"
"""The installation directory of plotter data files in the
IPython webserver"""

def install_http_resource(url, to_path):
    """Install a HTTP Resource (eg. javascript) to
    a destination on the disk

    :param url: HTTP URL
    :type url: str

    :param to_path: Destination path on the disk
    :type to_path: str
    """
    try:
        urllib.urlretrieve(url, filename=to_path)
    except IOError:
        raise ImportError("Could not receive Web Resource {}"
                          .format(to_path))


def install_local_resource(from_path, to_path):
    """Move a local resource  to the desired
    a destination.

    :param from_path: Path relative to this file
    :type from_path: str

    :param to_path: Destination path on the disk
    :type to_path: str
    """
    base_dir = os.path.dirname(__file__)
    from_path = os.path.join(base_dir, from_path)
    shutil.copy(from_path, to_path)


def install_resource(from_path, to_path):
    """Install a resource to a location on the disk

    :param from_path: URL or relative path
    :type from_path: str

    :param to_path: Destination path on the disk
    :type to_path: str
    """

    if from_path.startswith("http"):
        if not os.path.isfile(to_path):
            install_http_resource(from_path, to_path)
    else:
        install_local_resource(from_path, to_path)


def iplot_install(module_name):
    """Install the resources for the module to the Ipython
    profile directory

    :param module_name: Name of the module
    :type module_name: str

    :return: A list than can be consumed by requirejs or
        any relative resource dependency resolver
    """

    resources = IPLOT_RESOURCES[module_name]
    for resource in resources:
        resource_name = os.path.basename(resource)
        resource_dest_dir = os.path.join(
            get_scripts_path(),
            module_name)

        # Ensure if the directory exists
        if not os.path.isdir(resource_dest_dir):
            os.mkdir(resource_dest_dir)
        resource_dest_path = os.path.join(resource_dest_dir, resource_name)
        install_resource(resource, resource_dest_path)


def get_ipython():
    """Return an IPython instance. Returns None
    if IPython is not installed"""

    try:
        import IPython
        return IPython.get_ipython()
    except ImportError:
        return None

def check_ipython():
    """A boolean function to check if IPython
    is available"""

    try:
        import IPython
    except ImportError:
        return False

    return True

def get_profile_name():
    """Get the name of the profile of the current IPython
     notebook. This is only relevant to V <= 4.0.0"""

    ipy = get_ipython()
    if not ipy:
        raise ImportError("Cannot Find IPython Profile")

    return ipy.profile

def get_ipython_dir(profile=None):
    """Returns the base directory of the IPython server

    :param profile: The name of the IPython profile
    :type profile: str
    """

    if not check_ipython():
        raise ImportError("Cannot Find IPython Environment")

    import IPython
    # IPython 4.0+ changes the position of files in the profile
    # directory
    if V(IPython.__version__) >= V('4.0.0'):
        from jupyter_core.paths import jupyter_data_dir
        return os.path.join(
            jupyter_data_dir(),
            IPYTHON_V4_BASE.strip("/"))
    else:
        if not profile:
            profile = get_profile_name()
        return os.path.join(
            IPython.utils.path.locate_profile(
                profile),
            IPYTHON_V3_BASE.strip("/"))

def add_web_base(path):
    """Add the base of the IPython dependency URLs

    :param path: The path to be augmented with the
        webserver base
    :type path: str
    """

    import IPython
    if V(IPython.__version__) >= V('4.0.0'):
        return os.path.join(IPYTHON_V4_BASE, path)
    else:
        return os.path.join(IPYTHON_V3_BASE, path)

def get_scripts_path(profile=None):
    """Directory where plotter scripts are installed

    :param profile: The name of the IPython profile
    :type profile: str
    """

    dir_name = os.path.join(get_ipython_dir(profile), PLOTTER_SCRIPTS)
    if not os.path.isdir(dir_name):
        os.makedirs(dir_name)
    return dir_name

def get_data_path(profile=None):
    """Directory where Plotter Data is stored

    :param profile: The name of the IPython profile
    :type profile: str
    """

    dir_name = os.path.join(get_ipython_dir(profile), PLOTTER_DATA)
    if not os.path.isdir(dir_name):
        os.makedirs(dir_name)
    return dir_name