Source

yt.hub / ythub / models.py

  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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
from sqlalchemy import Column, Integer, String, Float, PickleType, \
    ForeignKey, LargeBinary
from sqlalchemy.orm import relationship
from ythub.database import Base, db_session, sdb, bucket
from yt.mods import *
import uuid, json, time
from werkzeug.security import \
    generate_password_hash, check_password_hash
from boto.s3.key import Key
from tempfile import TemporaryFile
from ythub.local_config import tmp_dir
import cStringIO
from utilities import slugify
from yt.funcs import iterable

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)
    email = Column(String(120), unique=True, nullable=False)
    api_key = Column(String(32), unique=True, nullable=False)
    username = Column(String(20), unique=True, nullable=False)
    user_hash = Column(String(32), unique=True, nullable=False)
    pw_hash = Column(String(40), nullable=False)
    url = Column(String(64), nullable=True)

    def __init__(self, **kwargs):
        self.user_hash = uuid.uuid4().hex
        kwargs.pop("user_hash", None)
        self.api_key = uuid.uuid4().hex
        kwargs.pop("api_key", None)
        self.set_password(kwargs.pop("password"))
        super(User, self).__init__(**kwargs)

    def set_password(self, password):
        self.pw_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.pw_hash, password)

def _data_results(q):
    rs = sdb.select(q)
    data = []
    for r in rs:
        if 'obj_type' in r and r['obj_type'] in view_proxies:
            cls = view_proxies[r['obj_type']]
            data.append(cls(r))
        else:
            print "UNKNOWN TYPE", r['obj_type']
            continue
            #data.append(dict(r.items()))
    return data

def data_query(output_hash = None):
    q = 'select * from `%s`' % (sdb.name)
    if output_hash is not None:
        q += ' where output_hash="%s"' % (output_hash)
    return _data_results(q)

def type_query(data_type, output_hash = None):
    q = 'select * from `%s` where obj_type="%s"' % (sdb.name, data_type)
    if output_hash is not None:
        q += ' where output_hash="%s"' % (output_hash)
    return _data_results(q)

def obj_query(hub_id, obj_type = None):
    q = 'select * from `%s` where hub_id="%s"' % (sdb.name, hub_id)
    if obj_type is not None:
        q += ' and obj_type="%s"' % (obj_type)
    return _data_results(q)

def shorturl_query(shorturl):
    q = 'select * from `%s` where shorturl="%s"' % (sdb.name, shorturl)
    return _data_results(q)

def sim_query(output_hash):
    cached_sims.check_expiration()
    if output_hash in cached_sims: return cached_sims[output_hash]
    q = 'select * from `%s` where obj_type="simulation_output"' % (sdb.name)
    q += ' and output_hash="%s"' % (output_hash)
    print q
    dr = _data_results(q)
    #assert(len(dr) == 1)
    cached_sims[output_hash] = dr[0]
    return dr[0]

def project_query(project_descr):
    q = 'select hub_id, title from `%s` where obj_type="project"' % (sdb.name)
    rs = sdb.select(q)
    for r in rs:
        possible = (r['hub_id'], slugify(r['title']))
        if project_descr in possible:
            return obj_query(r['hub_id'], 'project')[0]
    return None

view_proxies = {}

class LoadableDataProxy(object):
    loaded = False
    def __init__(self, obj):
        self.hub_id = obj['hub_id']
        self.pf = sim_query(obj['output_hash'])
        self.chunk_names = obj['chunk_names']
        self.obj_type = obj['obj_type']
        self.created = float(obj['created'])

    @property
    def user(self):
        return self.pf.user

    def load(self):
        self.data = dict([(cn, d) for cn, d in self._load()])

    def _load(self):
        chunk_names = self.chunk_names.split(";")
        uu = self.hub_id
        item_name = "%s_%s" % (self.obj_type, uu)
        for chunk_name in chunk_names:
            f = TemporaryFile()
            key = Key(bucket, name="%s/%s" % (item_name, chunk_name))
            print "Retrieving key", key.name
            key.get_contents_to_file(f)
            f.seek(0)
            yield chunk_name, na.load(f)
        self.loaded = True

    def delete(self):
        chunk_names = self.chunk_names.split(";")
        uu = self.hub_id
        item_name = "%s_%s" % (self.obj_type, uu)
        for chunk_name in chunk_names:
            key = Key(bucket, name="%s/%s" % (item_name, chunk_name))
            print "Deleting key", key.name
            key.delete()
        # Now we delete ourself.
        q = sdb.select('select * from `%s` where hub_id="%s"' % (sdb.name, uu))
        for item in q:
            print "Deleting", item.name
            item.delete()

    def __getitem__(self, key):
        if not self.loaded: self.load()
        return self.data[key]

    def __setitem__(self, key, value):
        if not self.loaded: self.load()
        self.data[key] = value

    def keys(self):
        if not self.loaded: self.load()
        return self.data.keys()

    def __iter__(self):
        if not self.loaded: self.load()
        return self.data.__iter__()

    def opt(self):
        return self.pf.url(self.pf.descr())

