<commit_before>#include <math.h>       // for pow()
#include <stdio.h>      // for printf, scanf, fgets
#include <stdlib.h>     // for malloc()
#include <string.h>     // for strlen(), strcpy()

#include <algorithm>    // for std::accumulate()
#include <cstring>      // for std::strcpy
#include <fstream>
#include <iostream>     // for std::cout
#include <limits>       // for numericlimits
#include <map>          // for std::map
#include <set>          // for std::set

const std::string input_file_name = "data/Fergus26genes_05may15_idt.txt";
const int tail_len = 5;
const int max_mismatches = 1;
const int number_of_bases = 4;
const int hash_base = number_of_bases;

class PrimerClass {
	std::string name_;
  std::string sequence_;
 public:
  void SetName(std::string str) {
    name_ = str;
  }
  void SetSequence(std::string str) {
    sequence_ = str;
  }
  void Print() {
    std::cout << "name: " << name_ << '\n';
    std::cout << "sequence: " << sequence_ << '\n';
  }
  std::string GetName() {
    return name_;
  }
  std::string GetSequence() {
    return sequence_;
  }
};

typedef struct node {
  int primer_index;
  node* next;
} node_t;

std::vector<char> bases = {'A', 'T', 'C', 'G'};
std::map<char, char> complement_map = {{'A', 'T'}, {'T', 'A'}, {'C', 'G'}, {'G', 'C'}};
std::map<char, char> next_base = {{'A', 'T'}, {'T', 'C'}, {'C', 'G'}, {'G', 'A'}};
std::map<char, int> base_map = {{'A', 0}, {'T', 1}, {'C', 2}, {'G', 3}};

int hash(std::string str) {
  int ret_val = 0;
  for (auto i = 0u; i < str.size(); ++i) ret_val += pow(hash_base, i) * base_map[str[i]];
  return ret_val;
}

std::string ReverseComplement(std::string src) {
  int len = src.size();
  std::string ret_str = src;
  for (int i = 0; i < len; ++i) {
    ret_str[len - 1 - i] = complement_map[src[i]];
  }
  return ret_str;
}

std::set<std::set<int>> kSubsets(int n, int k) {
  // returns all k-subsets of {0, 1, ..., n-1}
  if (k < 1) printf("ERROR: in kSubsets k must be >= 1");
  if (k > n) printf("ERROR: in kSubsets k must be <= n");

  std::set<std::set<int>> ret_set;
  std::set<int> tmp_set;
  std::vector<int> include_indexes;
  for (int i = 0; i < k; ++i) include_indexes.push_back(i);

  while(1) {
    tmp_set.clear();
    for (int i: include_indexes) tmp_set.insert(i);
    ret_set.insert(tmp_set);
    if (include_indexes[0] == (n-1)-(k-1)) break;

    // update include_indexes
    for (auto i = include_indexes.size() - 1; i >= 0; --i) {
      if (i == include_indexes.size() - 1 && include_indexes[i] < n-1) {
        ++include_indexes[i];
        break;
      } else if (i < include_indexes.size() - 1 && include_indexes[i] < include_indexes[i+1] - 1) {
        ++include_indexes[i];
        for (auto j = i + 1; j < include_indexes.size(); ++j) {
          include_indexes[j] = include_indexes[j-1]+1;
        }
        break;
      }
    }
  }
  return ret_set;
}

std::set<std::string> kMismatch(std::string input_str, int max_mismatches) {
  // returns a set of strings which have less than or equal to
  // max_mismatches with input_str
  std::set<std::string> ret_set;
  int len = input_str.size();
  if (max_mismatches < 0) {
    printf("ERROR: in kMismatch, max_mismatches must be nonnegative.");
    exit(EXIT_FAILURE);
  } else if (max_mismatches == 0) {
    ret_set.insert(input_str);
  } else {
    if (max_mismatches > len) max_mismatches = len;
    std::set<std::set<int>> s = kSubsets(len, max_mismatches);
    std::vector<int> include_indexes_sorted;
    std::string tmp_str;
    for (std::set<int> include_indexes: s) {
      tmp_str = input_str;
      include_indexes_sorted.clear();
      for (int i: include_indexes) include_indexes_sorted.push_back(i);
      std::sort(include_indexes_sorted.begin(), include_indexes_sorted.end());
      if (include_indexes_sorted[0] == 0) {
        continue; // the 0th base (the 3' end) must match
      }
      for (int i: include_indexes_sorted) tmp_str[i] = 'A';
      for (int j = 0; j < pow(number_of_bases, max_mismatches); j++) {
        ret_set.insert(tmp_str);
        for (auto i = 0u; i < include_indexes_sorted.size(); ++i) {
          if (tmp_str[include_indexes_sorted[i]] != 'G') {
            tmp_str[include_indexes_sorted[i]] = next_base[tmp_str[include_indexes_sorted[i]]];
            for (auto u = 0u; u < i; ++u) tmp_str[include_indexes_sorted[u]] = 'A';
            break;
          }
        }
      }
    }
  }
  return ret_set;
}

void PrintHashTableStatistics(node** hash_table, int hash_table_size) {
  int count, max_count = 0, total_count = 0;
  node_t* tmp_node_ptr;
  for (auto i = 0; i < hash_table_size; ++i) {
    count = 0;
    tmp_node_ptr = hash_table[i];
    while (tmp_node_ptr != nullptr) {
      ++count;
      tmp_node_ptr = tmp_node_ptr->next;
    }
    if (count > max_count) max_count = count;
    total_count += count;
  }
  //printf("There are %i total entries in the hash table\n", total_count);
  //printf("The most entries in one index is %i\n", max_count);
  printf(" %-10i|", total_count);
}

void PrintHitStatistics(std::vector<std::vector<int>> hit, int number_of_primers) {
  int hits, max_hits = 0, max_hits_index;
  std::vector<int> all_hits;
  for (int i = 0; i < number_of_primers; ++i) {
    hits = 0;
    for (int j = 0; j < number_of_primers; ++j) {
      if (hit[i][j]) ++hits;
    }
    if (hits > max_hits) {
      max_hits = hits;
      max_hits_index = i;
    }
    all_hits.push_back(hits);
  }
  double avg_hits = std::accumulate(all_hits.begin(), all_hits.end(), 0ull) / (double)all_hits.size();
  //printf("the max_hits for any primer = %i, for primer %i\n", max_hits, max_hits_index);
  //printf("the avg_hits for each primer = %f\n", avg_hits);
  //printf("the avg percentage hits for each primer = %f%%\n", 100*avg_hits/number_of_primers);
  printf(" %-12f|", avg_hits/number_of_primers);
}

std::vector<PrimerClass> ReadInputFile(std::string input_file_name) {
  std::ifstream instream(input_file_name);
  if (!instream.is_open()) {
    std::cout << "Could not open input file.\n";
    std::exit(EXIT_FAILURE);
  }
  std::vector<PrimerClass> primers;
  std::string name;
  std::string sequence;
  for (;;) {
    std::getline(instream, name, ',');
    std::getline(instream, sequence, ',');
    std::transform(sequence.begin(), sequence.end(), sequence.begin(),
      ::toupper);
    instream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    if (instream.eof()) {
      break;
    } else {
      PrimerClass primer;
      primer.SetName(name);
      primer.SetSequence(sequence);
      primers.push_back(primer);
    }
  }
  instream.close();
  return primers;
}

std::vector<node_t*> LoadTable(std::vector<PrimerClass> primers,
    int tail_len, int max_mismatches) {
  std::vector<node_t*> table;
  for (int i = 0; i < pow(number_of_bases, tail_len); ++i) table.push_back(nullptr);
  std::string primer;
  std::string tail;
  std::string tail_rc;
  std::set<std::string> similar_sequences;
  int hash_val;
  int primer_len;
  for (int i = 0; i < static_cast<int>(primers.size()); ++i) {
    primer = primers[i].GetSequence();
    primer_len = primer.size();
    tail = primer.substr(primer_len - tail_len, tail_len);
    tail_rc = ReverseComplement(tail);
    similar_sequences = kMismatch(tail_rc, max_mismatches);
    for (std::string sequence: similar_sequences) {
      hash_val = hash(sequence);
      node_t* tmp_node_ptr = (node_t*) malloc(sizeof(node_t));
      tmp_node_ptr->primer_index = i;
      if (table[hash_val] == nullptr) {
        tmp_node_ptr->next = nullptr;
      } else {
        tmp_node_ptr->next = table[hash_val];
      }
      table[hash_val] = tmp_node_ptr;
    }
  }
  return table;
}

std::vector<std::vector<int>> MatchTails(std::vector<PrimerClass> primers,
    int tail_len, int max_mismatches) {
  std::vector<std::vector<int>> hit;
  std::vector<node_t*> table = LoadTable(primers, tail_len, max_mismatches);
  std::vector<int> zero_vect(primers.size(), 0);
  for (auto i = 0u; i < primers.size(); ++i) hit.push_back(zero_vect);
  std::string tmp_primer;
  std::string window;
  node_t* tmp_node_ptr;
  for (int i = 0; i < static_cast<int>(primers.size()); ++i) {
    tmp_primer = primers[i].GetSequence();
    for (int start_index = 0;
        start_index + tail_len != static_cast<int>(tmp_primer.size());
        ++start_index) {
      window = tmp_primer.substr(start_index, tail_len);
      tmp_node_ptr = table[hash(window)];
      while(tmp_node_ptr != nullptr) {
        hit[i][tmp_node_ptr->primer_index] = 1;
        hit[tmp_node_ptr->primer_index][i] = 1;
        tmp_node_ptr = tmp_node_ptr->next;
      }
    }
  }
  return hit;
}

/*
std::vector<std::vector<bool> LoadJmerHashTable(
    std::array<std::vector<bool>, hash_table_size> &jmer_rc_hash_table,
    char** primers, int number_of_primers, int j, bool rc = false) {
  std::string primer;
  std::string jmer;
  std::string jmer_rc;
  char tmp_primer[primer_len + 1];
  int hash_val;
  for (int i = 0; i < number_of_primers; ++i) {
    strcpy(tmp_primer, primers[i]);
    char* jmer = tmp_primer + strlen(tmp_primer) - j;
    for (; jmer != tmp_primer; --jmer) {
      //std::cout << "jmer = " << jmer << '\n';
      jmer_rc = ReverseComplement(jmer);
      hash_val = hash(jmer_rc);
      jmer_rc_hash_table[hash_val][i] = true;
      tmp_primer[strlen(tmp_primer) - 1] = '\0';
    }
  }
}
*/

int main(int argc, char* argv[]) {
  auto primers = ReadInputFile(input_file_name);

  auto tail_hits = MatchTails(primers, tail_len, max_mismatches);

  for (int i = 0; i < primers.size()/60; ++i) {
    for (int j = 0; j < primers.size()/60; ++j) {
      std::cout << tail_hits[i][j] << ' ';
    }
    std::cout << '\n';
  }

  auto jmer_hits = 1;
  return 0;
}
<commit_msg>added lcs to main.cc<commit_after>#include <math.h>       // for pow()
#include <stdio.h>      // for printf, scanf, fgets
#include <stdlib.h>     // for malloc()
#include <string.h>     // for strlen(), strcpy()

#include <algorithm>    // for std::accumulate()
#include <cstring>      // for std::strcpy
#include <fstream>      // for std::ifstream
#include <iostream>     // for std::cout
#include <limits>       // for std::numericlimits
#include <map>          // for std::map
#include <set>          // for std::set

const char* input_file_name = "data/Fergus28genes_05may15_idt.txt";
const unsigned tail_len = 5;
const unsigned max_mismatches = 1;
const unsigned j = 5;
const unsigned minimum_matching_jmers = 2;
const unsigned minimum_lcs_threshold = 6;

const unsigned number_of_bases = 4;

class PrimerClass {
  std::string name_;
  std::string sequence_;
 public:
  void SetName(std::string str) {
    name_ = str;
  }
  void SetSequence(std::string str) {
    sequence_ = str;
  }
  void Print() {
    std::cout << "name: " << name_ << '\n';
    std::cout << "sequence: " << sequence_ << '\n';
  }
  std::string GetName() {
    return name_;
  }
  std::string GetSequence() {
    return sequence_;
  }
};

typedef struct node {
  int primer_index;
  node* next;
} node_t;

