Coupure prévue mardi 3 Août au matin pour maintenance du serveur. Nous faisons au mieux pour que celle-ci soit la plus brève possible.

visualization_views.py 12.6 KB
Newer Older
1
import sys
Janez K's avatar
Janez K committed
2
from django.shortcuts import render
3
from django.http import Http404, HttpResponse
4

5
from workflows import module_importer
6
7
def setattr_local(name, value, package):
    setattr(sys.modules[__name__], name, value)
8
module_importer.import_all_packages_libs("visualization_views",setattr_local)
Janez K's avatar
Janez K committed
9
10
11

def odt_to_tab(request,input_dict,output_dict,widget):
    import Orange
Janez K's avatar
Janez K committed
12
    from mothra.settings import MEDIA_ROOT
Janez K's avatar
Janez K committed
13
    from workflows.helpers import ensure_dir
Janez K's avatar
Janez K committed
14
    destination = MEDIA_ROOT+'/'+str(request.user.id)+'/'+str(widget.id)+'.tab'
Janez K's avatar
Janez K committed
15
16
17
18
19
20
21
22
    ensure_dir(destination)
    input_dict['data'].save(destination)
    filename = str(request.user.id)+'/'+str(widget.id)+'.tab'
    output_dict['filename'] = filename
    return render(request, 'visualizations/string_to_file.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})
    
def odt_to_csv(request,input_dict,output_dict,widget):
    import Orange
Janez K's avatar
Janez K committed
23
    from mothra.settings import MEDIA_ROOT
Janez K's avatar
Janez K committed
24
    from workflows.helpers import ensure_dir
Janez K's avatar
Janez K committed
25
    destination = MEDIA_ROOT+'/'+str(request.user.id)+'/'+str(widget.id)+'.csv'
Janez K's avatar
Janez K committed
26
27
28
29
30
31
32
33
    ensure_dir(destination)
    input_dict['data'].save(destination)
    filename = str(request.user.id)+'/'+str(widget.id)+'.csv'
    output_dict['filename'] = filename
    return render(request, 'visualizations/string_to_file.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})    
    
def odt_to_arff(request,input_dict,output_dict,widget):
    import Orange
Janez K's avatar
Janez K committed
34
    from mothra.settings import MEDIA_ROOT
Janez K's avatar
Janez K committed
35
    from workflows.helpers import ensure_dir
Janez K's avatar
Janez K committed
36
    destination = MEDIA_ROOT+'/'+str(request.user.id)+'/'+str(widget.id)+'.arff'
Janez K's avatar
Janez K committed
37
38
39
40
41
42
43
    ensure_dir(destination)
    input_dict['data'].save(destination)
    filename = str(request.user.id)+'/'+str(widget.id)+'.arff'
    output_dict['filename'] = filename
    return render(request, 'visualizations/string_to_file.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})

def string_to_file(request,input_dict,output_dict,widget):
Janez K's avatar
Janez K committed
44
    from mothra.settings import MEDIA_ROOT
Janez K's avatar
Janez K committed
45
    from workflows.helpers import ensure_dir
Janez K's avatar
Janez K committed
46
    destination = MEDIA_ROOT+'/'+str(request.user.id)+'/'+str(widget.id)+'.txt'
Janez K's avatar
Janez K committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    ensure_dir(destination)
    f = open(destination,'w')
    f.write(str(input_dict['string']))
    f.close()
    filename = str(request.user.id)+'/'+str(widget.id)+'.txt'
    output_dict['filename'] = filename
    return render(request, 'visualizations/string_to_file.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})

def display_string(request,input_dict,output_dict,widget):
    return render(request, 'visualizations/display_string.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})

def object_viewer(request,input_dict,output_dict,widget):
    import pprint
    output_dict = {'object_string':pprint.pformat(input_dict['object'])}
    return render(request, 'visualizations/object_viewer.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})

Izidorf's avatar
Izidorf committed
63
64
65
66
67
68
69
70
#YOU HAVE TO MOVE THIS FUNCTION TO ScikitAlgorithms/visualization_views.py
def scikitAlgorithms_displayDS(request,input_dict,output_dict,widget):
    data = input_dict['data']
    output_dict={'data':data}
    return render(request, 'visualizations/scikitAlgorithms_displayDS.html',{'widget':widget,'input_dict':input_dict,'output_dict':helperDisplayDS(output_dict)})
   
def helperDisplayDS(data):
    #get data to fill table
Izidorf's avatar
bacon  
Izidorf committed
71
72
73
74
    info = data['data']
    n_sample = info["data"]
    n_feature = info["target"]

Izidorf's avatar
Izidorf committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    # join data in the right format
    import numpy
    csv=[]
    count=0
    for sample in n_sample:
        csv.append(numpy.append(sample,n_feature[count])) #join n_sample and n_feature array
        count+=1

    attrs = ["attribute" for i in range(len(n_sample[0]))] #name of attributes
    class_var = 'category'
    metas = '' 
    data_new = csv #fill table with data
    
    return {'attrs':attrs, 'metas':metas, 'data_new':data_new, 'class_var':class_var}

Izidorf's avatar
bacon  
Izidorf committed
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
# def helperDisplayDS(data):
#     #get data to fill table
#     info = data['data']
#     n_sample = info["data"]
#     n_feature = info["target"]
#     attrs = info["feature_names"]

#     # join data in the right format
#     import numpy
#     csv=[]
#     count=0
#     for sample in n_sample:
#         csv.append(numpy.append(sample,n_feature[count])) #join n_sample and n_feature array
#         count+=1

#    # attrs = ["attribute" for i in range(len(n_sample[0]))] #name of attributes
#     class_var = ["class" for i in range(len([n_sample[0]]))]
#     metas = '' 
#     data_new = csv #fill table with data
    
#  
# return {'attrs':attrs, 'metas':metas, 'data_new':data_new, 'class_var':class_var}



115
116
117
def orng_table_to_dict(data):
    import Orange
    attrs, metas, data_new = [], [], []
Janez K's avatar
Janez K committed
118
119
120
121
122
123
124
125
    try:
        class_var = data.domain.class_var.name
    except:
        class_var = ''
    for m in data.domain.get_metas():
        metas.append(data.domain.get_meta(m).name)
    for a in data.domain.attributes:
        attrs.append(a.name)
126
    pretty_float = lambda x, a: '%.3f' % x if a.var_type == Orange.feature.Type.Continuous and x!='?' else x
Janez K's avatar
Janez K committed
127
128
129
    for inst in xrange(len(data)):
        inst_new = []
        for a in data.domain.variables:
130
            value = data[inst][a.name].value
131
            inst_new.append((a.name, pretty_float(value, a)))
Janez K's avatar
Janez K committed
132
        for m in data.domain.get_metas():
133
134
            value = data[inst][m].value
            a = data.domain.get_meta(m)
135
            inst_new.append((a.name, pretty_float(value, a)))
Janez K's avatar
Janez K committed
136
        data_new.append(inst_new)
137
    return {'attrs':attrs, 'metas':metas, 'data':data_new, 'class_var':class_var}
Janez K's avatar
Janez K committed
138

139
140
141
def table_viewer(request,input_dict,output_dict,widget):
    data = input_dict['data']
    return render(request, 'visualizations/table_viewer.html',{'widget':widget,'input_dict':input_dict,'output_dict':orng_table_to_dict(data)})
Janez K's avatar
Janez K committed
142
143
144
145
146
    
def pr_space_view(request,input_dict,output_dict,widget):
    return render(request, 'visualizations/pr_space.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})
    
def eval_bar_chart_view(request,input_dict,output_dict,widget):
Janez K's avatar
bugfix  
Janez K committed
147
148
    for i in input_dict['eval_results']:
        try:
Janez K's avatar
bugfix  
Janez K committed
149
            i['accuracy'] = i['accuracy']/100.0
Janez K's avatar
bugfix  
Janez K committed
150
151
        except:
            pass
Janez K's avatar
Janez K committed
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
    return render(request, 'visualizations/eval_bar_chart.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})
    
def eval_to_table_view(request,input_dict,output_dict,widget):
    return render(request, 'visualizations/eval_to_table.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})

def data_table_view(request,input_dict,output_dict,widget):
    #import orange
    data = input_dict['data']
    if data == None:
        view_dict = {'attributes':[], 'examples': []}
        return render(request, 'visualizations/data_table.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict,'view_dict':view_dict})
    else:
        attrs = [x[1].name for x in data.domain.getmetas().items()]
        attrs.extend([x.name for x in data.domain])
        view_dict = {'attributes': attrs}
        view_dict['examples'] = []
        for ex in data:
            newex = []
            for meta in ex.getmetas().items():
                print meta[1].variable.name, ex[meta[1].variable.name]
                newex.append(ex[meta[1].variable.name])
            for x in ex:
                newex.append(x)
            view_dict['examples'].append(newex)    
        return render(request, 'visualizations/data_table.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict,'view_dict':view_dict})
    
def data_info_view(request,input_dict,output_dict,widget):
    import orange
    data = input_dict['data']
    n = len(data)    
    info_dict = {'instances': len(data),
                 'attrs': len(data.domain.attributes),
                 'num_classes' : len(data.domain.classVar.values),
                 'class_type': data.domain.classVar.varType,
                 'has_miss_values': ('yes' if data.hasMissingValues() == 1 else 'no'),
                 'has_miss_classes' : ('yes' if data.hasMissingClasses() == 1 else 'no'),
                 'metas': data.domain.getmetas(),
                 'has_metas': len(data.domain.getmetas())
                 }#                 'classes': data.domain.classVar.values,
    # count number of continuous and discrete attributes
    ncont=0; ndisc=0; 
    for a in data.domain.attributes:
        if a.varType == orange.VarTypes.Discrete:
            ndisc +=  1
        else:
            ncont +=  1
    
    info_dict['discrete'] = ndisc
    info_dict['continuous'] = ncont
    
    # number of instances with missing values
    miss_val_insts =  []
    miss_val_attrs =  [] 
    if info_dict['has_miss_values'] == 'yes':
        for i in range(n):
            for j in range(len(data[i])):
                if data[i][j].isSpecial():
                    if i not in miss_val_insts:
                        miss_val_insts.append(i)
                    if j not in miss_val_attrs:
                        miss_val_attrs.append(j)
                    
    info_dict['miss_val_insts'] = len(miss_val_insts)
    info_dict['mvir'] = len(miss_val_insts)*100./n
    info_dict['miss_val_attrs'] = len(miss_val_attrs)
    info_dict['mvar'] = len(miss_val_attrs)*100./n
    
    # obtain class distribution
    c = [0] * len(data.domain.classVar.values)
    for e in data:
        c[int(e.getclass())] += 1
    r = [0.] * len(c)
    for i in range(len(c)):
        r[i] = c[i]*100./len(data)
    
    info_dict['class_distr'] = [{'class': z[0], 'instances':z[1], 'ratio':z[2]} for z in zip(data.domain.classVar.values, c, r)]
      
    
    return render(request, 'visualizations/data_table_info.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict, 'info_dict':info_dict})

232
233
234
235
236
237
238
239
240
241
242
def treeToJSON(node, path="", nodes={}):
    #made by Bogdan Okresa Duric :)
    
    import Orange
    import json

    if not node:
        return

    if path=="": #get the dictionary prepared, insert root node
        nodes.update ({ #root node properties
243
244
            "name": "root",
            # "name":node.node_classifier.class_var.name,
245
246
247
248
249
250
            "ID":node.reference(),
            "children":[]
        })
        path = "['children']" #prepare path for future use, it points into 'children' property of the root node

    if node.branch_selector: #if the node has branches
bogdan's avatar
bogdan committed
251
        for n in range(len(node.branches)): #walk through all the branches one by one
252
            try:
bogdan's avatar
bogdan committed
253
                if node.branches[n].branch_selector: #if the node (branch) has branches
254
                    child = { #set node properties
255
256
                        "name":node.branch_selector.class_var.name[:15] + " "
                         + node.branch_descriptions[n][:10],
bogdan's avatar
bogdan committed
257
                        "ID":node.branches[n].reference(),
258
259
260
261
262
263
264
265
266
267
                        "children":[] #stays open for future descendant nodes
                        }

                    eval ("nodes" + path + ".append(" + str(child) + ")") #write node properties
                    # 'nodes' is the dictionary
                    #path is the path to the current node, i.e. current parent node
                    #child is dictionary with node properties

                else: #if node is a leaf
                    child = {
268
269
270
271
272
273
274
                        "name":node.branch_selector.class_var.name + " "
                         + node.branch_descriptions[n]
                          + ": "
                           + node.branches[n].node_classifier.default_value.value
                            + " ("
                             + str(node.branches[n].node_classifier.GetProbabilities*100)
                              + "%)",
bogdan's avatar
bogdan committed
275
                        "ID":node.branches[n].reference(),
276
277
278
279
280
281
282
283
284
285
286
                        }
                    eval ("nodes" + path + ".append(" + str(child) + ")")
            except:
                pass
        for i in range(len(node.branches)): #go and work with the branches, one by one
            treeToJSON(node.branches[i], path + "[" + str(i) + "]" + "['children']", nodes) #work with child node, adding it's "address"
    else: #if the node has no branches, simply return
        return

    return json.JSONEncoder().encode(nodes) #output complete JSON description of the tree

bogdan's avatar
bogdan committed
287
288
def tree_visualization(request, input_dict, output_dict, widget):
    import Orange
289
    import json
bogdan's avatar
bogdan committed
290

291
    tc = input_dict['clt']
bogdan's avatar
bogdan committed
292

293
294
295
    jsonJ = treeToJSON(tc.tree)
    
    return render(request, 'visualizations/tree_visualization.html', {'widget':widget, 'input_dict':input_dict, 'json':jsonJ})