library.py 28.1 KB
Newer Older
Janez K's avatar
Janez K committed
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 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
from workflows.security import safeOpen
import nlp
import cPickle

def test_interaction(input_dict):
    return input_dict

def create_list(input_dict):
    return input_dict
    
def add_multiple(input_dict):
    output_dict = {}
    output_dict['sum'] = 0
    for i in input_dict['integer']:
        output_dict['sum'] = int(i)+output_dict['sum']
    return output_dict

def delay(input_dict,widget):
    widget.progress=0
    widget.save()
    timeleft = int(input_dict['time'])
    i = 0
    import time
    import math
    while i<timeleft:
        time.sleep(1)
        i=i+1
        widget.progress = math.floor(((i*1.0)/timeleft)*100)
        widget.save()
    widget.progress=100
    widget.save()
    output_dict = {}
    output_dict['data'] = input_dict['data']
    return output_dict

def load_file(input_dict):
    return input_dict
    
def file_to_string(input_dict):
    f = safeOpen(input_dict['file'])
    output_dict = {}
    output_dict['string']=f.read()
    return output_dict

def load_to_string(input_dict):
    '''
    Opens the file and reads its contents into a string.
    '''
    f = safeOpen(input_dict['file'])
    output_dict = {}
    output_dict['string']=f.read()
    return output_dict

def pickle_object(input_dict):
    '''
    Serializes the input object.
    '''
    pkl_obj = cPickle.dumps(input_dict['object'])
    output_dict = {}
    output_dict['pickled_object'] = pkl_obj
    return output_dict

def unpickle_object(input_dict):
    '''
    Serializes the input object.
    '''
    obj = cPickle.loads(str(input_dict['pickled_object']))
    output_dict = {}
    output_dict['object'] = obj
    return output_dict

def call_webservice(input_dict):
    from services.webservice import WebService
    ws = WebService(input_dict['wsdl'],float(input_dict['timeout']))
    selected_method = {}
    for method in ws.methods:
        if method['name']==input_dict['wsdl_method']:
            selected_method = method
    function_to_call = getattr(ws.client,selected_method['name'])
    ws_dict = {}
    for i in selected_method['inputs']:
        try:
            ws_dict[i['name']]=input_dict[i['name']]
            if ws_dict[i['name']] is None:
                pass
            if i['type'] == bool:
                if input_dict[i['name']]=="true":
                    ws_dict[i['name']]=1
                else:
                    ws_dict[i['name']]=0
            if ws_dict[i['name']] == '':
                if input_dict['sendemptystrings']=="true":
                    ws_dict[i['name']] = ''
                else:
                    ws_dict.pop(i['name'])
        except Exception as e: 
            print e
            ws_dict[i['name']]=''
    print ws_dict
    results = function_to_call(**ws_dict)
    output_dict=results
    return output_dict

def multiply_integers(input_dict):
    product = 1
    for i in input_dict['integers']:
        product = product*int(i)
    output_dict={'integer':product}
    return output_dict

def filter_integers(input_dict):
    return input_dict
    
def filter_integers_post(postdata,input_dict,output_dict):
    try:
        output_dict['integers'] = postdata['integer']
    except:
        pass
    return output_dict

def create_integer(input_dict):
    output_dict = {}
    output_dict['integer'] = input_dict['integer']
    return output_dict
    
def create_string(input_dict):
    return input_dict  
    
def concatenate_strings(input_dict):
    output_dict = {}
    j = len(input_dict['strings'])
    for i in range(j):
        input_dict['strings'][i]=str(input_dict['strings'][i])
    output_dict['string'] = input_dict['delimiter'].join(input_dict['strings'])
    return output_dict
    
def display_string(input_dict):
    return {}

def add_integers(input_dict):
    output_dict = {}
    output_dict['integer'] = int(input_dict['integer1'])+int(input_dict['integer2'])
    return output_dict

def object_viewer(input_dict):
    return {}

def table_viewer(input_dict):
    return {}

def subtract_integers(input_dict):
    output_dict = {}
    output_dict['integer'] = int(input_dict['integer1'])-int(input_dict['integer2'])
    return output_dict
    
def create_range(input_dict):
    output_dict = {}
    output_dict['rangeout'] = range(int(input_dict['n_range']))
    return output_dict

def select_attrs(input_dict):
    return input_dict