std::vector<char> bases = {'A', 'T', 'C', 'G'};
std::map<char, char> complement_map = {{'A', 'T'}, {'T', 'A'}, {'C', 'G'}, {'G', 'C'}};
std::map<char, char> next_base = {{'A', 'T'}, {'T', 'C'}, {'C', 'G'}, {'G', 'A'}};
std::map<char, int> base_map = {{'A', 0}, {'T', 1}, {'C', 2}, {'G', 3}};

int hash(std::string str);
std::string ReverseComplement(std::string src);
std::vector<PrimerClass> ReadInputFile(std::string input_file_name);
std::set<std::set<int>> kSubsets(int n, int k);
std::set<std::string> kMismatch(std::string input_str, int max_mismatches);
std::vector<node_t*> LoadTailTable(std::vector<PrimerClass> primers, int tail_len,
    int max_mismatches);
std::vector<std::vector<bool>> MatchTails(std::vector<PrimerClass> primers,
    int tail_len, int max_mismatches);
std::vector<std::vector<bool>> LoadJmerTable(std::vector<PrimerClass> primers,
    unsigned j, bool rc = false);
std::vector<std::vector<unsigned>> MatchJmers(std::vector<PrimerClass> primers,
    int j);
unsigned LcsLen(std::string str1, std::string str2);

int main(int argc, char* argv[]) {
  auto primers = ReadInputFile(input_file_name);

  // investigate lcs
  int lcs_len;
  std::vector<int> all_matches;
  for (auto i = 0u; i < primers.size()/10; ++i) {
    for (auto j = 0u; j < primers.size()/10; ++j) {
      lcs_len = LcsLen(ReverseComplement(primers[i].GetSequence()), primers[j].GetSequence());
      all_matches.push_back(lcs_len);
    }
  }
  printf("========================================\n");
  printf("lcs statistics =========================\n");
  printf("avg matches = %f\n", std::accumulate(all_matches.begin(), all_matches.end(), 0ull)/(double)all_matches.size());
  printf("all_matches.size() = %f\n", (double)all_matches.size());
  std::vector<int> stats(100000, 0);
  for (int match : all_matches) {
    ++stats[match];
  }
  for (auto i = 0u; i < stats.size(); ++i) {
    if (stats[i] != 0) {
      printf("matches = %-10i, occurrences = %-10i, prob = %-10f\n", i, stats[i], stats[i]/(double)all_matches.size());
    }
  }
  printf("========================================\n");

  auto tail_hits = MatchTails(primers, tail_len, max_mismatches);
  auto jmer_hits = MatchJmers(primers, j);

  // investigate all conditions
  unsigned sample_size = std::min(1000u, static_cast<unsigned>(primers.size()));
  unsigned tail_count = 0;
  unsigned jmer_count = 0;
  unsigned lcs_count = 0;
  unsigned all_count = 0;
  unsigned conditions_met;
  for (unsigned i = 0; i < sample_size; ++i) {
    for (unsigned j = 0; j < sample_size; ++j) {
      conditions_met = 0;
      if (tail_hits[i][j]) {
        ++tail_count;
        ++conditions_met;
      }
      if (jmer_hits[i][j] >= minimum_matching_jmers) {
        ++jmer_count;
        ++conditions_met;
      }
      if (LcsLen(ReverseComplement(primers[i].GetSequence()), primers[j].GetSequence()) >= minimum_lcs_threshold) {
        ++lcs_count;
        ++conditions_met;
      }
      if (conditions_met == 3) {
        ++all_count;
      }
    }
  }
  std::cout << "proportion of pairs in small sample successful for tail: " << (double)tail_count / (sample_size * sample_size) << '\n';
  std::cout << "proportion of pairs in small sample successful for jmer: " << (double)jmer_count / (sample_size * sample_size) << '\n';
  std::cout << "proportion of pairs in small sample successful for all: " << (double)all_count / (sample_size * sample_size) << '\n';

  // final results
  /*
  count = 0;
  for (auto i = 0u; i < primers.size(); ++i) {
    for (auto j = 0u; j < primers.size(); ++j) {
      if (!tail_hits[i][j]) continue;
      if (jmer_hits[i][j] < minimum_matching_jmers) continue;
      if (LcsLen(ReverseComplement(primers[i].GetSequence()), primers[j].GetSequence()) < minimum_lcs_threshold) continue;
      ++count;
      //if (count % 100 == 0) std::cout << "count = " << count << '\n';
    }
  }
  std::cout << count << '\n';
  std::cout << (double)count / (primers.size() * primers.size()) << '\n';
  */

  return 0;
}

int hash(std::string str) {
  int ret_val = 0;
  for (auto i = 0u; i < str.size(); ++i) {
    ret_val += pow(number_of_bases, i) * base_map[str[i]];
  }
  return ret_val;
}

std::string ReverseComplement(std::string src) {
  int len = src.size();
  std::string ret_str = src;
  for (int i = 0; i < len; ++i) {
    ret_str[len - 1 - i] = complement_map[src[i]];
  }
  return ret_str;
}

std::vector<PrimerClass> ReadInputFile(std::string input_file_name) {
  std::ifstream instream(input_file_name);
  if (!instream.is_open()) {
    std::cout << "Could not open input file.\n";
    std::exit(EXIT_FAILURE);
  }
  std::vector<PrimerClass> primers;
  std::string name;
  std::string sequence;
  for (;;) {
    std::getline(instream, name, ',');
    std::getline(instream, sequence, ',');
    std::transform(sequence.begin(), sequence.end(), sequence.begin(),
      ::toupper);
    instream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    if (instream.eof()) {
      break;
    } else {
      PrimerClass primer;
      primer.SetName(name);
      primer.SetSequence(sequence);
      primers.push_back(primer);
    }
  }
  instream.close();
  return primers;
}
std::set<std::set<int>> kSubsets(int n, int k) {
  // returns all k-subsets of {0, 1, ..., n-1}
  if (k < 1) printf("ERROR: in kSubsets k must be >= 1");
  if (k > n) printf("ERROR: in kSubsets k must be <= n");

  std::set<std::set<int>> ret_set;
  std::set<int> tmp_set;
  std::vector<int> include_indexes;
  for (int i = 0; i < k; ++i) include_indexes.push_back(i);

  while (1) {
    tmp_set.clear();
    for (int i : include_indexes) tmp_set.insert(i);
    ret_set.insert(tmp_set);
    if (include_indexes[0] == (n-1)-(k-1)) break;

    // update include_indexes
    for (auto i = include_indexes.size() - 1; i >= 0; --i) {
      if (i == include_indexes.size() - 1 && include_indexes[i] < n-1) {
        ++include_indexes[i];
        break;
      } else if (i < include_indexes.size() - 1 && include_indexes[i] < include_indexes[i+1] - 1) {
        ++include_indexes[i];
        for (auto j = i + 1; j < include_indexes.size(); ++j) {
          include_indexes[j] = include_indexes[j-1]+1;
        }
        break;
      }
    }
  }
  return ret_set;
}

std::set<std::string> kMismatch(std::string input_str, int max_mismatches) {
  // returns a set of strings which have less than or equal to
  // max_mismatches with input_str
  std::set<std::string> ret_set;
  int len = input_str.size();
  if (max_mismatches < 0) {
    printf("ERROR: in kMismatch, max_mismatches must be nonnegative.");
    exit(EXIT_FAILURE);
  } else if (max_mismatches == 0) {
    ret_set.insert(input_str);
  } else {
    if (max_mismatches > len) max_mismatches = len;
    std::set<std::set<int>> s = kSubsets(len, max_mismatches);
    std::vector<int> include_indexes_sorted;
    std::string tmp_str;
    for (std::set<int> include_indexes : s) {
      tmp_str = input_str;
      include_indexes_sorted.clear();
      for (int i : include_indexes) include_indexes_sorted.push_back(i);
      std::sort(include_indexes_sorted.begin(), include_indexes_sorted.end());
      if (include_indexes_sorted[0] == 0) {
        continue;  // the 0th base (the 3' end) must match
      }
      for (int i : include_indexes_sorted) tmp_str[i] = 'A';
      for (int j = 0; j < pow(number_of_bases, max_mismatches); j++) {
        ret_set.insert(tmp_str);
        for (auto i = 0u; i < include_indexes_sorted.size(); ++i) {
          if (tmp_str[include_indexes_sorted[i]] != 'G') {
            tmp_str[include_indexes_sorted[i]] = next_base[tmp_str[include_indexes_sorted[i]]];
            for (auto u = 0u; u < i; ++u) tmp_str[include_indexes_sorted[u]] = 'A';
            break;
          }
        }
      }
    }
  }
  return ret_set;
}

std::vector<node_t*> LoadTailTable(std::vector<PrimerClass> primers, int tail_len,
    int max_mismatches) {
  std::vector<node_t*> table;
  for (int i = 0; i < pow(number_of_bases, tail_len); ++i) table.push_back(nullptr);
  std::string primer;
  std::string tail;
  std::string tail_rc;
  std::set<std::string> similar_sequences;
  int hash_val;
  int primer_len;
  for (int i = 0; i < static_cast<int>(primers.size()); ++i) {
    primer = primers[i].GetSequence();
    primer_len = primer.size();
    tail = primer.substr(primer_len - tail_len, tail_len);
    tail_rc = ReverseComplement(tail);
    similar_sequences = kMismatch(tail_rc, max_mismatches);
    for (std::string sequence : similar_sequences) {
      hash_val = hash(sequence);
      node_t* tmp_node_ptr = (node_t*) malloc(sizeof(node_t));
      tmp_node_ptr->primer_index = i;
      if (table[hash_val] == nullptr) {
        tmp_node_ptr->next = nullptr;
      } else {
        tmp_node_ptr->next = table[hash_val];
      }
      table[hash_val] = tmp_node_ptr;
    }
  }
  return table;
}

std::vector<std::vector<bool>> MatchTails(std::vector<PrimerClass> primers,
    int tail_len, int max_mismatches) {
  std::vector<std::vector<bool>> hit;
  std::vector<node_t*> table = LoadTailTable(primers, tail_len, max_mismatches);
  std::vector<bool> zero_v(primers.size(), false);
  for (auto i = 0u; i < primers.size(); ++i) hit.push_back(zero_v);
  std::string tmp_primer;
  std::string window;
  node_t* tmp_node_ptr;
  for (unsigned i = 0; i < primers.size(); ++i) {
    tmp_primer = primers[i].GetSequence();
    for (unsigned start_index = 0;
        start_index + tail_len != tmp_primer.size();
        ++start_index) {
      window = tmp_primer.substr(start_index, tail_len);
      tmp_node_ptr = table[hash(window)];
      while (tmp_node_ptr != nullptr) {
        hit[i][tmp_node_ptr->primer_index] = true;
        hit[tmp_node_ptr->primer_index][i] = true;
        tmp_node_ptr = tmp_node_ptr->next;
      }
    }
  }
  return hit;
}

std::vector<std::vector<bool>> LoadJmerTable(std::vector<PrimerClass> primers,
    unsigned j, bool rc) {
  std::vector<std::vector<bool>> jmer_table;
  std::vector<bool> false_v(primers.size(), false);
  for (int i = 0; i < pow(number_of_bases, j); ++i) {
    jmer_table.push_back(false_v);
  }
  std::string primer;
  std::string jmer;
  int hash_val;
  for (unsigned i = 0; i < primers.size(); ++i) {
    primer = primers[i].GetSequence();
    if (rc) primer = ReverseComplement(primer);
    std::string jmer;
    for (unsigned start_index = 0; start_index + j != primer.size(); ++start_index) {
      jmer = primer.substr(start_index, j);
      hash_val = hash(jmer);
      jmer_table[hash_val][i] = true;
    }
  }
  return jmer_table;
}

