Source

orange / source / orange / filter.cpp

  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
/*
    This file is part of Orange.
    
    Copyright 1996-2010 Faculty of Computer and Information Science, University of Ljubljana
    Contact: janez.demsar@fri.uni-lj.si

    Orange is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Orange is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Orange.  If not, see <http://www.gnu.org/licenses/>.
*/


#include <stdlib.h>
#include <iostream>
#include <fstream>

#include "stladdon.hpp"
#include "random.hpp"

#include "vars.hpp"
#include "stringvars.hpp"
#include "domain.hpp"
#include "distvars.hpp"
#include "examplegen.hpp"

#include "filter.hpp"

DEFINE_TOrangeVector_classDescription(PValueFilter, "TValueFilterList", true, ORANGE_API)
DEFINE_TOrangeVector_classDescription(PFilter, "TFilterList", true, ORANGE_API)

#include "filter.ppp"


// Sets the negate field (default is false)
TFilter::TFilter(bool anegate, PDomain dom) 
: negate(anegate),
  domain(dom)
{}

void TFilter::reset()
{}

PFilter TFilter::deepCopy() const
{
  raiseWarning("Deep copy not implemented.");
  return PFilter();
}

// Sets the maxrand field to RAND_MAX*ap
TFilter_random::TFilter_random(const float ap, bool aneg, PRandomGenerator rgen)
: TFilter(aneg, PDomain()),
  prob(ap),
  randomGenerator(rgen ? rgen : PRandomGenerator(mlnew TRandomGenerator()))
{};

// Chooses an example (returns true) if rand()<maxrand; example is ignored
bool TFilter_random::operator()(const TExample &)
{
  if (!randomGenerator)
    randomGenerator = mlnew TRandomGenerator;

  return (randomGenerator->randfloat()<prob)!=negate;
}



TFilter_hasSpecial::TFilter_hasSpecial(bool aneg, PDomain dom)
  : TFilter(aneg, dom)
  {}


// Chooses an example if it has (no) special values.
bool TFilter_hasSpecial::operator()(const TExample &exam)
{ int i=0, Nv;
  if (domain) {
    TExample example(domain, exam);
    for(Nv = domain->variables->size(); (i<Nv) && !example[i].isSpecial(); i++);
  }
  else
    for(Nv = exam.domain->variables->size(); (i<Nv) && !exam[i].isSpecial(); i++);

  return ((i==Nv)==negate);
}


TFilter_isDefined::TFilter_isDefined(bool aneg, PDomain dom)
: TFilter(aneg, dom),
  check(mlnew TAttributedBoolList(dom ? dom->variables : PVarList(), dom ? dom->variables->size(): 0, true))
{}


bool TFilter_isDefined::operator()(const TExample &exam)
{
  TExample *example;
  PExample wex;
  if (domain && (domain != exam.domain)) {
    example = mlnew TExample(domain, exam);
    wex = example;
  }
  else
    example = const_cast<TExample *>(&exam);

  if (!check || !check->size()) {
    const_PITERATE(TExample, ei, example)
      if ((*ei).isSpecial())
        return negate;
    return !negate;
  }

  else {
    TBoolList::const_iterator ci(check->begin()), ce(check->end());
    TExample::const_iterator ei(example->begin()), ee(example->end());
    for(; (ci!=ce) && (ei!=ee); ci++, ei++)
      if (*ci && (*ei).isSpecial())
        return negate;
    return !negate;
  }
}


void TFilter_isDefined::afterSet(const char *name)
{
  if (!strcmp(name, "domain") && domain && (!check || !check->size()) && (domain->variables != check->attributes))
    check = mlnew TAttributedBoolList(domain->variables, domain->variables->size(), true);

  TFilter::afterSet(name);
}


TFilter_hasMeta::TFilter_hasMeta(const int &anid, bool aneg, PDomain dom)
: TFilter(aneg, dom),
  id(anid)
{}


bool TFilter_hasMeta::operator()(const TExample &exam)
{
  return exam.hasMeta(id) != negate;
}


TFilter_hasClassValue::TFilter_hasClassValue(bool aneg, PDomain dom)
  : TFilter(aneg, dom)
  {}

// Chooses an example if it has (no) special values.
bool TFilter_hasClassValue::operator()(const TExample &exam)
{ return (domain ? TExample(domain, exam).getClass().isSpecial() : exam.getClass().isSpecial()) ==negate; }


// Constructor; sets the value and position
TFilter_sameValue::TFilter_sameValue(const TValue &aval, int apos, bool aneg, PDomain dom)
: TFilter(aneg, dom), 
  position(apos),
  value(aval)
{}


