aboutsummaryrefslogtreecommitdiffstats
path: root/97suifangqa/apps/indicator/tools.py
blob: 7a74ac4050e6153e96edd645cd36d1fda19d1fb7 (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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# -*- coding: utf-8 -*-

"""
utils for apps/indicator
"""

from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404

from indicator import models as im
from sciblog import models as sciblogm

import re
import datetime


# follow_indicator {{{
def follow_indicator(user_id, indicator_id):
    """
    用户关注指标
    """
    try:
        user = get_object_or_404(User, id=user_id)
        indicator = im.Indicator.objects.get(id=indicator_id)
        ui, created = im.UserIndicator.objects.get_or_create(user=user)
        ui.followedIndicators.add(indicator)
        # to remove the indicator from 'followedHistories' if exists
        if indicator in ui.followedHistories.all():
            ui.followedHistories.remove(indicator)
        return True
    except:
        return False
# }}}


# unfollow_indicator {{{
def unfollow_indicator(user_id, indicator_id):
    """
    用户取消关注指标
    """
    try:
        user = get_object_or_404(User, id=user_id)
        indicator = im.Indicator.objects.get(id=indicator_id)
        ui, created = im.UserIndicator.objects.get_or_create(user=user)
        ui.followedIndicators.remove(indicator)
        # add indicator to 'followedHistories'
        ui.followedHistories.add(indicator)
        return True
    except:
        return False
# }}}


# get_indicator {{{
def get_indicator(category_id="all", startswith="all"):
    """
    根据指定的 category_id 和 startswith 获取 indicator
    返回一个 dict
    Dict format:
    dict = {
        'a': [ {'pinyin': 'aa', ...}, {'pinyin': 'ab', ...}, ... ],
        'b': [ {'pinyin': 'ba', ...}, {'pinyin': 'bb', ...}, ... ],
        ...
    }
    """

    _idict = {}
    if category_id == 'all':
        iqueryset = im.Indicator.objects.all()
    else:
        try:
            cid = int(category_id)
            cate = im.IndicatorCategory.objects.get(id=cid)
            iqueryset = cate.indicators.all()
        except ValueError:
            raise ValueError(u'category_id 不是整数型')
            return _idict
        except im.IndicatorCategory.DoesNotExist:
            raise ValueError(u'id=%s 的 IndicatorCategory 不存在'
                    % cid)
            return _idict

    if startswith == 'all':
        starts = map(chr, range(ord('a'), ord('z')+1))
    else:
        starts = []
        _str = startswith.lower()
        for i in _str:
            if i >= 'a' and i <= 'z':
                starts.append(i)

    for l in starts:
        iq = iqueryset.filter(pinyin__istartswith=l).order_by('pinyin')
        _idict[l] = [ i.dump() for i in iq ]
    return _idict
# }}}


# get_followed_indicator {{{
def get_followed_indicator(user_id, category_id="all", startswith="all"):
    """
    获取已关注的指标
    返回 dict, 格式与 get_indicator() 一致
    """

    u = User.objects.get(id=user_id)
    ui, created = im.UserIndicator.objects.get_or_create(user=u)
    _idict = {}
    iqueryset = ui.followedIndicators.all()
    if not category_id == 'all':
        try:
            cid = int(category_id)
            iqueryset = iqueryset.filter(categories__id=cid)
        except ValueError:
            raise ValueError(u'category_id 不是整数型')
            return _idict

    if startswith == 'all':
        starts = map(chr, range(ord('a'), ord('z')+1))
    else:
        starts = []
        _str = startswith.lower()
        for i in _str:
            if i >= 'a' and i <= 'z':
                starts.append(i)

    for l in starts:
        iq = iqueryset.filter(pinyin__istartswith=l).order_by('pinyin')
        _idict[l] = [ i.dump() for i in iq ]
    return _idict
# }}}


# get_unfollowed_indicator {{{
def get_unfollowed_indicator(user_id, category_id="all", startswith="all"):
    """
    获取未关注的指标
    返回 dict, 格式与 get_indicator() 一致
    """

    u = User.objects.get(id=user_id)
    ui, created = im.UserIndicator.objects.get_or_create(user=u)
    _idict = {}
    # XXX: if 'exclude(followed_indicators=ui)' OK??
    iqueryset = im.Indicator.objects.exclude(followed_indicators=ui)
    if not category_id == 'all':
        try:
            cid = int(category_id)
            iqueryset = iqueryset.filter(categories__id=cid)
        except ValueError:
            raise ValueError(u'category_id 不是整数型')
            return _idict

    if startswith == 'all':
        starts = map(chr, range(ord('a'), ord('z')+1))
    else:
        starts = []
        _str = startswith.lower()
        for i in _str:
            if i >= 'a' and i <= 'z':
                starts.append(i)

    for l in starts:
        iq = iqueryset.filter(pinyin__istartswith=l).order_by('pinyin')
        _idict[l] = [ i.dump() for i in iq ]
    return _idict
# }}}


# get_record {{{
def get_record(user_id, indicator_id, begin=None, end=None, number=None, std=False):
    """
    args 'begin' and 'end' to specify the date range.
    arg 'std=True' to get data in standard unit

    if 'begin=None', then the earliest date is given;
    if 'end=None', then the latest date is given.

    if 'number' given, then return the lastest number of records.
    if there is not that much, then return all the records.

    the date range filter *first*, then number filter

    return dict format: (data sorted by 'date')
    rdata = {
        'failed': False,
        'number_req': number_of_records_request,
        'begin_req': begin_req,
        'end_req': end_req,
        'number_rsp': number_of_records_response,
        'begin_rsp': begin_rsp,
        'end_rsp': end_rsp,
        'has_more': True|False,
        'has_earlier': True|False,
        'has_later': True|False,
        'data': [d1r1.get_data(), d1r2.get_data(), ...],
    }
    """
    # default parameters
    number_req = None
    begin_req = None
    end_req = None
    #
    uid = int(user_id)
    indid = int(indicator_id)
    all_records = im.IndicatorRecord.objects.\
            filter(user__id=uid, indicator__id=indid).\
            order_by('date', 'created_at')
    # check if 'all_records' empty
    if not all_records:
        return {'failed': True}
    # check date range and given number
    if (begin is None) and (end is None):
        # select by given 'number'
        if number is not None:
            try:
                number_req = int(number)
                records = all_records.reverse()[:number_req]
            except ValueError:
                raise ValueError(u"number='%s' 错误" % number)
                return {'failed': True}
        else:
            records = all_records.reverse()
        # convert to list, and re-sort by 'date'
        records_list = list(records)
        records_list.reverse()
    else:
        # check date range
        # begin
        if begin is None:
            begin = all_records[0].date
        elif isinstance(begin, datetime.date):
            begin_req = begin.isoformat()
        else:
            raise ValueError(u"begin='%s' 不是合法的日期" % begin)
            return {'failed': True}
        # end
        if end is None:
            end = all_records.reverse()[0].date
        elif isinstance(end, datetime.date):
            end_req = end.isoformat()
        else:
            raise ValueError(u"end='%s' 不是合法的日期" % end)
            return {'failed': True}
        # filter by date range
        records = all_records.filter(date__range=(begin, end))
        records_list = list(records)

    # process records
    number_rsp = len(records_list)
    begin_rsp_py = records_list[0].date
    begin_rsp = begin_rsp_py.isoformat()
    end_rsp_py = records_list[-1].date
    end_rsp = end_rsp_py.isoformat()
    # has_earlier, has_later, has_more
    has_earlier = False
    has_later = False
    has_more = False
    r_earlier = all_records.filter(date__lt=begin_rsp_py)
    r_later = all_records.filter(date__gt=end_rsp_py)
    if r_earlier:
        has_earlier = True
    if r_later:
        has_later = True
    if has_earlier or has_later:
        has_more = True
    #
    _rdata = {
        'failed': False,
        'number_req': number_req,
        'begin_req': begin_req,
        'end_req': end_req,
        'number_rsp': number_rsp,
        'begin_rsp': begin_rsp,
        'end_rsp': end_rsp,
        'has_more': has_more,
        'has_earlier': has_earlier,
        'has_later': has_later,
        'data': [],
    }
    for r in records_list:
        # get data
        if std:
            _data = r.get_data_std()
        else:
            _data = r.get_data()
        # append data
        _rdata['data'].append(_data)

    # return
    return _rdata
# }}}


# get_num_record {{{
def get_num_record(user_id, indicator_id, number, end=None, std=False):
    """
    return the *latest* number records.
    args 'end' to specify the end date range.
    arg 'std=True' to get data in standard unit

    return dict format: (data sorted by 'date')
    rdata = {
        'failed': False,
        'number_req': number_of_records_request,
        'begin_req': begin_req,
        'end_req': end_req,
        'number_rsp': number_of_records_response,
        'begin_rsp': begin_rsp,
        'end_rsp': end_rsp,
        'has_more': True|False,
        'has_earlier': True|False,
        'has_later': True|False,
        'data': [r1.get_data(), r2.get_data(), ...],
    }
    """
    # default parameters
    number_req = None
    begin_req = None
    end_req = None
    #
    uid = int(user_id)
    indid = int(indicator_id)
    all_records = im.IndicatorRecord.objects.\
            filter(user__id=uid, indicator__id=indid).\
            order_by('date', 'created_at')
    # check if 'all_records' empty
    if not all_records:
        return {'failed': True}
    # check end date
    if end is None:
        end = all_records.reverse()[0].date
    elif isinstance(end, datetime.date):
        end_req = end.isoformat()
    else:
        raise ValueError(u"end='%s' 不是合法的日期" % end)
        return {'failed': True}
    records = all_records.filter(date__lte=end)
    # check number (required param)
    try:
        number_req = int(number)
        records_list = list(records.reverse()[:number_req])
    except ValueError:
        raise ValueError(u"number='%s' 错误" % number)
        return {'failed': True}
    # re-sort by 'date'
    records_list.reverse()

    # process records
    number_rsp = len(records_list)
    begin_rsp_py = records_list[0].date
    begin_rsp = begin_rsp_py.isoformat()
    end_rsp_py = records_list[-1].date
    end_rsp = end_rsp_py.isoformat()
    # has_earlier, has_later, has_more
    has_earlier = False
    has_later = False
    has_more = False
    r_earlier = all_records.filter(date__lt=begin_rsp_py)
    r_later = all_records.filter(date__gt=end_rsp_py)
    if r_earlier:
        has_earlier = True
    if r_later:
        has_later = True
    if has_earlier or has_later:
        has_more = True
    #
    _rdata = {
        'failed': False,
        'number_req': number_req,
        'begin_req': begin_req,
        'end_req': end_req,
        'number_rsp': number_rsp,
        'begin_rsp': begin_rsp,
        'end_rsp': end_rsp,
        'has_more': has_more,
        'has_earlier': has_earlier,
        'has_later': has_later,
        'data': [],
    }
    for r in records_list:
        # get data
        if std:
            _data = r.get_data_std()
        else:
            _data = r.get_data()
        # append data
        _rdata['data'].append(_data)

    # return
    return _rdata
# }}}


# get_record_std {{{
def get_record_std(**kwargs):
    return get_record(std=True, **kwargs)
# }}}


# get_num_record_std {{{
def get_num_record_std(**kwargs):
    return get_num_record(std=True, **kwargs)
# }}}


# types of recommended indicators, and weights {{{
RI_TYPES = {
    'ANNOTATION_COLLECTED': u'ANN_CL',
    'BLOG_CATCHED': u'BLG_CT',
    'BLOG_COLLECTED': u'BLG_CL',
    'OTHER': u'OTHER',
    'ERROR': u'ERROR',      # no 'RelatedIndicator' data
}
RI_WEIGHTS = {
    RI_TYPES['ANNOTATION_COLLECTED']: 4.0,
    RI_TYPES['BLOG_CATCHED']: 3.0,
    RI_TYPES['BLOG_COLLECTED']: 2.0,
    RI_TYPES['OTHER']: 1.0,
    RI_TYPES['ERROR']: 0.0,
}
# }}}


# calc_indicator_weight {{{
def calc_indicator_weight(user_id, indicator_id):
    """
    calculate the weight of given indicator
    used by 'recommend_indicator'

    return format:
    {'weight': w, 'type': t}
    """
    # weight = weight_type * relatedindicator.weight
    user = User.objects.get(id=user_id)
    ri_qs = im.RelatedIndicator.objects.filter(indicator__id=indicator_id)
    if not ri_qs:
        # queryset empty: no 'RelatedIndicator' for this indicator
        type = RI_TYPES['ERROR']
        w = 0.0
        return {'weight': w, 'type': type}
    # queryset not empty
    annotation_ri_qs = ri_qs.filter(annotation__collected_by=user)
    blogcatch_ri_qs = ri_qs.filter(blog__catched_by=user)
    blogcollect_ri_qs = ri_qs.filter(blog__collected_by=user)
    weights = []
    if annotation_ri_qs:
        # related to annotations collected by user
        type = RI_TYPES['ANNOTATION_COLLECTED']
        for ri in annotation_ri_qs:
            w = RI_WEIGHTS[type] * ri.weight
            weights.append({'weight': w, 'type': type})
    elif blogcatch_ri_qs:
        # related to blogs catched by user
        type = RI_TYPES['BLOG_CATCHED']
        for ri in blogcatch_ri_qs:
            w = RI_WEIGHTS[type] * ri.weight
            weights.append({'weight': w, 'type': type})
    elif blogcollect_ri_qs:
        # related to blogs collected by user
        type = RI_TYPES['BLOG_COLLECTED']
        for ri in blogcollect_ri_qs:
            w = RI_WEIGHTS[type] * ri.weight
            weights.append({'weight': w, 'type': type})
    else:
        # other type, use 'ri_qs' here
        type = RI_TYPES['OTHER']
        for ri in ri_qs:
            w = RI_WEIGHTS[type] * ri.weight
            weights.append({'weight': w, 'type': type})
    # sort results
    weights_sorted = sorted(weights, key = lambda item: item['weight'])
    # return final result
    return weights_sorted[-1]
# }}}


# recommend_indicator {{{
def recommend_indicator(user_id, number):
    """
    recommend unfollowed indicator for user,
    based on his/her readings and collections.

    return a list of recommended indicators in format:
    [ {'id': id, 'weight': w, 'type': t}, ... ]
    """
    user_id = int(user_id)
    number = int(number)
    # get unfollowed indicators
    u = User.objects.get(id=user_id)
    ui, created = im.UserIndicator.objects.get_or_create(user=u)
    # XXX: if 'exclude(followed_indicators=ui)' OK??
    uf_ind_qs = im.Indicator.objects.exclude(followed_indicators=ui)
    # calc weight for each unfollowed indicator
    weights = []
    for ind in uf_ind_qs:
        wdict = calc_indicator_weight(user_id, ind.id)
        weights.append({
            'id': ind.id,
            'weight': wdict.get('weight'),
            'type': wdict.get('type'),
        })
    # sort 'weights' dict list by key 'weight'
    weights_sorted = sorted(weights, key=lambda item: item['weight'])
    weights_sorted.reverse()
    # return results with largest weights
    return weights_sorted[:number]
# }}}


# format_data {{{
def format_data(indicator_obj, value=None, val_max=None, val_min=None):
    """
    format given data according to the dataType of given Indicator,
    make it proper for django templates
    e.g.:
    if number very big, then display in 'exponent notation'

    used in '.views.indicator_status()'
    """
    # threshold to show a float number in scientific notation
    float_threshold = 9999.9
    # float display format: fixed point, exponent notation
    fix_fmt = '{:,.1f}'    # comma as a thousands separator
    exp_fmt = '{:.2e}'
    # regex to process exponent notation
    rep = re.compile(r'^(?P<sign>[-+]?)(?P<num>\d\.\d+)[eE]\+?(?P<expminus>-?)0*(?P<exp>[1-9]+)$')
    # range symbol (range: low $symbol$ high)
    range_sym = '&sim;'
    # default return value
    value_str = u''

    # check given 'indicator_obj'
    ind = indicator_obj
    if not isinstance(ind, im.Indicator):
        print u'Error: given indicator_obj NOT a instance of Indicator'
        raise ValueError(u'Given indicator_obj NOT a instance of Indicator')
    # get dataType
    dataType = ind.dataType

    if value is not None:
        # a) record float data; b) record integer/pm data;
        # c) confine integer/pm data.
        if dataType == ind.INTEGER_TYPE:
            # TODO: process 'integer type' data
            value_str = u'INTEGER: %s' % value
        elif dataType == ind.PM_TYPE:
            if value == u'+':
                value_str = u'阳性(+)'
            else:
                value_str = u'阳性(-)'
        elif dataType in [ind.FLOAT_TYPE, ind.FLOAT_RANGE_TYPE]:
            # process float number
            value = float(value)
            if value <= float_threshold:
                value_str = fix_fmt.format(value)
            else:
                value_expstr = exp_fmt.format(value)
                # convert to html exponent format
                m = rep.match(value_expstr)
                value_str = "%s%s&times;10<sup>%s%s</sup>" % (
                        m.group('sign'), m.group('num'),
                        m.group('expminus'), m.group('exp'))
        else:
            # unknown XXX
            pass
    elif (val_max is not None) and (val_min is not None):
        # a) record range data; b) confine range.
        # val_max
        if val_max <= float_threshold:
            val_max_str = fix_fmt.format(val_max)
        else:
            val_max_expstr = exp_fmt.format(val_max)
            # convert to html exponent format
            m = rep.match(val_max_expstr)
            val_max_str = "%s%s&times;10<sup>%s%s</sup>" % (
                    m.group('sign'), m.group('num'),
                    m.group('expminus'), m.group('exp'))
        # val_min
        if val_min <= float_threshold:
            val_min_str = fix_fmt.format(val_min)
        else:
            val_min_expstr = exp_fmt.format(val_min)
            # convert to html exponent format
            m = rep.match(val_min_expstr)
            val_min_str = "%s%s&times;10<sup>%s%s</sup>" % (
                    m.group('sign'), m.group('num'),
                    m.group('expminus'), m.group('exp'))
        # value_str
        value_str = u'%s %s %s' % (val_min_str, range_sym, val_max_str)
    else:
        # other type??
        pass

    return value_str
# }}}