source: plugins/base2/net.sf.basedb.normalizers/trunk/src/c++/bin/qQN.cc @ 1164

Last change on this file since 1164 was 1164, checked in by Jari Häkkinen, 14 years ago

Fixes #247. A work around for the erroneous export from exportPlainMatrix.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 8.9 KB
Line 
1// $Id: qQN.cc 1164 2009-09-23 09:08:19Z jari $
2
3/*
4  Copyright (C) 2009 Jari Häkkinen
5
6  This file is part of the Normalizers plug-in package for BASE
7  (net.sf.based.normalizers). The package is available at
8  http://baseplugins.thep.lu.se/ BASE main site is
9  http://base.thep.lu.se/
10
11  This is free software; you can redistribute it and/or modify it
12  under the terms of the GNU General Public License as published by
13  the Free Software Foundation; either version 3 of the License, or
14  (at your option) any later version.
15
16  The software is distributed in the hope that it will be useful, but
17  WITHOUT ANY WARRANTY; without even the implied warranty of
18  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  General Public License for more details.
20
21  You should have received a copy of the GNU General Public License
22  along with this program. If not, see <http://www.gnu.org/licenses/>.
23*/
24
25#include <config.h> // this header file is created by configure
26
27#include <yat/normalizer/ColumnNormalizer.h>
28#include <yat/normalizer/qQuantileNormalizer.h>
29
30#include <yat/utility/CommandLine.h>
31#include <yat/utility/MatrixWeighted.h>
32#include <yat/utility/OptionHelp.h>
33#include <yat/utility/OptionInFile.h>
34#include <yat/utility/OptionOutFile.h>
35#include <yat/utility/OptionSwitch.h>
36#include <yat/utility/stl_utility.h>
37#include <yat/statistics/utility.h>
38
39#include <cstdlib>
40#include <fstream>
41#include <functional>
42#include <iostream>
43#include <limits>
44#include <stdexcept>
45
46using namespace theplu::yat::normalizer;
47using namespace theplu::yat::utility;
48
49
50class CleanUpMatrix : std::unary_function<DataWeight, DataWeight>
51{
52public:
53  CleanUpMatrix(void) {}
54
55  inline DataWeight operator()(DataWeight x) const
56    { return ( x.data()>0 ?
57               x : DataWeight(std::numeric_limits<double>::quiet_NaN(),0.0) ); }
58};
59
60
61void create_matrix_until_183_fixed(MatrixWeighted**, const MatrixWeighted&,
62                                   const std::string&);
63void create_target(std::vector<double>&, const MatrixWeighted&, bool use_median);
64void create_target(std::vector<double>&, const MatrixWeighted&,
65                   const std::string&, bool use_median);
66
67/**
68   writes the data values in the matrix ignoring the weights, i.e.,
69   produces the same output as the Matrix output operator does.
70 */
71std::ostream& operator<< (std::ostream&, const MatrixWeighted&);
72
73
74int main(int argc, char* argv[])
75{
76  CommandLine cmd;
77  OptionInFile assay(cmd, "assay-data", "assay annotations");
78  OptionInFile indata(cmd, "in-data", "data to be normalized");
79  OptionOutFile outdata(cmd, "out-data", "normalized data");
80  OptionSwitch target_median(cmd, "median",
81                             "use median instead of mean for targets", false);
82  OptionHelp help(cmd);
83  help.synopsis()=(std::string("See ") +
84                   "http://baseplugins.thep.lu.se/net.sf.basedb.normalizers " +
85                   "for\ndetails on this program\n");
86  OptionSwitch version(cmd, "version", "output version and exit");
87  std::stringstream copyright;
88  copyright << PACKAGE_STRING << '\n'
89            << "Copyright (C) 2009 Jari Häkkinen\n\n"
90            << "This is free software see the source for copying "
91            << "conditions. There is NO\nwarranty; not even for "
92            << "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n";
93  try {
94    cmd.parse(argc, argv);
95  }
96  catch (cmd_error& e) {
97    if (version.present()) {
98      std::cout << copyright.str();
99      return EXIT_SUCCESS;
100    }
101    std::cout << e.what() << std::endl;
102    return EXIT_FAILURE;
103  }
104  if (version.present()) {
105    std::cout << copyright.str();
106    return EXIT_SUCCESS;
107  }
108  std::ifstream* infile=NULL;
109  std::streambuf* cin_buffer=NULL;
110  if (indata.present()) {
111    infile=new std::ifstream(indata.value().c_str());
112    cin_buffer = std::cin.rdbuf(); // save cin's input buffer
113    std::cin.rdbuf(infile->rdbuf());
114  }
115
116  // The BASE core API deprecated exportPlainMatrix method of the
117  // deprecated BioAssaySetExporter does not behave well when
118  // exporting bioassaysets where assays have been filtered out in
119  // some filter step. Variables and functions with 183 in their name
120  // should be removed when http://baseplugins.thep.lu.se/ticket/183
121  // is fixed.
122
123  // m is a pointer below, should be changed to a normal variable when
124  // http://baseplugins.thep.lu.se/ticket/183 is fixed.
125
126  // Change to m when http://baseplugins.thep.lu.se/ticket/183 fixed.
127  MatrixWeighted m_tmp_until_183_fixed(std::cin,'\t');
128  if (indata.present()) {
129    std::cin.rdbuf(cin_buffer); // restore old input buffer
130    infile->close();
131    delete infile;
132  }
133  // Remove until HERE below when
134  // http://baseplugins.thep.lu.se/ticket/183 fixed.
135  MatrixWeighted* m=NULL;
136  if (assay.present())
137    create_matrix_until_183_fixed(&m, m_tmp_until_183_fixed, assay.value());
138  else
139    m = &m_tmp_until_183_fixed;
140  // HERE remove until here.
141
142  std::transform(m->begin(), m->end(), m->begin(), CleanUpMatrix());
143  std::vector<double> target;
144  ( assay.present() ?
145    create_target(target, *m, assay.value(), target_median.value()) :
146    create_target(target, *m, target_median.value()) );
147  std::transform(target.begin(), target.end(),
148                 target.begin(), theplu::yat::utility::Log<double>());
149  std::transform(data_iterator(m->begin()), data_iterator(m->end()),
150                 data_iterator(m->begin()), theplu::yat::utility::Log<double>());
151  // q = min(100,target_size/10) but no smaller than 10
152  unsigned int q=target.size()/10;
153  q = q>100 ? 100 : ( q<10 ? 10 : q );
154  qQuantileNormalizer qqn(target.begin(), target.end(), q);
155  ColumnNormalizer<qQuantileNormalizer> cn(qqn);
156  MatrixWeighted result(m->rows(),m->columns());
157  cn(*m,result);
158  std::transform(data_iterator(result.begin()), data_iterator(result.end()),
159                 data_iterator(result.begin()), theplu::yat::utility::Exp<double>());
160
161  std::ofstream* outfile=NULL;
162  std::streambuf* cout_buffer = std::cout.rdbuf();
163  if (outdata.present()) {
164    outfile=new std::ofstream(outdata.value().c_str());
165    cout_buffer = std::cout.rdbuf(); // save cout's output buffer
166    std::cout.rdbuf(outfile->rdbuf());
167  }
168  std::cout << result << std::endl;
169  if (outdata.present()) {
170    std::cout.rdbuf(cout_buffer); // restore old output buffer
171    outfile->close();
172    delete outfile;
173  }
174
175  // clean up until http://baseplugins.thep.lu.se/ticket/183 fixed.
176  if (assay.present())
177    delete m;
178
179  return EXIT_SUCCESS;
180}
181
182
183void create_matrix_until_183_fixed(MatrixWeighted** m,
184                                   const MatrixWeighted& m_tmp_183,
185                                   const std::string& assay)
186{
187  std::ifstream is(assay.c_str());
188  std::vector<size_t> idx;
189  while (is.good()) {
190    size_t i;
191    is >> i;
192    if (is.good()) idx.push_back(i);
193    std::string line;
194    getline(is, line);
195    if (idx.size()>m_tmp_183.columns())
196      throw std::runtime_error(std::string("183_tmp: Too many annotation ") +
197                               "columns wrt data matrix");
198  }
199
200  if (*m) delete *m;
201  size_t rows=m_tmp_183.rows();
202  size_t cols=idx.size();
203  *m=new MatrixWeighted(rows,cols);
204  for (size_t i=0; i<rows; ++i)
205    for (size_t j=0; j<cols; ++j)
206      (**m)(i,j)=m_tmp_183(i,idx[j]-1);
207}
208
209
210void create_target(std::vector<double>& t, const MatrixWeighted& m,
211                   const std::string& assay, bool use_median)
212{
213  std::vector< std::vector<double> > calc_support(m.rows());
214  for (std::vector< std::vector<double> >::iterator i=calc_support.begin();
215       i!=calc_support.end(); ++i)
216    i->reserve(m.columns());
217
218  std::ifstream is(assay.c_str());
219  std::string line;
220  size_t column=0;
221  while (getline(is, line)) {
222    size_t found=line.find("yes");
223    if (found!=std::string::npos) // use this assay as a part of reference
224      for (size_t row=0; row<m.rows(); ++row)
225        if (m(row,column).weight())       // weight either 0 or 1
226          calc_support[row].push_back(m(row,column).data());
227    ++column;
228    if (column>m.columns())
229      throw std::runtime_error("Too many annotation columns wrt data matrix");
230  }
231
232  t.reserve(m.rows());
233  for (size_t row=0; row<m.rows(); ++row) {
234    const std::vector<double>& cs=calc_support[row];
235    if (!cs.empty())
236      t.push_back( use_median ?
237                   theplu::yat::statistics::median(cs.begin(), cs.end()) :
238                   std::accumulate(cs.begin(), cs.end(), 0.0) / cs.size() );
239  }
240  if (!t.size())
241    throw std::runtime_error("Not a well defined reference, aborting");
242}
243
244
245void create_target(std::vector<double>& t, const MatrixWeighted& m,
246                   bool use_median)
247{
248  t.reserve(m.rows());
249  std::vector<double> cs;
250  cs.reserve(m.columns());
251  for (size_t row=0; row<m.rows(); ++row) {
252    cs.clear();
253    for (size_t column=0; column<m.columns(); ++column)
254      if (m(row,column).weight())      // weight either 0 or 1
255        cs.push_back(m(row,column).data());
256    if (!cs.empty())
257      t.push_back( use_median ?
258                   theplu::yat::statistics::median(cs.begin(), cs.end()) :
259                   std::accumulate(cs.begin(), cs.end(), 0.0) / cs.size() );
260  }
261  if (!t.size())
262    throw std::runtime_error("Not a well defined reference, aborting");
263}
264
265
266std::ostream& operator<< (std::ostream& s, const MatrixWeighted& m)
267{
268  s.setf(std::ios::dec);
269  s.precision(12);
270  for(size_t i=0, j=0; i<m.rows(); i++)
271    for (j=0; j<m.columns(); j++) {
272      s << m(i,j).data();
273      if (j<m.columns()-1)
274        s << s.fill();
275      else if (i<m.rows()-1)
276        s << "\n";
277    }
278  return s;
279}
Note: See TracBrowser for help on using the repository browser.