Example #1
0
void UnpoolingLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
  if (!propagate_down[0]) {
    return;
  }
  const Dtype* top_diff = top[0]->cpu_diff();
  Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
  // Different unpooling methods. We explicitly do the switch outside the for
  // loop to save time, although this results in more codes.
  caffe_set(bottom[0]->count(), Dtype(0), bottom_diff);
  // We'll output the mask to top[1] if it's of size >1.
  const bool use_bottom_mask = bottom.size() > 1;
  const Dtype* bottom_mask = NULL;
  switch (this->layer_param_.unpooling_param().unpool()) {
  case UnpoolingParameter_UnpoolMethod_MAX:
    if (use_bottom_mask) {
      bottom_mask = bottom[1]->cpu_data();
    } 
    // The main loop
    for (int n = 0; n < top[0]->num(); ++n) {
      for (int c = 0; c < channels_; ++c) {
        for (int ph = 0; ph < height_; ++ph) {
          for (int pw = 0; pw < width_; ++pw) {
            int uph = max(0,min(ph * stride_h_ - pad_h_, unpooled_height_-1));
            int upw = max(0,min(pw * stride_w_ - pad_w_, unpooled_width_-1)); 
            const int index = ph * width_ + pw;
            const int unpooled_index = uph * unpooled_width_ + upw; 
            if (use_bottom_mask) {
              const int mask_index = bottom_mask[index];
              bottom_diff[index] = top_diff[mask_index]; 
            } else {
              bottom_diff[index] = top_diff[unpooled_index];
            }
          }
        }
        // compute offset
        bottom_diff += bottom[0]->offset(0, 1);
        top_diff += top[0]->offset(0, 1);
        if (use_bottom_mask) {
          bottom_mask += bottom[1]->offset(0, 1);
        } 
      }
    }
    break;
  case UnpoolingParameter_UnpoolMethod_AVE:
    for (int i = 0; i < bottom[0]->count(); ++i) {
      bottom_diff[i] = 0;
    }
    // The main loop
    for (int n = 0; n < bottom[0]->num(); ++n) {
      for (int c = 0; c < channels_; ++c) {
        for (int ph = 0; ph < height_; ++ph) {
          for (int pw = 0; pw < width_; ++pw) {
            int hstart = ph * stride_h_ - pad_h_;
            int wstart = pw * stride_w_ - pad_w_;
            int hend = min(hstart + kernel_h_, unpooled_height_ + pad_h_);
            int wend = min(wstart + kernel_w_, unpooled_width_ + pad_w_);
            int pool_size = (hend - hstart) * (wend - wstart);
            hstart = max(hstart, 0);
            wstart = max(wstart, 0);
            hend = min(hend, unpooled_height_);
            wend = min(wend, unpooled_width_);
            for (int h = hstart; h < hend; ++h) {
              for (int w = wstart; w < wend; ++w) {
                bottom_diff[ph * width_ + pw] +=
                    top_diff[h * unpooled_width_ + w];
              }
            }
            bottom_diff[ph * width_ + pw] /= pool_size;
          }
        }
        // compute offset
        bottom_diff += bottom[0]->offset(0, 1);
        top_diff += top[0]->offset(0, 1);
      }
    }
    break;
  case UnpoolingParameter_UnpoolMethod_TILE:
    for (int i = 0; i < bottom[0]->count(); ++i) {
      bottom_diff[i] = 0;
    }
    // The main loop
    for (int n = 0; n < bottom[0]->num(); ++n) {
      for (int c = 0; c < channels_; ++c) {
        for (int ph = 0; ph < height_; ++ph) {
          for (int pw = 0; pw < width_; ++pw) {
            int hstart = ph * stride_h_ - pad_h_;
            int wstart = pw * stride_w_ - pad_w_;
            int hend = min(hstart + kernel_h_, unpooled_height_ + pad_h_);
            int wend = min(wstart + kernel_w_, unpooled_width_ + pad_w_);
            int pool_size = (hend - hstart) * (wend - wstart);
            hstart = max(hstart, 0);
            wstart = max(wstart, 0);
            hend = min(hend, unpooled_height_);
            wend = min(wend, unpooled_width_);
            for (int h = hstart; h < hend; ++h) {
              for (int w = wstart; w < wend; ++w) {
                bottom_diff[ph * width_ + pw] +=
                    top_diff[h * unpooled_width_ + w];
              }
            }
            bottom_diff[ph * width_ + pw] /= pool_size;
          }
        }
        // compute offset
        bottom_diff += bottom[0]->offset(0, 1);
        top_diff += top[0]->offset(0, 1);
      }
    }
    break;
  default:
    LOG(FATAL) << "Unknown unpooling method.";
  }
}
Example #2
0
bool CBuilder::StartBuild(BuildInfo& buildInfo, CFeature*& feature, bool& waitStance)
{
	StopBuild(false);
	TempHoldFire(-1);

	buildInfo.pos = CGameHelper::Pos2BuildPos(buildInfo, true);

	// Pass -1 as allyteam to behave like we have maphack.
	// This is needed to prevent building on top of cloaked stuff.
	const CGameHelper::BuildSquareStatus tbs = CGameHelper::TestUnitBuildSquare(buildInfo, feature, -1, true);

	switch (tbs) {
		case CGameHelper::BUILDSQUARE_OPEN:
			break;

		case CGameHelper::BUILDSQUARE_BLOCKED:
		case CGameHelper::BUILDSQUARE_OCCUPIED: {
			// the ground is blocked at the position we want
			// to build at; check if the blocking object is
			// of the same type as our buildee (which means
			// another builder has already started it)
			// note: even if construction has already started,
			// the buildee is *not* guaranteed to be the unit
			// closest to us
			CSolidObject* o = groundBlockingObjectMap->GroundBlocked(buildInfo.pos);
			CUnit* u = NULL;

			if (o != NULL) {
				u = dynamic_cast<CUnit*>(o);
			} else {
				// <pos> might map to a non-blocking portion
				// of the buildee's yardmap, fallback check
				u = CGameHelper::GetClosestFriendlyUnit(NULL, buildInfo.pos, buildDistance, allyteam);
			}

			if (u != NULL && CanAssistUnit(u, buildInfo.def)) {
				curBuild = u;
				AddDeathDependence(u, DEPENDENCE_BUILD);
				ScriptStartBuilding(u->pos, false);
				return true;
			}

			return false;
		}

		case CGameHelper::BUILDSQUARE_RECLAIMABLE:
			// caller should handle this
			return false;
	}

	if ((waitStance = !ScriptStartBuilding(buildInfo.pos, true))) {
		return false;
	}

	const UnitDef* buildeeDef = buildInfo.def;
	const UnitLoadParams buildeeParams = {buildeeDef, this, buildInfo.pos, ZeroVector, -1, team, buildInfo.buildFacing, true, false};

	CUnit* buildee = unitLoader->LoadUnit(buildeeParams);

	// floating structures don't terraform the seabed
	const float groundheight = CGround::GetHeightReal(buildee->pos.x, buildee->pos.z);
	const bool onWater = (buildeeDef->floatOnWater && groundheight <= 0.0f);

	if (mapDamage->disabled || !buildeeDef->levelGround || onWater ||
	    buildeeDef->IsAirUnit() || !buildeeDef->IsImmobileUnit()
	) {
		// skip the terraforming job
		buildee->terraformLeft = 0;
		buildee->groundLevelled = true;
	} else {
		tx1 = (int)max(    0.0f, (buildee->pos.x - (buildeeDef->xsize * 0.5f * SQUARE_SIZE)) / SQUARE_SIZE);
		tx2 =      min(gs->mapx,             tx1 +  buildeeDef->xsize                                     );
		tz1 = (int)max(    0.0f, (buildee->pos.z - (buildeeDef->zsize * 0.5f * SQUARE_SIZE)) / SQUARE_SIZE);
		tz2 =      min(gs->mapy,             tz1 +  buildeeDef->zsize                                     );

		buildee->terraformLeft = CalculateBuildTerraformCost(buildInfo);
		buildee->groundLevelled = false;

		terraforming    = true;
		terraformType   = Terraform_Building;
		terraformRadius = (tx2 - tx1) * SQUARE_SIZE;
		terraformCenter = buildee->pos;
	}

	if (!this->unitDef->canBeAssisted) {
		buildee->soloBuilder = this;
		buildee->AddDeathDependence(this, DEPENDENCE_BUILDER);
	}

	AddDeathDependence(buildee, DEPENDENCE_BUILD);
	curBuild = buildee;

	/* The ground isn't going to be terraformed.
	 * When the building is completed, it'll 'pop'
	 * into the correct height for the (un-flattened)
	 * terrain it's on.
	 *
	 * To prevent this visual artifact, put the building
	 * at the 'right' height to begin with.
	 */
	curBuild->moveType->SlowUpdate();
	return true;
}
void
FortranCUDAHostSubroutineDirectLoop::createCUDAKernelInitialisationStatements ()
{
  using namespace SageBuilder;
  using namespace SageInterface;
  using namespace OP2VariableNames;
  using namespace OP2::Macros;
  using boost::lexical_cast;
  using std::string;
  using std::max;

  Debug::getInstance ()->debugMessage (
      "Creating CUDA kernel initialisation statements", Debug::FUNCTION_LEVEL,
      __FILE__, __LINE__);

  /*
   * ======================================================
   * The following values are copied from Mike Giles'
   * implementation and may be subject to future changes
   * ======================================================
   */
  int const nblocks = 200;
  int const nthreads = 128;

  SgExprStatement * assignmentStatement1 = buildAssignStatement (
      variableDeclarations->getReference (CUDA::blocksPerGrid), buildIntVal (
          nblocks));

  appendStatement (assignmentStatement1, subroutineScope);

  SgExprStatement * assignmentStatement2 = buildAssignStatement (
      variableDeclarations->getReference (CUDA::threadsPerBlock), buildIntVal (
          nthreads));

  appendStatement (assignmentStatement2, subroutineScope);

  SgExprStatement * assignmentStatement3 = buildAssignStatement (
      variableDeclarations->getReference (warpSize), buildOpaqueVarRefExp (
          warpSizeMacro, subroutineScope));

  appendStatement (assignmentStatement3, subroutineScope);

  /*
   * ======================================================
   * Compute the value of shared memory passed at CUDA kernel
   * launch.
   *
   * An OP_DAT is only copied into shared memory if its
   * dimension exceeds 1 and it is not an OP_GBL. To
   * compute the value, therefore, we need to get the maximum
   * of (dimension * size of primitive type) across all
   * OP_DATs
   * ======================================================
   */

  unsigned int sharedOpDatMemorySize = 0;
  unsigned int sharedReductionMemorySize = 0;

  for (unsigned int i = 1; i <= parallelLoop->getNumberOfOpDatArgumentGroups (); ++i)
  {
    if (parallelLoop->isDuplicateOpDat (i) == false)
    {
      if (parallelLoop->isGlobal (i) == false)
      {
        unsigned int opDatMemoryRequirements = parallelLoop->getOpDatDimension (
            i) * parallelLoop->getSizeOfOpDat (i);

        if (opDatMemoryRequirements > sharedOpDatMemorySize)
        {
          sharedOpDatMemorySize = opDatMemoryRequirements;
        }
      }
      else if (parallelLoop->isReductionRequired (i))
      {
        unsigned int reductionMemoryRequirements =
            parallelLoop->getOpDatDimension (i) * parallelLoop->getSizeOfOpDat (
                i);

        if (reductionMemoryRequirements > sharedReductionMemorySize)
        {
          sharedReductionMemorySize = reductionMemoryRequirements;
        }
      }
    }
  }

  if (sharedOpDatMemorySize == 0 && sharedReductionMemorySize == 0)
  {
    throw Exceptions::CUDA::SharedMemorySizeException (
        "The shared memory size will be set to zero during kernel launch");
  }
  else
  {
    Debug::getInstance ()->debugMessage (
        "The shared memory size will be set to " + lexical_cast <string> (max (
            sharedOpDatMemorySize, sharedReductionMemorySize))
            + " during kernel launch", Debug::OUTER_LOOP_LEVEL, __FILE__,
        __LINE__);
  }

  SgExprStatement * assignmentStatement4 = buildAssignStatement (
      variableDeclarations->getReference (CUDA::sharedMemorySize), buildIntVal (
          max (sharedOpDatMemorySize, sharedReductionMemorySize)));

  appendStatement (assignmentStatement4, subroutineScope);

  /*
   * ======================================================
   * Initialise the offset into shared memory to <shared
   * memory size> * <warp size>
   * ======================================================
   */

  SgMultiplyOp * multiplyExpression5 = buildMultiplyOp (
      variableDeclarations->getReference (CUDA::sharedMemorySize),
      buildOpaqueVarRefExp (warpSizeMacro, subroutineScope));

  SgExprStatement * assignmentStatement5 = buildAssignStatement (
      variableDeclarations->getReference (sharedMemoryOffset),
      multiplyExpression5);

  appendStatement (assignmentStatement5, subroutineScope);

  SgMultiplyOp * multiplyExpression6 = buildMultiplyOp (
      variableDeclarations->getReference (CUDA::sharedMemorySize),
      variableDeclarations->getReference (CUDA::threadsPerBlock));

  SgExprStatement * assignmentStatement6 = buildAssignStatement (
      variableDeclarations->getReference (CUDA::sharedMemorySize),
      multiplyExpression6);

  appendStatement (assignmentStatement6, subroutineScope);
}
Example #4
0
/* STATIC */
void Line::drawProfile(float *y, int npts, double len, string ylabel) {
    const int buflen = 100;
    static int index = 0;

    if (y && len <= 0) {
        y = NULL;
    }

    // Open file
    char fname[128];
    sprintf(fname, "%s%d.%d", baseFilename.c_str(), getpid(), index);
    index++;
    index %= 2;
    FILE *fd = fopen(fname, "w");
    if (!fd) {
        fprintf(stderr,"Cannot open file for line profile: %s\n", fname);
        return;
    }

    char buf[buflen];
    if (y == NULL) {
        // Write out header
        fprintf(fd, "XLabel Distance (cm)\n");
        fprintf(fd, "YLabel %s\n", ylabel.c_str());
        //fprintf(fd,"YMin 0\n");
        //fprintf(fd,"YMax getReal("aipProfileMaxY", 0)\n");
        fprintf(fd, "NPoints 0\n");
        fprintf(fd, "Data\n");
        sprintf(buf, "Max:");
    } else {
        double ymax;
        // Set scale
        ymax = y[0];
        for (int i=0; i<npts; ++i) {
            if (ymax < y[i]) {
                ymax = y[i];
            }
        }
        double graphYmax = ymax;
        if (::isActive("aipProfileMaxY")) {
            graphYmax = max(ymax, getReal("aipProfileMaxY", 0));
        }
        setReal("aipProfileMaxY", ymax, false); // No notification

        // Write out header
        //fprintf(fd,"YMin 0\n");
        //fprintf(fd,"YMax %g\n", graphYmax);
        string showZero;
        showZero = getString("aipProfileShowZero", "y");
        if (showZero[0] == 'y' || showZero[0] == 'Y') {
            fprintf(fd,"ShowZeroY\n");
        }
        fprintf(fd,"XLabel Distance (cm)\n");
        fprintf(fd,"YLabel %s\n", ylabel.c_str());
        fprintf(fd,"NPoints %d\n", npts);
        fprintf(fd,"Data\n");
        sprintf(buf, "Max: %.4g", ymax);

        // Write out the data
        double x = 0;
        double dx = len / (npts - 1);
        for (int i=0; i<npts; ++i, x += dx) {
            fprintf(fd,"%g %g\n", x, y[i]);
        }
    }
    fprintf(fd,"EndData\n");
    fclose(fd);

    // Set parameters
    setString("aipProfileFile", fname, true);// Send notification of change
    static char maxStr[buflen] = "---";
    if (strcmp(buf, maxStr)) {
        strcpy(maxStr, buf);
        setString("aipProfileMaxMsg", buf, true);
    }
}
void PeakConvert2::ComputeMagnitudeAndPhase (mrs_realvec in)
{
  mrs_real a, c;
  mrs_real b, d;
  mrs_real phasediff;
  for (mrs_natural o=0; o < size_; o++)
  {
    if (o==0) //DC bins
    {
      a = in(0);
      b = 0.0;
      c = in(N_);
      d = 0.0;
    }
    else if (o == size_-1) //Nyquist bins
    {
      a = in(1);
      b = 0.0;
      c = in(N_+1);
      d = 0.0;
    }
    else //all other bins
    {
      a = in(2*o);
      b = in(2*o+1);
      c = in(N_+2*o);
      d = in(N_+2*o+1);
    }

    if (o < downFrequency_ || o > upFrequency_)
    {
      frequency_(o)	= 0;
      mag_(o)			= sqrt((a*a + b*b))*2;
      continue;
    }
    if ( a == .0 || c == .0)
    {
      frequency_(o) = o*fundamental_;
    }
    else
    {
      if(prec_ && pick_)
      {
        mrs_real Omega = TWOPI*o*instFreqHopSize_/N_;    // now works with hopsizes != 1 as well  (AL)

        // compute phase
        phase_(o)		= atan2(b,a);

        // compute precise frequency using the phase difference
        lastphase_(o)	= atan2(d,c);
        phasediff		= princArg(phase_(o)-lastphase_(o) - Omega) + Omega;
        frequency_(o)	= abs(phasediff * factor_ );
      }
      else
        frequency_(o) = o*fundamental_;
    }


    // compute precise amplitude
    mag_(o) = sqrt((a*a + b*b))*2;
    if (pick_)
    {
      mrs_real mag = lobe_value_compute((o * fundamental_-frequency_(o))/factor_, 1, N_);
      magCorr_(o) = mag_(o)/mag;
    }
    else
    {
      magCorr_(o) = mag_(o);
    }
    //mrs_real freq = frequency_(o);

    if(frequency_(o) != 0.0)
    {
      const mrs_natural searchRange	= 8;
      mrs_natural	k,
                  kd	= o,
                   ku	= o,
                    kEndSearch;
      mrs_real	diff[2];

      // find closest preceding frequency
      kEndSearch = max ((mrs_natural)0, o-searchRange);
      for (k = o-1; k > kEndSearch; k--)
      {
        diff[0]	= abs(frequency_(o) - lastfrequency_(k));
        diff[1] = abs(frequency_(o) - lastfrequency_(kd));
        if (diff[0] < diff[1])
          kd	= k;
      }
      kEndSearch = min (size_, o+searchRange);
      for (k = o+1; k < kEndSearch; k++)
      {
        diff[0]	= abs(frequency_(o) - lastfrequency_(k));
        diff[1] = abs(frequency_(o) - lastfrequency_(ku));
        if (diff[0] < diff[1])
          ku	= k;
      }
      diff[0]	= abs(frequency_(o) - lastfrequency_(kd));
      diff[1] = abs(frequency_(o) - lastfrequency_(ku));
      k = (diff[0] < diff[1])? kd : ku;

      deltafrequency_(o) = (lastfrequency_(k) == 0)? .0 : log10(lastfrequency_(k)/frequency_(o));
      //deltafrequency_(o) = (frequency_(o)-lastfrequency_(o))/(frequency_(o)+lastfrequency_(o));
    }
    else
      deltafrequency_(o) = .0;

    mrs_real lastmag	= lastmag_(o);
    if (o > 0)
      lastmag		= max(lastmag_(o-1), lastmag);
    if (o < size_-1)
      lastmag		= max(lastmag_(o+1), lastmag);

    if (mag_(o) > 0)
      deltamag_(o)		= (mag_(o)-lastmag)/mag_(o);
    else if (lastmag > 0)
      deltamag_(o)		= (mag_(o)-lastmag)/lastmag;
    else
      deltamag_(o)		= 0;
  }
  lastfrequency_	= frequency_;
  lastmag_		= mag_;
}
Example #6
0
template<typename T> T _max(T a, T b, T c, T d) { return max(_max(a,b,d),c); }
Example #7
0
inline void DPmatrixConstrained::forward_cell(int i2,int j2) 
{
  assert(0 < i2 and i2 < size1());
  assert(0 < j2 and j2 < size2());

  prepare_cell(i2,j2);

  // determine initial scale for this cell
  scale(i2,j2) = max(scale(i2-1,j2), max( scale(i2-1,j2-1), scale(i2,j2-1) ) );

  double maximum = 0;

  for(int s2=0;s2<states(j2).size();s2++) 
  {
    int S2 = states(j2)[s2];

    //--- Get (i1,j1) from (i2,j2) and S2
    int i1 = i2;
    if (di(S2)) i1--;

    int j1 = j2;
    if (dj(S2)) j1--;

    //--- Compute Arrival Probability ----
    unsigned MAX = states(j1).size();
    if (not di(S2) and not dj(S2)) MAX = s2;

    double temp = 0.0;
    for(int s1=0;s1<MAX;s1++) {
      int S1 = states(j1)[s1];

      temp +=  (*this)(i1,j1,S1) * GQ(S1,S2);
    }

    //--- Include Emission Probability----
    double sub;
    if (i1 != i2 and j1 != j2)
      sub = emitMM(i2,j2);
    else if (i1 != i2)
      sub = emitM_(i2,j2);
    else if (j1 != j2)
      sub = emit_M(i2,j2);
    else          // silent state - nothing emitted
      sub = emit__(i2,j2);

    temp *= sub;

    // rescale result to scale of this cell
    if (scale(i1,j1) != scale(i2,j2))
      temp *= pow2(scale(i1,j1)-scale(i2,j2));

    // record maximum
    if (temp > maximum) maximum = temp;

    // store the result
    (*this)(i2,j2,S2) = temp;
  }

  //------- if exponent is too low, rescale ------//
  if (maximum > 0 and maximum < fp_scale::cutoff) {
    int logs = -(int)log2(maximum);
    double scale_ = pow2(logs);
    for(int i=0;i<states(j2).size();i++) {
      int S2 = states(j2)[i];
      (*this)(i2,j2,S2) *= scale_;
    }
    scale(i2,j2) -= logs;
  }
}
void ScrollView::updateScrollbars(const IntSize& desiredOffset)
{
    if (m_inUpdateScrollbars || prohibitsScrolling() || platformWidget())
        return;

    // If we came in here with the view already needing a layout, then go ahead and do that
    // first.  (This will be the common case, e.g., when the page changes due to window resizing for example).
    // This layout will not re-enter updateScrollbars and does not count towards our max layout pass total.
    if (!m_scrollbarsSuppressed) {
        m_inUpdateScrollbars = true;
        visibleContentsResized();
        m_inUpdateScrollbars = false;
    }

    bool hasHorizontalScrollbar = m_horizontalScrollbar;
    bool hasVerticalScrollbar = m_verticalScrollbar;
    
    bool newHasHorizontalScrollbar = hasHorizontalScrollbar;
    bool newHasVerticalScrollbar = hasVerticalScrollbar;
   
    ScrollbarMode hScroll = m_horizontalScrollbarMode;
    ScrollbarMode vScroll = m_verticalScrollbarMode;

    if (hScroll != ScrollbarAuto)
        newHasHorizontalScrollbar = (hScroll == ScrollbarAlwaysOn);
    if (vScroll != ScrollbarAuto)
        newHasVerticalScrollbar = (vScroll == ScrollbarAlwaysOn);

    if (m_scrollbarsSuppressed || (hScroll != ScrollbarAuto && vScroll != ScrollbarAuto)) {
        if (hasHorizontalScrollbar != newHasHorizontalScrollbar)
            setHasHorizontalScrollbar(newHasHorizontalScrollbar);
        if (hasVerticalScrollbar != newHasVerticalScrollbar)
            setHasVerticalScrollbar(newHasVerticalScrollbar);
    } else {
        bool sendContentResizedNotification = false;
        
        IntSize docSize = contentsSize();
        IntSize frameSize = frameRect().size();

        if (hScroll == ScrollbarAuto) {
            newHasHorizontalScrollbar = docSize.width() > visibleWidth();
            if (newHasHorizontalScrollbar && !m_updateScrollbarsPass && docSize.width() <= frameSize.width() && docSize.height() <= frameSize.height())
                newHasHorizontalScrollbar = false;
        }
        if (vScroll == ScrollbarAuto) {
            newHasVerticalScrollbar = docSize.height() > visibleHeight();
            if (newHasVerticalScrollbar && !m_updateScrollbarsPass && docSize.width() <= frameSize.width() && docSize.height() <= frameSize.height())
                newHasVerticalScrollbar = false;
        }

        // If we ever turn one scrollbar off, always turn the other one off too.  Never ever
        // try to both gain/lose a scrollbar in the same pass.
        if (!newHasHorizontalScrollbar && hasHorizontalScrollbar && vScroll != ScrollbarAlwaysOn)
            newHasVerticalScrollbar = false;
        if (!newHasVerticalScrollbar && hasVerticalScrollbar && hScroll != ScrollbarAlwaysOn)
            newHasHorizontalScrollbar = false;

        if (hasHorizontalScrollbar != newHasHorizontalScrollbar) {
            setHasHorizontalScrollbar(newHasHorizontalScrollbar);
            sendContentResizedNotification = true;
        }

        if (hasVerticalScrollbar != newHasVerticalScrollbar) {
            setHasVerticalScrollbar(newHasVerticalScrollbar);
            sendContentResizedNotification = true;
        }

        if (sendContentResizedNotification && m_updateScrollbarsPass < cMaxUpdateScrollbarsPass) {
            m_updateScrollbarsPass++;
            contentsResized();
            visibleContentsResized();
            IntSize newDocSize = contentsSize();
            if (newDocSize == docSize) {
                // The layout with the new scroll state had no impact on
                // the document's overall size, so updateScrollbars didn't get called.
                // Recur manually.
                updateScrollbars(desiredOffset);
            }
            m_updateScrollbarsPass--;
        }
    }
    
    // Set up the range (and page step/line step), but only do this if we're not in a nested call (to avoid
    // doing it multiple times).
    if (m_updateScrollbarsPass)
        return;

    m_inUpdateScrollbars = true;
    IntSize maxScrollPosition(contentsWidth() - visibleWidth(), contentsHeight() - visibleHeight());
    IntSize scroll = desiredOffset.shrunkTo(maxScrollPosition);
    scroll.clampNegativeToZero();
 
    if (m_horizontalScrollbar) {
        int clientWidth = visibleWidth();
        m_horizontalScrollbar->setEnabled(contentsWidth() > clientWidth);
        int pageStep = max(max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1);
        IntRect oldRect(m_horizontalScrollbar->frameRect());
        IntRect hBarRect = IntRect(0,
                                   height() - m_horizontalScrollbar->height(),
                                   width() - (m_verticalScrollbar ? m_verticalScrollbar->width() : 0),
                                   m_horizontalScrollbar->height());
        m_horizontalScrollbar->setFrameRect(hBarRect);
        if (!m_scrollbarsSuppressed && oldRect != m_horizontalScrollbar->frameRect())
            m_horizontalScrollbar->invalidate();

        if (m_scrollbarsSuppressed)
            m_horizontalScrollbar->setSuppressInvalidation(true);
        m_horizontalScrollbar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
        m_horizontalScrollbar->setProportion(clientWidth, contentsWidth());
        m_horizontalScrollbar->setValue(scroll.width());
        if (m_scrollbarsSuppressed)
            m_horizontalScrollbar->setSuppressInvalidation(false); 
    } 

    if (m_verticalScrollbar) {
        int clientHeight = visibleHeight();
        m_verticalScrollbar->setEnabled(contentsHeight() > clientHeight);
        int pageStep = max(max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1);
        if (pageStep < 0)
            pageStep = clientHeight;
        IntRect oldRect(m_verticalScrollbar->frameRect());
        IntRect vBarRect = IntRect(width() - m_verticalScrollbar->width(), 
                                   0,
                                   m_verticalScrollbar->width(),
                                   height() - (m_horizontalScrollbar ? m_horizontalScrollbar->height() : 0));
        m_verticalScrollbar->setFrameRect(vBarRect);
        if (!m_scrollbarsSuppressed && oldRect != m_verticalScrollbar->frameRect())
            m_verticalScrollbar->invalidate();

        if (m_scrollbarsSuppressed)
            m_verticalScrollbar->setSuppressInvalidation(true);
        m_verticalScrollbar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
        m_verticalScrollbar->setProportion(clientHeight, contentsHeight());
        m_verticalScrollbar->setValue(scroll.height());
        if (m_scrollbarsSuppressed)
            m_verticalScrollbar->setSuppressInvalidation(false);
    }

    if (hasHorizontalScrollbar != (m_horizontalScrollbar != 0) || hasVerticalScrollbar != (m_verticalScrollbar != 0)) {
        frameRectsChanged();
        updateScrollCorner();
    }

    // See if our offset has changed in a situation where we might not have scrollbars.
    // This can happen when editing a body with overflow:hidden and scrolling to reveal selection.
    // It can also happen when maximizing a window that has scrollbars (but the new maximized result
    // does not).
    IntSize scrollDelta = scroll - m_scrollOffset;
    if (scrollDelta != IntSize()) {
       m_scrollOffset = scroll;
       scrollContents(scrollDelta);
    }

    m_inUpdateScrollbars = false;
}
Example #9
0
void PoolingLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {
  const Dtype* bottom_data = bottom[0]->cpu_data();
  Dtype* top_data = (*top)[0]->mutable_cpu_data();
  const int top_count = (*top)[0]->count();
  // We'll output the mask to top[1] if it's of size >1.
  const bool use_top_mask = top->size() > 1;
  int* mask = NULL;  // suppress warnings about uninitalized variables
  Dtype* top_mask = NULL;
  // Different pooling methods. We explicitly do the switch outside the for
  // loop to save time, although this results in more code.
  switch (this->layer_param_.pooling_param().pool()) {
  case PoolingParameter_PoolMethod_MAX:
    // Initialize
    if (use_top_mask) {
      top_mask = (*top)[1]->mutable_cpu_data();
      caffe_set(top_count, Dtype(-1), top_mask);
    } else {
      mask = max_idx_.mutable_cpu_data();
      caffe_set(top_count, -1, mask);
    }
    caffe_set(top_count, Dtype(-FLT_MAX), top_data);
    // The main loop
    for (int n = 0; n < bottom[0]->num(); ++n) {
      for (int c = 0; c < channels_; ++c) {
        for (int ph = 0; ph < pooled_height_; ++ph) {
          for (int pw = 0; pw < pooled_width_; ++pw) {
            int hstart = ph * stride_h_ - pad_h_;
            int wstart = pw * stride_w_ - pad_w_;
            int hend = min(hstart + kernel_h_, height_);
            int wend = min(wstart + kernel_w_, width_);
            hstart = max(hstart, 0);
            wstart = max(wstart, 0);
            const int pool_index = ph * pooled_width_ + pw;
            for (int h = hstart; h < hend; ++h) {
              for (int w = wstart; w < wend; ++w) {
                const int index = h * width_ + w;
                if (bottom_data[index] > top_data[pool_index]) {
                  top_data[pool_index] = bottom_data[index];
                  if (use_top_mask) {
                    top_mask[pool_index] = static_cast<Dtype>(index);
                  } else {
                    mask[pool_index] = index;
                  }
                }
              }
            }
          }
        }
        // compute offset
        bottom_data += bottom[0]->offset(0, 1);
        top_data += (*top)[0]->offset(0, 1);
        if (use_top_mask) {
          top_mask += (*top)[0]->offset(0, 1);
        } else {
          mask += (*top)[0]->offset(0, 1);
        }
      }
    }
    break;
  case PoolingParameter_PoolMethod_AVE:
    for (int i = 0; i < top_count; ++i) {
      top_data[i] = 0;
    }
    // The main loop
    for (int n = 0; n < bottom[0]->num(); ++n) {
      for (int c = 0; c < channels_; ++c) {
        for (int ph = 0; ph < pooled_height_; ++ph) {
          for (int pw = 0; pw < pooled_width_; ++pw) {
            int hstart = ph * stride_h_ - pad_h_;
            int wstart = pw * stride_w_ - pad_w_;
            int hend = min(hstart + kernel_h_, height_ + pad_h_);
            int wend = min(wstart + kernel_w_, width_ + pad_w_);
            int pool_size = (hend - hstart) * (wend - wstart);
            hstart = max(hstart, 0);
            wstart = max(wstart, 0);
            hend = min(hend, height_);
            wend = min(wend, width_);
            for (int h = hstart; h < hend; ++h) {
              for (int w = wstart; w < wend; ++w) {
                top_data[ph * pooled_width_ + pw] +=
                    bottom_data[h * width_ + w];
              }
            }
            top_data[ph * pooled_width_ + pw] /= pool_size;
          }
        }
        // compute offset
        bottom_data += bottom[0]->offset(0, 1);
        top_data += (*top)[0]->offset(0, 1);
      }
    }
    break;
  case PoolingParameter_PoolMethod_STOCHASTIC:
    NOT_IMPLEMENTED;
    break;
  default:
    LOG(FATAL) << "Unknown pooling method.";
  }
}
Example #10
0
int WindZigZagUpdate(NMEA_INFO* Basic, DERIVED_INFO* Calculated,
		      double *zzwindspeed, double *zzwindbearing) {
  static double tLastEstimate = -1;

  if (!Basic->AirspeedAvailable) {
    return 0;
  }

#if (WINDOWSPC>0)
#ifdef DEBUG_ZIGZAG
  TestZigZagLoop();
#endif
#endif  

  // TODO accuracy: correct TAS for vertical speed if dynamic pullup

  if ((Basic->Time<= tLastEstimate)||(tLastEstimate==-1)) {
    tLastEstimate = Basic->Time-UPDATE_RATE;
  }

  if (!WindZigZagCheckAirData(Basic, Calculated)) {
    return 0;
  }

  // ok to add a point

  myzigzag.AddPoint(Basic->Time, Basic->TrueAirspeed, 
		    Basic->Speed, Basic->TrackBearing*DEGTORAD);

#ifdef DEBUG_ZIGZAG_A
    DebugStore("%f %03.0f %03.0f %03.0f # zigpoint\n",
            Basic->Time,
            Basic->TrueAirspeed,
            Basic->Speed,
            Basic->TrackBearing);
#endif

  // don't update wind from zigzag more often than 
  // every UPDATE_RATE seconds, so it is balanced with respect
  // to circling
  if (Basic->Time<tLastEstimate+UPDATE_RATE) {
    return 0;
  } 

  double V_wind_estimate = Calculated->WindSpeed;
  double theta_wind_estimate = Calculated->WindBearing*DEGTORAD;
  double percent_error = 
    myzigzag.StartSearch(V_wind_estimate, theta_wind_estimate);

  // Check spread of zig-zag manoeuver
  if (!myzigzag.CheckSpread(Basic->Time, percent_error)) {
    return 0;
  }

  double v_error = percent_error*Basic->TrueAirspeed/100.0;

  if (v_error<0.5) {
    // don't refine search if error is small

#ifdef DEBUG_ZIGZAG
    DebugStore("zigzag error small %02.0f %03.1f\n",
            percent_error, v_error);
#endif
    return 0;
  }

  if (myzigzag.Estimate(&V_wind_estimate, 
                        &theta_wind_estimate, 
                        &percent_error)) {

    // ok, we have made an update
    tLastEstimate = Basic->Time;

    theta_wind_estimate /= DEGTORAD;
    
    *zzwindspeed = V_wind_estimate;
    *zzwindbearing = theta_wind_estimate;

    // calculate error quality
    int quality;
    //    double pes = v_error/(V_SCALE/NUM_V_POINTS);
    //quality = iround(0.5+4.5/(1.0+percent_error*percent_error/30.0));
    quality = max(1,5-iround(percent_error/2));
    if (Calculated->Circling) {
      quality = max(1,quality/2); // de-value updates in circling mode
    }

#ifdef DEBUG_ZIGZAG
    DebugStore("%f %3.1f %03.0f %3.1f %03.0f %f %d # zigzag\n",
            Basic->Time,
            V_wind_estimate,
            theta_wind_estimate,
            Calculated->WindSpeed, 
            Calculated->WindBearing,
            percent_error,
            quality);
#endif
    return quality;
  } else {
#ifdef DEBUG_ZIGZAG
    DebugStore("zigzag estimate failed to improve\n");
#endif
  }
  return 0;
}
Example #11
0
static  double ItoV(int i) {
    return max(0,min(i,NUM_V_POINTS-1))*V_SCALE/(NUM_V_POINTS-1);
  }