std::vector<std::vector<unsigned>> MatchJmers(std::vector<PrimerClass> primers,
    int j) {
  std::vector<std::vector<unsigned>> hit;
  auto jmer_table = LoadJmerTable(primers, j, false);
  auto jmer_rc_table = LoadJmerTable(primers, j, true);
  std::vector<unsigned> zero_v(primers.size(), 0);
  for (unsigned i = 0; i < primers.size(); ++i) hit.push_back(zero_v);
  int matches;
  std::vector<int> all_matches;
  for (unsigned i = 0; i < primers.size(); ++i) {
    if (i%300 == 0) std::cout << i << '\n';
    for (unsigned k = i; k < primers.size(); ++k) {
      matches = 0;
      for (unsigned p = 0; p < jmer_table.size(); ++p) {
        if (jmer_rc_table[p][i] == true &&
            jmer_table[p][k] == true) {
          ++matches;
        }
      }
      hit[i][k] = hit[k][i] = matches;
      all_matches.push_back(matches);
    }
  }

  printf("avg matches = %f\n", std::accumulate(all_matches.begin(), all_matches.end(), 0ull)/(double)all_matches.size());
  printf("all_matches.size() = %f\n", (double)all_matches.size());
  std::vector<int> stats(jmer_table.size(), 0);
  for (int match : all_matches) {
    ++stats[match];
  }
  for (auto i = 0u; i < stats.size(); ++i) {
    if (stats[i] != 0) {
      printf("matches = %-10i, occurrences = %-10i, prob = %-10f\n", i, stats[i], stats[i]/(double)all_matches.size());
    }
  }

  return hit;
}

unsigned LcsLen(std::string str1, std::string str2) {
  unsigned lcs_len = 0;
	unsigned len1 = str1.size();
  unsigned len2 = str2.size();
  unsigned rows = len2 + 1;
  unsigned cols = len1 + 1;
  std::vector<unsigned> zero_v(cols, 0);
  std::vector<std::vector<unsigned>> table;
  for (unsigned row = 0; row < rows; ++row) table.push_back(zero_v);
  for (unsigned row = 1; row < rows; ++row) {
    for (unsigned col = 1; col < cols; ++col) {
      if (str1.at(col-1) == str2.at(row-1)) {
        table.at(row).at(col) = table.at(row-1).at(col-1)+1;
        lcs_len = std::max(lcs_len, table.at(row).at(col));
      } else {
        table.at(row).at(col) = 0;
      }
    }
  }
  return lcs_len;
}
<|endoftext|>


<commit_before>#include <inttypes.h>
#include <math.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
  double x = pow(2.0, 3.0);
  x = 1.0 / x;
  printf("%lf\n", x);

  double y = pow(2.0, -3.0);
  printf("%lf\n", y);

  uint64_t z = 1;
  int count = __builtin_clzll(z);
  printf("count=%d\n", count);

  return 0;
}

<commit_msg>remove main.cc - was just used for testing<commit_after><|endoftext|>


<commit_before>#include <GL/glew.h>
#define GLM_SWIZZLE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "SDL.h"
#undef main
#include <list>
#include <algorithm>
#include <functional>

#include "RenderingContext.h"
#include "scene/GraphNode.h"
#include "scene/Skybox.h"
#include "scene/Terrain.h"
#include "scene/Mech.h"
#include "animations/Animation.h"

static SDL_Window *win;
static SDL_GLContext context;

GraphNode *scene = NULL;
RenderingContext *rc;
std::list<Animation*> animations;
int move_forward = 0;

class TestSceneRotation : public Animation
{
private:
	GraphNode* subject;

public:
	TestSceneRotation(GraphNode* subject) : subject(subject)
	{
		rotation = 0;
		y = 0;
	};

	virtual void update(float timestep)
	{
		glm::vec4 cam_pos =
			subject->getWorldCoordinates(
				glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)) *
				glm::vec4(0.0f, y, 3.0f, 1.0f));
		rc->setCamera(cam_pos.xyz(), subject);
		while (rotation > 360.0f) rotation -= 360.0f;
	};

	float y;
	float rotation;
} *scene_rot;

class MechWalk : public Animation
{
private:
	Mech* subject;
	Terrain* terrain;
	float leg_bend;
	int leg_state;

public:
	MechWalk(Mech* subject, Terrain* terrain) : subject(subject), terrain(terrain)
	{
		leg_state = 0;
		leg_bend = 90.0f;
	};

	virtual void update(float timestep)
	{
		if (move_forward) {
			subject->bendLeg(0, 35.0f + leg_bend);
			subject->bendLeg(1, 95.0f - leg_bend);
			subject->bendLeg(2, 35.0f + leg_bend);
			subject->bendLeg(3, 95.0f - leg_bend);
			if (leg_state) {
				leg_bend--;
				if (leg_bend <= 0.0f) leg_state = 0;
			} else {
				leg_bend++;
				if (leg_bend >= 60.0f) leg_state = 1;
			}
		}

		glm::vec4 current_pos = subject->getWorldCoordinates();
		current_pos.z += move_forward * timestep;
		glm::vec3 new_pos(current_pos.x, terrain->getHeight(current_pos.x, current_pos.z) + subject->getDistanceToGround(), current_pos.z);
		subject->setPosition(new_pos.x, new_pos.y, new_pos.z);

	}
};

void reshape(int width, int height)
{
	glViewport(0, 0, (GLint) width, (GLint) height);
	rc->reshape(width, height);
}

/// Sets up rendering and creates the initial scene graph.
void init_scene()
{
	static GLfloat pos[4] =
	{3000.0, 1000.0, -3000.0, 0.0};
	glLightfv(GL_LIGHT0, GL_POSITION, pos);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_TEXTURE_2D);
	//glEnable(GL_MULTISAMPLE);

	scene = new GraphNode;
	scene->addMember(new Skybox);

	Mech *mech = new Mech();
	scene->addMember(mech);
	//mech->setVisibility(false);

	Terrain *terrain = new Terrain("textures/heightmap.bmp", 20.0f);
	scene->addMember(terrain);

	rc = new RenderingContext(scene);
	rc->setCamera(glm::vec3(0.0f, 1.0f, -3.0f), mech);

	scene_rot = new TestSceneRotation(mech);
	animations.push_back(scene_rot);
	animations.push_back(new MechWalk(mech, terrain));
}

/// Sets up a new frame and renders the scene.
void draw_scene()
{
	rc->update();
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
		puts((const char*)gluErrorString(error));

	glFlush();
	SDL_GL_SwapWindow(win);
}

/// Updates scene state
void update_scene(float timestep)
{
	std::for_each(
			animations.begin(),
			animations.end(),
			std::bind2nd(std::mem_fun(&Animation::update), timestep));
}

int main(int argc, char const *argv[])
{
	//SDL_Surface *screen;
	Uint8 *keys;
	int w = 800, h = 600;

	//CommonState *state;

	printf("Hello!\n");

	if (0 != SDL_Init(SDL_INIT_EVERYTHING)) return 1;

	// Set up an OpenGL window
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	//screen = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL|SDL_RESIZABLE);
	win = SDL_CreateWindow("Mech",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        w, h,
        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

	if ( ! win ) {
		puts(SDL_GetError());
		SDL_Quit();
		exit(2);
	}
	//SDL_WM_SetCaption("Mech", "mech");

	context = SDL_GL_CreateContext(win);

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
	  printf("glewInit error: %s\n", glewGetErrorString(err));
	}
	printf("Using GLEW %s\n", glewGetString(GLEW_VERSION));

	printf("OpenGL version: %s\n", glGetString(GL_VERSION));
	init_scene();
	//reshape(screen->w, screen->h);
	reshape(w, h);

	Uint32 previous_ticks = SDL_GetTicks();
	Uint32 fps_prev_t = previous_ticks, frames = 0;

	int done = 0;
	SDL_Event event;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			switch(event.type) {
				/*case SDL_VIDEORESIZE:
					screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 16,
							SDL_OPENGL|SDL_RESIZABLE);
					if (screen)
						reshape(screen->w, screen->h);
					break;
					*/
				case SDL_MOUSEMOTION:
					scene_rot->y = 4.0f * (float)(event.motion.y) / (float)(h) - 2.0f;
					scene_rot->rotation = -360.0f * (float)(event.motion.x) / (float)(w);
					break;

				case SDL_QUIT:
					done = 1;
					break;
			}
		}
		/*keys = SDL_GetKeyState(NULL);

		if (keys[SDLK_ESCAPE]) {
			done = 1;
		}

		if (keys[SDLK_w])
			move_forward = 1;
		else if (keys[SDLK_s])
			move_forward = -1;
		else
			move_forward = 0;*/

		// update
		Uint32 t = SDL_GetTicks();
		update_scene((float)(t - previous_ticks) / 1000.0f);
		previous_ticks = t;

		// count FPS
		frames++;
		if (fps_prev_t + 5000 < t) {
			printf("FPS: %f\n", (float)frames / ((float)(t - fps_prev_t) / 1000.0f));
			fps_prev_t = t;
			frames = 0;
		}

		// render
		draw_scene();
	}
	SDL_Quit();
	delete scene;
	return 0;
}
<commit_msg>Restore keyboard functionality.<commit_after>#include <GL/glew.h>
#define GLM_SWIZZLE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "SDL.h"
#undef main
#include <list>
#include <algorithm>
#include <functional>

#include "RenderingContext.h"
#include "scene/GraphNode.h"
#include "scene/Skybox.h"
#include "scene/Terrain.h"
#include "scene/Mech.h"
#include "animations/Animation.h"

static SDL_Window *win;
static SDL_GLContext context;

GraphNode *scene = NULL;
RenderingContext *rc;
std::list<Animation*> animations;
int move_forward = 0;

class TestSceneRotation : public Animation
{
private:
	GraphNode* subject;

public:
	TestSceneRotation(GraphNode* subject) : subject(subject)
	{
		rotation = 0;
		y = 0;
	};

	virtual void update(float timestep)
	{
		glm::vec4 cam_pos =
			subject->getWorldCoordinates(
				glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)) *
				glm::vec4(0.0f, y, 3.0f, 1.0f));
		rc->setCamera(cam_pos.xyz(), subject);
		while (rotation > 360.0f) rotation -= 360.0f;
	};

	float y;
	float rotation;
} *scene_rot;

class MechWalk : public Animation
{
private:
	Mech* subject;
	Terrain* terrain;
	float leg_bend;
	int leg_state;

public:
	MechWalk(Mech* subject, Terrain* terrain) : subject(subject), terrain(terrain)
	{
		leg_state = 0;
		leg_bend = 90.0f;
	};

	virtual void update(float timestep)
	{
		if (move_forward) {
			subject->bendLeg(0, 35.0f + leg_bend);
			subject->bendLeg(1, 95.0f - leg_bend);
			subject->bendLeg(2, 35.0f + leg_bend);
			subject->bendLeg(3, 95.0f - leg_bend);
			if (leg_state) {
				leg_bend--;
				if (leg_bend <= 0.0f) leg_state = 0;
			} else {
				leg_bend++;
				if (leg_bend >= 60.0f) leg_state = 1;
			}
		}

		glm::vec4 current_pos = subject->getWorldCoordinates();
		current_pos.z += move_forward * timestep;
		glm::vec3 new_pos(current_pos.x, terrain->getHeight(current_pos.x, current_pos.z) + subject->getDistanceToGround(), current_pos.z);
		subject->setPosition(new_pos.x, new_pos.y, new_pos.z);

	}
};

void reshape(int width, int height)
{
	glViewport(0, 0, (GLint) width, (GLint) height);
	rc->reshape(width, height);
}

/// Sets up rendering and creates the initial scene graph.
void init_scene()
{
	static GLfloat pos[4] =
	{3000.0, 1000.0, -3000.0, 0.0};
	glLightfv(GL_LIGHT0, GL_POSITION, pos);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_TEXTURE_2D);
	//glEnable(GL_MULTISAMPLE);

	scene = new GraphNode;
	scene->addMember(new Skybox);

	Mech *mech = new Mech();
	scene->addMember(mech);
	//mech->setVisibility(false);

	Terrain *terrain = new Terrain("textures/heightmap.bmp", 20.0f);
	scene->addMember(terrain);

	rc = new RenderingContext(scene);
	rc->setCamera(glm::vec3(0.0f, 1.0f, -3.0f), mech);

	scene_rot = new TestSceneRotation(mech);
	animations.push_back(scene_rot);
	animations.push_back(new MechWalk(mech, terrain));
}

/// Sets up a new frame and renders the scene.
void draw_scene()
{
	rc->update();
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
		puts((const char*)gluErrorString(error));

	glFlush();
	SDL_GL_SwapWindow(win);
}

/// Updates scene state
void update_scene(float timestep)
{
	std::for_each(
			animations.begin(),
			animations.end(),
			std::bind2nd(std::mem_fun(&Animation::update), timestep));
}