// Chooses an example if position-th attribute's value equals (or not) the specified value
bool TFilter_sameValue::operator()(const TExample &example)
{ 
  if (domain && (domain != example.domain)) {
    // this is slow & inefficient, but it's the only legal way of doing it
    TExample ex(domain, example);
    return ((position != -1 ? ex[position] : example.getClass()) == value) != negate;
  }
  else
    return ((position != -1 ? example[position]  : example.getClass()) == value) != negate;
}


TValueFilter::TValueFilter(const int &pos, const int &accs)
: position(pos),
  acceptSpecial(accs)
{}

PValueFilter TValueFilter::deepCopy() const
{
  raiseWarning("Deep copy not implemented.");
  return PValueFilter();
}


TValueFilter_continuous::TValueFilter_continuous()
: TValueFilter(ILLEGAL_INT, -1),
  min(0.0),
  max(0.0),
  outside(false),
  oper(None)
{}

TValueFilter_continuous::TValueFilter_continuous(const int &pos, const float &amin, const float &amax, const bool &outs, const int &accs)
: TValueFilter(pos, accs),
  min(amin),
  max(amax),
  outside(outs),
  oper(None)
{}


TValueFilter_continuous::TValueFilter_continuous(const int &pos, const int &op, const float &amin, const float &amax, const int &accs)
: TValueFilter(pos, accs),
  min(amin),
  max(amax),
  oper(op)
{}


#define EQUAL(x,y)  (fabs(x-y) <= y*1e-10) ? 1 : 0
#define LESS_EQUAL(x,y) (x-y <= y*1e-10) ? 1 : 0
#define TO_BOOL(x) (x) ? 1 : 0;

int TValueFilter_continuous::operator()(const TExample &example) const
{ const TValue &val = example[position];
  if (val.isSpecial())
    return acceptSpecial;

  switch (oper) {
    case None:         return TO_BOOL(((val.floatV>=min) && (val.floatV<=max)) != outside);

    case Equal:        return EQUAL(val.floatV, min);
    case NotEqual:     return 1 - EQUAL(val.floatV, min);
    case Less:         return TO_BOOL(val.floatV < min);
    case LessEqual:    return LESS_EQUAL(val.floatV, min);
    case Greater:      return TO_BOOL(min < val.floatV);
    case GreaterEqual: return LESS_EQUAL(min, val.floatV);
    case Between:      return (LESS_EQUAL(min, val.floatV)) * (LESS_EQUAL(val.floatV, max));
    case Outside:      return TO_BOOL((val.floatV < min) || (val.floatV > max));

    default:  return -1;
  }
}

PValueFilter TValueFilter_continuous::deepCopy() const
{
  TValueFilter *filter = mlnew TValueFilter_continuous(position,oper,min,max,acceptSpecial);
  PValueFilter wfilter = filter;
  return wfilter;
}

TValueFilter_discrete::TValueFilter_discrete(const int &pos, PValueList bl, const int &accs, bool neg)
: TValueFilter(pos, accs),
  values(bl ? bl : mlnew TValueList()),
  negate(neg)
{}

TValueFilter_discrete::TValueFilter_discrete(const int &pos, PVariable var, const int &accs, bool neg)
: TValueFilter(pos, accs),
  values(mlnew TValueList(var)),
  negate(neg)
{}

int TValueFilter_discrete::operator()(const TExample &example) const
{ const TValue &val = example[position];
  if (val.isSpecial())
    return negate ? 1-acceptSpecial : acceptSpecial;

  const_PITERATE(TValueList, vi, values)
    if ((*vi).intV == val.intV)
      return negate ? 0 : 1;

  return negate ? 1 : 0;
}

PValueFilter TValueFilter_discrete::deepCopy() const
{
  if (values->size())
  {
    TValueList *newValues = mlnew TValueList();
    PValueList wnewValues = newValues;
    const_PITERATE(TValueList, vi, values) 
      wnewValues->push_back(TValue(*vi));
    TValueFilter *filter = mlnew TValueFilter_discrete(position,wnewValues,acceptSpecial, negate);
    PValueFilter wfilter = filter;
    return wfilter;
  }
  TValueFilter *filter = mlnew TValueFilter_discrete(position,PValueList(),acceptSpecial, negate);
  PValueFilter wfilter = filter;
  return wfilter;
}

TValueFilter_string::TValueFilter_string()
: TValueFilter(ILLEGAL_INT, -1),
  min(),
  max(),
  oper(None),
  caseSensitive(true)
{}



TValueFilter_string::TValueFilter_string(const int &pos, const int &op, const string &amin, const string &amax, const int &accs, const bool csens)
: TValueFilter(pos, accs),
  min(amin),
  max(amax),
  oper(op),
  caseSensitive(csens)
{}


char *strToLower(string nm)
{ 
  char *s = strcpy(new char[nm.size()+1], nm.c_str());
  for(char *i = s; *i; i++)
    *i = tolower(*i);
  return s;
}

