Création d'un compte pour un collaborateur extérieur au laboratoire depuis l'intranet ICube : https://intranet.icube.unistra.fr/fr/labs/member/profile

visualization_views.py 11.5 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})

63
64
65
def orng_table_to_dict(data):
    import Orange
    attrs, metas, data_new = [], [], []
Janez K's avatar
Janez K committed
66
67
68
69
70
71
72
73
    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)
74
    pretty_float = lambda x, a: '%.3f' % x if a.var_type == Orange.feature.Type.Continuous else x
Janez K's avatar
Janez K committed
75
76
77
    for inst in xrange(len(data)):
        inst_new = []
        for a in data.domain.variables:
78
            value = data[inst][a.name].value
79
            inst_new.append((a.name, pretty_float(value, a)))
Janez K's avatar
Janez K committed
80
        for m in data.domain.get_metas():
81
82
            value = data[inst][m].value
            a = data.domain.get_meta(m)
83
            inst_new.append((a.name, pretty_float(value, a)))
Janez K's avatar
Janez K committed
84
        data_new.append(inst_new)
85
    return {'attrs':attrs, 'metas':metas, 'data':data_new, 'class_var':class_var}
Janez K's avatar
Janez K committed
86

87
88
89
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
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
    
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):
    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})

def sdmsegs_viewer(request,input_dict,output_dict,widget):
    import json
    d = json.loads(input_dict['json'])
    output = {}
    for k, v in d['A']['WRAcc'].items():
        terms = []
        for t in v['terms']:
            try:
                terms.append(d['ontDict'][t])
            except Exception, e:
                pass
        output[int(k)] = {
        'name': terms,
        'topGenes': int(len(v['topGenes'])),
        'allGenes': int(len(v['allGenes'])),
        'wracc': round(v['scores']['wracc'], 3)
        }
    output_dict = {'json_output':output}
    return render(request, 'visualizations/sdmsegs_viewer.html',{'widget':widget,'input_dict':input_dict,'output_dict':output_dict})
bogdan's avatar
bogdan committed
194

195
196
197
198
199
200
201
202
203
204
205
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
206
207
            "name": "root",
            # "name":node.node_classifier.class_var.name,
208
209
210
211
212
213
            "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
214
        for n in range(len(node.branches)): #walk through all the branches one by one
215
            try:
bogdan's avatar
bogdan committed
216
                if node.branches[n].branch_selector: #if the node (branch) has branches
217
                    child = { #set node properties
218
219
                        "name":node.branch_selector.class_var.name[:15] + " "
                         + node.branch_descriptions[n][:10],
bogdan's avatar
bogdan committed
220
                        "ID":node.branches[n].reference(),
221
222
223
224
225
226
227
228
229
230
                        "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 = {
231
232
233
234
235
236
237
                        "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
238
                        "ID":node.branches[n].reference(),
239
240
241
242
243
244
245
246
247
248
249
                        }
                    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
250
251
def tree_visualization(request, input_dict, output_dict, widget):
    import Orange
252
    import json
bogdan's avatar
bogdan committed
253

254
    tc = input_dict['clt']
bogdan's avatar
bogdan committed
255

256
257
258
    jsonJ = treeToJSON(tc.tree)
    
    return render(request, 'visualizations/tree_visualization.html', {'widget':widget, 'input_dict':input_dict, 'json':jsonJ})