int main(int argc, char const *argv[])
{
	//SDL_Surface *screen;
	Uint8 *keys;
	int w = 800, h = 600;

	//CommonState *state;

	printf("Hello!\n");

	if (0 != SDL_Init(SDL_INIT_EVERYTHING)) return 1;

	// Set up an OpenGL window
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	//screen = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL|SDL_RESIZABLE);
	win = SDL_CreateWindow("Mech",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        w, h,
        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

	if ( ! win ) {
		puts(SDL_GetError());
		SDL_Quit();
		exit(2);
	}
	//SDL_WM_SetCaption("Mech", "mech");

	context = SDL_GL_CreateContext(win);

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
	  printf("glewInit error: %s\n", glewGetErrorString(err));
	}
	printf("Using GLEW %s\n", glewGetString(GLEW_VERSION));

	printf("OpenGL version: %s\n", glGetString(GL_VERSION));
	init_scene();
	//reshape(screen->w, screen->h);
	reshape(w, h);

	Uint32 previous_ticks = SDL_GetTicks();
	Uint32 fps_prev_t = previous_ticks, frames = 0;

	int done = 0;
	SDL_Event event;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			switch(event.type) {
				/*case SDL_VIDEORESIZE:
					screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 16,
							SDL_OPENGL|SDL_RESIZABLE);
					if (screen)
						reshape(screen->w, screen->h);
					break;
					*/
				case SDL_MOUSEMOTION:
					scene_rot->y = 4.0f * (float)(event.motion.y) / (float)(h) - 2.0f;
					scene_rot->rotation = -360.0f * (float)(event.motion.x) / (float)(w);
					break;

				case SDL_QUIT:
					done = 1;
					break;
			}
		}
		keys = SDL_GetKeyboardState(NULL);

		if (keys[SDL_SCANCODE_ESCAPE]) {
			done = 1;
		}

		if (keys[SDL_SCANCODE_W])
			move_forward = 1;
		else if (keys[SDLK_s])
			move_forward = -1;
		else
			move_forward = 0;

		// update
		Uint32 t = SDL_GetTicks();
		update_scene((float)(t - previous_ticks) / 1000.0f);
		previous_ticks = t;

		// count FPS
		frames++;
		if (fps_prev_t + 5000 < t) {
			printf("FPS: %f\n", (float)frames / ((float)(t - fps_prev_t) / 1000.0f));
			fps_prev_t = t;
			frames = 0;
		}

		// render
		draw_scene();
	}
	SDL_Quit();
	delete scene;
	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Fixed scoring<commit_after><|endoftext|>


<commit_before>//
// Created by alex on 09/07/2015.
//

#include "lbitwise.h"

static void b_arshift(void) {

}

/* bit and
 *
 * a & b
 *
 * */
static void b_and(void) {
    int a = luaL_check_int(1);
    int b = luaL_check_int(2);
    lua_pushnumber(a & b);
}

static void b_not(void) {

}

static void b_or(void) {

}

static void b_xor(void) {

}

static void b_lrot(void) {

}

static void b_lshift(void) {

}

static void b_rrot(void) {

}

static void b_rshift(void) {

}

static struct luaL_reg bitlib[] = {
    {(char *) "arshift", b_arshift},
    {(char *) "band",    b_and},
    {(char *) "bnot",    b_not},
    {(char *) "bor",     b_or},
    {(char *) "bxor",    b_xor},
    {(char *) "lrotate", b_lrot},
    {(char *) "lshift",  b_lshift},
    {(char *) "rrotate", b_rrot},
    {(char *) "rshift",  b_rshift}
};

void DLL_EXPORT lua_bitwiseopen(lua_State *L) {
    lua_state = L;
    luaL_openlib(bitlib, (sizeof(bitlib) / sizeof(bitlib[0])));
}
<commit_msg>bit not implementation.<commit_after>//
// Created by alex on 09/07/2015.
//

#include "lbitwise.h"

static void b_arshift(void) {

}

/* bit and
 *
 * a & b
 *
 * */
static void b_and(void) {
    int a = luaL_check_int(1);
    int b = luaL_check_int(2);
    lua_pushnumber(a & b);
}

/* bit not
 *
 * ~a
 *
 * */
static void b_not(void) {
    int a = luaL_check_int(1);
    lua_pushnumber(~a);
}

static void b_or(void) {

}

static void b_xor(void) {

}

static void b_lrot(void) {

}

static void b_lshift(void) {

}

static void b_rrot(void) {

}

static void b_rshift(void) {

}

static struct luaL_reg bitlib[] = {
    {(char *) "arshift", b_arshift},
    {(char *) "band",    b_and},
    {(char *) "bnot",    b_not},
    {(char *) "bor",     b_or},
    {(char *) "bxor",    b_xor},
    {(char *) "lrotate", b_lrot},
    {(char *) "lshift",  b_lshift},
    {(char *) "rrotate", b_rrot},
    {(char *) "rshift",  b_rshift}
};

void DLL_EXPORT lua_bitwiseopen(lua_State *L) {
    lua_state = L;
    luaL_openlib(bitlib, (sizeof(bitlib) / sizeof(bitlib[0])));
}
<|endoftext|>


<commit_before>#include "SDL/SDL.h"
#include "CSurface.h"
#include "map.h"
#include "random.h"

Map::Map() {
  max_width = MAP_MAX_WIDTH;
  max_height = MAP_MAX_HEIGHT;

  for (int i = 0; i < MAP_MAX_SIZE; i++) {
    cells[i].tile = (flipCoin() ? 0 : 64);
  }
}

void Map::setBoundaries(int max_width, int max_height) {
  this->max_width = max_width;
  this->max_height = max_height;
}

//=============================================================================
//
MapCamera::MapCamera(int x, int y, SDL_Surface* screen, Map* map) {
  this->x = x; // pixel size, relative to map (starts at 0,0)
  this->y = y;
  this->max_cells_width_on_screen = screen->w / 32;
  this->max_cells_height_on_screen = screen->h / 32;
  this->map_y_boundary = map->getMaxHeight();
  this->map_x_boundary = map->getMaxWidth();
}

void MapCamera::draw(Map* map, SDL_Surface* tileset, SDL_Surface* screen) {
  // determine x and y from map data.
  int startX = (this->x / 32);
  int startY = (this->y / 32);

  int offsetX = (this->x % 32);
  int offsetY = (this->y % 32);

  int endX = startX + (getWidth() + 1);
  int endY = startY + (getHeight() + 1);

  for (int dx = startX; dx < endX; dx++) {
    for (int dy = startY; dy < endY; dy++) {
      Cell c = map->getCell(dx, dy);

      int mouse_x, mouse_y;
      SDL_GetMouseState(&mouse_x, &mouse_y);

      // weird: have to compensate for the coordinates above. Drawing should be done separately
      // from coordinates of map.
      int drawX = (dx - startX) * 32;
      int drawY = (dy - startY) * 32;

      drawX -= offsetX;
      drawY -= offsetY;

      CSurface::drawTile(tileset, screen, c.tile, drawX, drawY);

      if ((mouse_x >= drawX && mouse_x <= (drawX + 32)) && (mouse_y >= drawY && mouse_y <= (drawY + 32))) {
	      SDL_Rect rect;
	      rect.w = 32;
	      rect.h = 32;
	      rect.x = drawX;
	      rect.y = drawY;
	      SDL_FillRect(screen, &rect, SDL_MapRGB(screen->format , 0 , 0 , 20 ) );
      }
    }
  }
}

<commit_msg>ceil width/height amount of cells for camera<commit_after>#include "SDL/SDL.h"
#include "CSurface.h"
#include "map.h"
#include "random.h"
#include <math.h>       /* ceil */

Map::Map() {
  max_width = MAP_MAX_WIDTH;
  max_height = MAP_MAX_HEIGHT;

  for (int i = 0; i < MAP_MAX_SIZE; i++) {
    cells[i].tile = (flipCoin() ? 0 : 64);
  }
}

void Map::setBoundaries(int max_width, int max_height) {
  this->max_width = max_width;
  this->max_height = max_height;
}

//=============================================================================
//
MapCamera::MapCamera(int x, int y, SDL_Surface* screen, Map* map) {
  this->x = x; // pixel size, relative to map (starts at 0,0)
  this->y = y;
  this->max_cells_width_on_screen = ceil(screen->w / 32);
  this->max_cells_height_on_screen = ceil(screen->h / 32);
  this->map_y_boundary = map->getMaxHeight();
  this->map_x_boundary = map->getMaxWidth();
}

