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
|
/* TRANSLATOR BALL::QSAR
Necessary for lupdate.
*/
#include <validationItem.h>
#include <exception.h>
#include <mainWindow.h>
#include <validationResultDialog.h>
#include <BALL/QSAR/configIO.h>
#include <QtGui/QDrag>
#include <QtCore/QMimeData>
#include <BALL/VIEW/KERNEL/iconLoader.h>
#include <BALL/QSAR/classificationModel.h>
using namespace BALL::QSAR;
using namespace BALL::Exception;
namespace BALL
{
namespace VIEW
{
ValidationItem::ValidationItem(int type, DataItemView* view):
DataItem(view),
k_(0),
num_of_samples_(0),
num_of_runs_(0),
model_item_(NULL),
q2_(0.0),
r2_(0.0)
{
nested_val_item_ = NULL;
type_ = type;
partitioner_ = NULL;
validation_statistic_ = 0;
init();
}
ValidationItem::ValidationItem(ValidationItem& item):
DataItem(item.view_)
{
type_ = item.type_;
k_ = item.k_;
num_of_samples_ = item.num_of_samples_;
num_of_runs_ = item.num_of_runs_;
model_item_ = item.model_item_;
q2_ = -1;
r2_ = -1;
nested_val_item_ = NULL;
partitioner_ = NULL;
validation_statistic_ = 0;
init();
}
ValidationItem::~ValidationItem()
{
if (view_->name == "view")
{
//if the item was connected to others, delete it from its respective pipeline
if (!removeDisconnectedItem())
{
removeFromPipeline();
}
}
if(nested_val_item_!=NULL && view_->data_scene->main_window->val_pipeline_.contains(nested_val_item_))
{
nested_val_item_->external_validations_.remove(this);
// one fold validation (this item) is being deleted, so that the average of the remaining predictive qualities has to calculated anew ...
nested_val_item_->change();
}
delete plotter_;
}
ValidationItem::ValidationItem(String& configfile_section, std::map<String, DataItem*>& filenames_map, std::list<std::pair<double,double> >* item_positions, DataItemView* view)
: DataItem(view)
{
result_color_ = QColor(205,225,205);
type_ = -1;
std::istringstream input;
input.str(configfile_section);
ValidationConfiguration conf = ConfigIO::readValidationConfiguration(&input);
int no = conf.external_predictions.size();
for(int i=0; i<no; i++)
{
String file_i = conf.external_predictions[i];
std::map<String,DataItem*>::iterator it = filenames_map.find(file_i);
if(it==filenames_map.end())
{
std::cout<<file_i<<" can not be found!!"<<std::endl;
throw BALL::Exception::GeneralException(__FILE__,__LINE__,"ValidationItem reading error","PredictionItem of a nested cross validation fold could not be found!");
}
PredictionItem* pred_i = (PredictionItem*) it->second;
addExternalFoldValidation(pred_i);
if(i==0) // all folds of ONE validationItem for nested validation come from
// ONE PartitioningItem
{
Edge* edge = pred_i->dottedEdge();
if(edge!=NULL)
{
if(edge->sourceNode()->inEdges().size()>0)
{
DataItem* tmp = (*edge->sourceNode()->inEdges().begin())->sourceNode();
if(tmp->type()==PartitioningItem::Type)
{
setPartitioner((PartitioningItem*)tmp);
}
}
}
}
}
// conf.data is not used since the inputItem connected to the modelItem is used for obtaining input data
k_ = conf.k_folds;
num_of_samples_ = conf.bootstrap_samples;
num_of_runs_ = conf.no_of_permutation_tests;
validation_statistic_ = conf.statistic;
type_ = conf.val_type;
std::map<String,DataItem*>::iterator it = filenames_map.find(conf.model);
if(it==filenames_map.end())
{
throw BALL::Exception::GeneralException(__FILE__,__LINE__,"ValidationItem reading error","ModelItem for which the validation should be done can not be found!");
}
model_item_ = (ModelItem*) it->second;
view_->data_scene->addItem(this);
addToPipeline();
if(item_positions!=0 && item_positions->size()>0)
{
std::pair<double,double> pos = item_positions->front();
item_positions->pop_front();
setPos(pos.first,pos.second);
}
Edge* edge = new Edge(model_item_, this);
view_->data_scene->addItem(edge);
setSavedAs(conf.output.c_str());
/// if not defined in config-section explicitly, find type of validation to be done:
if(type_==-1)
{
if(k_<2 && conf.external_predictions.size()>0) type_ = 5;
else
{
if(k_<=0) type_ = 1;
else if(num_of_samples_<=0) type_ = 2;
else type_ = 3;
if(num_of_runs_>0) type_ = 4;
}
}
init();
}
void ValidationItem::init()
{
result_color_ = QColor(205,225,205);
initName();
setPixmap(findPixmap("validation"));
createActions();
coeff_stderr_ratio_ = 0;
plotter_ = NULL;
}
void ValidationItem::initName()
{
name_ = view_->data_scene->main_window->registry()->getValidationName(type_).c_str();
}
void ValidationItem::createActions()
{
if(type_>2 && type_!=7) // for other types, redoing the validation makes no sense, since that would always yield the same result
{
QAction* redo_action = new QAction("Redo", this);
connect(redo_action, SIGNAL(triggered()), this, SLOT(changeSlot()));
context_menu_actions_.push_back(redo_action);
}
QAction* show_values = new QAction("Show predictions", this);
connect(show_values, SIGNAL(triggered()), this, SLOT(showPredictionDialog()));
context_menu_actions_.push_back(show_values);
if(type_==5)
{
QAction* show_plotter = new QAction(QIcon(""),tr("Plot all predictions"), this);
connect(show_plotter, SIGNAL(triggered()), this, SLOT(showPlotter()));
context_menu_actions_.push_back(show_plotter);
}
}
void ValidationItem::showPlotter()
{
if(plotter_ == NULL)
{
plotter_=new PredictionPlotter(this);
}
plotter_->show();
}
void ValidationItem::changeSlot()
{
change();
if(partitioner_!=NULL) partitioner_->change();
view_->data_scene->update();
}
void ValidationItem::change()
{
DataItem::change();
delete plotter_;
plotter_=NULL;
}
void ValidationItem::setPartitioner(PartitioningItem* partitioner)
{
partitioner_ = partitioner;
}
// overloaded by PredictionItem
void ValidationItem::setValidationInput()
{
model_item_->model()->setDataSource(model_item_->inputDataItem()->data());
}
bool ValidationItem::execute()
{
if (model_item_ == NULL)
{
throw InvalidValidationItem(__FILE__,__LINE__);
}
if(done_) return 0; // do nothing twice...
setValidationInput();
if(validation_statistic_>=0)
{
model_item_->model()->model_val->selectStat(validation_statistic_);
}
switch(type_)
{
case 1:
model_item_->model()->model_val->testInputData();
break;
case 2:
model_item_->model()->model_val->crossValidation(k_);
break;
case 3:
model_item_->model()->model_val->bootstrap(num_of_samples_);
break;
case 4:
result_of_rand_test_ = model_item_->model()->model_val->yRandomizationTest(num_of_runs_, k_);
break;
case 5:
q2_ = 0;
for(list<ValidationItem*>::iterator it=external_validations_.begin(); it!=external_validations_.end(); it++)
{
// if one prediction is not yet ready, stop calc. average quality
if(!(*it)->isDone()) return 0;
q2_ += (*it)->getQ2();
}
q2_ /= external_validations_.size(); // average Q^2 obtained from nested cross validation
break;
case 6:
if(!model_item_->getRegistryEntry()->regression)
{
throw BALL::Exception::GeneralException(__FILE__,__LINE__,"validation error","coefficient stddev can only be calculated for regression models!");
}
((RegressionModel*)model_item_->model())->validation->calculateCoefficientStdErrors(num_of_samples_,1);
break;
case 7:
model_item_->model()->model_val->testInputData(1);
break;
default:
throw InvalidValidationItem(__FILE__,__LINE__);
}
processResults();
done_ = 1;
return 1;
}
void ValidationItem::processResults()
{
if(type_<5 || type_==7)
{
r2_ = model_item_->model()->model_val->getFitRes();
q2_ = model_item_->model()->model_val->getCVRes();
}
if(type_==1||type_==7) setResultString(r2_);
else if(type_==6)
{
coeff_stddev_ = *((RegressionModel*)model_item_->model())->validation->getCoefficientStdErrors();
const Eigen::MatrixXd* training_result = ((RegressionModel*)model_item_->model())->getTrainingResult();
// calculate&display average stddev
double mean_stddev=0;
Size rows=coeff_stddev_.rows();
Size cols=coeff_stddev_.cols();
double epsilon = std::numeric_limits<double>::epsilon();
if(training_result->cols()==cols && training_result->rows()==rows)
{
for(unsigned int i=0; i<rows;i++) // for each feature
{
for(unsigned int j=0; j<cols;j++) // for each activity
{
double t_ij = (*training_result)(i,j);
double s_ij = coeff_stddev_(i,j);
if(abs(t_ij) > epsilon && abs(s_ij) > epsilon)
{
std::cout<<s_ij/t_ij;
mean_stddev += abs(s_ij/t_ij);
}
std::cout << std::endl;
}
}
coeff_stderr_ratio_ = mean_stddev/(rows*cols);
setResultString(coeff_stderr_ratio_);
}
}
else if(type_==4)
{
double mean_q2=0;
for(unsigned int i=0;i<result_of_rand_test_.rows();i++)
{
mean_q2+=result_of_rand_test_(i,1);
}
mean_q2/=result_of_rand_test_.rows();
setResultString(mean_q2);
}
else setResultString(q2_);
}
BALL::String ValidationItem::getStatName()
{
String name="";
if(validation_statistic_==-1) return name;
return model_item_->getRegistryEntry()->getStatName(validation_statistic_);
}
void ValidationItem::setModelItem(ModelItem* model_item)
{
model_item_ = model_item;
}
int ValidationItem::getValidationType()
{
return type_;
}
void ValidationItem::setValFraction(double frac)
{
val_fraction_ = frac;
}
double ValidationItem::getValFraction()
{
return val_fraction_;
}
void ValidationItem::setK(int k)
{
k_ = k;
}
void ValidationItem::setNumOfRuns(int num)
{
num_of_runs_ = num;
}
void ValidationItem::setNumOfSamples(int num)
{
num_of_samples_ = num;
}
void ValidationItem::setNumOfNCVFolds(int num)
{
n_of_ncv_folds_ = num;
}
ModelItem* ValidationItem::modelItem()
{
return model_item_;
}
double ValidationItem::getQ2()
{
return q2_;
}
double ValidationItem::getR2()
{
return r2_;
}
int ValidationItem::numOfRuns()
{
return num_of_runs_;
}
int ValidationItem::numOfSamples()
{
return num_of_samples_;
}
int ValidationItem::numOfNCVFolds()
{
return n_of_ncv_folds_;
}
int ValidationItem::k()
{
return k_;
}
Eigen::MatrixXd* ValidationItem::resultOfRandTest()
{
return &result_of_rand_test_;
}
// SLOT
void ValidationItem::showPredictionDialog()
{
ValidationResultDialog validationResultDialog(this);
validationResultDialog.exec();
}
void ValidationItem::writeConfigSection(std::ofstream& out)
{
out << "[Validator]" << "\n";
out << "model_file = "<< modelItem()->savedAs().toStdString() << "\n";
out << "data_file = "<< modelItem()->inputDataItem()->savedAs().toStdString() << "\n";
out << "validation_type = "<<type_<<std::endl;
// for nested cross validation save the names of the prediction output-files in order to be able to restore the pipeline later
if(external_validations_.size()>0)
{
out<<"external_validation_predictions = ";
for(list<ValidationItem*>::iterator it=external_validations_.begin(); it!=external_validations_.end(); it++)
{
out<<(*it)->savedAs().toStdString()<<" ";
}
out<<std::endl;
}
int s = getValidationStatistic();
if(s>=0)
{
String stat = modelItem()->getRegistryEntry()->getStatName(s);
if(!model_item_->getRegistryEntry()->regression) out<< "classification_statistic = "<<stat.c_str()<<std::endl;
else out<< "regression_statistic = "<<stat.c_str()<<std::endl;
}
if(type_>0) out << "k_fold = "<< k() << "\n";
if(num_of_samples_>0) out << "bootstrap_samples = "<< num_of_samples_ << "\n";
if(num_of_runs_>0) out << "no_of_permutation_tests = " << num_of_runs_ << "\n";
out << "output = " << savedAs().toStdString() << "\n\n";
}
void ValidationItem::addToPipeline()
{
view_->data_scene->main_window->val_pipeline_.insert(this);
view_->data_scene->main_window->all_items_pipeline_.insert(this);
}
void ValidationItem::removeFromPipeline()
{
view_->data_scene->main_window->val_pipeline_.erase(this);
view_->data_scene->main_window->all_items_pipeline_.erase(this);
}
void ValidationItem::addExternalFoldValidation(ValidationItem* item)
{
external_validations_.push_back(item);
item->nested_val_item_ = this;
}
int ValidationItem::getNoExternalFolds()
{
return external_validations_.size();
}
BALL::String ValidationItem::getMouseOverText()
{
String message="";
if(view_->name!="view") return message;
if(type_!=6)
{
message+="using ";
message += modelItem()->getRegistryEntry()->getStatName(validation_statistic_);
}
else if(done_ && type_==6)
{
message+="average ratio between stddev\nand coeff: "+String(coeff_stderr_ratio_);
}
return message;
}
void ValidationItem::saveToFile(String filename)
{
if(model_item_->getRegistryEntry()->regression)
{
((RegressionModel*)model_item_->model())->validation->saveToFile(filename,r2_,q2_,coeff_stddev_,result_of_rand_test_);
}
else
{
((ClassificationModel*)model_item_->model())->validation->saveToFile(filename,r2_,q2_);
}
}
void ValidationItem::loadFromFile(String filename)
{
try
{
model_item_->model()->model_val->readFromFile(filename);
}
catch(BALL::Exception::GeneralException e)
{
QMessageBox::warning(view_,"Error",e.getMessage());
return;
}
r2_ = model_item_->model()->model_val->getFitRes();
q2_ = model_item_->model()->model_val->getCVRes();
result_of_rand_test_ = model_item_->model()->model_val->getYRandResults();
if(r2_!=-1 || q2_!=-1) // if some result was loaded
{
processResults();
done_=1;
}
}
}
}
|