class MapDataProxy(LoadableDataProxy):
    loaded = False
    def __init__(self, obj):
        super(MapDataProxy, self).__init__(obj)
        self.axis = int(obj['axis'])
        self.field = obj['field']
        self.weight_field = obj.get("weight_field", None)
        # Now we have to set up the field data

    def descr(self):
        ax = {0:'x',1:'y',2:'z'}[self.axis]
        if self.obj_type == 'proj':
            return "Projection of %s (%s) along %s" % (
                self.field, self.weight_field, ax)
        elif self.obj_type == 'slice':
            return "Slice of %s along %s" % (
                self.field, ax)
        return "UNKNOWN"

    @property
    def _url(self):
        return "/map_server/%s" % (self.hub_id)

    def url(self):
        return "<a href='%s'>Map it!</a>" % (self._url)

class ProjectionMapDataProxy(MapDataProxy):
    display_name = "Data Projection"

class SliceMapDataProxy(MapDataProxy):
    display_name = "Data Slice"
        
class VertexProxy(LoadableDataProxy):
    loaded = False
    display_name = "3D Vertices"
    def __init__(self, obj):
        super(VertexProxy, self).__init__(obj)
        self.field = obj['field']

    def tovtk(self, field):
        print "GETTING THE FIELD"
        vert = self[field] * 100
        f = cStringIO.StringIO()
        f.write("vtk output\nASCII\nDATASET POLYDATA\nPOINTS %s float\n" % (vert.shape[0]))
        for v in vert:
            f.write("%0.14f %0.14f %0.14f\n" % (v[0], v[1], v[2]))
        f.write("VERTICES %s %s\n" % (vert.shape[0]/3, vert.shape[0] + vert.shape[0]/3))
        for i in range(vert.shape[0]/3):
            f.write("3 %i %i %i\n" % (i*3, i*3+1, i*3+2))
        f.seek(0)
        return f.getvalue()

    def descr(self):
        return "Extraction of %s" % (self.field)

    @property
    def _url(self):
        return '/vertices/%s' % (self.hub_id)

    def url(self):
        return "<a href='%s'>View in 3D</a>" % (self._url)

class ImageCollectionProxy(LoadableDataProxy):
    loaded = False
    display_name = "Image Collection"
    def __init__(self, obj):
        self.pf = sim_query(obj['output_hash'])
        self.name = obj['name']
        self.hub_id = obj['hub_id']
        self.image_metadata = json.loads(obj['image_metadata'])
        self.chunk_names = obj['chunk_names']
        self.obj_type = obj['obj_type']
        self.created = float(obj['created'])

    def load(self):
        self.data = [d.tostring() for cn, d in self._load()]

    def __iter__(self):
        if not self.loaded: self.load()
        for i, md in enumerate(self.image_metadata):
            url = "/image_collection/%s/image/%s.png" % (self.hub_id, i)
            yield url, md

    def __len__(self):
        return len(self.image_metadata)

    def descr(self):
        return "Image collection '%s'" % (self.name)

    @property
    def _url(self):
        return '/image_collection/%s' % (self.hub_id)

    def url(self):
        return "<a href='%s'>View</a>" % (self._url)

view_proxies['vertices'] = VertexProxy
view_proxies['proj'] = ProjectionMapDataProxy
view_proxies['slice'] = SliceMapDataProxy
view_proxies['image_collection'] = ImageCollectionProxy