void MapCamera::draw(Map* map, SDL_Surface* tileset, SDL_Surface* screen) {
  // determine x and y from map data.
  int startX = (this->x / 32);
  int startY = (this->y / 32);

  int offsetX = (this->x % 32);
  int offsetY = (this->y % 32);

  int endX = startX + (getWidth() + 1);
  int endY = startY + (getHeight() + 1);

  for (int dx = startX; dx < endX; dx++) {
    for (int dy = startY; dy < endY; dy++) {
      Cell c = map->getCell(dx, dy);

      int mouse_x, mouse_y;
      SDL_GetMouseState(&mouse_x, &mouse_y);

      // weird: have to compensate for the coordinates above. Drawing should be done separately
      // from coordinates of map.
      int drawX = (dx - startX) * 32;
      int drawY = (dy - startY) * 32;

      drawX -= offsetX;
      drawY -= offsetY;

      CSurface::drawTile(tileset, screen, c.tile, drawX, drawY);

      if ((mouse_x >= drawX && mouse_x <= (drawX + 32)) && (mouse_y >= drawY && mouse_y <= (drawY + 32))) {
	      SDL_Rect rect;
	      rect.w = 32;
	      rect.h = 32;
	      rect.x = drawX;
	      rect.y = drawY;
	      SDL_FillRect(screen, &rect, SDL_MapRGB(screen->format , 0 , 0 , 20 ) );
      }
    }
  }
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <random>

#include "gtest/gtest.h"
#include "perfetto/trace/test_event.pbzero.h"
#include "perfetto/trace/trace_packet.pb.h"
#include "perfetto/trace/trace_packet.pbzero.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "src/base/test/test_task_runner.h"
#include "test/test_helper.h"

#include "perfetto/trace/trace_packet.pb.h"

namespace perfetto {

class PerfettoCtsTest : public ::testing::Test {
 protected:
  void TestMockProducer(const std::string& producer_name) {
    base::TestTaskRunner task_runner;

    TestHelper helper(&task_runner);
    helper.ConnectConsumer();
    helper.WaitForConsumerConnect();

    TraceConfig trace_config;
    trace_config.add_buffers()->set_size_kb(1024);
    trace_config.set_duration_ms(200);

    auto* ds_config = trace_config.add_data_sources()->mutable_config();
    ds_config->set_name(producer_name);
    ds_config->set_target_buffer(0);

    static constexpr uint32_t kRandomSeed = 42;
    static constexpr uint32_t kEventCount = 10;
    static constexpr uint32_t kMessageSizeBytes = 1024;
    ds_config->mutable_for_testing()->set_seed(kRandomSeed);
    ds_config->mutable_for_testing()->set_message_count(kEventCount);
    ds_config->mutable_for_testing()->set_message_size(kMessageSizeBytes);
    ds_config->mutable_for_testing()->set_send_batch_on_register(true);

    helper.StartTracing(trace_config);
    helper.WaitForTracingDisabled();

    helper.ReadData();
    helper.WaitForReadData();

    const auto& packets = helper.trace();
    ASSERT_EQ(packets.size(), kEventCount);

    std::minstd_rand0 rnd_engine(kRandomSeed);
    for (const auto& packet : packets) {
      ASSERT_TRUE(packet.has_for_testing());
      ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
    }
  }
};

TEST_F(PerfettoCtsTest, TestProducerActivity) {
  TestMockProducer("android.perfetto.cts.ProducerActivity");
}

TEST_F(PerfettoCtsTest, TestProducerService) {
  TestMockProducer("android.perfetto.cts.ProducerService");
}

TEST_F(PerfettoCtsTest, TestProducerIsolatedService) {
  TestMockProducer("android.perfetto.cts.ProducerIsolatedService");
}

}  // namespace perfetto
<commit_msg>Snap for 4739962 from b17f08162a554e3c1c48887cf0997e68ff458a00 to pi-release<commit_after>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <random>
#include <sys/system_properties.h>

#include "gtest/gtest.h"
#include "perfetto/trace/test_event.pbzero.h"
#include "perfetto/trace/trace_packet.pb.h"
#include "perfetto/trace/trace_packet.pbzero.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "src/base/test/test_task_runner.h"
#include "test/test_helper.h"

#include "perfetto/trace/trace_packet.pb.h"

namespace perfetto {

class PerfettoCtsTest : public ::testing::Test {
 protected:
  void TestMockProducer(const std::string& producer_name) {
    // Filter out watches; they do not have the required infrastructure to run
    // these tests.
    char chars[PROP_VALUE_MAX + 1];
    int ret = __system_property_get("ro.build.characteristics", chars);
    ASSERT_GE(ret, 0);
    std::string characteristics(chars);
    if (characteristics.find("watch") != std::string::npos) {
      return;
    }

    base::TestTaskRunner task_runner;

    TestHelper helper(&task_runner);
    helper.ConnectConsumer();
    helper.WaitForConsumerConnect();

    TraceConfig trace_config;
    trace_config.add_buffers()->set_size_kb(1024);
    trace_config.set_duration_ms(200);

    auto* ds_config = trace_config.add_data_sources()->mutable_config();
    ds_config->set_name(producer_name);
    ds_config->set_target_buffer(0);

    static constexpr uint32_t kRandomSeed = 42;
    static constexpr uint32_t kEventCount = 10;
    static constexpr uint32_t kMessageSizeBytes = 1024;
    ds_config->mutable_for_testing()->set_seed(kRandomSeed);
    ds_config->mutable_for_testing()->set_message_count(kEventCount);
    ds_config->mutable_for_testing()->set_message_size(kMessageSizeBytes);
    ds_config->mutable_for_testing()->set_send_batch_on_register(true);

    helper.StartTracing(trace_config);
    helper.WaitForTracingDisabled();

    helper.ReadData();
    helper.WaitForReadData();

    const auto& packets = helper.trace();
    ASSERT_EQ(packets.size(), kEventCount);

    std::minstd_rand0 rnd_engine(kRandomSeed);
    for (const auto& packet : packets) {
      ASSERT_TRUE(packet.has_for_testing());
      ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
    }
  }
};

TEST_F(PerfettoCtsTest, TestProducerActivity) {
  TestMockProducer("android.perfetto.cts.ProducerActivity");
}

TEST_F(PerfettoCtsTest, TestProducerService) {
  TestMockProducer("android.perfetto.cts.ProducerService");
}

TEST_F(PerfettoCtsTest, TestProducerIsolatedService) {
  TestMockProducer("android.perfetto.cts.ProducerIsolatedService");
}

}  // namespace perfetto
<|endoftext|>


<commit_before>#include <iostream>

#define SEQAN_DEBUG
#define SEQAN_TEST

#define TEST_PATH "/projects/tests/find_motif/"

#include <seqan/find_motif.h>
#include <seqan/align.h>

using namespace seqan;

//////////////////////////////////////////////////////////////////////////////

void Test_approximationAlgorithms()
{
	unsigned int t = 0;		//number of input sequences
	unsigned int n = 0;		//length of sequence
	unsigned int l = 0;		//length of motif
	unsigned int d = 0;		//number of substitutions
	bool is_exact = false;	//size of Hamming distance
	unsigned int m =0;		//total number of possible l-mers
	unsigned int h = 0;		//size of the neighborhood considering at first
	unsigned int i = 0;

	srand((unsigned) time(NULL));

//____________________________________________________________________________
// Test1 - Search for OOPS motifs on a small set of nucleotide sequences
//         given the exact Hamming distance (=d)
	t = 3;
	n = 6;
	l = 4;
	d = 1;
	is_exact = true;
	m = t*(n-l+1);

	String<DnaString> dataset1;
	appendValue(dataset1,DnaString("ACAGCA"));
	appendValue(dataset1,DnaString("AGGCAG"));
	appendValue(dataset1,DnaString("TCAGTC"));

	//Application of PROJECTION-OOPS
    MotifFinder<Dna, Projection> motif_finder1(t,l,m,d,is_exact);
	findMotif(motif_finder1, dataset1, OOPS());
	SEQAN_TASSERT(motif_finder1.consensus_pattern=="AGCC");

	//Application of ePatternBranching-OOPS
    MotifFinder<Dna, EPatternBranching> motif_finder2(t,l,d,is_exact,h);
	findMotif(motif_finder2, dataset1, OOPS());
	SEQAN_TASSERT(motif_finder2.set_of_motifs[0]=="AGCC");

//____________________________________________________________________________
// Test2 - Search for OMOPS motifs on a small set of nucleotide sequences
//         given the exact Hamming distance (<=d)

	is_exact = false;

	//Application of PROJECTION-OMOPS
    MotifFinder<Dna, Projection> motif_finder3(t,l,m,d,is_exact);
	findMotif(motif_finder3, dataset1, OMOPS());
	displayResult(motif_finder3);
	//SEQAN_TASSERT(motif_finder3.consensus_pattern=="AGCC");

	//Application of ePatternBranching-OMOPS
	MotifFinder<Dna, EPatternBranching> motif_finder4(t,l,d,is_exact,h);
	findMotif(motif_finder4, dataset1, OMOPS());
	displayResult(motif_finder4);
	//SEQAN_TASSERT(motif_finder4.set_of_motifs[0]=="AGCC");

//____________________________________________________________________________
// Test3 - Search for ZOOPS motifs on a set of small nucleotide sequences
//         given the inexact Hamming distance (<=d)

	//Application of PROJECTION-ZOOPS
    MotifFinder<Dna, Projection> motif_finder5(t,l,m,d,is_exact);
	findMotif(motif_finder5, dataset1, ZOOPS());
	SEQAN_TASSERT(motif_finder5.consensus_pattern=="TCAG");

//____________________________________________________________________________
// Test4 - Search for TCM motifs on a set of small nucleotide sequences
//         given the exact Hamming distance (=d)

	is_exact = true;

	//Application of PROJECTION-TCM
    MotifFinder<Dna, Projection> motif_finder6(t,l,m,d,is_exact);
	findMotif(motif_finder6, dataset1, ZOOPS());
	SEQAN_TASSERT(motif_finder6.consensus_pattern=="TCAG");
}

void Test_exactAlgorithms()
{
	unsigned int l = 0;		//length of motif
	unsigned int d = 0;		//number of substitutions
	bool is_exact = false;	//size of Hamming distance
	unsigned int i = 0;

//____________________________________________________________________________
// Test1 - Search for OOPS motifs on a small set of nucleotide sequences
//         given the exact Hamming distance (=d)

	l = 8;
	d = 2;
	is_exact = true;

	String<DnaString> dataset1;
	appendValue(dataset1,DnaString("CAGAAGGCTCTAAACAGGTA"));
	appendValue(dataset1,DnaString("CCACAAATCTTTCTCCGGCG"));
	appendValue(dataset1,DnaString("TCGACTGAAATGGAGAACAG"));
	appendValue(dataset1,DnaString("GCTTACGTACTGAACGTGCG"));
	appendValue(dataset1,DnaString("TAACTTACACTCAACAGGTG"));

	//Application of PMS1-OOPS
	MotifFinder<Dna, PMS1> motif_finder1(l,d,is_exact);
	findMotif(motif_finder1,dataset1,OOPS());

	//Application of PMSP-OOPS
	MotifFinder<Dna, PMSP> motif_finder2(l,d,is_exact);
	findMotif(motif_finder2,dataset1,OOPS());

	SEQAN_TASSERT(length(motif_finder1.set_of_motifs)==length(motif_finder2.set_of_motifs));

	for(i=0; i<length(motif_finder1.set_of_motifs); ++i)
	{
		SEQAN_TASSERT(motif_finder1.set_of_motifs[i]==motif_finder2.set_of_motifs[i]);
	}

//____________________________________________________________________________
// Test2 - Search for OMOPS motifs on a small set of nucleotide sequences
//         given the inexact Hamming distance (<=d)

	l = 6;
	d = 2;
	is_exact = false;

	String<DnaString> dataset2;
	appendValue(dataset2,DnaString("TTTAGGCCACTCGATAAGAG"));
	appendValue(dataset2,DnaString("GAGCTACAACCGAGGAATTG"));
	appendValue(dataset2,DnaString("CGAATGTTGTGACTCGATAA"));
	appendValue(dataset2,DnaString("GTCCGAAAATACCTGGAGCC"));
	appendValue(dataset2,DnaString("CCGCTTAAAAATGTATTATC"));

	//Application of PMS1-OMOPS
	MotifFinder<Dna, PMS1> motif_finder3(l,d,is_exact);
	findMotif(motif_finder3,dataset2,OMOPS());

	//Application of PMSP-OMOPS
	MotifFinder<Dna, PMSP> motif_finder4(l,d,is_exact);
	findMotif(motif_finder4,dataset2,OMOPS());

	SEQAN_TASSERT(length(motif_finder3.set_of_motifs)==length(motif_finder4.set_of_motifs));

	for(i=0; i<length(motif_finder3.set_of_motifs); ++i)
	{
		SEQAN_TASSERT(motif_finder3.set_of_motifs[i]==motif_finder4.set_of_motifs[i]);
	}

//____________________________________________________________________________
// Test3 - Search for ZOOPS motifs on a small set of nucleotide sequences
//         given the exact Hamming distance (=d)

	l = 6;
	d = 1;
	is_exact = true;

	String<DnaString> dataset3;
	appendValue(dataset3,DnaString("CTATTACCCAGAGTGCCAAG"));
	appendValue(dataset3,DnaString("AACGGACCCAACGGCAAAGA"));
	appendValue(dataset3,DnaString("TCTTGTCTTCACAGTCAGAT"));

	//Application of PMS1-ZOOPS
	MotifFinder<Dna, PMS1> motif_finder5(l,d,is_exact);
	findMotif(motif_finder5,dataset3,ZOOPS());

	//Application of PMSP-ZOOPS
	MotifFinder<Dna, PMSP> motif_finder6(l,d,is_exact);
	findMotif(motif_finder6,dataset3,ZOOPS());

	SEQAN_TASSERT(length(motif_finder5.set_of_motifs)==length(motif_finder6.set_of_motifs));

	for(i=0; i<length(motif_finder5.set_of_motifs); ++i)
	{
		SEQAN_TASSERT(motif_finder5.set_of_motifs[i]==motif_finder6.set_of_motifs[i]);
	}
}

int main()
{
	SEQAN_TREPORT("TEST FIND MOTIF BEGIN")

	Test_approximationAlgorithms();
	Test_exactAlgorithms();

	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_base.h");
	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_projection.h");
	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_epatternbranching.h");
	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_pms1.h");
	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_pmsp.h");

	SEQAN_TREPORT("TEST FIND MOTIF END");

	return 0;
}<commit_msg><commit_after>#include <iostream>

#define SEQAN_DEBUG
#define SEQAN_TEST

#include <seqan/find_motif.h>

using namespace seqan;

//////////////////////////////////////////////////////////////////////////////

void Test_approximationAlgorithms()
{
	unsigned int t = 0;		//number of input sequences
	unsigned int n = 0;		//length of sequence
	unsigned int l = 0;		//length of motif
	unsigned int d = 0;		//number of substitutions
	bool is_exact = false;	//size of Hamming distance
	unsigned int m =0;		//total number of possible l-mers
	unsigned int h = 0;		//size of the neighborhood considering at first
	unsigned int i = 0;

	srand((unsigned) time(NULL));

//____________________________________________________________________________
// Test1 - Search for OOPS motifs on a small set of nucleotide sequences
//         given the exact Hamming distance (=d)
	t = 3;
	n = 6;
	l = 4;
	d = 1;
	is_exact = true;
	m = t*(n-l+1);

	String<DnaString> dataset1;
	appendValue(dataset1,DnaString("ACAGCA"));
	appendValue(dataset1,DnaString("AGGCAG"));
	appendValue(dataset1,DnaString("TCAGTC"));

	//Application of PROJECTION-OOPS
    MotifFinder<Dna, Projection> motif_finder1(t,l,m,d,is_exact);
	findMotif(motif_finder1, dataset1, OOPS());
	SEQAN_TASSERT(motif_finder1.consensus_pattern=="AGCC");

	//Application of ePatternBranching-OOPS
    MotifFinder<Dna, EPatternBranching> motif_finder2(t,l,d,is_exact,h);
	findMotif(motif_finder2, dataset1, OOPS());
	SEQAN_TASSERT(motif_finder2.set_of_motifs[0]=="AGCC");

//____________________________________________________________________________
// Test2 - Search for OMOPS motifs on a small set of nucleotide sequences
//         given the exact Hamming distance (<=d)

	is_exact = false;

	//Application of PROJECTION-OMOPS
    MotifFinder<Dna, Projection> motif_finder3(t,l,m,d,is_exact);
	findMotif(motif_finder3, dataset1, OMOPS());
	displayResult(motif_finder3);
	//SEQAN_TASSERT(motif_finder3.consensus_pattern=="AGCC");

	//Application of ePatternBranching-OMOPS
	MotifFinder<Dna, EPatternBranching> motif_finder4(t,l,d,is_exact,h);
	findMotif(motif_finder4, dataset1, OMOPS());
	displayResult(motif_finder4);
	//SEQAN_TASSERT(motif_finder4.set_of_motifs[0]=="AGCC");

//____________________________________________________________________________
// Test3 - Search for ZOOPS motifs on a set of small nucleotide sequences
//         given the inexact Hamming distance (<=d)

	//Application of PROJECTION-ZOOPS
    MotifFinder<Dna, Projection> motif_finder5(t,l,m,d,is_exact);
	findMotif(motif_finder5, dataset1, ZOOPS());
	SEQAN_TASSERT(motif_finder5.consensus_pattern=="TCAG");

//____________________________________________________________________________
// Test4 - Search for TCM motifs on a set of small nucleotide sequences
//         given the exact Hamming distance (=d)

	is_exact = true;

	//Application of PROJECTION-TCM
    MotifFinder<Dna, Projection> motif_finder6(t,l,m,d,is_exact);
	findMotif(motif_finder6, dataset1, ZOOPS());
	SEQAN_TASSERT(motif_finder6.consensus_pattern=="TCAG");
}

void Test_exactAlgorithms()
{
	unsigned int l = 0;		//length of motif
	unsigned int d = 0;		//number of substitutions
	bool is_exact = false;	//size of Hamming distance
	unsigned int i = 0;

//____________________________________________________________________________
// Test1 - Search for OOPS motifs on a small set of nucleotide sequences
//         given the exact Hamming distance (=d)

	l = 8;
	d = 2;
	is_exact = true;

	String<DnaString> dataset1;
	appendValue(dataset1,DnaString("CAGAAGGCTCTAAACAGGTA"));
	appendValue(dataset1,DnaString("CCACAAATCTTTCTCCGGCG"));
	appendValue(dataset1,DnaString("TCGACTGAAATGGAGAACAG"));
	appendValue(dataset1,DnaString("GCTTACGTACTGAACGTGCG"));
	appendValue(dataset1,DnaString("TAACTTACACTCAACAGGTG"));

	//Application of PMS1-OOPS
	MotifFinder<Dna, PMS1> motif_finder1(l,d,is_exact);
	findMotif(motif_finder1,dataset1,OOPS());

	//Application of PMSP-OOPS
	MotifFinder<Dna, PMSP> motif_finder2(l,d,is_exact);
	findMotif(motif_finder2,dataset1,OOPS());

	SEQAN_TASSERT(length(motif_finder1.set_of_motifs)==length(motif_finder2.set_of_motifs));

	for(i=0; i<length(motif_finder1.set_of_motifs); ++i)
	{
		SEQAN_TASSERT(motif_finder1.set_of_motifs[i]==motif_finder2.set_of_motifs[i]);
	}

//____________________________________________________________________________
// Test2 - Search for OMOPS motifs on a small set of nucleotide sequences
//         given the inexact Hamming distance (<=d)

	l = 6;
	d = 2;
	is_exact = false;

	String<DnaString> dataset2;
	appendValue(dataset2,DnaString("TTTAGGCCACTCGATAAGAG"));
	appendValue(dataset2,DnaString("GAGCTACAACCGAGGAATTG"));
	appendValue(dataset2,DnaString("CGAATGTTGTGACTCGATAA"));
	appendValue(dataset2,DnaString("GTCCGAAAATACCTGGAGCC"));
	appendValue(dataset2,DnaString("CCGCTTAAAAATGTATTATC"));

	//Application of PMS1-OMOPS
	MotifFinder<Dna, PMS1> motif_finder3(l,d,is_exact);
	findMotif(motif_finder3,dataset2,OMOPS());

	//Application of PMSP-OMOPS
	MotifFinder<Dna, PMSP> motif_finder4(l,d,is_exact);
	findMotif(motif_finder4,dataset2,OMOPS());

	SEQAN_TASSERT(length(motif_finder3.set_of_motifs)==length(motif_finder4.set_of_motifs));

	for(i=0; i<length(motif_finder3.set_of_motifs); ++i)
	{
		SEQAN_TASSERT(motif_finder3.set_of_motifs[i]==motif_finder4.set_of_motifs[i]);
	}

//____________________________________________________________________________
// Test3 - Search for ZOOPS motifs on a small set of nucleotide sequences
//         given the exact Hamming distance (=d)

	l = 6;
	d = 1;
	is_exact = true;

	String<DnaString> dataset3;
	appendValue(dataset3,DnaString("CTATTACCCAGAGTGCCAAG"));
	appendValue(dataset3,DnaString("AACGGACCCAACGGCAAAGA"));
	appendValue(dataset3,DnaString("TCTTGTCTTCACAGTCAGAT"));

	//Application of PMS1-ZOOPS
	MotifFinder<Dna, PMS1> motif_finder5(l,d,is_exact);
	findMotif(motif_finder5,dataset3,ZOOPS());

	//Application of PMSP-ZOOPS
	MotifFinder<Dna, PMSP> motif_finder6(l,d,is_exact);
	findMotif(motif_finder6,dataset3,ZOOPS());

	SEQAN_TASSERT(length(motif_finder5.set_of_motifs)==length(motif_finder6.set_of_motifs));

	for(i=0; i<length(motif_finder5.set_of_motifs); ++i)
	{
		SEQAN_TASSERT(motif_finder5.set_of_motifs[i]==motif_finder6.set_of_motifs[i]);
	}
}

int main()
{
	SEQAN_TREPORT("TEST FIND MOTIF BEGIN")

	Test_approximationAlgorithms();
	Test_exactAlgorithms();

	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_base.h");
	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_projection.h");
	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_epatternbranching.h");
	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_pms1.h");
	debug::verifyCheckpoints("projects/library/seqan/find_motif/find_motif_pmsp.h");

	SEQAN_TREPORT("TEST FIND MOTIF END");

	return 0;
}<|endoftext|>


<commit_before>
#include <gmock/gmock.h>

#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>

#include <glbinding/Binding.h>
#include <glbinding/Meta.h>

#include <glbinding/gl/functions.h>  // < imagine this was included by a 3rd party library (e.g., globjects.cpp)

#include <glbinding/gl/types.h>
#include <glbinding/gl/functions.h>
#include <glbinding/gl/enum.h>

class Regression_185 : public testing::Test
{
public:
};

TEST(Regression_185, GLbooleanReturnValueCall)  // GL calls fail if function returns GLboolean
{
    if (!glfwInit())
    {
        SUCCEED();
        return;
    }

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, false);

#ifdef SYSTEM_DARWIN
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif

    GLFWwindow * window = glfwCreateWindow(320, 240, "", nullptr, nullptr);
    if (window == nullptr)
    {
        SUCCEED();
        return;
    }

    glfwMakeContextCurrent(window);

    glbinding::Binding::initialize();

    ASSERT_EQ(gl::GL_NO_ERROR, gl::glGetError());

    // "Death Test": resolve a basic OpenGL of return type GLboolean (with underlying type char)
    // note: this might work on some OpenGL drivers without expected failure (try NVIDIA for expected failure on windows x64)
    ASSERT_NO_THROW(gl::glIsProgram(0));

    ASSERT_EQ(gl::GL_NO_ERROR, gl::glGetError());

    glfwMakeContextCurrent(nullptr);
    glfwTerminate();

    SUCCEED();
}