int TValueFilter_string::operator()(const TExample &example) const
{ 
  const TValue &val = example[position];
  if (val.isSpecial())
    return acceptSpecial;

  char *value = caseSensitive ? const_cast<char *>(val.svalV.AS(TStringValue)->value.c_str())
                              : strToLower(val.svalV.AS(TStringValue)->value.c_str());

  char *ref = caseSensitive ? const_cast<char *>(min.c_str()) : strToLower(min);
  
  switch(oper) {
    case Equal:        return TO_BOOL(!strcmp(value, ref));
    case NotEqual:     return TO_BOOL(strcmp(value, ref));
    case Less:         return TO_BOOL(strcmp(value, ref) < 0);
    case LessEqual:    return TO_BOOL(strcmp(value, ref) <= 0);
    case Greater:      return TO_BOOL(strcmp(value, ref) > 0);
    case GreaterEqual: return TO_BOOL(strcmp(value, ref) >= 0);
    case Between:      return TO_BOOL((strcmp(value, ref) >= 0) && (strcmp(value, max.c_str()) <= 0));
    case Outside:      return TO_BOOL((strcmp(value, ref) < 0) && (strcmp(value, max.c_str()) >= 0));
    case Contains:     return TO_BOOL(string(value).find(ref) != string::npos);
    case NotContains:  return TO_BOOL(string(value).find(ref) == string::npos);
    case BeginsWith:   return TO_BOOL(!strncmp(value, ref, strlen(ref)));

    case EndsWith:
      { const int vsize = strlen(value), rsize = strlen(ref);
        return TO_BOOL((vsize >= rsize) && !strcmp(value + (vsize-rsize), ref));
      }

    default:
      return -1;
  }

  if (!caseSensitive) {
    delete value;
    delete ref;
  }
}


TValueFilter_stringList::TValueFilter_stringList()
: TValueFilter(ILLEGAL_INT, -1),
  values(mlnew TStringList()),
  caseSensitive(true)
{}


TValueFilter_stringList::TValueFilter_stringList(const int &pos, PStringList bl, const int &accs, const int &op, const bool csens)
: TValueFilter(pos, accs),
  values(bl),
  caseSensitive(csens)
{}

int TValueFilter_stringList::operator()(const TExample &example) const
{ 
  const TValue &val = example[position];
  if (val.isSpecial())
    return acceptSpecial;

  char *value = caseSensitive ? const_cast<char *>(val.svalV.AS(TStringValue)->value.c_str())
                              : strToLower(val.svalV.AS(TStringValue)->value.c_str());
  char *ref = caseSensitive ? NULL : new char[1024];

  TStringList::const_iterator vi(values->begin()), ve(values->end());
  for(; vi!=ve; vi++)
    if (caseSensitive) {
      if (!strcmp((*vi).c_str(), value))
        break;
    }
    else {
      if ((*vi).size() >= 1024)
        raiseError("reference string too long (1023 characters is the limit)");
      strcpy(ref, (*vi).c_str());
      for(char *i = ref; *i; i++)
        *i = tolower(*i);
      if (!strcmp(ref, value))
        break;
    }

  if (!caseSensitive) {
    delete ref;
    delete value;
  }

  return vi==ve ? 0 : 1;
}


#undef DIFFERENT
#undef LESS_EQUAL
#undef TO_BOOL

TFilter_values::TFilter_values(bool anAnd, bool aneg, PDomain dom)
: TFilter(aneg, dom),
  conditions(mlnew TValueFilterList()),
  conjunction(anAnd)
{}


TFilter_values::TFilter_values(PValueFilterList v, bool anAnd, bool aneg, PDomain dom)
: TFilter(aneg, dom),
  conditions(v),
  conjunction(anAnd)
{}


TValueFilterList::iterator TFilter_values::findCondition(PVariable var, const int &varType, int &position)
{
  if (varType && (var->varType != varType))
    raiseError("invalid variable type");

  checkProperty(domain);

  position = domain->getVarNum(var);
  TValueFilterList::iterator condi(conditions->begin()), conde(conditions->end());
  while((condi!=conde) && ((*condi)->position != position))
    condi++;

  return condi;
}

void TFilter_values::updateCondition(PVariable var, const int &varType, PValueFilter filter)
{
  TValueFilterList::iterator condi = findCondition(var, varType, filter->position);
  if (condi==conditions->end())
    conditions->push_back(filter);
  else
    *condi = filter;
}