def select_attrs_post(postdata, input_dict, output_dict):
    import Orange
    
    data = Orange.data.Table(input_dict['data'])
    
    new_attrs = []
    for name in postdata['attrs']:
        new_attrs.append(str(name))
    
    try:
        new_attrs.append(str(postdata['ca'][0]))
        class_attr = True
    except:
        class_attr = False

    new_domain = Orange.data.Domain(new_attrs, class_attr, data.domain)

    try:
        for meta in postdata['ma']:
            if data.domain.has_meta(str(meta)):
                new_domain.addmeta(Orange.feature.Descriptor.new_meta_id(), data.domain.getmeta(str(meta)))
            else:
                new_domain.add_meta(Orange.feature.Descriptor.new_meta_id(), data.domain[str(meta)])
    except:
        pass    

    new_data = Orange.data.Table(new_domain, data)

    output_dict = {'data':new_data}
    return output_dict

def select_data(input_dict):
    return input_dict

def build_filter(val, attr, data):
    import Orange

    pos = 0

    try:
        pos = data.domain.meta_id(attr)
    except Exception, e:
        pos = data.domain.variables.index(attr)

    if val['operator'] == ">":
        return(
            Orange.data.filter.ValueFilterContinuous(
                position = pos,
                ref = float(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.Greater
            )
        )
    elif val['operator'] == "<":
        return(
            Orange.data.filter.ValueFilterContinuous(
                position = pos,
                ref = float(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.Less
            )
        )
    elif val['operator'] == "=":
        return(
            Orange.data.filter.ValueFilterContinuous(
                position = pos,
                ref = float(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.Equal
            )
        )
    elif val['operator'] == "<=":
        return(
            Orange.data.filter.ValueFilterContinuous(
                position = pos,
                ref = float(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.LessEqual
            )
        )
    elif val['operator'] == ">=":
        return(
            Orange.data.filter.ValueFilterContinuous(
                position = pos,
                ref = float(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.GreaterEqual
            )
        )
    elif val['operator'] == "between":
        return(
            Orange.data.filter.ValueFilterContinuous(
                position = pos,
                min = float(val['values'][0]),
                max = float(val['values'][1]),
                oper = Orange.data.filter.ValueFilter.Between
            )
        )
    elif val['operator'] == "outside":
        return(
            Orange.data.filter.ValueFilterContinuous(
                position = pos,
                min = float(val['values'][0]),
                max = float(val['values'][1]),
                oper = Orange.data.filter.ValueFilter.Outside
            )
        )
    elif val['operator'] in ["equals", "in"]:
        vals=[]
        for v in val['values']:
            vals.append(Orange.data.Value(attr, str(v)))
        return(
            Orange.data.filter.ValueFilterDiscrete(
                position = pos,
                values=vals
            )
        )
    elif val['operator'] == "s<":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.Less,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "s>":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.Greater,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "s=":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.Equal,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "s<=":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.LessEqual,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "s>=":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.GreaterEqual,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "sbetween":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                min = str(val['values'][0]),
                max = str(val['values'][1]),
                oper = Orange.data.filter.ValueFilter.Between,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "soutside":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                min = str(val['values'][0]),
                max = str(val['values'][1]),
                oper = Orange.data.filter.ValueFilter.Outside,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "scontains":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.Contains,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "snot contains":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.NotContains,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "sbegins with":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.BeginsWith,
                case_sensitive = bool(val['case'])
            )
        )
    elif val['operator'] == "sends with":
        return(
            Orange.data.filter.ValueFilterString(
                position = pos,
                ref = str(val['values'][0]),
                oper = Orange.data.filter.ValueFilter.EndsWith,
                case_sensitive = bool(val['case'])
            )
        )

def select_data_post(postdata, input_dict, output_dict):
    import Orange, json

    data = input_dict['data']

    try:
        conditions = json.loads(str(postdata['conditions'][0]))

        for c in conditions['conditions']:
            if c['condition'][0]['operator'] in ["is defined", "sis defined"]:
                # if the operator is "is defined"

                fil = Orange.data.filter.IsDefined(domain = data.domain)
                for v in range(len(data.domain.variables)):
                    fil.check[int(v)] = 0
                    
                if c['negate']:
                    fil.negate = True

                fil.check[str(c['condition'][0]['attr'])] = 1

            else:
                fil = Orange.data.filter.Values()
                fil.domain = data.domain

                if c['negate']:
                    fil.negate = True

                if len(c['condition']) > 1:
                    fil.conjunction = False
                    for val in c['condition']:
                        attr = data.domain[str(val['attr'])]
                        fil.conditions.append(build_filter(val, attr, data))

                else:
                    for val in c['condition']:
                        attr = data.domain[str(val['attr'])]
                        fil.conditions.append(build_filter(val, attr, data))

            data = fil(data)
    except Exception, e:
        pass
    
    output_dict = {'data': data}
    return output_dict

def build_classifier(input_dict):
    learner = input_dict['learner']
    data = input_dict['data']

    classifier = learner(data)

    output_dict = {'classifier': classifier}

    return output_dict

def apply_classifier(input_dict):
    import Orange

    classifier = input_dict['classifier']
    data = input_dict['data']

    new_domain = Orange.data.Domain(data.domain, classifier(data[0]).variable)
    new_domain.add_metas(data.domain.get_metas())
    
    new_data = Orange.data.Table(new_domain, data)

    for i in range(len(data)):
        c = classifier(data[i])
        new_data[i][c.variable.name] = c

    output_dict = {'data':new_data}

    return output_dict

# ORANGE CLASSIFIERS (update imports when switching to new orange version)

def bayes(input_dict):
    import orange
    output_dict = {}
    output_dict['bayesout']= orange.BayesLearner(name = "Naive Bayes (Orange)", hovername="DOlgo ime bajesa")
    return output_dict

def knn(input_dict):
    import orange
    output_dict = {}
    output_dict['knnout']= orange.kNNLearner(name = "kNN (Orange)")
    return output_dict

def rules(input_dict):
    import orange
    output_dict = {}
    output_dict['rulesout']= orange.RuleLearner(name = "Rule Learner (Orange)")
    return output_dict
    
def cn2(input_dict):
    import orngCN2
    output_dict = {}
    output_dict['cn2out']= orngCN2.CN2Learner(name = "CN2 Learner (Orange)")
    return output_dict
    
def svm(input_dict):
    import orngSVM
    output_dict = {}
    output_dict['svmout']= orngSVM.SVMLearner(name = 'SVM (Orange)')
    return output_dict
    
def svmeasy(input_dict):
    import orngSVM
    output_dict = {}
    output_dict['svmeasyout']= orngSVM.SVMLearnerEasy(name='SVMEasy (Orange)')
    return output_dict
    
def class_tree(input_dict):
    import orange
    output_dict = {}
    output_dict['treeout']= orange.TreeLearner(name = "Classification Tree (Orange)")
    return output_dict
    
def c45_tree(input_dict):
    import orange
    output_dict = {}
    output_dict['c45out']= orange.C45Learner(name = "C4.5 Tree (Orange)")
    return output_dict  
    
def logreg(input_dict):
    import orange
    output_dict = {}
    output_dict['logregout']= orange.LogRegLearner(name = "Logistic Regression (Orange)")
    return output_dict
    
def majority_learner(input_dict):
    import orange
    output_dict = {}
    output_dict['majorout']= orange.MajorityLearner(name = "Majority Classifier (Orange)")
    return output_dict
    
def lookup_learner(input_dict):
    import orange
    output_dict = {}
    output_dict['lookupout']= orange.LookupLearner(name = "Lookup Classifier (Orange)")
    return output_dict

def random_forest(input_dict):
    from workflows.helpers import UnpicklableObject 
    output_dict = {}
    rfout = UnpicklableObject("orngEnsemble.RandomForestLearner(trees="+input_dict['n']+", name='RF"+str(input_dict['n'])+" (Orange)')")
    rfout.addimport("import orngEnsemble")
    output_dict['rfout']=rfout
    return output_dict    

# HARF (HIGH AGREEMENT RANDOM FOREST)

def harf(input_dict):
    #import orngRF_HARF
    from workflows.helpers import UnpicklableObject
    agrLevel = input_dict['agr_level']
    #data = input_dict['data']
    harfout = UnpicklableObject("orngRF_HARF.HARFLearner(agrLevel ="+agrLevel+", name='HARF-"+str(agrLevel)+"')")
    harfout.addimport("import orngRF_HARF")
    #harfLearner = orngRF_HARF.HARFLearner(agrLevel = agrLevel, name = "_HARF-"+agrLevel+"_")
    output_dict = {}
    output_dict['harfout']= harfout
    return output_dict
    
# CLASSIFICATION NOISE FILTER

def classification_filter(input_dict, widget):
    import noiseAlgorithms4lib    
    output_dict = {}
    output_dict['noise_dict']= noiseAlgorithms4lib.cfdecide(input_dict, widget)
    return output_dict    
    
def send_filename(input_dict):
    output_dict = {}
    output_dict['filename']=input_dict['fileloc'].strip('\"').replace('\\', '\\\\')
    return output_dict
    
def load_dataset(input_dict):
    import orange
    output_dict = {}
    output_dict['dataset'] = orange.ExampleTable(input_dict['file'])
    return output_dict
    
# SATURATION NOISE FILTER

def saturation_filter(input_dict, widget):
    import noiseAlgorithms4lib    
    output_dict = {}
    output_dict['noise_dict']= noiseAlgorithms4lib.saturation_type(input_dict, widget)
    return output_dict
    
# ENSEMBLE

def ensemble(input_dict):
    import math
    ens = {}
    data_inds = input_dict['data_inds']
    ens_type = input_dict['ens_type']
    # TODO ens_level = input_dict['ens_level']
    for item in data_inds:
        #det_by = item['detected_by']
        for i in item['inds']:
            if not ens.has_key(i):
                ens[i] = 1
            else:
                ens[i] += 1
    
    ens_out = {}
    ens_out['name'] = input_dict['ens_name']
    ens_out['inds'] = []
    n_algs = len(data_inds)
    print ens_type
    if ens_type == "consensus":
        ens_out['inds'] = sorted([x[0] for x in ens.items() if x[1] == n_algs])
    else: # majority
        ens_out['inds'] = sorted([x[0] for x in ens.items() if x[1] >= math.floor(n_algs/2+1)])
    
    output_dict = {}
    output_dict['ens_out'] = ens_out
    return output_dict

# NOISE RANK
    
def noiserank(input_dict):
    allnoise = {}
    data = input_dict['data']
    for item in input_dict['noise']:
        det_by = item['name']
        for i in item['inds']:
            if not allnoise.has_key(i):
                allnoise[i] = {}
                allnoise[i]['id'] = i
                allnoise[i]['class'] = data[int(i)].getclass().value
                allnoise[i]['by'] = []
            allnoise[i]['by'].append(det_by)
            print allnoise[i]['by']
    
    from operator import itemgetter
    outallnoise = sorted(allnoise.values(), key=itemgetter('id'))
    outallnoise.sort(compareNoisyExamples)
    
    output_dict = {}
    output_dict['allnoise'] = outallnoise
    output_dict['selection'] = {}
    return output_dict
    
def compareNoisyExamples(item1, item2):
    len1 = len(item1["by"])
    len2 = len(item2["by"])
    if len1 > len2: # reversed, want to have decreasing order 
        return -1
    elif len1 < len2: # reversed, want to have decreasing order 
        return 1
    else:
        return 0
    
def noiserank_select(postdata,input_dict, output_dict):
    try:    
        outselection = postdata['selected']
        data = input_dict['data']
        selection = [0]*len(data)
        for i in outselection:
            selection[int(i)] = 1
            outdata = data.select(selection, 1)
        output_dict['selection'] = outdata if outdata != None else None
    except KeyError:
        output_dict['selection'] = None
    
    #output_dict['selection'] = outselection if outselection != None else None
    return output_dict


# EVALUATION OF NOISE DETECTION PERFORMANCE
    
def add_class_noise(input_dict):
    import noiseAlgorithms4lib    
    output_dict = noiseAlgorithms4lib.insertNoise(input_dict)
    return output_dict
    
def aggr_results(input_dict):
    output_dict = {}
    output_dict['aggr_dict'] = { 'positives' : input_dict['pos_inds'], 'by_alg': input_dict['detected_inds']}
    return output_dict
    
def eval_batch(input_dict):
    alg_perfs = input_dict['perfs']
    beta = float(input_dict['beta'])
    performances = []    
    for exper in alg_perfs:
        noise = exper['positives']
        nds = exper['by_alg']
            
        performance = []
        for nd in nds:
            nd_alg = nd['name']
            det_noise = nd['inds']
            inboth = set(noise).intersection(set(det_noise))
            recall = len(inboth)*1.0/len(noise) if len(noise) > 0 else 0
            precision = len(inboth)*1.0/len(det_noise) if len(det_noise) > 0 else 0
            
            print beta, recall, precision
            if precision == 0 and recall == 0:
                fscore = 0
            else:
                fscore = (1+beta**2)*precision*recall/((beta**2)*precision + recall)
            performance.append({'name':nd_alg, 'recall': recall, 'precision' : precision, 'fscore' : fscore, 'fbeta': beta})
        
        performances.append(performance)
    
    output_dict = {}
    output_dict['perf_results'] = performances
    return output_dict

def eval_noise_detection(input_dict):
    noise = input_dict['noisy_inds']
    nds = input_dict['detected_noise']
        
    performance = []
    for nd in nds:
        nd_alg = nd['name']
        det_noise = nd['inds']
        inboth = set(noise).intersection(set(det_noise))
        recall = len(inboth)*1.0/len(noise) if len(noise) > 0 else 0
        precision = len(inboth)*1.0/len(det_noise) if len(det_noise) > 0 else 0
        beta = float(input_dict['f_beta'])
        print beta, recall, precision
        if precision == 0 and recall == 0:
            fscore = 0
        else:
            fscore = (1+beta**2)*precision*recall/((beta**2)*precision + recall)
        performance.append({'name':nd_alg, 'recall': recall, 'precision' : precision, 'fscore' : fscore, 'fbeta': beta})
    
    from operator import itemgetter
    output_dict = {}
    output_dict['nd_eval'] = sorted(performance, key=itemgetter('name'))  
    return output_dict
    
def avrg_std(input_dict):
    perf_results = input_dict['perf_results']
    stats = {}
    # Aggregate performance results
    n = len(perf_results)
    for i in range(n):
        for item in perf_results[i]:
            alg = item['name']
            if not stats.has_key(alg):
                stats[alg] = {}
                stats[alg]['precisions'] = [item['precision']]
                stats[alg]['recalls'] = [item['recall']]
                stats[alg]['fscores'] = [item['fscore']]
                stats[alg]['fbeta'] = item['fbeta']
            else:
                stats[alg]['precisions'].append(item['precision'])
                stats[alg]['recalls'].append(item['recall'])
                stats[alg]['fscores'].append(item['fscore'])
            
            # if last experiment: compute averages    
            if i == n-1:
                stats[alg]['avrg_pr'] = reduce(lambda x,y: x+y, stats[alg]['precisions'])/n
                stats[alg]['avrg_re'] = reduce(lambda x,y: x+y, stats[alg]['recalls'])/n
                stats[alg]['avrg_fs'] = reduce(lambda x,y: x+y, stats[alg]['fscores'])/n
        
    # Compute Standard Deviations
    import numpy
    avrgstdout = []
    print stats
    for alg, stat in stats.items():
        avrgstdout.append({'name': alg, 'precision': stat['avrg_pr'], 'recall': stat['avrg_re'],
                           'fscore' : stat['avrg_fs'],
                           'fbeta'  : stat['fbeta'],
                           'std_pr' : numpy.std(stat['precisions']),
                           'std_re' : numpy.std(stat['recalls']),
                           'std_fs' : numpy.std(stat['fscores']) })
                         
    from operator import itemgetter
    output_dict = {}
    output_dict['avrg_w_std'] = sorted(avrgstdout, key=itemgetter('name'))
    return output_dict

# VISUALIZATIONS
            
def pr_space(input_dict):
    return {}
    
def eval_bar_chart(input_dict):
    return {}
    
def eval_to_table(input_dict):
    return {}   
    
def data_table(input_dict):
    return {}

def data_info(input_dict):
    return {}

def sdmsegs(input_dict):
    return{}

def definition_sentences(input_dict):
    return {}

def term_candidates(input_dict):
    return {}

# FILE LOADING

def uci_to_odt(input_dict):
Janez K's avatar
Janez K committed
787
    from mothra.settings import FILES_FOLDER
Janez K's avatar
Janez K committed
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
    import orange
    output_dict = {}
    output_dict['data'] = orange.ExampleTable(FILES_FOLDER+"uci-datasets/"+input_dict['filename'])
    return output_dict
    
def odt_to_arff(input_dict):
    from noiseAlgorithms4lib import toARFFstring
    output_dict = {}
    f = toARFFstring(input_dict['odt'])
    output_dict['arff'] = f.getvalue()
    return output_dict  
             
# NLP tools

def merge_sentences(input_dict):
    """
    Merges the input sentences in XML according to the specified method.
    """
    method = input_dict['method']
    merged_sen, id_to_sent = set(), {}
808
    ids_list = []
Janez K's avatar
Janez K committed
809 810 811
    for sentsXML in input_dict['sentences']:
        sents = nlp.parse_def_sentences(sentsXML)
        ids = set(map(lambda x: x['id'], sents))
812
        ids_list.append(ids)
Janez K's avatar
Janez K committed
813 814 815
        # Save the map from id to sentence
        for sent in sents:
            id_to_sent[sent['id']] = sent
816 817
        if len(merged_sen) == 0:
            merged_sen = ids
Janez K's avatar
Janez K committed
818 819 820 821
        if method == 'union':
            merged_sen = merged_sen | ids
        elif method == 'intersection':
            merged_sen = merged_sen & ids
822 823 824
        elif method == 'intersection_two':
            for ids_alt in ids_list:
                merged_sen = merged_sen | (ids_alt & ids)
Janez K's avatar
Janez K committed
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    return {'merged_sentences' : nlp.sentences_to_xml([id_to_sent[sid] for sid in merged_sen])}

def load_corpus(input_dict):
    '''
    Parses an input file and encodes it in base 64.
    '''
    import os.path
    import base64
    f = safeOpen(input_dict['file'])
    fname = os.path.basename(input_dict['file'])
    data = base64.b64encode(f.read())
    from services.webservice import WebService
    ws = WebService('http://bodysnatcher.ijs.si:8092/totale?wsdl', 600)
    response = ws.client.parseFile(fileName=fname, inFile=data)
    return {'corpus' : response['parsedFile']}

def kepner_tregoe(input_dict):
842 843 844 845 846 847 848 849 850 851 852 853
    output_dict = input_dict
    output_dict['model'] = None
    return output_dict

class KepnerTregoe:
    '''
    Kepner Tregoe model.
    '''
    def __init__(self, data, weights, smaller_is_better=None):
        self.data = data
        self.weights = weights
        self.smaller_is_better = smaller_is_better if smaller_is_better else set()
854
        self.name = 'Kepner-Tregoe'
855 856 857 858 859
    def __call__(self, weights=None):
        import Orange
        from Orange.feature import Type
        if weights == None:
            weights = self.weights
860
        # New augmented table
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
        norm_data = Orange.data.Table(self.data)
        newid = min(norm_data.domain.get_metas().keys()) - 1
        score_attr = Orange.feature.Continuous('score')
        norm_data.domain.add_meta(newid, score_attr)
        norm_data.add_meta_attribute(score_attr)
        # Normalize the attributes column-wise
        for att in norm_data.domain:
            if att.var_type == Type.Continuous:
                col = [ex[att] for ex in norm_data]
                col_norm = float(sum(col))
            for ex in norm_data:
                if att.var_type == Type.Continuous:
                    ex[att] = ex[att] / col_norm 
        # Use the inverse of an attr. value if smaller values should be treated as 'better'.
        inverse = lambda x, att: 1-x if att in self.smaller_is_better else x
        for ex in norm_data:
877
            score = sum([inverse(ex[att], att.name) * weights.get(att.name, 1) for att in norm_data.domain.features if att.var_type == Type.Continuous])
878 879 880 881 882 883 884
            ex['score'] = score
        return norm_data

def kepner_tregoe_finished(postdata, input_dict, output_dict):
    # Fetch the data and the weights from the form.
    data = input_dict['data']
    attributes = [att.name for att in data.domain.features]
Janez K's avatar
Janez K committed
885 886
    weights = {}
    widget_id = postdata['widget_id'][0]
887
    smaller_is_better = set()
Janez K's avatar
Janez K committed
888 889
    for att in attributes:
        weights[att]=int(postdata['weight'+str(widget_id)+str(att)][0])
890 891 892 893
        if postdata.has_key('smallerIsBetter'+str(widget_id)+str(att)):
            smaller_is_better.add(att)
    # Instantiate a KepnerTregoe model.
    kt = KepnerTregoe(data, weights, smaller_is_better=smaller_is_better)
Janez K's avatar
Janez K committed
894
    output_dict = {}
895 896
    output_dict['data'] = kt()
    output_dict['model'] = kt
Janez K's avatar
Janez K committed
897 898
    return output_dict

899 900 901
def sensitivity_analysis(input_dict):
    return input_dict

902 903 904
def ds_charts(input_dict):
    return input_dict

Janez K's avatar
Janez K committed
905 906
def string_to_file(input_dict):
    return {}