Example #12
0
long ARX_SPEECH_AddSpeech(Entity * io, const std::string & data, long mood,
                          SpeechFlags flags) {

    if(data.empty()) {
        return -1;
    }

    ARX_SPEECH_ClearIOSpeech(io);

    long num = ARX_SPEECH_GetFree();
    if(num < 0) {
        return -1;
    }

    aspeech[num].exist = 1;
    aspeech[num].time_creation = arxtime.get_updated_ul();
    aspeech[num].io = io; // can be NULL
    aspeech[num].duration = 2000; // Minimum value
    aspeech[num].flags = flags;
    aspeech[num].sample = -1;
    aspeech[num].fDeltaY = 0.f;
    aspeech[num].iTimeScroll = 0;
    aspeech[num].fPixelScroll = 0.f;
    aspeech[num].mood = mood;

    LogDebug("speech \"" << data << '"');

    res::path sample;

    if(flags & ARX_SPEECH_FLAG_NOTEXT) {

        // For non-conversation speech choose a random variant

        long count = getLocalisedKeyCount(data);
        long variant = 1;

        // TODO For some samples there are no corresponding entries
        // in the localization file  (utext_*.ini) -> count will be 0
        // We should probably just count the number of sample files

        if(count > 1) {
            do {
                variant = Random::get(1, count);
            } while(io->lastspeechflag == variant);
            io->lastspeechflag = checked_range_cast<short>(variant);
        }

        LogDebug(" -> " << variant << " / " << count);

        if(variant > 1) {
            sample = data + boost::lexical_cast<std::string>(variant);
        } else {
            sample = data;
        }

    } else {

        std::string _output = getLocalised(data);

        io->lastspeechflag = 0;
        aspeech[num].text.clear();
        aspeech[num].text = _output;
        aspeech[num].duration = max(aspeech[num].duration, (unsigned long)(strlen(_output.c_str()) + 1) * 100);

        sample = data;
    }

    Entity * source = (aspeech[num].flags & ARX_SPEECH_FLAG_OFFVOICE) ? NULL : io;
    aspeech[num].sample = ARX_SOUND_PlaySpeech(sample, source);

    if(aspeech[num].sample == ARX_SOUND_TOO_FAR) {
        aspeech[num].sample = audio::INVALID_ID;
    }

    //Next lines must be removed (use callback instead)
    aspeech[num].duration = (unsigned long)ARX_SOUND_GetDuration(aspeech[num].sample);

    if ((io->ioflags & IO_NPC) && !(aspeech[num].flags & ARX_SPEECH_FLAG_OFFVOICE)) {
        float fDiv = aspeech[num].duration /= io->_npcdata->speakpitch;
        aspeech[num].duration = static_cast<unsigned long>(fDiv);
    }

    if (aspeech[num].duration < 500) aspeech[num].duration = 2000;

    if (ARX_CONVERSATION && io)
        for (long j = 0; j < main_conversation.actors_nb; j++)
            if (main_conversation.actors[j] >= 0 && io == entities[main_conversation.actors[j]])
                main_conversation.current = num;

    return num;
}
Example #13
0
void MusRC::DrawBeamOriginal(  MusDC *dc, MusLayer *layer, MusStaff *staff )
{
	struct MusLayerElement *chk;
	static struct fb {
		unsigned _liaison : 1;	/* temoin pour liaison: si ON, il y a
                                 de la liaison dans l'air et beam doit
                                 doit appeler liaison_note. Cfr.liais_note()*/
		unsigned mrq_port : 2;	/* ON si changement in yy; necessaire
                                 pour decider beams lorsque 2 portees */
		unsigned mq_val   : 1;	/* marqueur de changement de valeur*/
		unsigned fl_cond : 1;	/* flags concernant partage portees */
		unsigned flsht    : 3;	/* garde le pnt->_shport */
		unsigned dir	  : 3;	/* marqueur direction queues */
		unsigned _grp	  : 1;	/* marqueur de groupes rythmiques */
	}	fb;
	int iHauteur=0;
	float fPente = 0.0;
	int ct;			/* compteur d'entree */
	int _ct;		/* compte d'entree moins 1 */
	int cpte_stop;	/* compteur de st_rl */
	unsigned st_rl[NbFRACTURES];	/* garde les ruptures de beams */
	int _yy[2];		/* garde dernier yy pour test mrq_port*/
	static int _ybeam[NbREL];	/* garde les sommets de queues  */
	int shortest, valref;	/* garde valeur la plus breve
                             * m_dur. de reference */
	double high;
	double low;		/* gardent les y extremes */
	double dx[2];			/* rayon / 2 */
	double y_moy;		/* calcul de moyenne y pour dir */
	double s_x=0.0, s_y=0.0, s_xy=0.0, s_x2=0.0, s_y2=0.0;	/* sommes pour la regress. */
	double xr;				/* variables de travail */
	double delt_y, barre_y, ecart, y1;
	double sy_dec_moy, sy_dec[2];
	double fbarre_y;
	int mx_i[MAX_MIF], mx_f[MAX_MIF], my_i[MAX_MIF], my_f[MAX_MIF];
	char m_i[MAX_MIF];	/* pour stocker les prov des marqueurs */
	int fx1,fx2,fy1,fy2;		/* coord. */
	float milieu;
    
	int i, j, t, h, k, si;		/* compteurs de boucles */
	int _mif, decalage;
	int valtest;			/* travail */
	int apax;	 	/* test pour valeur breve isolee en debut  de groupes */
	//int provshp=0;
	int deltabar, deltanbbar, deltablanc;
    
	if (!calcBeam)	/* eviter side-effect de circuit... */
	{	fb._liaison = OFF;
		fb._grp = OFF;			/* reinitialisation du test (static) */
	}
	if (layer->beamListPremier == NULL) return;
	chk = layer->beamListPremier;
    //	bch.markchrd = shortest = fb.mq_val = valref = ct = cpte_stop = fb.mrq_port = OFF;
	bch.markchrd = 0;
	shortest = 0;
	fb.mq_val = 0;
	valref = ct = cpte_stop = 0;
	fb.mrq_port = OFF;
	high = y_moy = sy_up = sy_dec_moy = 0.0;
	for (i=0; i<NbFRACTURES; i++)
		st_rl[i] = 0;
	/***if (e_t->_shport) { provshp = e_t->_shport; shportee (0);}***/
    /* retablir a la fin si provshp existe */
    
	low = chk->m_y_drawing + staff->m_y_drawing;	/* initialiser */
    k = ((MusNote*)chk->m_layerElement)->m_colored ? ((MusNote*)chk->m_layerElement)->m_dur+1 : ((MusNote*)chk->m_layerElement)->m_dur;
	valref = k;		/* m_dur test conservee */
    //	valref = chk->m_dur;		/* m_dur test conservee */
	fb.flsht = 0;
    
	if (staff->notAnc) {
		dx[0] = dx[1] = 0.0;
    } 
    else
    {	
        dx[0] =  m_layout->m_noteRadius[staff->staffSize][0] - ((m_layout->m_noteRadius[staff->staffSize][0] * m_layout->m_env.m_stemCorrection) / 20);
        dx[1] =  m_layout->m_noteRadius[staff->staffSize][1] - ((m_layout->m_noteRadius[staff->staffSize][1] * m_layout->m_env.m_stemCorrection) / 20);
        dx[0] -= (m_layout->m_env.m_stemWidth)/2;
        dx[1] -= (m_layout->m_env.m_stemWidth)/2;
    }
	_yy[0] = staff->m_y_drawing;	
    
    /***
     if (calcBeam)	// eviter side-effect de circuit...
     {	extern_q_auto = chk->m_stemLen;
     extern_queue =  chk->m_stemDir;
     }
     ***/
    
    extern_q_auto = ((MusNote*)chk->m_layerElement)->m_stemLen;
    extern_queue =  ((MusNote*)chk->m_layerElement)->m_stemDir;
    
	do
	{
		if (chk->IsNote() || (((MusNote*)chk->m_layerElement)->m_beam[0] & BEAM_INITIAL) || (((MusNote*)chk->m_layerElement)->m_beam[0] & BEAM_TERMINAL))
			k = ((MusNote*)chk->m_layerElement)->m_colored ? ((MusNote*)chk->m_layerElement)->m_dur+1 : ((MusNote*)chk->m_layerElement)->m_dur;
        
        // if (chk->type == NOTE && /*chk->sil == _NOT &&*/ k > DUR_4)
		if (chk->IsNote() || (((MusNote*)chk->m_layerElement)->m_beam[0] & BEAM_INITIAL) || (((MusNote*)chk->m_layerElement)->m_beam[0] & BEAM_TERMINAL) && k > DUR_4)
		{	(crd+ct)->chk = chk;
			/* garantir uniformite des flags */
            
			if (!calcBeam)	/* on ne se limite pas au calcul des queues */
			{	
                ((MusNote*)chk->m_layerElement)->m_stemLen = extern_q_auto;
				if (!extern_q_auto)	((MusNote*)chk->m_layerElement)->m_stemDir = extern_queue;
				if ( !fb._liaison && (((MusNote*)chk->m_layerElement)->m_slur[0] & SLUR_TERMINAL)) {
					fb._liaison = ON;
                }
                /***if (chk->grp==END) {	
                 fb._grp = ON; 
                 group.fin = chk;
                 }***/
			}
			/***if (!fb.mrq_port && chk->_shport) {
             fb.mrq_port = chk->_shport;
             }***/
            
			(crd+ct)->a = chk->m_x_abs + chk->m_layerElement->m_hOffset - m_layout->m_env.m_stemWidth / 2;		/* enregistrement des coord. */
			(crd+ct)->vlr = k;
			if (((MusNote*)chk->m_layerElement)->m_breakSec && ct)
			/* enregistr. des ruptures de beaming; des la 2e note;(autrement idiot)*/
				*(st_rl + (cpte_stop++)) = ct;
            
			/***if (extern_q_auto && chk->chord)
             {	bch.markchrd=ON;
             fb.flsht = fb.flsht ? fb.flsht : chk->_shport;
             }***/
            if (chk->IsNote())	// Çviter de prendre en compte silences
            {			shortest = max (k,shortest);
                if (!fb.mq_val && k != valref)
                    fb.mq_val = ON; /* plus d'une valeur est presente*/
                valref = min (k,valref);
            }
			ct++;
		}
		if (((MusNote*)chk->m_layerElement)->m_beam[0] & BEAM_TERMINAL) 
            break;
		chk = layer->GetNext(chk);
		if (chk == NULL) { 
            layer->beamListPremier = NULL;
            return;
        }
	}	while (ct < NbREL);
    
    // SECURITE : EVITER DE BARRER UN ACCORD ISOLE...
	if (chk->IsNote() && (((MusNote*)chk->m_layerElement)->m_chord & CHORD_TERMINAL)  && (chk->m_x_abs == layer->beamListPremier->m_x_abs))
	{	chk = layer->beamListPremier;
		do {	
            ((MusNote*)chk->m_layerElement)->m_beam[0] = 0;
            chk = layer->GetNext(chk);
        }	while (chk && chk->IsNote() && !((MusNote*)chk->m_layerElement)->m_chord & CHORD_TERMINAL);
		layer->beamListPremier = NULL;
		return;
	}
    
    wxLogDebug("ct %d", ct );
    
	_ct = ct - 1;		/* compte d'entree moins 1 */
    
	/* ici, verifier la provenance (haut/bas) des queues en cas de
     partage entre portees, et repasser la liste */
    /***
     if (fb.mrq_port)
     // le y le plus haut est dans _yy[0] 
     {	if (fb.mrq_port==1)
     {	_yy[0] = (this != phead) ? staff->ptr_pp->m_y_drawing : staff->m_y_drawing; 
     _yy[1] = staff->m_y_drawing;
     }
     else
     {	_yy[1] = (this != ptail) ? staff->ptr_fp->m_y_drawing : staff->m_y_drawing; 
     _yy[0] = staff->m_y_drawing;
     }
     }
     ***/
	for (i = 0; i < ct; i++)
	{	switch (fb.mrq_port)
		{	case 0: crd[i].prov = OFF;
                (crd+i)->b = crd[i].chk->m_y_drawing+staff->m_y_drawing;
                break;
			case 1: if (crd[i].chk->m_layerElement->m_staffShift)
            {	crd[i].prov = ON;
                (crd+i)->b = crd[i].chk->m_y_drawing + _yy[0];
            }
            else
            {	crd[i].prov = OFF;
                (crd+i)->b = crd[i].chk->m_y_drawing + _yy[1];
            }
                break;
			case 2: if (crd[i].chk->m_layerElement->m_staffShift)
            {	crd[i].prov = OFF;
                (crd+i)->b = crd[i].chk->m_y_drawing + _yy[1];
            }
            else
            {	crd[i].prov = ON;
                (crd+i)->b = crd[i].chk->m_y_drawing + _yy[0];
            }
		}
		high= max ((double)(crd+i)->b,high);		/* enregistrement des extremes */
		low = min ((double)(crd+i)->b,low);
        /* lie au choix, plus bas, d'introduire l'accelerateur pour sy_up...
         if ((crd+i)->b==high) highIndice = i;
         if ((crd+i)->b==low) lowIndice = i;
         */
		y_moy += crd[i].b;
	}
    /***
     if (provshp)
     shportee (provshp);
     ***/
    
	if (ct<2) {
        layer->beamListPremier = NULL;
		return;		/* test erreur input */
    }
    
    
	fb.dir = OFF;
	if (extern_q_auto && (!fb.mrq_port)) /*** || (bch.inpt && bch.markchrd))) ***/
	/* direction queues: auto = moyenne */
	/* bch.inpt: le flot de donnees a ete envoye par input et non rd_objet */
	{	
        milieu = _yy[0] - (m_layout->m_staffSize[staff->staffSize] + m_layout->m_interl[staff->staffSize] * 2);
		y_moy /= ct;
		if ( y_moy <  milieu )
			fb.dir = ON;
        
		if (bch.inpt && bch.markchrd)
		/* entree de input: de l'accord est dans l'air */
		{	if (!fb.flsht)
            return;  //(fb.dir+1);
        else
            return; //(fb.flsht+2);
            /* ce sera la valeur de bch.beam_chrd retournee a input; beam() sera
             rappelee par corrchrd() qui se sert de bch. ... */
		}
	}
	else
		fb.dir = extern_queue;	// si mrq_port, dir tjrs egal a m_stemDir
    
    if (crd[_ct].chk->m_layerElement->m_cueSize == false)
    {
        deltanbbar = m_layout->m_beamWidth[staff->staffSize];
        deltablanc = m_layout->m_beamWhiteWidth[staff->staffSize];
    }
    else
    {	deltanbbar = max (2, (m_layout->m_beamWidth[staff->staffSize]/2));
        deltablanc = max (2, (m_layout->m_beamWhiteWidth[staff->staffSize]-1));
    }
	deltabar = deltanbbar + deltablanc;
    
    
    /* Calcul des sommes et facteurs s_y, s_xy necessaires a la regression.
     La regression se base sur les sommets des queues, calculÇs en ajoutant un
     Çcart standard fonction de la valeur la plus breve enregistree. Direction
     connue, donc ajout ou retrait de l'ecart, et correction du x d'origine en
     fonction de la direction.*/
    
    /***
     if (crd[_ct].chk->existDebord)
     {	ptdebord = (Debord *)chk->pdebord;
     ptdebord ++;	// pointe sur valeurs
     ptBeamEd = (BeamEdit *)ptdebord;
     iHauteur = ptBeamEd->iHauteur;
     fPente = ptBeamEd->fPente;
     BeamEd = *ptBeamEd;
     }
     else ***/
    {	
        iHauteur = 0;
        fPente = 0.0;
    }
    
    /***
     if (fb.mrq_port && extern_q_auto)
     // deux portees concernees (partage), en mode automatique 
     {	ecart = e_t->m_layout->m_interl[staff->staffSize]*6;
     for (i=0; i<ct; i++)
     {	if ((crd+i)->prov)
     {	(crd+i)->a -= dx[crd[i].chk->dimin];
     *(_ybeam+i) = crd[i].b - ecart;
     crd[i].chk->m_stemDir = 0;
     }
     else
     {	(crd+i)->a += dx[crd[i].chk->dimin];
     *(_ybeam+i) = crd[i].b + ecart;
     crd[i].chk->m_stemDir = 1;
     }
     s_y += _ybeam[i];
     s_x += crd[i].a;
     s_x2 += crd[i].a * crd[i].a;
     s_xy += crd[i].a * _ybeam[i];
     }
     }
     else ***/
    
	// une seule portee; on tient compte de la direction precedemment calculee*/
	{	
        ecart = ((shortest-DUR_8)*(deltabar));
        
		if (crd[_ct].chk->m_layerElement->m_cueSize)
			ecart += m_layout->m_halfInterl[staff->staffSize]*5;
		else
            //   Le 24 Septembre 1993: obtenir des DUR_8 reliees a la hauteur des separees 
			ecart += (shortest > DUR_8) ? m_layout->m_interl[staff->staffSize]*hauteurBarreMoyenne : m_layout->m_interl[staff->staffSize]*(hauteurBarreMoyenne+0.5);
        
		if (!fb.dir && !staff->notAnc)
		{	dx[0] = - dx[0];
			dx[1] = - dx[1];
		}
        /***
         if (crd[_ct].chk->existDebord) {
         ecart = m_layout->m_interl[0]*2;
         if (!fb.mrq_port) extern_q_auto= 0;
         }
         ***/
        
		ecart = (fb.dir ? ecart : -ecart);
        
		y_moy += ecart;
		if (extern_q_auto && ((fb.dir && y_moy <  milieu) || (!fb.dir && y_moy > milieu)) )
			ecart += milieu-y_moy;
        
		for (i=0; i<ct; i++)
		{	*(_ybeam+i) = crd[i].b + ecart;
			(crd+i)->a +=  dx[crd[i].chk->m_layerElement->m_cueSize];
			s_y += _ybeam[i];
 			s_y2 += _ybeam[i] * _ybeam[i];
			s_x += crd[i].a;
			s_x2 += crd[i].a * crd[i].a;
			s_xy += crd[i].a * _ybeam[i];
            if ( crd[i].chk->IsNote() ) {
                ((MusNote*)crd[i].chk->m_layerElement)->m_stemDir = fb.dir;
            }
		}
        
	}
    
	y1 = ct * s_xy - s_x * s_y;
	xr = ct * s_x2 - s_x * s_x;
    
	if (y1 && xr)	// securite: eviter division par 0 si deux x identiques
		dB = y1 / xr;
	else
		dB = 0.0;
	/* Correction esthetique : */
	if (fabs(dB) < m_layout->m_beamMinSlope ) dB = 0.0;
	if (fabs(dB) > m_layout->m_beamMaxSlope ) dB = (dB>0) ? m_layout->m_beamMaxSlope : - m_layout->m_beamMaxSlope;
	/* pente correcte: entre 0 et env 0.4 (0.2 a 0.4) */
    
    if (fPente)
        dB += fPente;
    
	dA = (s_y - dB * s_x) / ct;
    
    
	h = cpte_stop ? 1 : (!fb.mq_val ? (shortest - DUR_4) : 1); /***((fb.mrq_port && extern_q_auto)?(valref-DUR_4):1));***/
    /* nombre de barres a dessiner */
    
    
	/* flag condition: pour eviter tests complexes repetes in boucles;
	 * concerne les cas de partages entre portees. Vrai si pas de stop-rel
	 * (i.e. possibilite de plusieurs barres communes traversantes) */
    
	fb.fl_cond = OFF;
    
    /***
     if (fb.mrq_port && extern_q_auto)
     fb.fl_cond = ON;	// independamment de mq_val
     ***/
    
	if (fb.fl_cond)
	/*valeur pour allonger queues si partage entre portees et mode autom.*/
	{
		i = deltabar * h - deltablanc;	/* nombre de points de dec */
		j = i / 2;
		sy_dec[0] = j;
		sy_dec[1] = -sy_dec[0];
        
		if ( i % 2)
			sy_dec[1] -= 1;
		sy_dec_moy = sy_dec[0] + abs (sy_dec[1]);
	}
    
    if (iHauteur)
        dA += iHauteur;
    
	/* calcul du ybeam des queues */
	for ( i=0; i<ct; i++ )
	{	xr = *(_ybeam+i);	/* xr, variable de travail */
		*(_ybeam+i)= dA + sy_up + dB * crd[i].a;
		if (fb.fl_cond)
			*(_ybeam+i) += sy_dec [crd[i].prov];
		
		/* test pour garantir l'absence de recoupement */
        if (!iHauteur)
            if (!fb.mrq_port || !extern_q_auto)
            {	if ((fb.dir && xr > *(_ybeam+i)) || (!fb.dir && xr < *(_ybeam+i)))
            {	sy_up += xr - *(_ybeam+i);
                i = -1;	/* on refait la boucle avec un sy_up */
            }
            }	
        
        
	}
    
	if (calcBeam) return;
    
    
    
	/* dessin de la barre pilote et des queues */
    
	for (i=0; i<ct; i++)
	{
		if (fb.fl_cond)	/* esth: eviter que queues depassent barres */
		{	if (crd[i].prov)	/* venant du haut, m_stemDir en bas */
        {	/***fy1 = *(_ybeam+i)+v_pnt;***/	/* on raccourcit m_stemDir */
            fy2 = crd[i].b-m_layout->m_verticalUnit2[staff->staffSize];
        }
        else
        {	/***fy1 = *(_ybeam+i)-e_t->v_pnt;***/	/* on allonge m_stemDir */
            fy2 = crd[i].b+m_layout->m_verticalUnit2[staff->staffSize];
        }
		}
		else	// on tient compte de l'Çpaisseur qui fait des "bosses"
		{	if (fb.dir)	// m_stemDir en haut
        {	fy1 = *(_ybeam+i) - m_layout->m_env.m_stemWidth;
            fy2 = crd[i].b+m_layout->m_verticalUnit2[staff->staffSize];
        }
        else
        {	fy1 = *(_ybeam+i) + m_layout->m_env.m_stemWidth;
            fy2 = crd[i].b-m_layout->m_verticalUnit2[staff->staffSize];
        }
		}
		if ((crd+i)->chk->IsNote() && ((MusNote*)(crd+i)->chk)->m_headshape != SANSQUEUE)
		{	
            v_bline (dc,fy2, fy1, crd[i].a, m_layout->m_env.m_stemWidth);
            
            // ICI, bon endroit pour enfiler les STACCATOS - ne sont traitÈs ici que ceux qui sont opposÈs ‡ la tÍte (les autres, in wgnote.cpp)
			if (((MusNote*)(crd+i)->chk)->m_artic
                && (!((MusNote*)(crd+i)->chk)->m_chord || (((MusNote*)(crd+i)->chk)->m_chord & CHORD_TERMINAL)))
                // les cas non traitÈs par note()
            /*			{	if (fb.dir || (fb.mrq_port && m_stemLen && !crd[i].prov))
             putStacc (dc,crd[i].a-dx[crd[i].chk->dimin],fy1+e_t->m_layout->m_interl[staff->staffSize]-staff->m_y_drawing, 0,crd[i].chk->typStac);
             else
             putStacc (dc,crd[i].a-dx[crd[i].chk->dimin],fy1-e_t->m_layout->m_interl[staff->staffSize]-staff->m_y_drawing, -1,crd[i].chk->typStac);
             }
             */
			{	
                /***if (fb.mrq_port && extern_q_auto)
                 {	if (crd[i].prov)
                 putStacc (dc,crd[i].a+dx[crd[i].chk->dimin],fy1-e_t->m_layout->m_interl[staff->staffSize]-staff->m_y_drawing, -1,crd[i].chk->typStac);
                 else
                 putStacc (dc,crd[i].a-dx[crd[i].chk->dimin],fy1+e_t->m_layout->m_interl[staff->staffSize]-staff->m_y_drawing, 0,crd[i].chk->typStac);
                 }
                 else if (fb.dir)
                 putStacc (dc,crd[i].a-dx[crd[i].chk->dimin],fy1+e_t->m_layout->m_interl[staff->staffSize]-staff->m_y_drawing, 0,crd[i].chk->typStac);
                 else
                 putStacc (dc,crd[i].a-dx[crd[i].chk->dimin],fy1-e_t->m_layout->m_interl[staff->staffSize]-staff->m_y_drawing, -1,crd[i].chk->typStac);
                 ***/
			}
            
		}
        
	}
    
    // NOUVEAU
    // Correction des positions x extremes en fonction de l'Çpaisseur des queues
	(*crd).a -= (m_layout->m_env.m_stemWidth-1) / 3;
	(crd+_ct)->a += (m_layout->m_env.m_stemWidth-1) / 3;
    
	delt_y = (!fb.dir || fb.fl_cond ) ? 1.0 : -1.0;
	/* on choisit une direction pour faire le premier paquet horizontal */
    
	fy1 = *_ybeam; fy2 = *(_ybeam+_ct);
    
    
	if (fb.fl_cond)
    /* reequilibrage du tir horizontal: on aligne les beams sur les queues
     qui ont ete allongees selon leur direction pour couvrir l'epaisseur */
        
	{
		if (!crd[0].prov) fy1 -=  sy_dec_moy;
		if (!crd[_ct].prov) fy2 -= sy_dec_moy;
	}
    
	fx1 = (*crd).a; fx2 = (crd+_ct)->a;
    
    
	/* dessin des barres supplementaires jusqu'a concurrence de la valeur
	 *  minimum commune a tout le groupe: i.e. une seule s'il y a des "stoprel"
	 *  (fragmentation de beaming), ou sinon valref (ou h).
     */
	/* chk->cone est le flag des cones d'acc. et ralent. */
	//s_y = crd[0].chk->cone ? 0.0 : delt_y; // removed in ax2
	//s_y2 = (crd+_ct)->chk->cone ? 0.0 : delt_y; // removed in ax2
	s_y = delt_y; // removed in ax2
	s_y2 = delt_y; // removed in ax2
    
	for (j=0; j<h ; j++)
	{
		decalage = hGrosseligne (dc,fx1,fy1,fx2,fy2, deltanbbar*delt_y /***, workColor2***/);
		fy1 += decalage; fy2 += decalage;
        
        /* ici, redescendre  de l'epaisseur de la barre s'il y a accele */
		if (!s_y)
			fy1 += (deltanbbar * delt_y) * -1;
		else
			fy1 += s_y*deltablanc;
		if (!s_y2)
			fy2 += (deltanbbar * delt_y) * -1;
		else
			fy2 += s_y2*deltablanc;
	}
    
	/* calcul des x en cas de beaming multiple */
	/* parcours horizontal ajoutant barres en fonction de m_dur la plus 
     breve (shortest), controle par boucle while; la premiere boucle for
     controle le nombre d'etapes horizontales du parcours (par le nombre
     de commandes '+' enregistrees); la deuxieme boucle for teste pour
     chaque paquet entre deux '+' les valeurs; elle construit une array de 
     marqueurs partitionnant les sous-groupes; la troisieme boucle for est
     pilotee par l'indice de l'array; elle dessine horizontalement les barres 
     de chaque sous-groupe en suivant les marqueurs */ 
    
    
	/* cpte_stop=0 ? pas de rupture de beaming*/
    
    if (fb.mq_val || cpte_stop)	/* deuxieme partie du test */
    {
        valtest = DUR_8 + h;
        
        if ( fb.fl_cond )
        {	barre_y = deltablanc + sy_dec_moy;
            /* = decalage entre bout de m_stemDir et position acquise des barres */
        }
        else	/* pas de partage entre portees */
            
            barre_y = deltabar;
        
        /* h contient nombre de barres communes deja dessinees */
        if (fb.dir)	/* queues ascendantes: on descend */
            barre_y = -barre_y;
        
        while (valtest <= shortest)
        {	t = 0; si = 0;
            for (i=0; i<=cpte_stop; i++)	/* 1e boucle for */
            {	h = (*(st_rl+si) ? *(st_rl+si) : ct);
                /* var. test controlant 2e boucle for suivante
                 * en fonction du compteur de "+" */
                /*ici, t=j, i.e. increment des pos. de notes. On s'occupe maintenant de
                 l'ensemble des valeurs contenues dans un groupe marque par cpte_stop. C'est
                 la qu'il faut changer les signes des valeurs delta d'increment vertical.*/
                
                for(k=0; k<MAX_MIF; k++)	/* initialisation*/
                {	mx_i[k]=my_i[k]=mx_f[k]=my_f[k]=0;}
                
                for (j=t,_mif=0,m_i[_mif]=0; j < h; j++)	/* 2e boucle. */
                {	/* j<h : st_rl est trop loin de un cran */
                    
                    /* Ici, dÇcision si SILENCE doit ou non avoir des barres; si oui, ligne
                     suivante (condition: il doit etre pris aussi dans les crd plus haut):*/
                    if (((crd+j)->vlr) >= (unsigned int)valtest)	
                    /*	si NON, alors: */
                        // if (((crd+j)->vlr) >= valtest && (crd+j)->chk->sil == _NOT)	
                    {
                        /*place marqueurs pour m_dur.egales/superieures
                         * a valtest en cours */
                        mx_f[_mif] = crd[j].a; 
                        my_f[_mif] = *(_ybeam+j);
                        if(!mx_i[_mif])
                        {	mx_i[_mif] = crd[j].a;
                            my_i[_mif] = *(_ybeam+j);
                            if (!_mif) apax = j;
                            if (!crd[j].prov)
                            /* enregistre les cas ou delta y est neg.*/
                                m_i[_mif] = 1;
                        }
                    }
                    /* rupture de chaine: on passe a un 2e groupe
                     * de marqueurs */
                    else if(mx_i[_mif])
                    {	_mif++;	/*incr. s'il y a un marq.*/
                        m_i[_mif] = 0;
                    }
                }
                
                fbarre_y = barre_y;	/* stockage */
                for (k=0; k<=min((mx_f[_mif]?_mif:(_mif-1)),MAX_MIF); k++)
                {
                    /* "constantes" de corr. definissant origine du calcul des
                     * y, dans les cas de partage entre portees automatiques;
                     * (construction anterieure en montant si fl_cond) */
                    if ( fb.fl_cond)
                    {	barre_y = abs(fbarre_y); delt_y = abs (delt_y);
                        
                        if (m_i[k])		/* i.e. portee inf. (!crd[j].prov) */
                        {	barre_y = -barre_y;
                            delt_y = -delt_y;
                            sy_up = sy_dec[0];	/* valeur positive */
                        }
                        
                        else
                            sy_up = sy_dec[1];	/* valeur negative */
                        
                    }
                    
                    
                    /* on passe en revue, horizontalement, les marqueurs
                     * enregistres pour ce  groupe, en s'assurant que le
                     * max MAX_MIF n'est pas depasse */
                    if (mx_i[k] == mx_f[k])		/* une seule position concernee */
                    {
                        if (apax == t && k==0 && mx_i[k] != crd[_ct].a)	/* au debut du paquet */
                        {	fy1 = my_i[k] + barre_y;
                            mx_f[k] = mx_i[k] + m_layout->m_ledgerLine[staff->staffSize][0];
                            fy2 = dA + sy_up + barre_y + dB * mx_f[k];
                            
                            decalage= hGrosseligne (dc,mx_i[k],fy1,mx_f[k],fy2,deltanbbar*delt_y /***, workColor2***/ );
                            fy1 += decalage; fy2 += decalage;
                            
                        }
                        else		/* corps ou fin de paquet */
                        {	fy2 = my_i[k] + barre_y;
                            mx_i[k] -= m_layout->m_ledgerLine[staff->staffSize][0];
                            fy1 = dA + sy_up + barre_y + dB * mx_i[k];
                            decalage= hGrosseligne (dc,mx_i[k],fy1,mx_f[k],fy2,deltanbbar*delt_y /***,workColor2***/);
                            fy1 += decalage; fy2 += decalage;
                            
                        }
                    }
                    else if (mx_i[k])		/* s'il y a un marqueur */
                    {	fy1 = my_i[k] + barre_y;
                        fy2 = my_f[k] + barre_y;
                        decalage= hGrosseligne (dc,mx_i[k],fy1,mx_f[k],fy2,deltanbbar*delt_y /***,workColor2***/);
                        fy1 += decalage; fy2 += decalage;
                        
                    }				
                }	/* fin de boucle testant sous-ensembles marques _mif*/
                
                if ( fb.fl_cond)	/* retablissement des valeurs positives */
                {	barre_y = abs(fbarre_y);
                    delt_y =  abs(delt_y);
                }
                
                if (*st_rl)
                {	si++; t = j;} 
                else t = 0;
            }			/* fin de premiere boucle for */
            
            valtest += 1;	/* increments de valeur et d'espace */
            barre_y += delt_y*deltabar;
        }			/* fin de boucle while */
    }				/*fermeture de la deuxieme partie du test */
    
	/***beamPremier = layer->beamListPremier;***/
	layer->beamListPremier = NULL;
    
    /***
     if (fb._grp)	// group.fin)
     {	e_t->rel = OFF; 
     rythmeInf(dc);
     }
     ***/
    
    
	if (fb._liaison)
		return;	
    
    /*	1111, code retourne pour appeler liais_note (NULL) apres beam(): on
     evite ainsi le risque d'appel recursif de beam. C'est le code de la
	 liaison "retardee": la direction des
     queues n'etait pas encore connue de liais_note lorsque la liaison a
     ete demandee, puisqu' elle est calculee (en mode automatique) par
     la presente fonction (et placee dans le bit m_stemDir); le code NULL
     permet un test d'association avec variable "attente" in
     liais_note (attente est engendree par coincidence rel && m_stemLen inter-
     disant le choix de la direction de liaison); ainsi NULL && attente 
     permettent d'entrer dans l'algoritme */ 
    
	return;	
}				/* fermeture de la fonction */
Example #14
0
    void draw_quad(int qi, int qj,
		   vector<int>& imin, vector<int>& imax
	) {
	int i,j;
	double u, v;
	double v0, v1, v2, v3, v4;
	// Coordonnees du quad dans l'offscreen
	double ax = (X.value(qj+0,qi+0)-x1)*m_dx, ay=(Y.value(qj+0,qi+0)-y1)*m_dy;
	double bx = (X.value(qj+0,qi+1)-x1)*m_dx, by=(Y.value(qj+0,qi+1)-y1)*m_dy;
	double cx = (X.value(qj+1,qi+1)-x1)*m_dx, cy=(Y.value(qj+1,qi+1)-y1)*m_dy;
	double dx = (X.value(qj+1,qi+0)-x1)*m_dx, dy=(Y.value(qj+1,qi+0)-y1)*m_dy;
	// indice des sommets (A,B,C,D)<->0,1,2,3<->(qi,qj),(qi+1,qj),(qi+1,qj+1),(qi,qj+1)
	// trie par ordre x croissant ou y croissant (selon xarg, yarg)
	double ymin = min(ay,min(by,min(cy,dy)));
	double ymax = max(ay,max(by,max(cy,dy)));

	int i0 = int(ymin+.5);
	int i1 = int(ymax+.5);
//	printf("Quads: i=%d->%d\n", i0, i1);

	if (i0<0) i0=0;
	if (i1>=D.ni) i1=D.ni-1;
	if (i1<i0) return;

	iymin = min(iymin,i0);
	iymax = max(iymax,i1);
	for(i=i0;i<=i1;++i) {
	    imax[i]=-1;
	    imin[i]=D.nj;
	}

	// Compute the rasterized border of the quad
	bool visible = false;
	visible |= vert_line(ax,ay,bx,by,D.nj,imin,imax, border, 0xff000000, D);
	visible |= vert_line(bx,by,cx,cy,D.nj,imin,imax, border, 0xff000000, D);
	visible |= vert_line(cx,cy,dx,dy,D.nj,imin,imax, border, 0xff000000, D);
	visible |= vert_line(dx,dy,ax,ay,D.nj,imin,imax, border, 0xff000000, D);
	if (!visible)
	    return;

	double ex = ax+cx-dx-bx;
	double ey = ay+cy-dy-by;
	double n = 1./sqrt((cx-ax)*(cx-ax)+(cy-ay)*(cy-ay));
	if (n>1e2) n = 1.0;

	// Normalize vectors with ||AC||
	ax *= n; ay *= n;
	bx = bx*n-ax; by = by*n-ay;
	cx = cx*n-ax; cy = cy*n-ay;
	dx = dx*n-ax; dy = dy*n-ay;
	ex *= n; ey *= n;

	v1 = Z.value(qj,qi);
	v2 = Z.value(qj+1,qi);
	v3 = Z.value(qj+1,qi+1);
	v4 = Z.value(qj,qi+1);

	if (isnan(v1) || isnan(v2) || isnan(v3) || isnan(v4)) {
	    // XXX Color = Alpha
	    return ;
	}
	int dm=0, dM=0;
	if (border) {
	    dm=1;dM=-1;
	}
	npy_uint32 col = scale.eval( v1*(1-vflat)*(1-uflat) +
				 v2*  vflat  *(1-uflat) +
				 v3*  vflat  *  uflat   +
				 v4*(1-vflat)*  uflat   );
	for(i=i0+dm;i<=i1+dM;++i) {
	    ixmin = min(ixmin,imin[i]);
	    ixmax = max(ixmax,imax[i]);
	    int jmin=max(0,imin[i])+dm;
	    int jmax=min(imax[i],D.nj-1)+dM;
	    for(j=jmin;j<=jmax;++j) {
		if (!flat) {
		    params(j*n,i*n, ax,ay, bx,by, cx,cy, dx,dy, ex,ey, u,v);
		    if (u<0) u=0.; else if (u>1.) u=1.;
		    if (v<0) v=0.; else if (v>1.) v=1.;
		    /* v0 = v1*(1-v)*(1-u) + v2*v*(1-u) + v3*v*u + v4*(1-v)*u; */
		    v0 = u*( v*(v1-v2+v3-v4)+v4-v1 ) + v*(v2-v1) + v1;
		    col = scale.eval(v0);
		}
		D.value(j,i) = col;
	    }
	}
    }