TEST(Regression_185, GetString)  // Static initializiation issue ...
{
    ASSERT_EQ(glbinding::Meta::getString(gl::GL_TRUE), "GL_TRUE");
    ASSERT_EQ(glbinding::Meta::getString(gl::GL_FALSE), "GL_FALSE");

    SUCCEED();
}
<commit_msg>refine regression test for no-gl environments again<commit_after>
#include <gmock/gmock.h>

#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>

#include <glbinding/Binding.h>
#include <glbinding/Meta.h>

#include <glbinding/gl/functions.h>  // < imagine this was included by a 3rd party library (e.g., globjects.cpp)

#include <glbinding/gl/types.h>
#include <glbinding/gl/functions.h>
#include <glbinding/gl/enum.h>

class Regression_185 : public testing::Test
{
public:
};

TEST(Regression_185, GLbooleanReturnValueCall)  // GL calls fail if function returns GLboolean
{
    try
    {
        glfwInit();
    }
    catch (...)
    {
        SUCCEED();
        return;
    }

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, false);

#ifdef SYSTEM_DARWIN
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif

    GLFWwindow * window = nullptr;
    try
    {
        window = glfwCreateWindow(320, 240, "", nullptr, nullptr);
    }
    catch (...)
    {
        SUCCEED();
        return;
    }

    ASSERT_NE(nullptr, window);

    glfwMakeContextCurrent(window);

    glbinding::Binding::initialize();

    ASSERT_EQ(gl::GL_NO_ERROR, gl::glGetError());

    // "Death Test": resolve a basic OpenGL of return type GLboolean (with underlying type char)
    // note: this might work on some OpenGL drivers without expected failure (try NVIDIA for expected failure on windows x64)
    ASSERT_NO_THROW(gl::glIsProgram(0));

    ASSERT_EQ(gl::GL_NO_ERROR, gl::glGetError());

    glfwMakeContextCurrent(nullptr);
    glfwTerminate();

    SUCCEED();
}

TEST(Regression_185, GetString)  // Static initializiation issue ...
{
    ASSERT_EQ(glbinding::Meta::getString(gl::GL_TRUE), "GL_TRUE");
    ASSERT_EQ(glbinding::Meta::getString(gl::GL_FALSE), "GL_FALSE");

    SUCCEED();
}
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CMetab.cpp,v $
   $Revision: 1.56 $
   $Name:  $
   $Author: shoops $
   $Date: 2004/01/09 14:48:28 $
   End CVS Header */

// cmetab.cpp : implementation of the CMetab class
//

#include <iostream>
#include <string>
#include <vector>

#define  COPASI_TRACE_CONSTRUCTION

#include "copasi.h"
#include "utilities/CGlobals.h"
#include "utilities/utility.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "CCompartment.h"
#include "CModel.h"
#include "CMetab.h"

const CCompartment * CMetab::mpParentCompartment = NULL;

const std::string CMetab::StatusName[] =
  {"fixed", "independent", "dependent", ""};

const char * CMetab::XMLStatus[] =
  {"fixed", "variable", "variable", NULL};

void CMetab::setParentCompartment(const CCompartment * parentCompartment)
{mpParentCompartment = parentCompartment;}

/////////////////////////////////////////////////////////////////////////////
// CMetab

CMetab::CMetab(const std::string & name,
               const CCopasiContainer * pParent):
    CCopasiContainer(name, pParent, "Metabolite",
                     CCopasiObject::Container |
                     CCopasiObject::ValueDbl |
                     CCopasiObject::NonUniqueName),
    mKey(GlobalKeys.add("Metabolite", this)),
    mConc(1.0),
    mIConc(1.0),
    mNumber(1.0),
    mINumber(1.0),
    mRate(1.0),
    mTT(0.0),
    mStatus(METAB_VARIABLE)
{
  if (getObjectParent())
    {
      initModel();
      initCompartment(NULL);
    }

  initObjects();
  CONSTRUCTOR_TRACE;
}

CMetab::CMetab(const CMetab & src,
               const CCopasiContainer * pParent):
    CCopasiContainer(src, pParent),
    mKey(GlobalKeys.add("Metabolite", this)),
    mConc(src.mConc),
    mIConc(src.mIConc),
    mNumber(src.mNumber),
    mINumber(src.mINumber),
    mRate(src.mRate),
    mTT(src.mTT),
    mStatus(src.mStatus)
{
  initModel();
  initCompartment(src.mpCompartment);
  initObjects();
  CONSTRUCTOR_TRACE;
}

