Project

General

Profile

Download (6.69 KB) Statistics
| Branch: | Revision:

git_sitools_idoc / webstatDev / idoc_Maison / webstat / libChart4StatSitools2.py @ master

1
#!/usr/bin/env python
2
# -*-coding:utf-8-*-
3

    
4
import sys
5
try:
6
    import random
7
except BaseException:
8
    sys.exit("Import failed in module libStatSitools :\n\trandom module is required")
9
try:
10
    import cairo
11
except BaseException:
12
    sys.exit("Import failed in module libStatSitools :\n\tcairo module is required")
13
try:
14
    import pycha.pie as pie
15
except BaseException:
16
    sys.exit("Import failed in module libStatSitools :\n\tpycha module is required")
17
try:
18
    from datetime import datetime
19
except BaseException:
20
    sys.exit("Import failed in module libStatSitools :\n\tdatetime module is required")
21
try:
22
    from datetime import date
23
except BaseException:
24
    sys.exit("Import failed in module libStatSitools :\n\tdate module is required")
25
try:
26
    import pygal
27
except BaseException:
28
    sys.exit("Import failed in module libStatSitools :\n\tpygal module is required")
29
try:
30
    from dateutil.relativedelta import relativedelta
31
except:
32
    sys.exit("Import failed in module libStatSitools :\n\tdateutil.relativedelta module is required")
33

    
34
#PATH FOR DEV
35
home_base = "/home/marc/Projet/idoc_Maison"
36
#PATH FOR PROD
37
#home_base = "/var/www/django/mon_projet/"
38

    
39
url_png = "/static/chart/"
40

    
41
time_format_for_by_month = "%Y %m"
42

    
43
def create_dataset_from_data(dico_data):
44
    graph_dataset = [(data, [[0, dico_data[data]]]) for data in dico_data]
45
    return graph_dataset
46

    
47

    
48
def add_date():
49
    now = datetime.now()
50
    tmp = str(now).split(" ")
51
    date_to_add = tmp[0].split("-")[0]+tmp[0].split("-")[1]+tmp[0].split("-")[2]+tmp[1].split(".")[0].split(":")[0]+tmp[1].\
52
        split(".")[0].split(":")[1]+tmp[1].split(".")[0].split(":")[2]+tmp[1].split(".")[1]
53
    return date_to_add
54

    
55

    
56
def svg_chart(dico_data, title_chart):
57

    
58
    pie_chart_pygal = pygal.Pie()
59
    pie_chart_pygal.title = title_chart
60
    date = add_date()
61

    
62
    url_output_svg = url_png+title_chart+date+".svg"
63
    print "**********************************************"
64
    print "*************  Nb entrée pour", title_chart, " : ", len(dico_data)
65
    print "**********************************************"
66
    dico_data_tmp = dico_data.copy()
67
    if len(dico_data) > 24:
68
        dico_data2 = {}
69
        i = 0
70
        for key in dico_data_tmp:
71
            if i > 24:
72
                dico_data2[key] = dico_data_tmp[key]
73
                del dico_data[key]
74
            i += 1
75

    
76

    
77
    for data in dico_data:
78
            pie_chart_pygal.add(data, dico_data[data])
79

    
80
    if len(dico_data_tmp) > 24:
81
        for datas in dico_data2:
82
            pie_chart_pygal.add(datas, dico_data2[datas], secondary=True)
83

    
84
    output_svg = home_base+url_output_svg
85
    try:
86
        pie_chart_pygal.render_to_file(output_svg)
87
    except BaseException, e:
88
        print 'In svg Exception : ', str(e)
89

    
90
    url_chart_png = png_chart(dico_data, title_chart)
91
    return [url_output_svg, url_chart_png]
92

    
93

    
94
def png_chart(dico_data, title_chart):
95

    
96
    pie_chart_pygal_png = pygal.Pie()
97
    pie_chart_pygal_png.title = title_chart
98
    
99
    date = add_date()
100
    url_output_png = url_png+title_chart+date+".png"
101
    for data in dico_data:
102
        pie_chart_pygal_png.add(data, dico_data[data])
103
    output_png = home_base+url_output_png
104
    try:
105
        pie_chart_pygal_png.render_to_png(output_png)
106
    except BaseException, e:
107
        print 'In PNG Exception : ', str(e)
108
    return url_output_png
109

    
110

    
111
def svg_bar_chart(dico_data, start_date, end_date, title_chart):
112

    
113
    dates_tmp_not_sorted = []