NonlinearCGUtils::ESolveReturn
NonlinearCG<Scalar>::doSolve(
  const Ptr<Thyra::VectorBase<Scalar> > &p_inout,
  const Ptr<ScalarMag> &g_opt_out,
  const Ptr<const ScalarMag> &g_reduct_tol_in,
  const Ptr<const ScalarMag> &g_grad_tol_in,
  const Ptr<const ScalarMag> &alpha_init_in,
  const Ptr<int> &numIters_out
  )
{

  typedef ScalarTraits<Scalar> ST;
  typedef ScalarTraits<ScalarMag> SMT;
  
  using Teuchos::null;
  using Teuchos::as;
  using Teuchos::tuple;
  using Teuchos::rcpFromPtr;
  using Teuchos::optInArg;
  using Teuchos::inOutArg;
  using GlobiPack::computeValue;
  using GlobiPack::PointEval1D;
  using Thyra::VectorSpaceBase;
  using Thyra::VectorBase;
  using Thyra::MultiVectorBase;
  using Thyra::scalarProd;
  using Thyra::createMember;
  using Thyra::createMembers;
  using Thyra::get_ele;
  using Thyra::norm;
  using Thyra::V_StV;
  using Thyra::Vt_S;
  using Thyra::eval_g_DgDp;
  typedef Thyra::Ordinal Ordinal;
  typedef Thyra::ModelEvaluatorBase MEB;
  namespace NCGU = NonlinearCGUtils;
  using std::max;

  // Validate input

  g_opt_out.assert_not_null();

  // Set streams

  const RCP<Teuchos::FancyOStream> out = this->getOStream();
  linesearch_->setOStream(out);

  // Determine what step constants will be computed

  const bool compute_beta_PR =
    (
      solverType_ == NCGU::NONLINEAR_CG_PR_PLUS
      ||
      solverType_ == NCGU::NONLINEAR_CG_FR_PR
      );

  const bool compute_beta_HS = (solverType_ == NCGU::NONLINEAR_CG_HS);

  //
  // A) Set up the storage for the algorithm
  //
  
  const RCP<DefaultPolyLineSearchPointEvaluator<Scalar> >
    pointEvaluator = defaultPolyLineSearchPointEvaluator<Scalar>();

  const RCP<UnconstrainedOptMeritFunc1D<Scalar> >
    meritFunc = unconstrainedOptMeritFunc1D<Scalar>(
      model_, paramIndex_, responseIndex_ );

  const RCP<const VectorSpaceBase<Scalar> >
    p_space = model_->get_p_space(paramIndex_),
    g_space = model_->get_g_space(responseIndex_);

  // Stoarge for current iteration
  RCP<VectorBase<Scalar> >
    p_k = rcpFromPtr(p_inout),        // Current solution for p
    p_kp1 = createMember(p_space),    // Trial point for p (in line search)
    g_vec = createMember(g_space),    // Vector (size 1) form of objective g(p) 
    g_grad_k = createMember(p_space), // Gradient of g DgDp^T
    d_k = createMember(p_space),      // Search direction
    g_grad_k_diff_km1 = null;         // g_grad_k - g_grad_km1 (if needed)

  // Storage for previous iteration
  RCP<VectorBase<Scalar> >
    g_grad_km1 = null, // Will allocate if we need it!
    d_km1 = null; // Will allocate if we need it!
  ScalarMag
    alpha_km1 = SMT::zero(),
    g_km1 = SMT::zero(),
    g_grad_km1_inner_g_grad_km1 = SMT::zero(),
    g_grad_km1_inner_d_km1 = SMT::zero();
  
  if (compute_beta_PR || compute_beta_HS) {
    g_grad_km1 = createMember(p_space);
    g_grad_k_diff_km1 = createMember(p_space);
  }
  
  if (compute_beta_HS) {
    d_km1 = createMember(p_space);
  }

  //
  // B) Do the nonlinear CG iterations
  //

  *out << "\nStarting nonlinear CG iterations ...\n";

  if (and_conv_tests_) {
    *out << "\nNOTE: Using AND of convergence tests!\n";
  }
  else {
    *out << "\nNOTE: Using OR of convergence tests!\n";
  }

  const Scalar alpha_init =
    ( !is_null(alpha_init_in) ? *alpha_init_in : alpha_init_ );
  const Scalar g_reduct_tol =
    ( !is_null(g_reduct_tol_in) ? *g_reduct_tol_in : g_reduct_tol_ );
  const Scalar g_grad_tol =
    ( !is_null(g_grad_tol_in) ? *g_grad_tol_in : g_grad_tol_ );

  const Ordinal globalDim = p_space->dim();

  bool foundSolution = false;
  bool fatalLinesearchFailure = false;
  bool restart = true;
  int numConsecutiveLineSearchFailures = 0;

  int numConsecutiveIters = 0;

  for (numIters_ = 0; numIters_ < maxIters_; ++numIters_, ++numConsecutiveIters) {

    Teuchos::OSTab tab(out);

    *out << "\nNonlinear CG Iteration k = " << numIters_ << "\n";

    Teuchos::OSTab tab2(out);

    //
    // B.1) Evaluate the point (on first iteration)
    //
    
    eval_g_DgDp(
      *model_, paramIndex_, *p_k, responseIndex_,
      numIters_ == 0 ? g_vec.ptr() : null, // Only on first iteration
      MEB::Derivative<Scalar>(g_grad_k, MEB::DERIV_MV_GRADIENT_FORM) );

    const ScalarMag g_k = get_ele(*g_vec, 0);
    // Above: If numIters_ > 0, then g_vec was updated in meritFunc->eval(...).

    //
    // B.2) Check for convergence
    //

    // B.2.a) ||g_k - g_km1|| |g_k + g_mag| <= g_reduct_tol

    bool g_reduct_converged = false;

    if (numIters_ > 0) {

      const ScalarMag g_reduct = g_k - g_km1;
      
      *out << "\ng_k - g_km1 = "<<g_reduct<<"\n";
      
      const ScalarMag g_reduct_err =
        SMT::magnitude(g_reduct / SMT::magnitude(g_k + g_mag_));
      
      g_reduct_converged = (g_reduct_err <= g_reduct_tol);
      
      *out << "\nCheck convergence: |g_k - g_km1| / |g_k + g_mag| = "<<g_reduct_err
           << (g_reduct_converged ? " <= " : " > ")
           << "g_reduct_tol = "<<g_reduct_tol<<"\n";
      
    }

    // B.2.b) ||g_grad_k|| g_mag <= g_grad_tol

    const Scalar g_grad_k_inner_g_grad_k = scalarProd<Scalar>(*g_grad_k, *g_grad_k);
    const ScalarMag norm_g_grad_k = ST::magnitude(ST::squareroot(g_grad_k_inner_g_grad_k));

    *out << "\n||g_grad_k|| = "<<norm_g_grad_k << "\n";

    const ScalarMag g_grad_err = norm_g_grad_k / g_mag_;

    const bool g_grad_converged = (g_grad_err <= g_grad_tol);

    *out << "\nCheck convergence: ||g_grad_k|| / g_mag = "<<g_grad_err
         << (g_grad_converged ? " <= " : " > ")
         << "g_grad_tol = "<<g_grad_tol<<"\n";

    // B.2.c) Convergence status
    
    bool isConverged = false;
    if (and_conv_tests_) {
      isConverged = g_reduct_converged && g_grad_converged;
    }
    else {
      isConverged = g_reduct_converged || g_grad_converged;
    }

    if (isConverged) {
      if (numIters_ < minIters_) {
        *out << "\nnumIters="<<numIters_<<" < minIters="<<minIters_
             << ", continuing on!\n";
      }
      else {
        *out << "\nFound solution, existing algorithm!\n";
        foundSolution = true;
      }
    }
    else {
      *out << "\nNot converged!\n";
    }
    
    if (foundSolution) {
      break;
    }

    //
    // B.3) Compute the search direction d_k
    //

    if (numConsecutiveIters == globalDim) {

      *out << "\nThe number of consecutive iterations exceeds the"
           << " global dimension so restarting!\n";

      restart = true;

    }

    if (restart) {

      *out << "\nResetting search direction back to steppest descent!\n";

      // d_k = -g_grad_k
      V_StV( d_k.ptr(), as<Scalar>(-1.0), *g_grad_k );

      restart = false;

    }
    else {
      
      // g_grad_k - g_grad_km1
      if (!is_null(g_grad_k_diff_km1)) {
        V_VmV( g_grad_k_diff_km1.ptr(), *g_grad_k, *g_grad_km1 );
      }

      // beta_FR = inner(g_grad_k, g_grad_k) / inner(g_grad_km1, g_grad_km1)
      const Scalar beta_FR =
        g_grad_k_inner_g_grad_k / g_grad_km1_inner_g_grad_km1;
      *out << "\nbeta_FR = " << beta_FR << "\n";
      // NOTE: Computing beta_FR is free so we might as well just do it!

      // beta_PR = inner(g_grad_k, g_grad_k - g_grad_km1) /
      //    inner(g_grad_km1, g_grad_km1)
      Scalar beta_PR = ST::zero();
      if (compute_beta_PR) {
        beta_PR =
          inner(*g_grad_k, *g_grad_k_diff_km1) / g_grad_km1_inner_g_grad_km1;
        *out << "\nbeta_PR = " << beta_PR << "\n";
      }

      // beta_HS = inner(g_grad_k, g_grad_k - g_grad_km1) /
      //    inner(g_grad_k - g_grad_km1, d_km1)
      Scalar beta_HS = ST::zero();
      if (compute_beta_HS) {
        beta_HS =
          inner(*g_grad_k, *g_grad_k_diff_km1) / inner(*g_grad_k_diff_km1, *d_km1);
        *out << "\nbeta_HS = " << beta_HS << "\n";
      }
      
      Scalar beta_k = ST::zero();
      switch(solverType_) {
        case NCGU::NONLINEAR_CG_FR: {
          beta_k = beta_FR;
          break;
        }
        case NCGU::NONLINEAR_CG_PR_PLUS: {
          beta_k = max(beta_PR, ST::zero());
          break;
        }
        case NCGU::NONLINEAR_CG_FR_PR: {
          // NOTE: This does not seem to be working :-(
          if (numConsecutiveIters < 2) {
            beta_k = beta_PR;
          }
          else if (beta_PR < -beta_FR)
            beta_k = -beta_FR;
          else if (ST::magnitude(beta_PR) <= beta_FR)
            beta_k = beta_PR;
          else // beta_PR > beta_FR
            beta_k = beta_FR;
        }
        case NCGU::NONLINEAR_CG_HS: {
          beta_k = beta_HS;
          break;
        }
        default:
          TEST_FOR_EXCEPT(true);
      }
      *out << "\nbeta_k = " << beta_k << "\n";

      // d_k = beta_k * d_last + -g_grad_k
      if (!is_null(d_km1))
        V_StV( d_k.ptr(), beta_k, *d_km1 );
      else
        Vt_S( d_k.ptr(), beta_k );
      Vp_StV( d_k.ptr(), as<Scalar>(-1.0), *g_grad_k );

    }
    
    //
    // B.4) Perform the line search
    //

    // B.4.a) Compute the initial step length

    Scalar alpha_k = as<Scalar>(-1.0);

    if (numIters_ == 0) {
      alpha_k = alpha_init;
    }
    else {
      if (alpha_reinit_) {
        alpha_k = alpha_init;
      }
      else {
        alpha_k = alpha_km1;
        // ToDo: Implement better logic from Nocedal and Wright for selecting
        // this step length after first iteration!
      }
    }

    // B.4.b) Perform the linesearch (computing updated quantities in process)

    pointEvaluator->initialize(tuple<RCP<const VectorBase<Scalar> > >(p_k, d_k)());

    ScalarMag g_grad_k_inner_d_k = ST::zero();

    // Set up the merit function to only compute the value
    meritFunc->setEvaluationQuantities(pointEvaluator, p_kp1, g_vec, null);

    PointEval1D<ScalarMag> point_k(ST::zero(), g_k);
    if (linesearch_->requiresBaseDeriv()) {
      g_grad_k_inner_d_k = scalarProd(*g_grad_k, *d_k);
      point_k.Dphi = g_grad_k_inner_d_k;
    }

    ScalarMag g_kp1 = computeValue(*meritFunc, alpha_k);
    // NOTE: The above call updates p_kp1 and g_vec as well!

    PointEval1D<ScalarMag> point_kp1(alpha_k, g_kp1);

    const bool linesearchResult = linesearch_->doLineSearch(
      *meritFunc, point_k, inOutArg(point_kp1), null );

    alpha_k = point_kp1.alpha;
    g_kp1 = point_kp1.phi;

    if (linesearchResult) {
      numConsecutiveLineSearchFailures = 0;
    }
    else {
      if (numConsecutiveLineSearchFailures==0) {
        *out << "\nLine search failure, resetting the search direction!\n";
        restart = true;
      }
      if (numConsecutiveLineSearchFailures==1) {
        *out << "\nLine search failure on last iteration also, terminating algorithm!\n";
        fatalLinesearchFailure = true;
      }
      ++numConsecutiveLineSearchFailures;
    }

    if (fatalLinesearchFailure) {
      break;
    }

    //
    // B.5) Transition to the next iteration
    //
    
    alpha_km1 = alpha_k;
    g_km1 = g_k;
    g_grad_km1_inner_g_grad_km1 = g_grad_k_inner_g_grad_k;
    g_grad_km1_inner_d_km1 = g_grad_k_inner_d_k;
    std::swap(p_k, p_kp1);
    if (!is_null(g_grad_km1))
      std::swap(g_grad_km1, g_grad_k);
    if (!is_null(d_km1))
      std::swap(d_k, d_km1);
    
#ifdef TEUCHOS_DEBUG
    // Make sure we compute these correctly before they are used!
    V_S(g_grad_k.ptr(), ST::nan());
    V_S(p_kp1.ptr(), ST::nan());
#endif

  }

  //
  // C) Final clean up
  //
  
  // Get the most current value of g(p)
  *g_opt_out = get_ele(*g_vec, 0);

  // Make sure that the final value for p has been copied in!
  V_V( p_inout, *p_k );

  if (!is_null(numIters_out)) {
    *numIters_out = numIters_;
  }

  if (numIters_ == maxIters_) {
    *out << "\nMax nonlinear CG iterations exceeded!\n";
  }
  
  if (foundSolution) {
    return NonlinearCGUtils::SOLVE_SOLUTION_FOUND;
  }
  else if(fatalLinesearchFailure) {
    return NonlinearCGUtils::SOLVE_LINSEARCH_FAILURE;
  }

  // Else, the max number of iterations was exceeded
  return NonlinearCGUtils::SOLVE_MAX_ITERS_EXCEEDED;

}
Example #16
0
void PoolingLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {
  if (!propagate_down[0]) {
    return;
  }
  const Dtype* top_diff = top[0]->cpu_diff();
  Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
  // Different pooling methods. We explicitly do the switch outside the for
  // loop to save time, although this results in more codes.
  caffe_set((*bottom)[0]->count(), Dtype(0), bottom_diff);
  // We'll output the mask to top[1] if it's of size >1.
  const bool use_top_mask = top.size() > 1;
  const int* mask = NULL;  // suppress warnings about uninitialized variables
  const Dtype* top_mask = NULL;
  switch (this->layer_param_.pooling_param().pool()) {
  case PoolingParameter_PoolMethod_MAX:
    // The main loop
    if (use_top_mask) {
      top_mask = top[1]->cpu_data();
    } else {
      mask = max_idx_.cpu_data();
    }
    for (int n = 0; n < top[0]->num(); ++n) {
      for (int c = 0; c < channels_; ++c) {
        for (int ph = 0; ph < pooled_height_; ++ph) {
          for (int pw = 0; pw < pooled_width_; ++pw) {
            const int index = ph * pooled_width_ + pw;
            const int bottom_index =
                use_top_mask ? top_mask[index] : mask[index];
            bottom_diff[bottom_index] += top_diff[index];
          }
        }
        bottom_diff += (*bottom)[0]->offset(0, 1);
        top_diff += top[0]->offset(0, 1);
        if (use_top_mask) {
          top_mask += top[0]->offset(0, 1);
        } else {
          mask += top[0]->offset(0, 1);
        }
      }
    }
    break;
  case PoolingParameter_PoolMethod_AVE:
    // The main loop
    for (int n = 0; n < top[0]->num(); ++n) {
      for (int c = 0; c < channels_; ++c) {
        for (int ph = 0; ph < pooled_height_; ++ph) {
          for (int pw = 0; pw < pooled_width_; ++pw) {
            int hstart = ph * stride_h_ - pad_h_;
            int wstart = pw * stride_w_ - pad_w_;
            int hend = min(hstart + kernel_h_, height_ + pad_h_);
            int wend = min(wstart + kernel_w_, width_ + pad_w_);
            int pool_size = (hend - hstart) * (wend - wstart);
            hstart = max(hstart, 0);
            wstart = max(wstart, 0);
            hend = min(hend, height_);
            wend = min(wend, width_);
            for (int h = hstart; h < hend; ++h) {
              for (int w = wstart; w < wend; ++w) {
                bottom_diff[h * width_ + w] +=
                  top_diff[ph * pooled_width_ + pw] / pool_size;
              }
            }
          }
        }
        // offset
        bottom_diff += (*bottom)[0]->offset(0, 1);
        top_diff += top[0]->offset(0, 1);
      }
    }
    break;
  case PoolingParameter_PoolMethod_STOCHASTIC:
    NOT_IMPLEMENTED;
    break;
  default:
    LOG(FATAL) << "Unknown pooling method.";
  }
}
Example #17
0
template<typename T> T _max(T a, T b, T c) { return max(max(a,b),c); }
Example #18
0
void CBumpWater::UploadCoastline(const int x1, const int y1, const int x2, const int y2)
{
	GLfloat* coastmap=NULL;
	bool usedPBO = false;

	if (pboID) {
		glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboID);
		glBufferData(GL_PIXEL_UNPACK_BUFFER, gs->mapx*gs->mapy*4*4, 0, GL_STREAM_DRAW);
		coastmap = (GLfloat*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
		usedPBO = true;
	}

	if(coastmap == NULL) {
		coastmap = new GLfloat[gs->mapx*gs->mapy*4];
		usedPBO = false;
	}

	/*for (int y = 0; y < gs->mapy; y++) {
		for (int x = 0; x < gs->mapx; x++) {
			float3& normal = readmap->facenormals[(y*gs->mapx+x)*2];
			normalmap[(y*gs->mapx+x)*4]   = normal.x;
			normalmap[(y*gs->mapx+x)*4+1] = normal.y;
			normalmap[(y*gs->mapx+x)*4+2] = normal.z;
			normalmap[(y*gs->mapx+x)*4+3] = 1;
		}
	}*/

	int xmin = max(x1 - 10*2,0);
	int xmax = min(x2 + 10*2,gs->mapx);
	int ymin = max(y1 - 10*2,0);
	int ymax = min(y2 + 10*2,gs->mapy);
	int xsize = xmax - xmin;
	int ysize = ymax - ymin;

	const float* heightMap = readmap->GetHeightmap();
	for (int y = ymin; y < ymax; ++y) {
		int yindex  = y*(gs->mapx + 1);
		int yindex2 = (y-ymin)*xsize;
		for (int x = xmin; x < xmax; ++x) {
			int index  = yindex + x;
			int index2 = (yindex2 + (x-xmin)) << 2;
			const float& height = heightMap[index];
			coastmap[index2]   = (height>0.0f)?1:0;
			coastmap[index2+1] = (height>0.0f)?1:0;
			coastmap[index2+2] = (height>0.0f)?1:0;
			coastmap[index2+3] = height;
		}
	}


	if (usedPBO) {
		glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
		glBindTexture(GL_TEXTURE_2D, coastTexture[1]);
		glTexSubImage2D(GL_TEXTURE_2D, 0, xmin, ymin, xsize,ysize, GL_RGBA, GL_FLOAT, 0);
		glBufferData(GL_PIXEL_UNPACK_BUFFER, 0, 0, GL_STREAM_DRAW); //free it
		glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
	}else{
		glBindTexture(GL_TEXTURE_2D, coastTexture[1]);
		glTexSubImage2D(GL_TEXTURE_2D, 0, xmin, ymin, xsize,ysize, GL_RGBA, GL_FLOAT, coastmap);
		delete[] coastmap;
	}
}
Example #19
0
void DPmatrixSimple::forward_cell(int i2,int j2) 
{
  assert(0 < i2 and i2 < size1());
  assert(0 < j2 and j2 < size2());

  prepare_cell(i2,j2);

  // determine initial scale for this cell
  scale(i2,j2) = max(scale(i2-1,j2), max( scale(i2-1,j2-1), scale(i2,j2-1) ) );

  double maximum = 0;

  // If we have silent states, then we have to process them in
  // the correct order: after all non-silent states and maybe
  // after some silent states.
  assert(not silent(order(nstates()-1)));

  for(int S2=0;S2<nstates();S2++) 
  {
    //--- Get (i1,j1) from (i2,j2) and S2
    int i1 = i2;
    if (di(S2)) i1--;

    int j1 = j2;
    if (dj(S2)) j1--;

    //--- Compute Arrival Probability ----
    double temp  = 0;
    for(int S1=0;S1<nstates();S1++)
      temp += (*this)(i1,j1,S1) * GQ(S1,S2);

    //--- Include Emission Probability----
    double sub;
    if (i1 != i2 and j1 != j2)
      sub = emitMM(i2,j2);
    else if (i1 != i2)
      sub = emitM_(i2,j2);
    else if (j1 != j2)
      sub = emit_M(i2,j2);
    else          // silent state - nothing emitted

      sub = emit__(i2,j2);

    temp *= sub;

    // rescale result to scale of this cell
    if (scale(i1,j1) != scale(i2,j2))
      temp *= pow2(scale(i1,j1)-scale(i2,j2));

    // record maximum
    if (temp > maximum) maximum = temp;

    // store the result
    (*this)(i2,j2,S2) = temp;
  }

  //------- if exponent is too low, rescale ------//
  if (maximum > 0 and maximum < fp_scale::cutoff) {
    int logs = -(int)log2(maximum);
    double scale_ = pow2(logs);
    for(int S2=0;S2<nstates();S2++) 
      (*this)(i2,j2,S2) *= scale_;
    scale(i2,j2) -= logs;
  }
} 
Example #20
0
void CBumpWater::UpdateCoastmap(const int x1, const int y1, const int x2, const int y2)
{
	glDisable(GL_BLEND);
	glDepthMask(GL_FALSE);
	glDisable(GL_DEPTH_TEST);

	coastFBO.Bind();

	glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, coastTexture[1]);
	glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, coastTexture[0]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glMatrixMode(GL_TEXTURE);
		glPushMatrix();
		glLoadIdentity();
		glScalef(1.0f/gs->mapx, 1.0f/gs->mapy, 1);
	glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		glOrtho(0,1,0,1,-1,1);
	glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glLoadIdentity();
		glScalef(1.0f/gs->mapx, 1.0f/gs->mapy, 1);

	glViewport(0,0,gs->mapx, gs->mapy);
	glUseProgram(blurShader);

	int xmin = max(x1 - 10*2,0);
	int xmax = min(x2 + 10*2,gs->mapx);
	int ymin = max(y1 - 10*2,0);
	int ymax = min(y2 + 10*2,gs->mapy);
	int xsize = xmax - xmin;
	int ysize = ymax - ymin;

	glUniform2f(blurDirLoc,1.0f/gs->mapx,0.0f);
	glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
	glUniform1i(blurTexLoc,1);

	glBegin(GL_QUADS);
		glTexCoord2f(xmin,ymin); glVertex2f(xmin,ymin);
		glTexCoord2f(xmin,ymax); glVertex2f(xmin,ymax);
		glTexCoord2f(xmax,ymax); glVertex2f(xmax,ymax);
		glTexCoord2f(xmax,ymin); glVertex2f(xmax,ymin);
	glEnd();

	for (int i=0; i<5; ++i){
		glUniform2f(blurDirLoc,0.0f,1.0f/gs->mapy);
		glDrawBuffer(GL_COLOR_ATTACHMENT1_EXT);
		glUniform1i(blurTexLoc,0);

		glBegin(GL_QUADS);
			glTexCoord2f(xmin,ymin); glVertex2f(xmin,ymin);
			glTexCoord2f(xmin,ymax); glVertex2f(xmin,ymax);
			glTexCoord2f(xmax,ymax); glVertex2f(xmax,ymax);
			glTexCoord2f(xmax,ymin); glVertex2f(xmax,ymin);
		glEnd();

		glUniform2f(blurDirLoc,1.0f/gs->mapx,0.0f);
		glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
		glUniform1i(blurTexLoc,1);

		glBegin(GL_QUADS);
			glTexCoord2f(xmin,ymin); glVertex2f(xmin,ymin);
			glTexCoord2f(xmin,ymax); glVertex2f(xmin,ymax);
			glTexCoord2f(xmax,ymax); glVertex2f(xmax,ymax);
			glTexCoord2f(xmax,ymin); glVertex2f(xmax,ymin);
		glEnd();
	}

	glMatrixMode(GL_TEXTURE);
		glPopMatrix();
	glMatrixMode(GL_PROJECTION);
		glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
		glPopMatrix();

	//glActiveTexture(GL_TEXTURE0);
	//glBindTexture(GL_TEXTURE_2D, coastTexture[0]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glGenerateMipmapEXT(GL_TEXTURE_2D);

	glUseProgram(0);
	glViewport(gu->viewPosX,0,gu->viewSizeX,gu->viewSizeY);

	coastFBO.Unbind();
}
Example #21
0
void ZMST::exec() {
  smst.calculateMST();
  //reserve before mass data pushing back
  lines_.reserve(smst.lines().size());
  for (int i = 0; i < (int)smst.lines().size(); i ++)
    lines_.push_back(Line_Z(smst.lines()[i].start(), smst.lines()[i].end(),
                            Point()));
  //lines is a sorted line vector, while smst.lines_ is in father-child order
  sort(lines_.begin(), lines_.end(), lineCmp);
  //make the positive direction table
  int* head = new int[points().size() + 1];
  for (int i = 0, j = 0; i <= (int)points().size() && j <= (int)lines().size(); ) {
    if (j == (int)lines().size() || line(j).start() != i - 1)
      head[i ++] = j;
    else
      j ++;
  }
  //Discretization
  int* father = new int[points().size()],
     * xgrids = new int[points().size()],
     * ygrids = new int[points().size()],
     xgridsize, ygridsize;
  for (int i = 0; i < (int)lines_.size(); i ++) {
    father[lines_[i].end()] = lines_[i].start();
  }
  father[0] = -1;
  for (int i = 0; i < (int)points().size(); i ++) {
    xgrids[i] = point(i).x();
    ygrids[i] = point(i).y();
  }
  sort (xgrids, xgrids + points().size());
  sort (ygrids, ygrids + points().size());
  xgridsize = unique(xgrids, xgrids + points().size()) - xgrids;
  ygridsize = unique(ygrids, ygrids + points().size()) - ygrids;
  vector<vector<layout> > subProb(vector<vector<layout> >(points().size(),
                                                          vector<layout>()));
  //Enumerate all layouts
  for (vector<Line_Z>::iterator it = lines_.begin();
       it != lines_.end(); ++ it) {
    int minx = min(point(it->start()).x(), point(it->end()).x()),
        maxx = max(point(it->start()).x(), point(it->end()).x()),
        miny = min(point(it->start()).y(), point(it->end()).y()),
        maxy = max(point(it->start()).y(), point(it->end()).y());
    int minxid = lower_bound(xgrids, xgrids + xgridsize, minx) - xgrids,
        maxxid = lower_bound(xgrids, xgrids + xgridsize, maxx) - xgrids,
        minyid = lower_bound(ygrids, ygrids + ygridsize, miny) - ygrids,
        maxyid = lower_bound(ygrids, ygrids + ygridsize, maxy) - ygrids;
    for (int i = minxid; i <= maxxid; i ++) {
      subProb[it->end()].push_back(Point(xgrids[i], point(it->start()).y()));
    }
    for (int i = minyid; i <= maxyid; i ++) {
      subProb[it->end()].push_back(Point(point(it->start()).x(), ygrids[i]));
    }
  }
  //Caculate from leaves to root
  int stack[6];
  for (vector<Line>::const_reverse_iterator it = smst.lines().rbegin();
       it != smst.lines().rend(); ++ it) {
    for (vector<layout>::iterator lit = subProb[it->end()].begin();
         lit != subProb[it->end()].end(); ++ lit) {
      dfs(it->end(), father[it->end()], head[it->end()], *lit, lines(),
          subProb, head, stack);
    }
  }
  subProb[0].push_back(point(0));
  dfs(0, 0, head[0], subProb[0][0], lines(), subProb, head, stack);
  getAns(0, subProb[0][0],subProb, head);
  delete []head;
  delete []xgrids;
  delete []ygrids;
  delete []father;
}
Example #22
0
int AVLTree::count_depth(node *r){
	if (r == NULL)
		return 0;
	return 1 + max(count_depth(r->left), count_depth(r->right));
}
Example #23
0
int
main(int argc, const char **argv) {

  try {

    bool VERBOSE = false;
    double sig_cutoff = 0.05;

    /****************** COMMAND LINE OPTIONS ********************/
    OptionParser opt_parse(strip_path(argv[0]), "computes DMRs based on "
        "HMRs and probability of differences at "
        "individual CpGs",
        "<methdiffs_1_gt_2> <hmr_1> <hmr_2> "
        "<dmr_1_lt_2> <dmr_2_lt_1>");
    opt_parse.add_opt("cutoff", 'c', "Significance cutoff (default: 0.05)",
        false, sig_cutoff);
    opt_parse.add_opt("verbose", 'v', "print more run info", false, VERBOSE);
    vector<string> leftover_args;
    opt_parse.parse(argc, argv, leftover_args);
    if (argc == 1 || opt_parse.help_requested()) {
      cerr << opt_parse.help_message() << endl
      << opt_parse.about_message() << endl;
      return EXIT_SUCCESS;
    }
    if (opt_parse.about_requested()) {
      cerr << opt_parse.about_message() << endl;
      return EXIT_SUCCESS;
    }
    if (opt_parse.option_missing()) {
      cerr << opt_parse.option_missing_message() << endl;
      return EXIT_SUCCESS;
    }
    if (leftover_args.size() != 5) {
      cerr << opt_parse.help_message() << endl;
      return EXIT_SUCCESS;
    }
    const string diffs_file = leftover_args[0];
    const string hmr1_file = leftover_args[1];
    const string hmr2_file = leftover_args[2];
    const string outfile_a = leftover_args[3];
    const string outfile_b = leftover_args[4];
    /****************** END COMMAND LINE OPTIONS *****************/

    if (VERBOSE)
      cerr << "[LOADING HMRS] " << hmr1_file << endl;

    vector<GenomicRegion> regions_a;
    ReadBEDFile(hmr1_file, regions_a);
    assert(check_sorted(regions_a));
    if (!check_sorted(regions_a))
      throw SMITHLABException("regions not sorted in file: " + hmr1_file);
    if (!check_no_overlap(regions_a))
      throw SMITHLABException("regions overlap in file: " + hmr1_file);

    if (VERBOSE)
      cerr << "[LOADING HMRS] " << hmr2_file << endl;

    vector<GenomicRegion> regions_b;
    ReadBEDFile(hmr2_file, regions_b);
    assert(check_sorted(regions_b));
    if (!check_sorted(regions_b))
      throw SMITHLABException("regions not sorted in file: " + hmr2_file);
    if (!check_no_overlap(regions_b))
      throw SMITHLABException("regions overlap in file: " + hmr2_file);

    if (VERBOSE)
      cerr << "[COMPUTING SYMMETRIC DIFFERENCE]" << endl;


    size_t max_end = 0;
    for (size_t i = 0; i < regions_a.size(); ++i)
      max_end = max(max_end, regions_a[i].get_end());
    for (size_t i = 0; i < regions_b.size(); ++i)
      max_end = max(max_end, regions_b[i].get_end());

    vector<GenomicRegion> a_cmpl, b_cmpl;
    complement_regions(max_end, regions_a, a_cmpl);
    complement_regions(max_end, regions_b, b_cmpl);

    vector<GenomicRegion> dmrs_a, dmrs_b;
    genomic_region_intersection_by_base(regions_a, b_cmpl, dmrs_a);
    genomic_region_intersection_by_base(regions_b, a_cmpl, dmrs_b);

    // separate the regions by chrom and by desert
    if (VERBOSE)
      cerr << "[READING CPG METH DIFFS]" << endl;
    vector<GenomicRegion> cpgs;
	read_diffs_file(diffs_file, cpgs, VERBOSE);
    if (!check_sorted(cpgs))
      throw SMITHLABException("CpGs not sorted in: " + diffs_file);
    if (VERBOSE)
      cerr << "[TOTAL CPGS]: " << cpgs.size() << endl;

    vector<pair<size_t, size_t> > sep_sites;
    separate_sites(dmrs_a, cpgs, sep_sites);

    for (size_t i = 0; i < dmrs_a.size(); ++i) {
      size_t total_cpgs = 0, total_sig = 0;
      get_cpg_stats(true, sig_cutoff,
      cpgs, sep_sites[i].first, sep_sites[i].second,
      total_cpgs, total_sig);
      dmrs_a[i].set_name(dmrs_a[i].get_name() + ":" + toa(total_cpgs));
      dmrs_a[i].set_score(total_sig);
    }

    sep_sites.clear();
    separate_sites(dmrs_b, cpgs, sep_sites);

    for (size_t i = 0; i < dmrs_b.size(); ++i) {
      size_t total_cpgs = 0, total_sig = 0;
      get_cpg_stats(false, sig_cutoff,
        cpgs, sep_sites[i].first, sep_sites[i].second,
        total_cpgs, total_sig);
      dmrs_b[i].set_name(dmrs_b[i].get_name() + ":" + toa(total_cpgs));
      dmrs_b[i].set_score(total_sig);
    }

    std::ofstream out_a(outfile_a.c_str());
    copy(dmrs_a.begin(), dmrs_a.end(),
    std::ostream_iterator<GenomicRegion>(out_a, "\n"));

    std::ofstream out_b(outfile_b.c_str());
    copy(dmrs_b.begin(), dmrs_b.end(),
    std::ostream_iterator<GenomicRegion>(out_b, "\n"));

    if (VERBOSE)
      cerr << "[OUTPUT FORMAT] COL4=NAME:N_COVERED_CPGS COL5=N_SIG_CPGS" << endl;
  }
  catch (const SMITHLABException &e) {
    cerr << e.what() << endl;
    return EXIT_FAILURE;
  }
  catch (std::bad_alloc &ba) {
    cerr << "ERROR: could not allocate memory" << endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
int
main( int argc, char* argv[])
{
  // seed for random number generator:
  int random_seed;
  // number of matrices:
  int num;
  // dimension of matrices to generate:
  int dim;
  // bound for matrix entries:
  int upper_entry_bound;
  // set of matrices to search:
  Matrix_cont matrices;
  // set of vectors the matrices are build from:
  Vector_cont vectors;
  // handle command line arguments:
  if ( argc < 4 ||
       (num = atoi(argv[1])) <= 0 ||
       (dim = atoi(argv[2])) <= 0 ||
       (upper_entry_bound = atoi(argv[3])) <= 0) {
    cerr << "usage: " << argv[0] <<
      " num dim upper_entry_bound [random_seed]" << endl;
    exit(1);
  }
  if ( argc < 5 || (random_seed = atoi(argv[4])) <= 0) {
  
    #ifdef OUTPUT
    cerr << "No random seed specified - generating it" << endl;
    #endif
  
    // generate random seed
    random_seed = get_default_random().get_int( 0, (1 << 30));
  }
  else
    random_seed = atoi(argv[4]);
  
  // define random source:
  Random r( random_seed);
  
  #ifdef OUTPUT
  cout << "random seed is " << random_seed << endl;
  #endif
  // maximum entry of all matrices:
  Value max_entry( -1);
  
  for ( int k = 0; k < num; ++k) {
    // generate two vectors a and b to build the cartesian
    // matrix from
    Vector a, b;
    assert( a.size() == 0 && b.size() == 0);
  
    // fill a and b with random values and sort them:
    for ( int i = 0; i < dim; ++i) {
      a.push_back( r( upper_entry_bound));
      b.push_back( r( upper_entry_bound));
    }
    // to test some non-quadratic matrices:
    // for ( i = 0; i < dim / 5; ++i) {
    //   b.push_back( r());
    // }
  
    sort( a.begin(), a.end(), less< Value >());
    sort( b.begin(), b.end(), less< Value >());
  
    /*
    cout << "a = (";
    for ( Vector_iterator pp( a.begin());
    pp != a.end();
    ++pp)
      cout << (*pp) << ", ";
    cout << ")\nb = (";
    for ( Vector_iterator pq( a.begin());
    pq != a.end();
    ++pq)
      cout << (*pq) << ", ";
    cout << ")" << endl;
    */
  
    // evt. update max_entry:
    max_entry = max( a[dim - 1] + b[dim - 1], max_entry);
  
    // keep both vectors:
    vectors.push_back( a);
    vectors.push_back( b);
  } // for ( int k = 0; k < num; ++k)
  
  
  // construct matrices:
  for ( Vector_iterator i( vectors.begin());
        i != vectors.end();
        i += 2)
    {
      Vector_iterator j = i + 1;
      matrices.push_back(
        Matrix( (*i).begin(), (*i).end(),
                (*j).begin(), (*j).end()));
    }
  // search lower bound for a random value v in matrices
  Value bound;
  // assure there is any feasible value in m:
  do
    bound = r.get_int( 0, 2 * upper_entry_bound);
  while ( bound > max_entry);
  
  #ifdef OUTPUT
  cout << "searching upper bound for " << bound << endl;
  #endif
  Value u(
    sorted_matrix_search(
      matrices.begin(),
      matrices.end(),
      sorted_matrix_search_traits_adaptor(
        boost::bind( greater_equal< Value >(), _1, bound),
        *(matrices.begin()))));
  
  #ifdef OUTPUT
  cout << "************* DONE *************\nresult: "
       << u << "\n********************************" << endl;
  CGAL_optimisation_assertion(
    u == compute_upper_bound(
      matrices.begin(), matrices.end(), bound, max_entry));
  #else
  Value brute_force(
    compute_upper_bound(
      matrices.begin(), matrices.end(), bound, max_entry));
  if ( u != brute_force)
    cerr << "\nerror: num( " << num << "), dim ( "
         << dim << "), upper_entry_bound( " << upper_entry_bound
         << ")\nrandom_seed( " << random_seed << ")"
         << "\nresult was " << u << "\ntrivial algorithm gives "
         << brute_force << endl;
  #endif

  return 0;
}
void
PeakConvert2::myProcess(realvec& in, realvec& out)
{
  mrs_natural o,i;
  out.setval(0);
  peakView pkViewOut(out);

  const mrs_bool useMasking	= getctrl("mrs_bool/useMasking")->to<mrs_bool>();
  const mrs_real probThresh	= getctrl("mrs_real/probabilityTresh")->to<mrs_real>();

  max_->updControl("mrs_natural/nMaximums", frameMaxNumPeaks_);

  max_->setctrl("mrs_natural/inSamples", size_);
  max_->setctrl("mrs_natural/inObservations", 1);
  max_->update();
  tmp_.stretch(frameMaxNumPeaks_*2);

  for(mrs_natural f=0 ; f < inSamples_; ++f)
  {
    //we should avoid the first empty frames,
    //that will contain silence and consequently create
    //discontinuities in the signal, ruining the peak calculation!
    //only process if we have a full data vector (i.e. no zeros)
    if(frame_ >= skip_)
    {
      // get pair of ffts
      in.getCol (f, tmpBuff_);

      // compute magnitude, phase, and instantaneous frequency
      this->ComputeMagnitudeAndPhase (tmpBuff_);

      // compute masking threshold
      if (useMasking && pick_)
        ComputeMasking (tmpBuff_);
      else
        masked_.setval(10.);

      // select bins with local maxima in magnitude (--> peaks)
      peaks_ = mag_;
      if(pick_)
        this->ComputePeaker (mag_, peaks_);
      else
      {
        for (o = 0 ; o < downFrequency_ ; o++)
          peaks_(o)=0.0;
        for (o = upFrequency_ ; o < (mrs_natural)peaks_.getSize() ; o++)
          peaks_(o)=0.0;
      }

      if (lpCoeff_ > 0)
        FreqSmear (lpPeakerRes_);

      //compute the probability of a peak being a peak
      for(o=0 ; o < size_ ; o++)
      {
        if (peaks_(o) <= 0)
        {
          frequency_(o)		= .0;
          //lastmag_(o)		= .0;
          lastfrequency_(o)	= .0;
          // time smearing if no new peak
          lpPeakerRes_(o)	*=lpCoeff_;
          continue;
        }
#ifdef ORIGINAL_VERSION
        // probability of peak being a masker
        peakProb_(0)	= 0;
        // probability of peak being stationary
        peakProb_(1)	= 0;
        // probability of peak being tonal
        peakProb_(2)	= (abs(frequency_(o)/fundamental_-o) > .5)? 0 : 1;
#else
        // probability of peak being a masker
        peakProb_(0)	= max((mrs_real).1, (mrs_real).5 * (mrs_real)(log10(masked_(o)) +1.));
        // probability of peak being stationary
        peakProb_(1)	= max((mrs_real).1, (mrs_real)lpPeakerRes_(o));
        // probability or peak being tonal
        peakProb_(2)	= GaussianPdf (frequency_(o)/fundamental_-o, gaussianStd);
#endif

        // reset lpPeakerRes with peaker results
        lpPeakerRes_(o)	= 1;

        peakProb_ *= peakProbWeight_;
        if ((peakProb_.sum() < probThresh) && pick_)
        {
          peaks_(o)		= .0;
          frequency_(o)	= .0;
          //lastmag_(o)		= .0;
          lastfrequency_(o)	= .0;
        }
      }

      // keep only the frameMaxNumPeaks_ highest amplitude local maxima
      tmp_.setval(0.);
      max_->process(peaks_, tmp_);

      nbPeaks_=tmp_.getSize()/2;
      realvec index_(nbPeaks_); //[!] make member to avoid reallocation at each tick!
      for (i=0 ; i<nbPeaks_ ; i++)
        index_(i) = tmp_(2*i+1);

      // search for bins interval
      realvec interval_(nbPeaks_*2); //[!] make member to avoid reallocation at each tick!
      interval_.setval(0);
      if(pick_)
        getShortBinInterval(interval_, index_, mag_);
      else
      {
        for (i=0 ; i<nbPeaks_ ; i++)
          interval_(2*i+1) = index_(i);
      }

#ifdef LOG2FILE
      for (i=0 ; i<nbPeaks_ ; i++)
      {
        mrs_real value = frequency_((mrs_natural) (index_(i)+.1));
        pFDbgFile << std::scientific << std::setprecision(4) << value << "\t";
      }
      pFDbgFile << std::endl;
#endif
#ifdef MARSYAS_MATLAB
#ifdef MTLB_DBG_LOG
      MATLAB_PUT(mag_, "peaks");
      MATLAB_PUT(peaks_, "k");
      MATLAB_PUT(tmp_, "tmp");
      MATLAB_PUT(interval_, "int");
      MATLAB_PUT(frequency_, "freq");
//			MATLAB_EVAL("figure(1);clf;hold on ;plot(peaks);stem(k);stem(tmp(2:2:end)+1, peaks(tmp(2:2:end)+1), 'r')");
//			MATLAB_EVAL("stem(int+1, peaks(int+1), 'k')");
      MATLAB_EVAL("figure(1);hold on ;stem(freq(tmp(2:2:end)+1), peaks(tmp(2:2:end)+1), 'r');hold off");
#endif
#endif


      // fill output with peaks data
      interval_ /= N_;

      for (i = 0; i < nbPeaks_; i++)
      {
        mrs_natural index = (mrs_natural) (index_(i)+.1);
        pkViewOut(i, peakView::pkFrequency, f) = frequency_(index);
        pkViewOut(i, peakView::pkAmplitude, f) = magCorr_(index);
        pkViewOut(i, peakView::pkPhase, f) = -phase_(index);
        pkViewOut(i, peakView::pkDeltaFrequency, f) = deltafrequency_(index);
        pkViewOut(i, peakView::pkDeltaAmplitude, f) = /*abs*/(deltamag_(index));
        pkViewOut(i, peakView::pkFrame, f) = frame_;
        pkViewOut(i, peakView::pkGroup, f) = 0.;//(pick_)?-1.:0.; //This should be -1!!!! [TODO]
        pkViewOut(i, peakView::pkVolume, f) = 1.0;
        pkViewOut(i, peakView::pkBinLow, f) = interval_(2*i);
        pkViewOut(i, peakView::pkBin, f) = index_(i);
        pkViewOut(i, peakView::pkBinHigh, f) = interval_(2*i+1);
        pkViewOut(i, peakView::pkTrack, f) = -1.0; //null-track ID

        MRSASSERT((index_(i) <= interval_(2*i)) || (interval_(2*i+1) <= index_(i)));

        if(useStereoSpectrum_)
          pkViewOut(i, peakView::pkPan, f) = in((mrs_natural)index_(i)+2*N_, f);
        else
          pkViewOut(i, peakView::pkPan, f) = 0.0;
      }
    }
    else //if not yet reached "skip" number of frames...
    {
      for(mrs_natural i=0; i< frameMaxNumPeaks_; ++i)
      {
        //pkViewOut(i, peakView::pkFrequency, f) = 0;
        //pkViewOut(i, peakView::pkAmplitude, f) = 0;
        //pkViewOut(i, peakView::pkPhase, f) = 0;
        //pkViewOut(i, peakView::pkDeltaFrequency, f) = 0;
        //pkViewOut(i, peakView::pkDeltaAmplitude, f) = 0;
        pkViewOut(i, peakView::pkFrame, f) = frame_;
        //pkViewOut(i, peakView::pkGroup, f) = -1;
        //pkViewOut(i, peakView::pkVolume, f) = 0;
        //pkViewOut(i, peakView::pkPan, f) = 0;
        //pkViewOut(i, peakView::pkBinLow, f) = 0;
        //pkViewOut(i, peakView::pkBin, f) = 0;
        //pkViewOut(i, peakView::pkBinHigh, f) = 0;
      }
    }
    frame_++;
  }

  //count the total number of existing peaks (i.e. peak freq != 0)
  ctrl_totalNumPeaks_->setValue(pkViewOut.getTotalNumPeaks());
}
Example #26
0
    void
AlignerContext::printStats()
{

    WriteStatusMessage("Total Reads    Aligned, MAPQ >= %2d    Aligned, MAPQ < %2d     Unaligned              Too Short/Too Many Ns  %s%s%sReads/s   Time in Aligner (s)\n", MAPQ_LIMIT_FOR_SINGLE_HIT, MAPQ_LIMIT_FOR_SINGLE_HIT,
        (stats->filtered > 0) ? "Filtered               " : "",
        (stats->extraAlignments) ? " Extra Alignments " : "",
        isPaired() ? "%Pairs    " : "   "
        );

	const size_t strBufLen = 50;	// Way more than enough for 64 bit numbers with commas
	char tooShort[strBufLen];
	char single[strBufLen];
	char multi[strBufLen];
	char unaligned[strBufLen];
	char numReads[strBufLen];
	char readsPerSecond[strBufLen];
	char alignTimeString[strBufLen];
    char filtered[strBufLen];
    char extraAlignments[strBufLen];
    char pctPairs[strBufLen];

    /*
                                                         total                                           total
                                                         |    single                                     |  single
                                                         |    |  multi                                   |  |  multi
                                                         |    |  |  unaligned                            |  |  |  unaligned
                                                         |    |  |  |  too short                         |  |  |  |  too short
                                                         |    |  |  |  |  filtered                       |  |  |  |  |  filtered 
                                                         |    |  |  |  |  |    extra      reads/s        |  |  |  |  |  | extra    reads/s     
                                                         |    |  |  |  |  |    |   pairs  |  time        |  |  |  |  |  | | pairs  |  time
                                                         |    |  |  |  |  |    |   |      |  |           |  |  |  |  |  | | |      |  |
                                                         v    v  v  v  v  v    v   v      v  v           v  v  v  v  v  v v v      v  v
    */
    WriteStatusMessage((stats->extraAlignments > 0) ? "%-14s %s %s %s %s %s %-16s %s   %-9s %s\n" : "%-14s %s %s %s %s %s%s%s   %-9s %s\n",
        FormatUIntWithCommas(stats->totalReads, numReads, strBufLen),
        numPctAndPad(single, stats->singleHits, 100.0 * stats->singleHits / stats->totalReads, 22, strBufLen),
        numPctAndPad(multi, stats->multiHits, 100.0 * stats->multiHits / stats->totalReads, 22, strBufLen),
        numPctAndPad(unaligned, stats->notFound, 100.0 * stats->notFound / stats->totalReads, 22, strBufLen),
        numPctAndPad(tooShort, stats->uselessReads , 100.0 * stats->uselessReads / max(stats->totalReads, (_int64)1), 22, strBufLen),
        (stats->filtered > 0) ? numPctAndPad(filtered, stats->filtered, 100.0 * stats->filtered / stats->totalReads, 23, strBufLen) : "",
        (stats->extraAlignments > 0) ? FormatUIntWithCommas(stats->extraAlignments, extraAlignments, strBufLen) : "",
		isPaired() ? pctAndPad(pctPairs,  100.0 * stats->alignedAsPairs / stats->totalReads, 7, strBufLen) : "",
		FormatUIntWithCommas((unsigned _int64)(1000 * stats->totalReads / max(alignTime, (_int64)1)), readsPerSecond, strBufLen),	// Aligntime is in ms
		FormatUIntWithCommas((alignTime + 500) / 1000, alignTimeString, strBufLen)
		);

    if (NULL != perfFile) {
        fprintf(perfFile, "%d\t%d\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%lld\t%lld\tt%.0f\n",
                maxHits_, maxDist_, 
                100.0 * (stats->totalReads - stats->uselessReads) / max(stats->totalReads, (_int64) 1),
				100.0 * stats->singleHits / stats->totalReads,
				100.0 * stats->multiHits / stats->totalReads,
				100.0 * stats->notFound / stats->totalReads,
                stats->lvCalls,
				100.0 * stats->alignedAsPairs / stats->totalReads,
                stats->totalReads,
                (1000.0 * (stats->totalReads - stats->uselessReads)) / max(alignTime, (_int64)1));

        fprintf(perfFile,"\n");
    }


#if TIME_HISTOGRAM
    WriteStatusMessage("Per-read alignment time histogram:\nlog2(ns)\tcount\ttotal time (ns)\n");
    for (int i = 0; i < 31; i++) {
        WriteStatusMessage("%d\t%lld\t%lld\n", i, stats->countByTimeBucket[i], stats->nanosByTimeBucket[i]);
    }
#endif // TIME_HISTOGRAM


    stats->printHistograms(stdout);

#ifdef  TIME_STRING_DISTANCE
    WriteStatusMessage("%llds, %lld calls in BSD noneClose, not -1\n",  stats->nanosTimeInBSD[0][1]/1000000000, stats->BSDCounts[0][1]);
    WriteStatusMessage("%llds, %lld calls in BSD noneClose, -1\n",      stats->nanosTimeInBSD[0][0]/1000000000, stats->BSDCounts[0][0]);
    WriteStatusMessage("%llds, %lld calls in BSD close, not -1\n",      stats->nanosTimeInBSD[1][1]/1000000000, stats->BSDCounts[1][1]);
    WriteStatusMessage("%llds, %lld calls in BSD close, -1\n",          stats->nanosTimeInBSD[1][0]/1000000000, stats->BSDCounts[1][0]);
    WriteStatusMessage("%llds, %lld calls in Hamming\n",                stats->hammingNanos/1000000000,         stats->hammingCount);
#endif  // TIME_STRING_DISTANCE

    extension->printStats();
}
Example #27
0
void GameplayAssist::PlayTicks( const NoteData &nd, const PlayerState *ps )
{
	using std::max;
	bool bClap = GAMESTATE->m_SongOptions.GetCurrent().m_bAssistClap;
	bool bMetronome = GAMESTATE->m_SongOptions.GetCurrent().m_bAssistMetronome;
	if( !bClap  &&  !bMetronome )
		return;

	// don't play sounds for dead players
	if( ps->m_HealthState == HealthState_Dead )
		return;

	/* Sound cards have a latency between when a sample is Play()ed and when the sound
	 * will start coming out the speaker.  Compensate for this by boosting fPositionSeconds
	 * ahead.  This is just to make sure that we request the sound early enough for it to
	 * come out on time; the actual precise timing is handled by SetStartTime. */
	SongPosition &position = GAMESTATE->m_pPlayerState[ps->m_PlayerNumber]->m_Position;
	float fPositionSeconds = position.m_fMusicSeconds;

	//float fPositionSeconds = GAMESTATE->m_Position.m_fMusicSeconds;
	fPositionSeconds += SOUNDMAN->GetPlayLatency() + (float)CommonMetrics::TICK_EARLY_SECONDS + 0.250f;
	const TimingData &timing = *GAMESTATE->m_pCurSteps[ps->m_PlayerNumber]->GetTimingData();
	const float fSongBeat = timing.GetBeatFromElapsedTimeNoOffset( fPositionSeconds );

	const int iSongRow = max( 0, BeatToNoteRowNotRounded( fSongBeat ) );
	static int iRowLastCrossed = -1;
	if( iSongRow < iRowLastCrossed )
		iRowLastCrossed = iSongRow;

	if( bClap )
	{
		int iClapRow = -1;
		// for each index we crossed since the last update:
		FOREACH_NONEMPTY_ROW_ALL_TRACKS_RANGE( nd, r, iRowLastCrossed+1, iSongRow+1 )
			if( nd.IsThereATapOrHoldHeadAtRow( r ) )
				iClapRow = r;

		if( iClapRow != -1 && timing.IsJudgableAtRow(iClapRow))
		{
			const float fTickBeat = NoteRowToBeat( iClapRow );
			const float fTickSecond = timing.GetElapsedTimeFromBeatNoOffset( fTickBeat );
			float fSecondsUntil = fTickSecond - position.m_fMusicSeconds;
			fSecondsUntil /= GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; /* 2x music rate means the time until the tick is halved */

			RageSoundParams p;
			p.m_StartTime = position.m_LastBeatUpdate  + (fSecondsUntil - (float)CommonMetrics::TICK_EARLY_SECONDS);
			m_soundAssistClap.Play(false, &p);
		}
	}

	if( bMetronome && iRowLastCrossed != -1 )
	{
		//iRowLastCrossed+1, iSongRow+1

		int iLastCrossedMeasureIndex;
		int iLastCrossedBeatIndex;
		int iLastCrossedRowsRemainder;
		timing.NoteRowToMeasureAndBeat( iRowLastCrossed, iLastCrossedMeasureIndex, iLastCrossedBeatIndex, iLastCrossedRowsRemainder );

		int iCurrentMeasureIndex;
		int iCurrentBeatIndex;
		int iCurrentRowsRemainder;
		timing.NoteRowToMeasureAndBeat( iSongRow, iCurrentMeasureIndex, iCurrentBeatIndex, iCurrentRowsRemainder );

		int iMetronomeRow = -1;
		bool bIsMeasure = false;

		if( iLastCrossedMeasureIndex != iCurrentMeasureIndex  ||  iLastCrossedBeatIndex != iCurrentBeatIndex )
		{
			iMetronomeRow = iSongRow - iCurrentRowsRemainder;
			bIsMeasure = iCurrentBeatIndex == 0  &&  iCurrentRowsRemainder == 0;
		}

		if( iMetronomeRow != -1 )
		{
			const float fTickBeat = NoteRowToBeat( iMetronomeRow );
			const float fTickSecond = timing.GetElapsedTimeFromBeatNoOffset( fTickBeat );
			float fSecondsUntil = fTickSecond - position.m_fMusicSeconds;
			fSecondsUntil /= GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; /* 2x music rate means the time until the tick is halved */

			RageSoundParams p;
			p.m_StartTime = position.m_LastBeatUpdate  + (fSecondsUntil - (float)CommonMetrics::TICK_EARLY_SECONDS);
			if( bIsMeasure )
				m_soundAssistMetronomeMeasure.Play(false, &p);
			else
				m_soundAssistMetronomeBeat.Play(false, &p);
		}
	}

	iRowLastCrossed = iSongRow;
}
Example #28
0
/**
 * Calculates the turn rate and the derived features.
 * Determines the current flight mode (cruise/circling).
 */
void
GlideComputerAirData::Turning()
{
  // You can't be circling unless you're flying
  if (!Basic().flight.Flying || !time_advanced())
    return;

  // JMW limit rate to 50 deg per second otherwise a big spike
  // will cause spurious lock on circling for a long time
  fixed Rate = max(fixed(-50), min(fixed(50), Basic().TurnRate));

  // average rate, to detect essing
  // TODO: use rotary buffer
  static fixed rate_history[60];
  fixed rate_ave = fixed_zero;
  for (int i = 59; i > 0; i--) {
    rate_history[i] = rate_history[i - 1];
    rate_ave += rate_history[i];
  }
  rate_history[0] = Rate;
  rate_ave /= 60;

  // Make the turn rate more smooth using the LowPassFilter
  Rate = LowPassFilter(LastCalculated().SmoothedTurnRate, Rate, fixed(0.3));
  SetCalculated().SmoothedTurnRate = Rate;

  // Determine which direction we are circling
  bool LEFT = false;
  if (negative(Rate)) {
    LEFT = true;
    Rate *= -1;
  }

  // Calculate circling time percentage and call thermal band calculation
  PercentCircling(Rate);

  // Force cruise or climb mode if external device says so
  bool forcecruise = false;
  bool forcecircling = false;
  if (SettingsComputer().EnableExternalTriggerCruise && !Basic().gps.Replay) {
    forcecircling = triggerClimbEvent.test();
    forcecruise = !forcecircling;
  }

  switch (Calculated().TurnMode) {
  case CRUISE:
    // If (in cruise mode and beginning of circling detected)
    if ((Rate >= MinTurnRate) || (forcecircling)) {
      // Remember the start values of the turn
      SetCalculated().TurnStartTime = Basic().Time;
      SetCalculated().TurnStartLocation = Basic().Location;
      SetCalculated().TurnStartAltitude = Basic().NavAltitude;
      SetCalculated().TurnStartEnergyHeight = Basic().EnergyHeight;
      SetCalculated().TurnMode = WAITCLIMB;
    }
    if (!forcecircling)
      break;

  case WAITCLIMB:
    if (forcecruise) {
      SetCalculated().TurnMode = CRUISE;
      break;
    }
    if ((Rate >= MinTurnRate) || (forcecircling)) {
      if (((Basic().Time - Calculated().TurnStartTime) > CruiseClimbSwitch)
          || forcecircling) {
        // yes, we are certain now that we are circling
        SetCalculated().Circling = true;

        // JMW Transition to climb
        SetCalculated().TurnMode = CLIMB;

        // Remember the start values of the climbing period
        SetCalculated().ClimbStartLocation = Calculated().TurnStartLocation;
        SetCalculated().ClimbStartAlt = Calculated().TurnStartAltitude
            + Calculated().TurnStartEnergyHeight;
        SetCalculated().ClimbStartTime = Calculated().TurnStartTime;

        // set altitude for start of circling (as base of climb)
        OnClimbBase(Calculated().TurnStartAltitude);

        // consider code: InputEvents GCE - Move this to InputEvents
        // Consider a way to take the CircleZoom and other logic
        // into InputEvents instead?
        // JMW: NO.  Core functionality must be built into the
        // main program, unable to be overridden.
        OnSwitchClimbMode(true, LEFT);
      }
    } else {
      // nope, not turning, so go back to cruise
      SetCalculated().TurnMode = CRUISE;
    }
    break;

  case CLIMB:
    if ((Rate < MinTurnRate) || (forcecruise)) {
      // Remember the end values of the turn
      SetCalculated().TurnStartTime = Basic().Time;
      SetCalculated().TurnStartLocation = Basic().Location;
      SetCalculated().TurnStartAltitude = Basic().NavAltitude;
      SetCalculated().TurnStartEnergyHeight = Basic().EnergyHeight;

      // JMW Transition to cruise, due to not properly turning
      SetCalculated().TurnMode = WAITCRUISE;
    }
    if (!forcecruise)
      break;

  case WAITCRUISE:
    if (forcecircling) {
      SetCalculated().TurnMode = CLIMB;
      break;
    }
    if((Rate < MinTurnRate) || forcecruise) {
      if (((Basic().Time - Calculated().TurnStartTime) > ClimbCruiseSwitch)
          || forcecruise) {
        // yes, we are certain now that we are cruising again
        SetCalculated().Circling = false;

        // Transition to cruise
        SetCalculated().TurnMode = CRUISE;
        SetCalculated().CruiseStartLocation = Calculated().TurnStartLocation;
        SetCalculated().CruiseStartAlt = Calculated().TurnStartAltitude;
        SetCalculated().CruiseStartTime = Calculated().TurnStartTime;

        OnClimbCeiling();

        OnSwitchClimbMode(false, LEFT);
      }
    } else {
      // nope, we are circling again
      // JMW Transition back to climb, because we are turning again
      SetCalculated().TurnMode = CLIMB;
    }
    break;

  default:
    // error, go to cruise
    SetCalculated().TurnMode = CRUISE;
  }
}
Example #29
0
    void
AlignerContext::printStats()
{
    double usefulReads = max((double) stats->usefulReads, 1.0);
    char errorRate[16];
    if (options->computeError) {
        _int64 numSingle = max(stats->singleHits, (_int64) 1);
        snprintf(errorRate, sizeof(errorRate), "%0.3f%%", (100.0 * stats->errors) / numSingle);
    } else {
        snprintf(errorRate, sizeof(errorRate), "-");
    }
    printf("%d\t%d\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%s\t%0.2f%%\t%lld\t%lld\t%.0f (at: %lld)\n",
            maxHits_, maxDist_, 
            100.0 * usefulReads / max(stats->totalReads, (_int64) 1),
            100.0 * stats->singleHits / usefulReads,
            100.0 * stats->multiHits / usefulReads,
            100.0 * stats->notFound / usefulReads,
            errorRate,
            100.0 * stats->alignedAsPairs / usefulReads,
            stats->lvCalls,
            stats->totalReads,
            (1000.0 * usefulReads) / max(alignTime, (_int64) 1), 
            alignTime);
    if (NULL != perfFile) {
        fprintf(perfFile, "%d\t%d\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%s\t%0.2f%%\t%lld\t%lld\tt%.0f\n",
                maxHits_, maxDist_, 
                100.0 * usefulReads / max(stats->totalReads, (_int64) 1),
                100.0 * stats->singleHits / usefulReads,
                100.0 * stats->multiHits / usefulReads,
                100.0 * stats->notFound / usefulReads,
                stats->lvCalls,
                errorRate,
                100.0 * stats->alignedAsPairs / usefulReads,
                stats->totalReads,
                (1000.0 * usefulReads) / max(alignTime, (_int64) 1));

        fprintf(perfFile,"\n");
    }
    // Running counts to compute a ROC curve (with error rate and %aligned above a given MAPQ)
    double totalAligned = 0;
    double totalErrors = 0;
    for (int i = AlignerStats::maxMapq; i >= 0; i--) {
        totalAligned += stats->mapqHistogram[i];
        totalErrors += stats->mapqErrors[i];
        double truePositives = (totalAligned - totalErrors) / max(stats->totalReads, (_int64) 1);
        double falsePositives = totalErrors / totalAligned;
        if (i <= 10 || i % 2 == 0 || i == 69) {
//            printf("%d\t%d\t%d\t%.3f\t%.2E\n", i, stats->mapqHistogram[i], stats->mapqErrors[i], truePositives, falsePositives);
        }
    }

    stats->printHistograms(stdout);

#ifdef  TIME_STRING_DISTANCE
    printf("%llds, %lld calls in BSD noneClose, not -1\n",  stats->nanosTimeInBSD[0][1]/1000000000, stats->BSDCounts[0][1]);
    printf("%llds, %lld calls in BSD noneClose, -1\n",      stats->nanosTimeInBSD[0][0]/1000000000, stats->BSDCounts[0][0]);
    printf("%llds, %lld calls in BSD close, not -1\n",      stats->nanosTimeInBSD[1][1]/1000000000, stats->BSDCounts[1][1]);
    printf("%llds, %lld calls in BSD close, -1\n",          stats->nanosTimeInBSD[1][0]/1000000000, stats->BSDCounts[1][0]);
    printf("%llds, %lld calls in Hamming\n",                stats->hammingNanos/1000000000,         stats->hammingCount);
#endif  // TIME_STRING_DISTANCE

    extension->printStats();
}
Example #30
0
// Creation of the physics box... quite cabalistic and extensive func...
// Need to put a (really) smarter algorithm in there...
void EERIE_PHYSICS_BOX_Create(EERIE_3DOBJ * obj)
{
	if (!obj) return;

	EERIE_PHYSICS_BOX_Release(obj);

	if (obj->vertexlist.empty()) return;

	obj->pbox =	(PHYSICS_BOX_DATA *)
	            malloc(sizeof(PHYSICS_BOX_DATA));
	memset(obj->pbox, 0, sizeof(PHYSICS_BOX_DATA));
	obj->pbox->nb_physvert = 15;
	obj->pbox->stopcount = 0;
	obj->pbox->vert =	(PHYSVERT *)
	                    malloc(sizeof(PHYSVERT) * obj->pbox->nb_physvert);
	memset(obj->pbox->vert, 0, sizeof(PHYSVERT)*obj->pbox->nb_physvert);
	
	Vec3f cubmin = Vec3f::repeat(std::numeric_limits<float>::max());
	Vec3f cubmax = Vec3f::repeat(-std::numeric_limits<float>::max());
	
	for(size_t k = 0; k < obj->vertexlist.size(); k++) {
		if(long(k) != obj->origin) {
			cubmin = componentwise_min(cubmin, obj->vertexlist[k].v);
			cubmax = componentwise_max(cubmax, obj->vertexlist[k].v);
		}
	}
	
	obj->pbox->vert[0].pos = cubmin + (cubmax - cubmin) * .5f;
	obj->pbox->vert[13].pos = obj->pbox->vert[0].pos;
	obj->pbox->vert[13].pos.y = cubmin.y;
	obj->pbox->vert[14].pos = obj->pbox->vert[0].pos;
	obj->pbox->vert[14].pos.y = cubmax.y;
	
	for (int k = 1; k < obj->pbox->nb_physvert - 2; k++)
	{
		obj->pbox->vert[k].pos.x = obj->pbox->vert[0].pos.x;
		obj->pbox->vert[k].pos.z = obj->pbox->vert[0].pos.z;

		if (k < 5)		obj->pbox->vert[k].pos.y = cubmin.y;
		else if (k < 9)	obj->pbox->vert[k].pos.y = obj->pbox->vert[0].pos.y;
		else			obj->pbox->vert[k].pos.y = cubmax.y;
	}

	float diff = cubmax.y - cubmin.y;

	if (diff < 12.f) 
	{
		cubmax.y += 8.f; 
		cubmin.y -= 8.f; 

		for (int k = 1; k < obj->pbox->nb_physvert - 2; k++)
		{
			obj->pbox->vert[k].pos.x = obj->pbox->vert[0].pos.x;
			obj->pbox->vert[k].pos.z = obj->pbox->vert[0].pos.z;

			if (k < 5)		obj->pbox->vert[k].pos.y = cubmin.y;
			else if (k < 9)	obj->pbox->vert[k].pos.y = obj->pbox->vert[0].pos.y;
			else			obj->pbox->vert[k].pos.y = cubmax.y;
		}

		obj->pbox->vert[14].pos.y = cubmax.y;
		obj->pbox->vert[13].pos.y = cubmin.y;
		float RATI = diff * ( 1.0f / 8 );

		for (size_t k = 0; k < obj->vertexlist.size(); k++)
		{
			if (k == (size_t)obj->origin) continue;

			Vec3f curr = obj->vertexlist[k].v;
			long SEC = 1;
			obj->pbox->vert[SEC].pos.x = min(obj->pbox->vert[SEC].pos.x, curr.x);
			obj->pbox->vert[SEC].pos.z = min(obj->pbox->vert[SEC].pos.z, curr.z);

			obj->pbox->vert[SEC+1].pos.x = min(obj->pbox->vert[SEC+1].pos.x, curr.x);
			obj->pbox->vert[SEC+1].pos.z = max(obj->pbox->vert[SEC+1].pos.z, curr.z);

			obj->pbox->vert[SEC+2].pos.x = max(obj->pbox->vert[SEC+2].pos.x, curr.x);
			obj->pbox->vert[SEC+2].pos.z = max(obj->pbox->vert[SEC+2].pos.z, curr.z);

			obj->pbox->vert[SEC+3].pos.x = max(obj->pbox->vert[SEC+3].pos.x, curr.x);
			obj->pbox->vert[SEC+3].pos.z = min(obj->pbox->vert[SEC+3].pos.z, curr.z);

			SEC = 5;
			obj->pbox->vert[SEC].pos.x = min(obj->pbox->vert[SEC].pos.x, curr.x - RATI);
			obj->pbox->vert[SEC].pos.z = min(obj->pbox->vert[SEC].pos.z, curr.z - RATI);

			obj->pbox->vert[SEC+1].pos.x = min(obj->pbox->vert[SEC+1].pos.x, curr.x - RATI);
			obj->pbox->vert[SEC+1].pos.z = max(obj->pbox->vert[SEC+1].pos.z, curr.z + RATI);

			obj->pbox->vert[SEC+2].pos.x = max(obj->pbox->vert[SEC+2].pos.x, curr.x + RATI);
			obj->pbox->vert[SEC+2].pos.z = max(obj->pbox->vert[SEC+2].pos.z, curr.z + RATI);

			obj->pbox->vert[SEC+3].pos.x = max(obj->pbox->vert[SEC+3].pos.x, curr.x + RATI);
			obj->pbox->vert[SEC+3].pos.z = min(obj->pbox->vert[SEC+3].pos.z, curr.z - RATI);


			SEC = 9;
			obj->pbox->vert[SEC].pos.x = min(obj->pbox->vert[SEC].pos.x, curr.x);
			obj->pbox->vert[SEC].pos.z = min(obj->pbox->vert[SEC].pos.z, curr.z);

			obj->pbox->vert[SEC+1].pos.x = min(obj->pbox->vert[SEC+1].pos.x, curr.x);
			obj->pbox->vert[SEC+1].pos.z = max(obj->pbox->vert[SEC+1].pos.z, curr.z);

			obj->pbox->vert[SEC+2].pos.x = max(obj->pbox->vert[SEC+2].pos.x, curr.x);
			obj->pbox->vert[SEC+2].pos.z = max(obj->pbox->vert[SEC+2].pos.z, curr.z);

			obj->pbox->vert[SEC+3].pos.x = max(obj->pbox->vert[SEC+3].pos.x, curr.x);
			obj->pbox->vert[SEC+3].pos.z = min(obj->pbox->vert[SEC+3].pos.z, curr.z);
		}
	}
	else
	{
		float cut = (cubmax.y - cubmin.y) * ( 1.0f / 3 );
		float ysec2 = cubmin.y + cut * 2.f;
		float ysec1 = cubmin.y + cut;

		for (size_t k = 0; k < obj->vertexlist.size(); k++)
		{
			if (k == (size_t)obj->origin) continue;

			Vec3f curr = obj->vertexlist[k].v;
			long SEC;

			if (curr.y < ysec1)
			{
				SEC = 1;
			}
			else if (curr.y < ysec2)
			{
				SEC = 5;
			}
			else
			{
				SEC = 9;
			}

			obj->pbox->vert[SEC].pos.x = min(obj->pbox->vert[SEC].pos.x, curr.x);
			obj->pbox->vert[SEC].pos.z = min(obj->pbox->vert[SEC].pos.z, curr.z);

			obj->pbox->vert[SEC+1].pos.x = min(obj->pbox->vert[SEC+1].pos.x, curr.x);
			obj->pbox->vert[SEC+1].pos.z = max(obj->pbox->vert[SEC+1].pos.z, curr.z);

			obj->pbox->vert[SEC+2].pos.x = max(obj->pbox->vert[SEC+2].pos.x, curr.x);
			obj->pbox->vert[SEC+2].pos.z = max(obj->pbox->vert[SEC+2].pos.z, curr.z);

			obj->pbox->vert[SEC+3].pos.x = max(obj->pbox->vert[SEC+3].pos.x, curr.x);
			obj->pbox->vert[SEC+3].pos.z = min(obj->pbox->vert[SEC+3].pos.z, curr.z);
		}
	}

	for (int k = 0; k < 4; k++)
	{
		if (EEfabs(obj->pbox->vert[5+k].pos.x - obj->pbox->vert[0].pos.x) < 2.f)
			obj->pbox->vert[5+k].pos.x = (obj->pbox->vert[1+k].pos.x + obj->pbox->vert[9+k].pos.x) * .5f;

		if (EEfabs(obj->pbox->vert[5+k].pos.z - obj->pbox->vert[0].pos.z) < 2.f)
			obj->pbox->vert[5+k].pos.z = (obj->pbox->vert[1+k].pos.z + obj->pbox->vert[9+k].pos.z) * .5f;
	}

	obj->pbox->radius = 0.f;

	for(int k = 0; k < obj->pbox->nb_physvert; k++) {
		float distt = dist(obj->pbox->vert[k].pos, obj->pbox->vert[0].pos);

		if (distt > 20.f)
		{
			obj->pbox->vert[k].pos.x = (obj->pbox->vert[k].pos.x
			                            - obj->pbox->vert[0].pos.x) * 0.5f +
			                           obj->pbox->vert[0].pos.x;
			obj->pbox->vert[k].pos.z = (obj->pbox->vert[k].pos.z
			                            - obj->pbox->vert[0].pos.z) * 0.5f +
			                           obj->pbox->vert[0].pos.z;
		}

		obj->pbox->vert[k].initpos = obj->pbox->vert[k].pos;

		if(k != 0) {
			float d = dist(obj->pbox->vert[0].pos, obj->pbox->vert[k].pos);
			obj->pbox->radius = max(obj->pbox->radius, d);
		}
	}
}