Example #1
0
int DataLoader::useResidualAsPhenotype() {
  if (binaryPhenotype) {
    logger->warn(
        "WARNING: Skip transforming binary phenotype, although you want to "
        "use residual as phenotype!");
    return 0;
  }

  LinearRegression lr;
  Vector pheno;
  Matrix covAndInt;
  const int numCovariate = covariate.ncol();

  copyPhenotype(phenotype, &pheno);
  copyCovariateAndIntercept(pheno.Length(), covariate, &covAndInt);
  if (!lr.FitLinearModel(covAndInt, pheno)) {
    if (numCovariate > 0) {
      logger->error(
          "Cannot fit model: [ phenotype ~ 1 + covariates ], now use the "
          "original phenotype");
    } else {
      logger->error(
          "Cannot fit model: [ phenotype ~ 1 ], now use the "
          "original phenotype");
    }
  } else {  // linear model fitted successfully
    copyVectorToMatrixColumn(lr.GetResiduals(), &phenotype, 0);
    // const int n = lr.GetResiduals().Length();
    // for (int i = 0; i < n; ++i) {
    //   // phenotypeInOrder[i] = lr.GetResiduals()[i];
    //   phenotype[i][0] = lr.GetResiduals()[i];
    // }
    covariate.clear();
    if (numCovariate > 0) {
      logger->info(
          "DONE: Fit model [ phenotype ~ 1 + covariates ] and model "
          "residuals will be used as responses");
    } else {
      logger->info("DONE: Use residual as phenotype by centerng it");
    }

    // store fitting results
    Vector& beta = lr.GetCovEst();
    Matrix& betaSd = lr.GetCovB();
    const int n = beta.Length();
    for (int i = 0; i < n; ++i) {
      addFittedParameter(covAndInt.GetColumnLabel(i), beta[i], betaSd[i][i]);
    }
    addFittedParameter("Sigma2", lr.GetSigma2(), NAN);
  }

#if 0
  if (covariate.ncol() > 0) {
    LinearRegression lr;
    Vector pheno;
    Matrix covAndInt;
    copyPhenotype(phenotype, &pheno);
    copyCovariateAndIntercept(covariate.nrow(), covariate, &covAndInt);
    if (!lr.FitLinearModel(covAndInt, pheno)) {
      logger->error(
          "Cannot fit model: [ phenotype ~ 1 + covariates ], now use the "
          "original phenotype");
    } else {
      const int n = lr.GetResiduals().Length();
      for (int i = 0; i < n; ++i) {
        // phenotypeInOrder[i] = lr.GetResiduals()[i];
        phenotype[i][0] = lr.GetResiduals()[i];
      }
      covariate.clear();
      logger->info(
          "DONE: Fit model [ phenotype ~ 1 + covariates ] and model "
          "residuals will be used as responses");
    }
    storeFittedModel(lr);
  } else {  // no covaraites
    // centerVector(&phenotypeInOrder);
    std::vector<double> v;
    phenotype.extractCol(0, &v);
    centerVector(&v);
    phenotype.setCol(0, v);

    logger->info("DONE: Use residual as phenotype by centerng it");
  }
#endif

  return 0;
}