|
| 1 | +import requests |
| 2 | +import json |
| 3 | +import warnings |
| 4 | + |
| 5 | +from .version import __version__ |
| 6 | + |
| 7 | +def signup(un, email): |
| 8 | + ''' Remote signup to plot.ly and plot.ly API |
| 9 | + Returns: |
| 10 | + :param r with r['tmp_pw']: Temporary password to access your plot.ly acount |
| 11 | + :param r['api_key']: A key to use the API with |
| 12 | + |
| 13 | + Full docs and examples at https://plot.ly/API |
| 14 | + :un: <string> username |
| 15 | + :email: <string> email address |
| 16 | + ''' |
| 17 | + payload = {'version': __version__, 'un': un, 'email': email, 'platform':'Python'} |
| 18 | + r = requests.post('https://plot.ly/apimkacct', data=payload) |
| 19 | + r.raise_for_status() |
| 20 | + r = json.loads(r.text) |
| 21 | + if 'error' in r and r['error'] != '': |
| 22 | + print(r['error']) |
| 23 | + if 'warning' in r and r['warning'] != '': |
| 24 | + warnings.warn(r['warning']) |
| 25 | + if 'message' in r and r['message'] != '': |
| 26 | + print(r['message']) |
| 27 | + |
| 28 | + return r |
| 29 | + |
| 30 | +class plotly: |
| 31 | + def __init__(self, username_or_email=None, key=None,verbose=True): |
| 32 | + ''' plotly constructor. Supply username or email and api key. |
| 33 | + ''' |
| 34 | + self.un = username_or_email |
| 35 | + self.key = key |
| 36 | + self.__filename = None |
| 37 | + self.__fileopt = None |
| 38 | + self.verbose = verbose |
| 39 | + self.open = True |
| 40 | + |
| 41 | + def ion(self): |
| 42 | + self.open = True |
| 43 | + def ioff(self): |
| 44 | + self.open = False |
| 45 | + |
| 46 | + def iplot(self, *args, **kwargs): |
| 47 | + ''' for use in ipython notebooks ''' |
| 48 | + res = self.__callplot(*args, **kwargs) |
| 49 | + width = kwargs.get('width', 600) |
| 50 | + height = kwargs.get('height', 450) |
| 51 | + s = '<iframe height="%s" id="igraph" scrolling="no" seamless="seamless" src="%s" width="%s"></iframe>' %\ |
| 52 | + (height+50, "/".join(map(str, [res['url'], width, height])), width+50) |
| 53 | + try: |
| 54 | + # see, if we are in the SageMath Cloud |
| 55 | + from sage_salvus import html |
| 56 | + return html(s, hide=False) |
| 57 | + except: |
| 58 | + pass |
| 59 | + try: |
| 60 | + from IPython.display import HTML |
| 61 | + return HTML(s) |
| 62 | + except: |
| 63 | + return s |
| 64 | + |
| 65 | + def plot(self, *args, **kwargs): |
| 66 | + res = self.__callplot(*args, **kwargs) |
| 67 | + if 'error' in res and res['error'] == '' and self.open: |
| 68 | + from webbrowser import open as wbopen |
| 69 | + wbopen(res['url']) |
| 70 | + return res |
| 71 | + |
| 72 | + def __callplot(self, *args, **kwargs): |
| 73 | + ''' Make a plot in plotly. |
| 74 | + Two interfaces: |
| 75 | + 1 - ploty.plot(x1, y1[,x2,y2,...],**kwargs) |
| 76 | + where x1, y1, .... are lists, numpy arrays |
| 77 | + 2 - plot.plot([data1[, data2, ...], **kwargs) |
| 78 | + where data1 is a dict that is at least |
| 79 | + {'x': x1, 'y': y1} but can contain more styling and sharing options. |
| 80 | + kwargs accepts: |
| 81 | + filename |
| 82 | + fileopt |
| 83 | + style |
| 84 | + layout |
| 85 | + See https://plot.ly/API for details. |
| 86 | + Returns: |
| 87 | + :param r with r['url']: A URL that displays the generated plot |
| 88 | + :param r['filename']: The filename of the plot in your plotly account. |
| 89 | + ''' |
| 90 | + |
| 91 | + un = kwargs['un'] if 'un' in kwargs else self.un |
| 92 | + key = kwargs['key'] if 'key' in kwargs else self.key |
| 93 | + if not un or not key: |
| 94 | + raise Exception('Not Signed in') |
| 95 | + |
| 96 | + if not 'filename' in kwargs: |
| 97 | + kwargs['filename'] = self.__filename |
| 98 | + if not 'fileopt' in kwargs: |
| 99 | + kwargs['fileopt'] = self.__fileopt |
| 100 | + |
| 101 | + origin = 'plot' |
| 102 | + r = self.__makecall(args, un, key, origin, kwargs) |
| 103 | + return r |
| 104 | + |
| 105 | + def layout(self, *args, **kwargs): |
| 106 | + ''' Style the layout of a Plotly plot. |
| 107 | + ploty.layout(layout,**kwargs) |
| 108 | + :param layout - a dict that customizes the style of the layout, |
| 109 | + the axes, and the legend. |
| 110 | + :param kwargs - accepts: |
| 111 | + filename |
| 112 | + See https://plot.ly/API for details. |
| 113 | + Returns: |
| 114 | + :param r with r['url']: A URL that displays the generated plot |
| 115 | + :param r['filename']: The filename of the plot in your plotly account. |
| 116 | + ''' |
| 117 | + |
| 118 | + un = kwargs['un'] if 'un' in kwargs.keys() else self.un |
| 119 | + key = kwargs['un'] if 'key' in kwargs.keys() else self.key |
| 120 | + if not un or not key: |
| 121 | + raise Exception('Not Signed in') |
| 122 | + if not 'filename' in kwargs.keys(): |
| 123 | + kwargs['filename'] = self.__filename |
| 124 | + if not 'fileopt' in kwargs.keys(): |
| 125 | + kwargs['fileopt'] = self.__fileopt |
| 126 | + |
| 127 | + origin = 'layout' |
| 128 | + r = self.__makecall(args, un, key, origin, kwargs) |
| 129 | + return r |
| 130 | + |
| 131 | + def style(self, *args, **kwargs): |
| 132 | + ''' Style the data traces of a Plotly plot. |
| 133 | + ploty.style([data1,[,data2,...],**kwargs) |
| 134 | + :param data1 - a dict that customizes the style of the i'th trace |
| 135 | + :param kwargs - accepts: |
| 136 | + filename |
| 137 | + See https://plot.ly/API for details. |
| 138 | + Returns: |
| 139 | + :param r with r['url']: A URL that displays the generated plot |
| 140 | + :param r['filename']: The filename of the plot in your plotly account. |
| 141 | + ''' |
| 142 | + |
| 143 | + un = kwargs['un'] if 'un' in kwargs.keys() else self.un |
| 144 | + key = kwargs['un'] if 'key' in kwargs.keys() else self.key |
| 145 | + if not un or not key: |
| 146 | + raise Exception('Not Signed in') |
| 147 | + if not 'filename' in kwargs.keys(): |
| 148 | + kwargs['filename'] = self.__filename |
| 149 | + if not 'fileopt' in kwargs.keys(): |
| 150 | + kwargs['fileopt'] = self.__fileopt |
| 151 | + |
| 152 | + origin = 'style' |
| 153 | + r = self.__makecall(args, un, key, origin, kwargs) |
| 154 | + return r |
| 155 | + |
| 156 | + class __plotlyJSONEncoder(json.JSONEncoder): |
| 157 | + def numpyJSONEncoder(self, obj): |
| 158 | + try: |
| 159 | + import numpy |
| 160 | + if type(obj).__module__.split('.')[0] == numpy.__name__: |
| 161 | + l = obj.tolist() |
| 162 | + d = self.datetimeJSONEncoder(l) |
| 163 | + return d if d is not None else l |
| 164 | + except: |
| 165 | + pass |
| 166 | + return None |
| 167 | + def datetimeJSONEncoder(self, obj): |
| 168 | + # if datetime or iterable of datetimes, convert to a string that plotly understands |
| 169 | + # format as %Y-%m-%d %H:%M:%S.%f, %Y-%m-%d %H:%M:%S, or %Y-%m-%d depending on what non-zero resolution was provided |
| 170 | + import datetime |
| 171 | + try: |
| 172 | + if isinstance(obj,(datetime.datetime, datetime.date)): |
| 173 | + if obj.microsecond != 0: |
| 174 | + return obj.strftime('%Y-%m-%d %H:%M:%S.%f') |
| 175 | + elif obj.second != 0 or obj.minute != 0 or obj.hour != 0: |
| 176 | + return obj.strftime('%Y-%m-%d %H:%M:%S') |
| 177 | + else: |
| 178 | + return obj.strftime('%Y-%m-%d') |
| 179 | + elif isinstance(obj[0],(datetime.datetime, datetime.date)): |
| 180 | + return [o.strftime('%Y-%m-%d %H:%M:%S.%f') if o.microsecond != 0 else |
| 181 | + o.strftime('%Y-%m-%d %H:%M:%S') if o.second != 0 or o.minute != 0 or o.hour != 0 else |
| 182 | + o.strftime('%Y-%m-%d') |
| 183 | + for o in obj] |
| 184 | + except: |
| 185 | + pass |
| 186 | + return None |
| 187 | + def pandasJSONEncoder(self, obj): |
| 188 | + try: |
| 189 | + import pandas |
| 190 | + if isinstance(obj, pandas.Series): |
| 191 | + return obj.tolist() |
| 192 | + except: |
| 193 | + pass |
| 194 | + return None |
| 195 | + def sageJSONEncoder(self, obj): |
| 196 | + try: |
| 197 | + from sage.all import RR, ZZ |
| 198 | + if obj in RR: |
| 199 | + return float(obj) |
| 200 | + elif obj in ZZ: |
| 201 | + return int(obj) |
| 202 | + except: |
| 203 | + pass |
| 204 | + return None |
| 205 | + def default(self, obj): |
| 206 | + try: |
| 207 | + return json.dumps(obj) |
| 208 | + except TypeError as e: |
| 209 | + encoders = (self.datetimeJSONEncoder, self.numpyJSONEncoder, self.pandasJSONEncoder, self.sageJSONEncoder) |
| 210 | + for encoder in encoders: |
| 211 | + s = encoder(obj) |
| 212 | + if s is not None: |
| 213 | + return s |
| 214 | + raise e |
| 215 | + return json.JSONEncoder.default(self,obj) |
| 216 | + |
| 217 | + def __makecall(self, args, un, key, origin, kwargs): |
| 218 | + platform = 'Python' |
| 219 | + |
| 220 | + args = json.dumps(args, cls=self.__plotlyJSONEncoder) |
| 221 | + kwargs = json.dumps(kwargs, cls=self.__plotlyJSONEncoder) |
| 222 | + url = 'https://plot.ly/clientresp' |
| 223 | + payload = {'platform': platform, 'version': __version__, 'args': args, 'un': un, 'key': key, 'origin': origin, 'kwargs': kwargs} |
| 224 | + r = requests.post(url, data=payload) |
| 225 | + r.raise_for_status() |
| 226 | + r = json.loads(r.text) |
| 227 | + if 'error' in r and r['error'] != '': |
| 228 | + print(r['error']) |
| 229 | + if 'warning' in r and r['warning'] != '': |
| 230 | + warnings.warn(r['warning']) |
| 231 | + if 'message' in r and r['message'] != '' and self.verbose: |
| 232 | + print(r['message']) |
| 233 | + |
| 234 | + return r |
| 235 | + |
| 236 | + |
| 237 | + |
0 commit comments