void TFilter_values::addCondition(PVariable var, const TValue &val, bool negate)
{
  int position;
  TValueFilterList::iterator condi = findCondition(var, TValue::INTVAR, position);

  TValueFilter_discrete *valueFilter;

  if (condi==conditions->end()) {
    valueFilter = mlnew TValueFilter_discrete(position); // it gets wrapped in the next line
    conditions->push_back(valueFilter);
  }
  else {
    valueFilter = (*condi).AS(TValueFilter_discrete);
    if (!valueFilter)
      raiseError("addCondition(Value) con only be used for setting ValueFilter_discrete");
  }

  if (val.isSpecial())
    valueFilter->acceptSpecial = 1;
  else {
    valueFilter->values->clear();
    valueFilter->values->push_back(val);
  }

  valueFilter->negate = negate;
}


void TFilter_values::addCondition(PVariable var, PValueList vallist, bool negate)
{
  int position;
  TValueFilterList::iterator condi = findCondition(var, TValue::INTVAR, position);

  if (condi==conditions->end())
    conditions->push_back(mlnew TValueFilter_discrete(position, vallist));

  else {
    TValueFilter_discrete *valueFilter = (*condi).AS(TValueFilter_discrete);
    if (!valueFilter)
      raiseError("addCondition(Value) can only be used for setting ValueFilter_discrete");
    else
      valueFilter->values = vallist;
    valueFilter->negate = negate;
  }
}


void TFilter_values::addCondition(PVariable var, const int &oper, const float &min, const float &max)
{
  updateCondition(var, TValue::FLOATVAR, mlnew TValueFilter_continuous(ILLEGAL_INT, oper, min, max));
}


void TFilter_values::addCondition(PVariable var, const int &oper, const string &min, const string &max)
{
  updateCondition(var, STRINGVAR, mlnew TValueFilter_string(ILLEGAL_INT, oper, min, max));
}


void TFilter_values::addCondition(PVariable var, PStringList slist)
{
  updateCondition(var, STRINGVAR, mlnew TValueFilter_stringList(ILLEGAL_INT, slist));
}


void TFilter_values::removeCondition(PVariable var)
{
  int position;
  TValueFilterList::iterator condi = findCondition(var, 0, position);

  if (condi==conditions->end())
    raiseError("there is no condition on value of '%s' in the filter", var->get_name().c_str());

  conditions->erase(condi);
}
  

bool TFilter_values::operator()(const TExample &exam)
{ checkProperty(domain);
  checkProperty(conditions);

  TExample *example;
  PExample wex;
  if (domain && (domain != exam.domain)) {
    example = mlnew TExample(domain, exam);
    wex = example;
  }
  else
    example = const_cast<TExample *>(&exam);

  PITERATE(TValueFilterList, fi, conditions) {
    const int r = (*fi)->call(*example);
    if ((r==0) && conjunction)
      return negate;
    if ((r==1) && !conjunction)
      return !negate; // if this one is OK, we should return true if negate=false and vice versa
  }

  // If we've come this far; if conjunction==true, all were OK; conjunction==false, none were OK
  return conjunction!=negate;
}

PFilter TFilter_values::deepCopy() const
{
  TValueFilterList *newValueFilters = mlnew TValueFilterList();
  PValueFilterList wnewValueFilters = newValueFilters;

  const_PITERATE(TValueFilterList, vi, conditions) 
    wnewValueFilters->push_back((*vi)->deepCopy());

  TFilter *filter = mlnew TFilter_values(wnewValueFilters,conjunction,negate,domain);
  PFilter wfilter = filter;
  return wfilter;
}


/// Constructor; sets the example
TFilter_sameExample::TFilter_sameExample(PExample anexample, bool aneg)
  : TFilter(aneg, anexample->domain), example(anexample)
  {}


/// Chooses an examples (not) equal to the 'example'
bool TFilter_sameExample::operator()(const TExample &other)
{ return (example->compare(TExample(domain, other))==0)!=negate; }



/// Constructor; sets the example
TFilter_compatibleExample::TFilter_compatibleExample(PExample anexample, bool aneg)
: TFilter(aneg, anexample->domain),
  example(anexample)
{}


/// Chooses an examples (not) compatible with the 'example'
bool TFilter_compatibleExample::operator()(const TExample &other)
{ return example->compatible(TExample(domain, other))!=negate; }




TFilter_conjunction::TFilter_conjunction()
: filters(mlnew TFilterList())
{}


TFilter_conjunction::TFilter_conjunction(PFilterList af)
: filters(af)
{}

bool TFilter_conjunction::operator()(const TExample &ex)
{
  if (filters)
    PITERATE(TFilterList, fi, filters)
      if (!(*fi)->call(ex))
        return negate;

  return !negate;
}


TFilter_disjunction::TFilter_disjunction()
: filters(mlnew TFilterList())
{}


TFilter_disjunction::TFilter_disjunction(PFilterList af)
: filters(af)
{}


bool TFilter_disjunction::operator()(const TExample &ex)
{
  if (filters)
    PITERATE(TFilterList, fi, filters)
      if ((*fi)->call(ex))
        return !negate;

  return negate;
}