114
    dates_tmp_str_sorted = []
115
    dates_sorted = []
116
    dico_data2 = {}
117
    for date in dico_data.keys():
118
        dates_tmp_not_sorted.append(str(date[1])+"/"+str(date[0]))
119

    
120
    for dd in sorted(dates_tmp_not_sorted, key=lambda d: map(int, d.split('/'))):
121
        dates_tmp_str_sorted.append(dd.split('/')[1]+"/"+dd.split('/')[0][2:])
122

    
123
    for i in range(0, int(diff_month(start_date, end_date)+1)):
124
        t = datetime.combine(start_date, datetime.min.time())+relativedelta(months=i)
125
        dates_sorted.append(t)
126

    
127
    for x in dates_tmp_str_sorted:
128
        date_test = datetime.strptime(str(x), "%m/%y")
129
        dico_data2[date_test] = dico_data[(date_test.month, date_test.year)]
130

    
131
    list_tmp = []
132
    list_tmp2 = []
133
    list_tmp.append("")
134

    
135
    #bar_chart = pygal.DateY(x_label_rotation=90, human_readable=True, y_scale=1073741824)
136
    #bar_chart.title = title_chart
137
    #bar_chart.x_label_format = "%m/%Y"
138
    #bar_chart.x_labels = dates_sorted
139
    #print "************* dates_sorted : ", dates_sorted
140
    try:
141
        for data in dates_sorted:
142
            if data not in dico_data2.keys():
143
                dico_data2[data] = 0
144
            list_tmp2.append((data, dico_data2[data]))
145
        list_tmp.append(list_tmp2)
146

    
147
        #bar_chart.add(list_tmp[0],  (list_tmp[1][i] for i in range(0, len(list_tmp[1]))))
148
        #bar_chart.show_legend = False
149
        date_svg = add_date()
150
        url_output_bar_chart_svg = url_png+"Bar_by_Month_"+date_svg+".svg"
151
        #bar_chart.render_to_file(home_base+url_output_bar_chart_svg)
152
        #url_output_bar_chart_png = url_bar_chart_png(list_tmp, dates_sorted, title_chart)
153

    
154
        datetimeline = pygal.DateTimeLine(x_label_rotation=35, truncate_label=-1,human_readable=True,x_value_formatter=lambda dt: dt.strftime('%m/%Y'))
155
        datetimeline.title = title_chart
156
        datetimeline.x_labels = dico_data2.keys()
157
        datetimeline.add("",list_tmp2)
158

    
159
        datetimeline.show_legend = False
160
        date_svg = add_date()
161
        url_output_bar_chart_svg = url_png+"Bar_by_Month_"+date_svg+".svg"
162
        datetimeline.render_to_file(home_base+url_output_bar_chart_svg)
163
        url_output_bar_chart_png = url_bar_chart_png(list_tmp2, dico_data2.keys(), title_chart)
164
    except BaseException, e:
165
        print str(e)
166
    return [url_output_bar_chart_svg, url_output_bar_chart_png]
167

    
168

    
169
def url_bar_chart_png(list_data, dates, title):
170
    datetimeline = pygal.DateTimeLine(x_label_rotation=35, truncate_label=-1,human_readable=True,x_value_formatter=lambda dt: dt.strftime('%m/%Y'))
171
    datetimeline.x_labels = dates
172
    datetimeline.title = title
173
    datetimeline.add("",list_data)
174
    # A METTRE POUR CREER LE PNG !
175
    datetimeline.print_values = False
176
    datetimeline.show_legend = False
177
    url_output_png = url_png+"Bar_by_Month_"+add_date()+".png"
178

    
179
    datetimeline.render_to_png(home_base+url_output_png)
180

    
181
    return url_output_png
182

    
183

    
184
def diff_month(d2, d1):
185
    return (d1.year - d2.year)*12 + d1.month - d2.month
186

    
187
def format_download_vol(vol_down):
188
    vol_data = ""
189
    try:
190
        if 1000 <= vol_down < 1000000:
191
            vol_data = str(round(vol_down/1000, 2))+" Ko"
192
        elif 1000000 <= vol_down < 1000000000:
193
            vol_data = str(round(vol_down/1000000, 2))+" Mo"
194
        elif 1000000000 <= vol_down < (1000000000*1000):
195
            vol_data = str(round(vol_down/1000000000, 2))+" Go"
196
    except BaseException, e:
197
        print str(e)
198
    return vol_data