void VortexTransition::LoadFromFile(const std::string& dataname, int ts, int tl)
{
  _ts = ts;
  _tl = tl;

  for (int i=ts; i<ts+tl-1; i++) {
    std::stringstream ss;
    ss << dataname << ".match." << i << "." << i+1;

    VortexTransitionMatrix tm;
    if (!tm.LoadFromFile(ss.str())) {
      fprintf(stderr, "cannot open file %s\n", ss.str().c_str());
      tm.SetToDummy();
    }
    
    _matrices.insert(std::make_pair(i, tm));
    _nvortices_per_frame[i] = tm.n0(); 
    _nvortices_per_frame[i+1] = tm.n1();
  }

  _max_nvortices_per_frame = 0;
  for (std::map<int, int>::iterator it = _nvortices_per_frame.begin(); it != _nvortices_per_frame.end(); it ++) {
    _max_nvortices_per_frame = std::max(_max_nvortices_per_frame, it->second);
  }
  // fprintf(stderr, "max_nvortices_per_frame=%d\n", _max_nvortices_per_frame);
}
void VortexTransition::ConstructSequence()
{
  for (int i=_ts; i<_ts+_tl-1; i++) {
    // fprintf(stderr, "=====t=%d\n", i);

    VortexTransitionMatrix tm = Matrix(i);
    assert(tm.Valid());

    if (i == _ts) { // initial
      for (int k=0; k<tm.n0(); k++) {
        int gid = NewVortexSequence(i);
        _seqs[gid].tl ++;
        _seqs[gid].lids.push_back(k);
        _seqmap[std::make_pair(i, k)] = gid;
        _invseqmap[std::make_pair(i, gid)] = k;
      }
    }

    for (int k=0; k<tm.NModules(); k++) {
      int event;
      std::set<int> lhs, rhs;
      tm.GetModule(k, lhs, rhs, event);

      if (lhs.size() == 1 && rhs.size() == 1) { // ordinary case
        int l = *lhs.begin(), r = *rhs.begin();
        int gid = _seqmap[std::make_pair(i, l)];
        _seqs[gid].tl ++;
        _seqs[gid].lids.push_back(r);
        _seqmap[std::make_pair(i+1, r)] = gid;
        _invseqmap[std::make_pair(i+1, gid)] = r;
      } else { // some events, need re-ID
        for (std::set<int>::iterator it=rhs.begin(); it!=rhs.end(); it++) {
          int r = *it; 
          int gid = NewVortexSequence(i+1);
          _seqs[gid].tl ++;
          _seqs[gid].lids.push_back(r);
          _seqmap[std::make_pair(i+1, r)] = gid;
          _invseqmap[std::make_pair(i+1, gid)] = r;
        }
      }

      // build events
      // if (event >= VORTEX_EVENT_MERGE) {
      if (event > VORTEX_EVENT_DUMMY) {
        VortexEvent e;
        e.frame = i;
        e.type = event;
        e.lhs = lhs;
        e.rhs = rhs;
        _events.push_back(e);
      }
    }
  }

  // RandomColorSchemes();
  SequenceGraphColoring(); 
}