CMetab &CMetab::operator=(const CMetabOld &RHS)
{
  setObjectName(RHS.getObjectName());

  setInitialConcentration(RHS.mIConc);
  setConcentration(RHS.mIConc);

  mRate = 1.0;
  mTT = 0.0;
  mStatus = RHS.mStatus;

  return *this;  // Assignment operator returns left side.
}

CMetab::~CMetab()
{
  GlobalKeys.remove(mKey);
  DESTRUCTOR_TRACE;
}

void CMetab::cleanup() {}

void CMetab::initModel()
{
  mpModel = (CModel *) getObjectAncestor("Model");
  if (!mpModel) mpModel = Copasi->pModel;
}

void CMetab::initCompartment(const CCompartment * pCompartment)
{
  mpCompartment = (const CCompartment *) getObjectAncestor("Compartment");
  if (!mpCompartment) mpCompartment = pCompartment;
  if (!mpCompartment) mpCompartment = mpParentCompartment;
}

C_INT32 CMetab::load(CReadConfig &configbuffer)
{
  C_INT32 Fail = 0;

  std::string tmp;
  Fail = configbuffer.getVariable("Metabolite", "string",
                                  (void *) & tmp,
                                  CReadConfig::SEARCH);

  if (Fail)
    return Fail;
  setObjectName(tmp);

  Fail = configbuffer.getVariable("InitialConcentration", "C_FLOAT64",
                                  (void *) & mIConc);

  setInitialConcentration(mIConc);
  setConcentration(mIConc);

  Fail = configbuffer.getVariable("Type", "C_INT16",
                                  (void *) & mStatus);

  if (Fail)
    return Fail;

  // sanity check
  if ((mStatus < 0) || (mStatus > 7))
    {
      CCopasiMessage(CCopasiMessage::WARNING,
                     "The file specifies a non-existing type "
                     "for '%s'.\nReset to internal metabolite.",
                     getObjectName().c_str());
      mStatus = CMetab::METAB_VARIABLE;
    }

  // sanity check
  if ((mStatus != METAB_MOIETY) && (mIConc < 0.0))
    {
      CCopasiMessage(CCopasiMessage::WARNING,
                     "The file specifies a negative concentration "
                     "for '%s'.\nReset to default.",
                     getObjectName().c_str());
      mIConc = 1.0;
    }

  return Fail;
}

C_INT32 CMetab::save(CWriteConfig &configbuffer)
{
  C_INT32 Fail = 0;
  std::string tmp = getObjectName();
  Fail = configbuffer.setVariable("Metabolite", "string", &tmp);

  if (Fail)
    return Fail;

  Fail = configbuffer.setVariable("InitialConcentration", "C_FLOAT64",
                                  (void *) & mIConc);

  if (Fail)
    return Fail;

  Fail = configbuffer.setVariable("Type", "C_INT16",
                                  (void *) & mStatus);

  return Fail;
}

C_INT32 CMetab::saveOld(CWriteConfig &configbuffer)
{
  C_INT32 c, Fail = 0;
  std::string tmp = getObjectName();
  Fail = configbuffer.setVariable("Metabolite", "string", &tmp);
  if (Fail)
    return Fail;
  Fail = configbuffer.setVariable("Concentration", "C_FLOAT64", (void *) & mIConc);
  if (Fail)
    return Fail;
  c = mpModel->getCompartments().getIndex(mpCompartment->getName());
  Fail = configbuffer.setVariable("Compartment", "C_INT32", (void *) & c);
  if (Fail)
    return Fail;
  Fail = configbuffer.setVariable("Type", "C_INT16", (void *) & mStatus);
  return Fail;
}

void CMetab::saveSBML(std::ofstream &fout)
{
  std::string str;
  FixSName(getObjectName(), str);
  fout << "\t\t\t<specie name=\"" << str << "\"";
  FixSName(getCompartment()->getName(), str);
  fout << " compartment=\"" + str + "\"";
  fout << " initialAmount=\"" << mIConc << "\"";
  fout << " boundaryCondition=\"";
  if (mStatus == METAB_FIXED)
    fout << "true";
  else
    fout << "false";
  fout << "\"/>" << std::endl;
}

std::string CMetab::getKey() const {return mKey;}

const std::string & CMetab::getName() const {return getObjectName();}

const C_FLOAT64 & CMetab::getConcentration() const {return mConc;}

const C_FLOAT64 & CMetab::getNumber() const {return mNumber;}

const C_FLOAT64 & CMetab::getInitialConcentration() const {return mIConc;}

const C_FLOAT64 & CMetab::getInitialNumber() const {return mINumber;}

const CMetab::Status & CMetab::getStatus() const {return mStatus;}

const CCompartment * CMetab::getCompartment() const {return mpCompartment;}

const CModel * CMetab::getModel() const {return mpModel;}

void CMetab::setTransitionTime(const C_FLOAT64 & transitionTime)
{mTT = transitionTime;}

const C_FLOAT64 & CMetab::getTransitionTime() const {return mTT;}

bool CMetab::setName(const std::string & name) {return setObjectName(name);}

bool CMetab::setObjectParent(const CCopasiContainer * pParent)
{
  CCopasiObject::setObjectParent(pParent);

  initCompartment(NULL);
  initModel();

  return true;
}

// ***** set quantities ********

void CMetab::setConcentration(const C_FLOAT64 concentration)
{
  mConc = concentration;
  mNumber = concentration * mpCompartment->getVolume()
            * mpModel->getQuantity2NumberFactor();
}

void CMetab::setInitialConcentration(const C_FLOAT64 initialConcentration)
{
  mIConc = initialConcentration;
  mINumber = initialConcentration * mpCompartment->getVolume()
             * mpModel->getQuantity2NumberFactor();
}

void CMetab::setNumber(const C_FLOAT64 number)
{
  mConc = number * mpCompartment->getVolumeInv()
          * mpModel->getNumber2QuantityFactor();
  mNumber = number;
}

void CMetab::setInitialNumber(const C_FLOAT64 initialNumber)
{
  mIConc = initialNumber * mpCompartment->getVolumeInv()
           * mpModel->getNumber2QuantityFactor();
  mINumber = initialNumber;
}

//  ******************

void CMetab::setStatus(const CMetab::Status & status) {mStatus = status;}

void CMetab::setCompartment(const CCompartment * compartment)
{mpCompartment = compartment;}

void CMetab::setModel(CModel * model) {mpModel = model;}

bool CMetab::isValidName(const std::string &name) const
  {return (name.find_first_of("; ") == std::string::npos);}

void CMetab::initObjects()
{
  addObjectReference("Concentration", mConc, CCopasiObject::ValueDbl);
  addObjectReference("InitialConcentration", mIConc, CCopasiObject::ValueDbl);
  addObjectReference("TransitionTime", mTT, CCopasiObject::ValueDbl);
}

CMetabOld::CMetabOld(const std::string & name,
                     const CCopasiContainer * pParent):
    CCopasiContainer(name, pParent, "Old Metabolite"),
    mIConc(1.0),
    mStatus(CMetab::METAB_VARIABLE),
    mCompartment()
{CONSTRUCTOR_TRACE;}

CMetabOld::CMetabOld(const CMetabOld & src,
                     const CCopasiContainer * pParent):
    CCopasiContainer(src, pParent),
    mIConc(src.mIConc),
    mStatus(src.mStatus),
    mCompartment(src.mCompartment)
{CONSTRUCTOR_TRACE;}

CMetabOld::~CMetabOld() {DESTRUCTOR_TRACE;}

void CMetabOld::cleanup(){}

C_INT32 CMetabOld::load(CReadConfig &configbuffer)
{
  C_INT32 Fail = 0;
  std::string tmp;
  Fail = configbuffer.getVariable("Metabolite", "string",
                                  (void *) & tmp,
                                  CReadConfig::SEARCH);

  if (Fail)
    return Fail;
  setObjectName(tmp);

  Fail = configbuffer.getVariable("Concentration", "C_FLOAT64",
                                  (void *) & mIConc);

  if (Fail)
    return Fail;

  Fail = configbuffer.getVariable("Compartment", "C_INT32",
                                  (void *) & mCompartment);

  if (Fail)
    return Fail;

  C_INT32 Status;

  Fail = configbuffer.getVariable("Type", "C_INT32",
                                  (void *) & Status);

  mStatus = (CMetab::Status) Status;

  // sanity check
  if ((mStatus < 0) || (mStatus > 7))
    {
      CCopasiMessage(CCopasiMessage::WARNING,
                     "The file specifies a non-existing type "
                     "for '%s'.\nReset to internal metabolite.",
                     getObjectName().c_str());
      mStatus = CMetab::METAB_VARIABLE;
    }

  // sanity check
  if ((mStatus != METAB_MOIETY) && (mIConc < 0.0))
    {
      CCopasiMessage(CCopasiMessage::WARNING,
                     "The file specifies a negative concentration "
                     "for '%s'.\nReset to default.",
                     getObjectName().c_str());
      mIConc = 1.0;
    }

  return Fail;
}
C_INT32 CMetabOld::save(CWriteConfig & C_UNUSED(configbuffer)){return 0;}
C_INT32 CMetabOld::getIndex() const {return mCompartment;}
const std::string & CMetabOld::getName() const {return getObjectName();}

/**
 * Returns the address of mIConc  Wei Sun
 */
void * CMetab::getIConcAddr()
{
  return &mIConc;
}

/**
 * Returns the address of mConc
 */
void * CMetab::getConcAddr()
{
  return &mConc;
}

/**
 * Returns the address of mTT
 */
void * CMetab::getTTAddr()
{
  return &mTT;
}

// non-member
bool operator<(const CMetab &lhs, const CMetab &rhs)
{
  // Do the comparison based on the name

  if (lhs.getName() < rhs.getName())
    {
      return true;
    }
  else
    {
      return false;
    }
}

/**
 * Return rate of production of this metaboLite
 */
const C_FLOAT64 & CMetab::getRate() const
  {
    return mRate;
  }

void CMetab::setRate(const C_FLOAT64 & rate)
{
  mRate = rate * getCompartment()->getVolumeInv()
          * mpModel->getNumber2QuantityFactor();
  //  calculateTransitionTime();
}
void CMetab::calculateTransitionTime(void) {mTT = mConc / mRate;}

void * CMetab::getReference() const
  {return const_cast<C_FLOAT64 *>(&mConc);}

std::ostream & operator<<(std::ostream &os, const CMetab & d)
{
  os << "    ++++CMetab: " << d.getObjectName() << std::endl;
  os << "        mConc " << d.mConc << " mIConc " << d.mIConc << std::endl;
  os << "        mNumber " << d.mNumber << " mINumber " << d.mINumber << std::endl;
  os << "        mRate " << d.mRate << " mTT " << d.mTT << " mStatus " << d.mStatus << std::endl;

  if (d.mpCompartment)
    os << "        mpCompartment == " << d.mpCompartment << std::endl;
  else
    os << "        mpCompartment == 0 " << std::endl;

  if (d.mpModel)
    os << "        mpModel == " << d.mpModel << std::endl;
  else
    os << "        mpModel == 0 " << std::endl;

  os << "    ----CMetab " << std::endl;

  return os;
}
<commit_msg>Fixed crash/hang when closing COPASI.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CMetab.cpp,v $
   $Revision: 1.57 $
   $Name:  $
   $Author: shoops $
   $Date: 2004/02/26 21:17:35 $
   End CVS Header */

// cmetab.cpp : implementation of the CMetab class
//

#include <iostream>
#include <string>
#include <vector>

#define  COPASI_TRACE_CONSTRUCTION

#include "copasi.h"
#include "utilities/CGlobals.h"
#include "utilities/utility.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "CCompartment.h"
#include "CModel.h"
#include "CMetab.h"

const CCompartment * CMetab::mpParentCompartment = NULL;

const std::string CMetab::StatusName[] =
  {"fixed", "independent", "dependent", ""};

const char * CMetab::XMLStatus[] =
  {"fixed", "variable", "variable", NULL};

void CMetab::setParentCompartment(const CCompartment * parentCompartment)
{mpParentCompartment = parentCompartment;}

/////////////////////////////////////////////////////////////////////////////
// CMetab