class ParameterFileProxy(object):
    display_name = "Simulation Output"
    def __init__(self, obj):
        for attr in ['refine_by', 'dimensionality', 'user_id']:
            # Get rid of lists!
            val = obj.pop(attr, "0").replace("[","").replace("]","")
            try:
                val = int(val)
            except ValueError:
                val = 0
            val = int(val)
            setattr(self, attr, val)
        for attr in ['current_time', 'omega_lambda', 'omega_matter',
                     'current_redshift', 'hubble_constant',
                     'cosmological_simulation', 'created']:
            setattr(self, attr, float(obj.pop(attr)))
        for attr in ['domain_left_edge', 'domain_right_edge']:
            v = json.loads(obj.pop(attr))
            setattr(self, attr, na.array(v, dtype="float64"))
        for attr in ['domain_dimensions']:
            v = json.loads(obj.pop(attr))
            setattr(self, attr, na.array(v, dtype="int32"))
        for attr in obj:
            setattr(self, attr, str(obj[attr]))
        self.user = User.query.filter_by(id = self.user_id).first()

    @property
    def _url(self):
        return '/simulation_outputs/%s' % (self.output_hash)

    def url(self, name = "Parameters"):
        return "<a href='%s'>%s</a>" % (self._url, name)
        
    def descr(self):
        return self.name

    def opt(self): return ""

    def delete(self):
        q = 'select * from `%s` where obj_type="simulation_output"' % (sdb.name)
        q += ' and output_hash="%s"' % (self.output_hash)
        print "PF Selecting", q
        for item in sdb.select(q):
            print "PF Deleting", item.name
            item.delete()
        
view_proxies['simulation_output'] = ParameterFileProxy

class ProjectProxy(object):
    display_name = "Project"
    def __init__(self, obj):
        self.title = obj['title']
        self.description = obj['description']
        self.project_url = obj['url']
        self.category = obj['category']
        self.hub_id = obj['hub_id']
        self.obj_type = obj['obj_type']
        self.created = float(obj['created'])
        self.image_url = obj.get('image_url', "")
        self.user_id = obj['user_id']
        self.user = User.query.filter_by(id = self.user_id).first()
        self.slug = slugify(self.title)

    def descr(self):
        return "Hub Project '%s'" % (self.title)

    @property
    def _url(self):
        return '/project/%s' % (self.slug)

    def url(self):
        return "<a href='%s'>Hub Page</a>" % (self._url)

    def delete(self):
        uu = self.hub_id
        item_name = "%s_%s" % (self.obj_type, uu)
        q = sdb.select('select * from `%s` where hub_id="%s"' % (sdb.name, uu))
        for item in q:
            print "Deleting", item.name
            item.delete()

    def clone(self):
        url = self.project_url
        ss = "bitbucket.org/"
        if ss not in url.lower(): return ""
        if "@" in url[:url.find(ss)]:
            url = "https://%s%s" % (ss, url[url.find(ss) + len(ss):])
        return "hg clone %s" % url
            
    def opt(self): return ""

view_proxies['project'] = ProjectProxy

class NotebookProxy(LoadableDataProxy):
    display_name = "IPython Notebook"
    loaded = False
    def __init__(self, obj):
        self.hub_id = obj['hub_id']
        self.chunk_names = obj['chunk_names']
        self.obj_type = obj['obj_type']
        self.created = float(obj['created'])
        self.user_id = obj['user_id']
        self.title = obj['title']
        self.shorturl = obj['shorturl']
        self._user = User.query.filter_by(id = self.user_id).first()

    def opt(self):
        return ""

    @property
    def user(self):
        return self._user

    def descr(self):
        return self.title

    @property
    def _url(self):
        return "/notebooks/%s.ipynb" % (self.hub_id)

    @property
    def _nburl(self):
        nb_url = "http://nbviewer.ipython.org/url/"
        my_url = "hub.yt-project.org%s" % (self._url)
        return "%s%s" % (nb_url, my_url)

    @property
    def _nbsurl(self):
        return "http://hub.yt-project.org/nb/%s" % (self.shorturl)

    def url(self):
        return "<a href='%s'>Download</a> / <a href='%s'>View</a>" % (
            self._url, self._nbsurl)

view_proxies['notebook'] = NotebookProxy

class ExpiringDataContainer(dict):
    def __init__(self, expiration = 3600):
        self.expiration = expiration
        self.last_seen = {}
        
    def __getitem__(self, key):
        if key in self:
            self.last_seen[key] = time.time()
        self.check_expiration()
        return super(ExpiringDataContainer, self).__getitem__(key)

    def check_expiration(self):
        t = time.time()
        todel = []
        for key in self:
            if key not in self.last_seen:
                todel.append(key)
            elif (t - self.last_seen[key]) > self.expiration:
                print "Expiring", key
                todel.append(key)
        for key in todel: del self[key]

container = ExpiringDataContainer()
cached_sims = ExpiringDataContainer(300)