crangeset.h 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
/*
 *  This file is part of libcxxsupport.
 *
 *  libcxxsupport is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  libcxxsupport is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with libcxxsupport; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

/*
 *  libcxxsupport is being developed at the Max-Planck-Institut fuer Astrophysik
 *  and financially supported by the Deutsches Zentrum fuer Luft- und Raumfahrt
 *  (DLR).
 */

/*! \file crangeset.h
 *  Class for storing sets of ranges of integer numbers
 *
 *  Copyright (C) 2015-2020 Max-Planck-Society
 *  \author Martin Reinecke
 */

#ifndef MRUTIL_CRANGESET_H
#define MRUTIL_CRANGESET_H

#include <algorithm>
#include <vector>
#include <utility>
#include <iostream>
#include "mr_util/error_handling.h"
#include "mr_util/math_utils.h"

namespace mr {

/*
compact rangeset (CRS)

The underlying type T must be signed.
BUT: All "on" ranges must lie entirely in N_0.

A nonnegative number indicates the start of an "on" range at this number.
A negative number indicates the start of an "off" range at the absolute value
of this number.

All numbers r are sorted in a way that |r_i| < |r_{i+1}|.

If two consecutive numbers are both nonnegative or negative, it means that the
interval between them contains in fact _two_ ranges: one of length 1 and the
other filling the remainder.

Consequences:

- The first number in CRS must be nonnegative
- numbers r_i and r_{i+1} in the CRS have the property
  |r_{i+1}| > |r_i| + 1 (because of the special treatment of short intervals)

Example:
The range set
[5;7[; [10;15[; [16;22[; [23;24[; [25;30[; [35;36[; [40;45[

would be encoded as
5 -7 10 -15 -22 -24 -30 35 40 -45
*/

/*! Class for storing sets of ranges of integer numbers
    T must be a signed integer type, but all numbers entered into the range set
    must be nonnegative! */
template<typename T> class crangeset
  {
  private:
    typedef std::vector<T> rtype;
    rtype r;

    struct abscomp
      {
      bool operator()(const T &a, const T &b)
        {
        using namespace std;
        return abs(a)<abs(b);
        }
      };

    class RsIter
      {
      private:
        size_t idx;
        bool extra;
        const crangeset &ref;
        T val;

        bool singleVal() const
          {
          if (idx==ref.r.size()-1)
            return (ref.r[idx]>=0);
          else
            return ((ref.r[idx]^ref.r[idx+1])>=0);
          }

      public:
      RsIter(const crangeset &ref_) : idx(0), extra(false), ref(ref_), val(0)
          {
          using namespace std;
          if (!atEnd())
            val=abs(ref.r[0]);
          }
        bool atEnd() const { return idx>=ref.r.size(); }
        T operator*() const
          {
          return val;
          }
        RsIter &operator++ ()
          {
          using namespace std;
          if (extra)
            {
            ++idx;
            extra=false;
            if (!atEnd()) val=abs(ref.r[idx]);
            }
          else
            {
            if (singleVal())
              {
              extra=true;
              ++val;
              }
            else
              {
              ++idx;
              if (!atEnd()) val=abs(ref.r[idx]);
              }
            }
          return *this;
          }
        void advance_up_to(T goal)
          {
          using namespace std;
          ptrdiff_t idx2=ref.iiv(goal-1);
          if (idx2>ptrdiff_t(idx))
            {
            idx=idx2;
            extra=false;
            val=abs(ref.r[idx]);
            }
          }
        bool onoff() const
          { return (ref.r[idx]>=0)^extra; }
      };
  public:
    class IvIter
      {
      private:
        RsIter rsi;
        T b,e;

      public:
        IvIter(const crangeset &ref_) : rsi(ref_)
          {
          if (rsi.atEnd()) return;
          b=*rsi;
          ++rsi;
          e=*rsi;
          }
        bool atEnd() const { return rsi.atEnd(); }
        T ivbegin() const { return b; }
        T ivend() const { return e; }
        ptrdiff_t ivlen() const { return e-b; }
        IvIter &operator++ ()
          {
          ++rsi;
          if (rsi.atEnd()) return *this;
          b=*rsi;
          ++rsi;
          e=*rsi;
          return *this;
          }
      };
    class RsOutputIter
      {
      private:
        T val;
        bool val_set;
        crangeset &ref;

      public:
        RsOutputIter(crangeset &ref_) : val(T(0)), val_set(false), ref(ref_)
          { ref.clear(); }
        RsOutputIter &operator*() { return *this; }
        RsOutputIter &operator++ () { return *this; }
        RsOutputIter &operator++ (int) { return *this; }
        RsOutputIter &operator= (const T &v)
          {
          if (val_set)
            ref.append(val,v);
          else
            val=v;
          val_set=!val_set;
          return *this;
          }
      };
    /*! Returns the index of the last number in \c r whose absolute value
        is <= \a val
        If \a val is smaller than all absolute values in \c r, returns -1. */
    ptrdiff_t iiv (const T &val) const
      {
      return ptrdiff_t(std::upper_bound(r.begin(),r.end(),val,abscomp())
                   -r.begin())-1;
      }

    /*! Estimate a good strategy for set operations involving two rangesets. */
    static int strategy (size_t sza, size_t szb)
      {
      const double fct1 = 1.;
      const double fct2 = 1.;
      size_t slo = sza<szb ? sza : szb,
            shi = sza<szb ? szb : sza;
      double cost1 = fct1 * (sza+szb);
      double cost2 = fct2 * slo * std::max(1u,ilog2(shi));
      return (cost1<=cost2) ? 1 : (slo==sza) ? 2 : 3;
      }

    static crangeset generalUnion1 (const crangeset &a, const crangeset &b,
      bool flip_a, bool flip_b)
      {
      crangeset res;
      bool state_a=flip_a, state_b=flip_b, state_res=state_a||state_b;
      RsIter ia(a), ib(b);
      RsOutputIter io(res);
      bool runa = !ia.atEnd(), runb = !ib.atEnd();
      while(runa||runb)
        {
        T va = runa ? *ia : T(0),
          vb = runb ? *ib : T(0);
        bool adv_a = runa && (!runb || (va<=vb)),
             adv_b = runb && (!runa || (vb<=va));
        if (adv_a) { state_a=!state_a; ++ia; runa = !ia.atEnd(); }
        if (adv_b) { state_b=!state_b; ++ib; runb = !ib.atEnd(); }
        if ((state_a||state_b)!=state_res)
          { *io++ = (adv_a ? va : vb); state_res = !state_res; }
        }
      return res;
      }
    static crangeset generalUnion2 (const crangeset &a, const crangeset &b,
      bool flip_a, bool flip_b)
      {
      crangeset res;
      bool state_a=flip_a, state_b=flip_b, state_res=state_a||state_b;
      RsIter ia(a), ib(b);
      RsOutputIter io(res);
      bool runa = !ia.atEnd(), runb = !ib.atEnd();
      while(runa||runb)
        {
        T va = runa ? *ia : T(0);
        if (state_a && runb) // changes in b are irrelevant while state_a is true
          {
          if (!runa) break; // we are at the end
          if (*ib<va)
            {
            ib.advance_up_to (va);
            state_b=!(flip_b^ib.onoff());
            }
          }
        T vb = runb ? *ib : T(0);
        bool adv_a = runa && (!runb || (va<=vb)),
             adv_b = runb && (!runa || (vb<=va));
        if (adv_a) { state_a=!state_a; ++ia; runa = !ia.atEnd(); }
        if (adv_b) { state_b=!state_b; ++ib; runb = !ib.atEnd(); }
        if ((state_a||state_b)!=state_res)
          { *io++ = (adv_a ? va : vb); state_res = !state_res; }
        }
      return res;
      }
    static crangeset generalUnion (const crangeset &a, const crangeset &b,
      bool flip_a, bool flip_b)
      {
      if (a.r.empty())
        return flip_a ? crangeset() : b;
      if (b.r.empty())
        return flip_b ? crangeset() : a;

      int strat = strategy (a.r.size(), b.r.size());
      return (strat==1) ? generalUnion1(a,b,flip_a,flip_b) :
               ((strat==2) ? generalUnion2(a,b,flip_a,flip_b)
                           : generalUnion2(b,a,flip_b,flip_a));
      }
    static crangeset generalXor (const crangeset &a, const crangeset &b)
      {
      crangeset res;
      bool state_a=false, state_b=false, state_res=state_a||state_b;
      RsIter ia(a), ib(b);
      RsOutputIter io(res);
      bool runa = !ia.atEnd(), runb = !ib.atEnd();
      while(runa||runb)
        {
        T va = runa ? *ia : T(0),
          vb = runb ? *ib : T(0);
        bool adv_a = runa && (!runb || (va<=vb)),
             adv_b = runb && (!runa || (vb<=va));
        if (adv_a) { state_a=!state_a; ++ia; runa = !ia.atEnd(); }
        if (adv_b) { state_b=!state_b; ++ib; runb = !ib.atEnd(); }
        if ((state_a^state_b)!=state_res)
          { *io++ = (adv_a ? va : vb); state_res = !state_res; }
        }
      return res;
      }

    static bool generalAllOrNothing1 (const crangeset &a, const crangeset &b,
      bool flip_a, bool flip_b)
      {
      bool state_a=flip_a, state_b=flip_b, state_res=state_a||state_b;
      RsIter ia(a), ib(b);
      bool runa = !ia.atEnd(), runb = !ib.atEnd();
      while(runa||runb)
        {
          using namespace std;
        T va = runa ? *ia : T(0),
          vb = runb ? *ib : T(0);
        bool adv_a = runa && (!runb || (va<=vb)),
             adv_b = runb && (!runa || (vb<=va));
        if (adv_a) { state_a=!state_a; ++ia; runa = !ia.atEnd(); }
        if (adv_b) { state_b=!state_b; ++ib; runb = !ib.atEnd(); }
        if ((state_a||state_b)!=state_res)
          return false;
        }
      return true;
      }
    static bool generalAllOrNothing2 (const crangeset &a, const crangeset &b,
      bool flip_a, bool flip_b)
      {
      bool state_a=flip_a, state_b=flip_b, state_res=state_a||state_b;
      RsIter ia(a), ib(b);
      bool runa = !ia.atEnd(), runb = !ib.atEnd();
      while(runa||runb)
        {
        T va = runa ? *ia : T(0);
        if (state_a && runb) // changes in b are irrelevant while state_a is true
          {
          if (!runa) break; // we are at the end
          if (*ib<va)
            {
            ib.advance_up_to (va);
            state_b=!(flip_b^ib.onoff());
            }
          }
        T vb = runb ? *ib : T(0);
        bool adv_a = runa && (!runb || (va<=vb)),
             adv_b = runb && (!runa || (vb<=va));
        if (adv_a) { state_a=!state_a; ++ia; runa = !ia.atEnd(); }
        if (adv_b) { state_b=!state_b; ++ib; runb = !ib.atEnd(); }
        if ((state_a||state_b)!=state_res)
          return false;
        }
      return true;
      }

    static bool generalAllOrNothing (const crangeset &a, const crangeset &b,
      bool flip_a, bool flip_b)
      {
      if (a.r.empty())
        return flip_a ? true : b.r.empty();
      if (b.r.empty())
        return flip_b ? true : a.r.empty();
      int strat = strategy (a.r.size(), b.r.size());
      return (strat==1) ? generalAllOrNothing1(a,b,flip_a,flip_b) :
               ((strat==2) ? generalAllOrNothing2(a,b,flip_a,flip_b)
                           : generalAllOrNothing2(b,a,flip_b,flip_a));
      }
  public:
    /*! Removes all rangeset entries. */
    void clear() { r.clear(); }
    bool empty() const { return r.empty(); }
    const rtype &data() const { return r; }
    void checkConsistency() const
      {
      using namespace std;
      if (r.size()==0) return;
      MR_assert(r[0]>=0,"incorrect first element in range set");
      for (size_t i=1; i<r.size(); ++i)
        MR_assert(abs(r[i])>abs(r[i-1]+1),"inconsistent entries");
      }
    void setData (const rtype &inp)
      {
      r=inp;
      checkConsistency();
      }
    /*! Appends \a [v1;v2[ to the rangeset. \a v1 must be larger
        than the minimum of the last range in the rangeset. */
    void append(const T &v1, const T &v2)
      {
      using namespace std;
      if (v2<=v1) return;
      T le = -100;
      if (!empty())
        le=(r.back()<0) ? -r.back() : r.back()+1;

      if (v1>le) // clean append
        {
        if ((v1>le+1)||(r.back()>0))
          {
          r.push_back(v1);
          if (v2-v1>1) r.push_back(-v2);
          }
        else // short off interval
          r.push_back(-v2);
        return;
        }
        T lastbegin=-200;
        if (!r.empty())
          {
          if (r.back()>=0) lastbegin= r.back();
          else if (r[r.size()-2]<0) lastbegin = -r[r.size()-2]+1;
          else lastbegin = r[r.size()-2];
          }
      MR_assert(v1>=lastbegin,"bad append operation");
      // merge with the last interval
      T endval=max(abs(r.back()),v2);
      if (r.back()<0)
        r.back()=-endval;
      else
        if (endval>r.back()+1) r.push_back(-endval);
      }
    /*! Appends \a [v;v+1[ to the rangeset. \a v must be larger
        than the minimum of the last range in the rangeset. */
    void append(const T &v)
      { append(v,v+1); }

    /*! Appends \a other to the rangeset. All values in \a other must be larger
        than the minimum of the last range in the rangeset. */
    void append (const crangeset &other)
      {
      typename crangeset<T>::IvIter iter(other);
      while (!iter.atEnd())
        {
        append(iter.ivbegin(),iter.ivend());
        ++iter;
        }
      }
    /*! Returns the total number of elements in the rangeset. */
    T nval() const
      {
      T res=0;
      typename crangeset<T>::IvIter iter(*this);
      while (!iter.atEnd())
        {res+=iter.ivlen(); ++iter;}
      return res;
      }

    crangeset op_or (const crangeset &other) const
      { return generalUnion (*this,other,false,false); }
    crangeset op_and (const crangeset &other) const
      { return generalUnion (*this,other,true,true); }
    crangeset op_andnot (const crangeset &other) const
      { return generalUnion (*this,other,true,false); }
    crangeset op_xor (const crangeset &other) const
      { return generalXor (*this,other); }

      /*! Returns \a true if the rangeset is identical to \a other, else \a false.
        */
    bool operator== (const crangeset &other) const
      { return r==other.r; }

    /*! Returns \a true if the rangeset contains all values in the range
        \a [a;b[, else \a false. */
    bool contains (T a,T b) const
      {
      ptrdiff_t res=iiv(a);
      if (res<0) return false;
      if (r[res]<0)
        {
        if (res==ptrdiff_t(r.size())-1) return false; // beyond end
        if (r[res+1]>=0) return false; // long "off" range
        return ((a>-r[res])&&(b<=-r[res+1])); // mixed range
        }
      // r[res]>=0
      if ((res==ptrdiff_t(r.size())-1) || (r[res+1]>=0)) // short interval
        return ((a==r[res])&&(b==a+1));
      return b<=-r[res+1];
      }
    /*! Returns \a true if the rangeset contains the value \a v,
        else \a false. */
    bool contains (T v) const
      {
      ptrdiff_t res=iiv(v);
      if (res<0) return false;
      if (r[res]<0)
        {
        if (res==ptrdiff_t(r.size())-1) return false; // beyond end
        if (r[res+1]>=0) return false; // long "off" range
        return (v>-r[res]); // mixed range
        }
      if ((res<ptrdiff_t(r.size())-1) && (r[res+1]<0))
        return true;
      return (r[res]==v);
      }
    /*! Returns \a true if the rangeset contains all values stored in \a other,
        else \a false. */
    bool contains (const crangeset &other) const
      { return generalAllOrNothing(*this,other,false,true); }

    /** Returns true if any of the numbers [a;b[ are contained in the set,
        else false. */
    bool overlaps (T a,T b) const
      {
      using namespace std;
      if (empty()) return false;
      ptrdiff_t res=iiv(a);
      if (res<ptrdiff_t(r.size())-1)
        if (b>abs(r[res+1])) return true; // at least one switch
      // now we know that [a;b[ lies entirely inside an interval,
      // but it may still contain a short sub-interval
      if (res==-1) return false; // no sub-intervals in that one
      if (res==ptrdiff_t(r.size())-1)
        return a==r[res]; // only overlaps if r[res]>0 and a==abs(r[res])
      // we are somewhere in the middle
      if (r[res]>=0)
        return (a==r[res]) || (r[res+1]<0);
      return (r[res+1]<0) && (b>-r[res]+1);
      }

    /** Returns true if there is overlap between the set and "other",
        else false. */
    bool overlaps (const crangeset &other) const
      { return !generalAllOrNothing(*this,other,true,true); }
  };

template<typename T> inline std::ostream &operator<< (std::ostream &os,
  const crangeset<T> &rs)
  {
  os << "{ ";
  typename crangeset<T>::IvIter iter(rs);
  while (!iter.atEnd())
    {
    os << "["<<iter.ivbegin()<<";"<<iter.ivend()<<"[ ";
    ++iter;
    }
  return os << "}";
  }

}

#endif