CMetab::CMetab(const std::string & name,
               const CCopasiContainer * pParent):
    CCopasiContainer(name, pParent, "Metabolite",
                     CCopasiObject::Container |
                     CCopasiObject::ValueDbl |
                     CCopasiObject::NonUniqueName),
    mKey(GlobalKeys.add("Metabolite", this)),
    mConc(1.0),
    mIConc(1.0),
    mNumber(1.0),
    mINumber(1.0),
    mRate(1.0),
    mTT(0.0),
    mStatus(METAB_VARIABLE)
{
  if (getObjectParent())
    {
      initModel();
      initCompartment(NULL);
    }

  initObjects();
  CONSTRUCTOR_TRACE;
}

CMetab::CMetab(const CMetab & src,
               const CCopasiContainer * pParent):
    CCopasiContainer(src, pParent),
    mKey(GlobalKeys.add("Metabolite", this)),
    mConc(src.mConc),
    mIConc(src.mIConc),
    mNumber(src.mNumber),
    mINumber(src.mINumber),
    mRate(src.mRate),
    mTT(src.mTT),
    mStatus(src.mStatus)
{
  initModel();
  initCompartment(src.mpCompartment);
  initObjects();
  CONSTRUCTOR_TRACE;
}

CMetab &CMetab::operator=(const CMetabOld &RHS)
{
  setObjectName(RHS.getObjectName());

  setInitialConcentration(RHS.mIConc);
  setConcentration(RHS.mIConc);

  mRate = 1.0;
  mTT = 0.0;
  mStatus = RHS.mStatus;

  return *this;  // Assignment operator returns left side.
}

CMetab::~CMetab()
{
  GlobalKeys.remove(mKey);
  DESTRUCTOR_TRACE;
}

void CMetab::cleanup() {}

void CMetab::initModel()
{
  mpModel = dynamic_cast< CModel * >(getObjectAncestor("Model"));
  if (!mpModel && Copasi) mpModel = Copasi->pModel;
}

void CMetab::initCompartment(const CCompartment * pCompartment)
{
  mpCompartment = (const CCompartment *) getObjectAncestor("Compartment");
  if (!mpCompartment) mpCompartment = pCompartment;
  if (!mpCompartment) mpCompartment = mpParentCompartment;
}

C_INT32 CMetab::load(CReadConfig &configbuffer)
{
  C_INT32 Fail = 0;

  std::string tmp;
  Fail = configbuffer.getVariable("Metabolite", "string",
                                  (void *) & tmp,
                                  CReadConfig::SEARCH);

  if (Fail)
    return Fail;
  setObjectName(tmp);

  Fail = configbuffer.getVariable("InitialConcentration", "C_FLOAT64",
                                  (void *) & mIConc);

  setInitialConcentration(mIConc);
  setConcentration(mIConc);

  Fail = configbuffer.getVariable("Type", "C_INT16",
                                  (void *) & mStatus);

  if (Fail)
    return Fail;

  // sanity check
  if ((mStatus < 0) || (mStatus > 7))
    {
      CCopasiMessage(CCopasiMessage::WARNING,
                     "The file specifies a non-existing type "
                     "for '%s'.\nReset to internal metabolite.",
                     getObjectName().c_str());
      mStatus = CMetab::METAB_VARIABLE;
    }

  // sanity check
  if ((mStatus != METAB_MOIETY) && (mIConc < 0.0))
    {
      CCopasiMessage(CCopasiMessage::WARNING,
                     "The file specifies a negative concentration "
                     "for '%s'.\nReset to default.",
                     getObjectName().c_str());
      mIConc = 1.0;
    }

  return Fail;
}

C_INT32 CMetab::save(CWriteConfig &configbuffer)
{
  C_INT32 Fail = 0;
  std::string tmp = getObjectName();
  Fail = configbuffer.setVariable("Metabolite", "string", &tmp);

  if (Fail)
    return Fail;

  Fail = configbuffer.setVariable("InitialConcentration", "C_FLOAT64",
                                  (void *) & mIConc);

  if (Fail)
    return Fail;

  Fail = configbuffer.setVariable("Type", "C_INT16",
                                  (void *) & mStatus);

  return Fail;
}

C_INT32 CMetab::saveOld(CWriteConfig &configbuffer)
{
  C_INT32 c, Fail = 0;
  std::string tmp = getObjectName();
  Fail = configbuffer.setVariable("Metabolite", "string", &tmp);
  if (Fail)
    return Fail;
  Fail = configbuffer.setVariable("Concentration", "C_FLOAT64", (void *) & mIConc);
  if (Fail)
    return Fail;
  c = mpModel->getCompartments().getIndex(mpCompartment->getName());
  Fail = configbuffer.setVariable("Compartment", "C_INT32", (void *) & c);
  if (Fail)
    return Fail;
  Fail = configbuffer.setVariable("Type", "C_INT16", (void *) & mStatus);
  return Fail;
}

void CMetab::saveSBML(std::ofstream &fout)
{
  std::string str;
  FixSName(getObjectName(), str);
  fout << "\t\t\t<specie name=\"" << str << "\"";
  FixSName(getCompartment()->getName(), str);
  fout << " compartment=\"" + str + "\"";
  fout << " initialAmount=\"" << mIConc << "\"";
  fout << " boundaryCondition=\"";
  if (mStatus == METAB_FIXED)
    fout << "true";
  else
    fout << "false";
  fout << "\"/>" << std::endl;
}

std::string CMetab::getKey() const {return mKey;}

const std::string & CMetab::getName() const {return getObjectName();}

const C_FLOAT64 & CMetab::getConcentration() const {return mConc;}

const C_FLOAT64 & CMetab::getNumber() const {return mNumber;}

const C_FLOAT64 & CMetab::getInitialConcentration() const {return mIConc;}

const C_FLOAT64 & CMetab::getInitialNumber() const {return mINumber;}

const CMetab::Status & CMetab::getStatus() const {return mStatus;}

const CCompartment * CMetab::getCompartment() const {return mpCompartment;}

const CModel * CMetab::getModel() const {return mpModel;}

void CMetab::setTransitionTime(const C_FLOAT64 & transitionTime)
{mTT = transitionTime;}

const C_FLOAT64 & CMetab::getTransitionTime() const {return mTT;}

bool CMetab::setName(const std::string & name) {return setObjectName(name);}

bool CMetab::setObjectParent(const CCopasiContainer * pParent)
{
  CCopasiObject::setObjectParent(pParent);

  initCompartment(NULL);
  initModel();

  return true;
}

// ***** set quantities ********

void CMetab::setConcentration(const C_FLOAT64 concentration)
{
  mConc = concentration;
  mNumber = concentration * mpCompartment->getVolume()
            * mpModel->getQuantity2NumberFactor();
}

void CMetab::setInitialConcentration(const C_FLOAT64 initialConcentration)
{
  mIConc = initialConcentration;
  mINumber = initialConcentration * mpCompartment->getVolume()
             * mpModel->getQuantity2NumberFactor();
}

void CMetab::setNumber(const C_FLOAT64 number)
{
  mConc = number * mpCompartment->getVolumeInv()
          * mpModel->getNumber2QuantityFactor();
  mNumber = number;
}

void CMetab::setInitialNumber(const C_FLOAT64 initialNumber)
{
  mIConc = initialNumber * mpCompartment->getVolumeInv()
           * mpModel->getNumber2QuantityFactor();
  mINumber = initialNumber;
}

//  ******************

void CMetab::setStatus(const CMetab::Status & status) {mStatus = status;}

void CMetab::setCompartment(const CCompartment * compartment)
{mpCompartment = compartment;}

void CMetab::setModel(CModel * model) {mpModel = model;}

bool CMetab::isValidName(const std::string &name) const
  {return (name.find_first_of("; ") == std::string::npos);}

void CMetab::initObjects()
{
  addObjectReference("Concentration", mConc, CCopasiObject::ValueDbl);
  addObjectReference("InitialConcentration", mIConc, CCopasiObject::ValueDbl);
  addObjectReference("TransitionTime", mTT, CCopasiObject::ValueDbl);
}

CMetabOld::CMetabOld(const std::string & name,
                     const CCopasiContainer * pParent):
    CCopasiContainer(name, pParent, "Old Metabolite"),
    mIConc(1.0),
    mStatus(CMetab::METAB_VARIABLE),
    mCompartment()
{CONSTRUCTOR_TRACE;}

CMetabOld::CMetabOld(const CMetabOld & src,
                     const CCopasiContainer * pParent):
    CCopasiContainer(src, pParent),
    mIConc(src.mIConc),
    mStatus(src.mStatus),
    mCompartment(src.mCompartment)
{CONSTRUCTOR_TRACE;}

CMetabOld::~CMetabOld() {DESTRUCTOR_TRACE;}

void CMetabOld::cleanup(){}

C_INT32 CMetabOld::load(CReadConfig &configbuffer)
{
  C_INT32 Fail = 0;
  std::string tmp;
  Fail = configbuffer.getVariable("Metabolite", "string",
                                  (void *) & tmp,
                                  CReadConfig::SEARCH);

  if (Fail)
    return Fail;
  setObjectName(tmp);

  Fail = configbuffer.getVariable("Concentration", "C_FLOAT64",
                                  (void *) & mIConc);

  if (Fail)
    return Fail;

  Fail = configbuffer.getVariable("Compartment", "C_INT32",
                                  (void *) & mCompartment);

  if (Fail)
    return Fail;

  C_INT32 Status;

  Fail = configbuffer.getVariable("Type", "C_INT32",
                                  (void *) & Status);

  mStatus = (CMetab::Status) Status;

  // sanity check
  if ((mStatus < 0) || (mStatus > 7))
    {
      CCopasiMessage(CCopasiMessage::WARNING,
                     "The file specifies a non-existing type "
                     "for '%s'.\nReset to internal metabolite.",
                     getObjectName().c_str());
      mStatus = CMetab::METAB_VARIABLE;
    }

  // sanity check
  if ((mStatus != METAB_MOIETY) && (mIConc < 0.0))
    {
      CCopasiMessage(CCopasiMessage::WARNING,
                     "The file specifies a negative concentration "
                     "for '%s'.\nReset to default.",
                     getObjectName().c_str());
      mIConc = 1.0;
    }

  return Fail;
}
C_INT32 CMetabOld::save(CWriteConfig & C_UNUSED(configbuffer)){return 0;}
C_INT32 CMetabOld::getIndex() const {return mCompartment;}
const std::string & CMetabOld::getName() const {return getObjectName();}

/**
 * Returns the address of mIConc  Wei Sun
 */
void * CMetab::getIConcAddr()
{
  return &mIConc;
}

/**
 * Returns the address of mConc
 */
void * CMetab::getConcAddr()
{
  return &mConc;
}

/**
 * Returns the address of mTT
 */
void * CMetab::getTTAddr()
{
  return &mTT;
}

// non-member
bool operator<(const CMetab &lhs, const CMetab &rhs)
{
  // Do the comparison based on the name

  if (lhs.getName() < rhs.getName())
    {
      return true;
    }
  else
    {
      return false;
    }
}

/**
 * Return rate of production of this metaboLite
 */
const C_FLOAT64 & CMetab::getRate() const
  {
    return mRate;
  }

void CMetab::setRate(const C_FLOAT64 & rate)
{
  mRate = rate * getCompartment()->getVolumeInv()
          * mpModel->getNumber2QuantityFactor();
  //  calculateTransitionTime();
}
void CMetab::calculateTransitionTime(void) {mTT = mConc / mRate;}

void * CMetab::getReference() const
  {return const_cast<C_FLOAT64 *>(&mConc);}

std::ostream & operator<<(std::ostream &os, const CMetab & d)
{
  os << "    ++++CMetab: " << d.getObjectName() << std::endl;
  os << "        mConc " << d.mConc << " mIConc " << d.mIConc << std::endl;
  os << "        mNumber " << d.mNumber << " mINumber " << d.mINumber << std::endl;
  os << "        mRate " << d.mRate << " mTT " << d.mTT << " mStatus " << d.mStatus << std::endl;

  if (d.mpCompartment)
    os << "        mpCompartment == " << d.mpCompartment << std::endl;
  else
    os << "        mpCompartment == 0 " << std::endl;

  if (d.mpModel)
    os << "        mpModel == " << d.mpModel << std::endl;
  else
    os << "        mpModel == 0 " << std::endl;

  os << "    ----CMetab " << std::endl;

  return os;
}
<|endoftext|>