Esempio n. 1
0
void Line::adjustPoint(ushort refLinePosY, bool startPoint) {
	short newDistX, newDistY;
	cv::Point refPoint;
	if (startPoint) {
		refPoint = m_StartPt;
	}
	else {
		refPoint = m_EndPt;
	}

	if (abs(m_DistY) <= 2 || abs(refPoint.y - refLinePosY) < 2 ) {
		return;
	}

	newDistY = refLinePosY - refPoint.y;
	newDistX = -(newDistY * m_DistX) / m_DistY;

	if (startPoint) {
		m_StartPt.x += newDistX;
		m_StartPt.y += newDistY;
		calcSlope();
	}
	else {
		m_EndPt.x += newDistX;
		m_EndPt.y += newDistY;
		calcSlope();
	}
}
Esempio n. 2
0
void Line::adjustLineLength(ushort rows) {
	corrLineDirection();
	adjustPoint(rows, true);
	adjustPoint((rows >> 1), false);
	calcLength();
	calcSlope();
}
Esempio n. 3
0
Line::Line(cv::Vec4i points) {
	m_StartPt = cv::Point(points[0], points[1]);
	m_EndPt = cv::Point(points[2], points[3]);
	m_Length = 0;
	calcSlope();
	calcLength();
}
bool WallFollowingStrategy::lineCondition(std::pair<cv::Vec4i, float> line,
                                          cv::Vec4i initialLineSegment) {
  float slope = calcSlope(initialLineSegment);
  return fabs(line.second - slope) < 0.3 &&
         abs(line.first[0] - initialLineSegment[0]) <
             getDifference(line.first[0], line.first[2]) &&
         compareY(line.first[1], initialLineSegment[1]) <
             compareY(line.first[1], line.first[3]);
}
Esempio n. 5
0
    void next(int inNumSamples, nova::control_signature_kk)
    {
        if ( !FreqInput::changed() && !ResInput::changed() ) {
            next( inNumSamples, nova::control_signature_ii() );
            return;
        }

        auto oldState = _filter.currentState();
        auto newState = Filter::computeState( FreqInput::readAndUpdateInput(), ResInput::readAndUpdateInput(), makeDSPContext() );
        _filter.setState( newState );

        auto stateSlope = calcSlope( newState, oldState );
        auto stateRamp = nova::makeScalarRamp<decltype(stateSlope)>( oldState, stateSlope );

        auto inFn  = SignalInput::template makeInputSignal<SampleType>();
        auto outFn = OutputSink ::template makeSink<SampleType>();
        _filter.run(inFn, outFn, inNumSamples, stateRamp );
    }
Esempio n. 6
0
struct gapCalc *gapCalcRead(struct lineFile *lf)
/* Create gapCalc from open file. */
{
int i, tableSize, startLong = -1;
struct gapCalc *gapCalc;
int *gapInitPos;  
double *gapInitQGap;  
double *gapInitTGap;  
double *gapInitBothGap;

AllocVar(gapCalc);

/* Parse file. */
readTaggedNumLine(lf, "tableSize", 1, &tableSize, NULL);
readTaggedNumLine(lf, "smallSize", 1, &gapCalc->smallSize, NULL);
AllocArray(gapInitPos,tableSize);
AllocArray(gapInitQGap,tableSize);
AllocArray(gapInitTGap,tableSize);
AllocArray(gapInitBothGap,tableSize);
readTaggedNumLine(lf, "position", tableSize, gapInitPos, NULL);
readTaggedNumLine(lf, "qGap", tableSize, NULL, gapInitQGap);
readTaggedNumLine(lf, "tGap", tableSize, NULL, gapInitTGap);
readTaggedNumLine(lf, "bothGap", tableSize, NULL, gapInitBothGap);

/* Set up precomputed interpolations for small gaps. */
AllocArray(gapCalc->qSmall, gapCalc->smallSize);
AllocArray(gapCalc->tSmall, gapCalc->smallSize);
AllocArray(gapCalc->bSmall, gapCalc->smallSize);
for (i=1; i<gapCalc->smallSize; ++i)
    {
    gapCalc->qSmall[i] = 
	interpolate(i, gapInitPos, gapInitQGap, tableSize);
    gapCalc->tSmall[i] = 
	interpolate(i, gapInitPos, gapInitTGap, tableSize);
    gapCalc->bSmall[i] = interpolate(i, gapInitPos, 
	gapInitBothGap, tableSize);
    }

/* Set up to handle intermediate values. */
for (i=0; i<tableSize; ++i)
    {
    if (gapCalc->smallSize == gapInitPos[i])
	{
	startLong = i;
	break;
	}
    }
if (startLong < 0)
    errAbort("No position %d in gapCalcRead()\n", gapCalc->smallSize);
gapCalc->longCount = tableSize - startLong;
gapCalc->qPosCount = tableSize - startLong;
gapCalc->tPosCount = tableSize - startLong;
gapCalc->bPosCount = tableSize - startLong;
gapCalc->longPos = cloneMem(gapInitPos + startLong, gapCalc->longCount * sizeof(int));
gapCalc->qLong = cloneMem(gapInitQGap + startLong, gapCalc->qPosCount * sizeof(double));
gapCalc->tLong = cloneMem(gapInitTGap + startLong, gapCalc->tPosCount * sizeof(double));
gapCalc->bLong = cloneMem(gapInitBothGap + startLong, gapCalc->bPosCount * sizeof(double));

/* Set up to handle huge values. */
gapCalc->qLastPos = gapCalc->longPos[gapCalc->qPosCount-1];
gapCalc->tLastPos = gapCalc->longPos[gapCalc->tPosCount-1];
gapCalc->bLastPos = gapCalc->longPos[gapCalc->bPosCount-1];
gapCalc->qLastPosVal = gapCalc->qLong[gapCalc->qPosCount-1];
gapCalc->tLastPosVal = gapCalc->tLong[gapCalc->tPosCount-1];
gapCalc->bLastPosVal = gapCalc->bLong[gapCalc->bPosCount-1];
gapCalc->qLastSlope = calcSlope(gapCalc->qLastPosVal, gapCalc->qLong[gapCalc->qPosCount-2],
			   gapCalc->qLastPos, gapCalc->longPos[gapCalc->qPosCount-2]);
gapCalc->tLastSlope = calcSlope(gapCalc->tLastPosVal, gapCalc->tLong[gapCalc->tPosCount-2],
			   gapCalc->tLastPos, gapCalc->longPos[gapCalc->tPosCount-2]);
gapCalc->bLastSlope = calcSlope(gapCalc->bLastPosVal, gapCalc->bLong[gapCalc->bPosCount-2],
			   gapCalc->bLastPos, gapCalc->longPos[gapCalc->bPosCount-2]);
freez(&gapInitPos);
freez(&gapInitQGap);
freez(&gapInitTGap);
freez(&gapInitBothGap);
return gapCalc;
}
Esempio n. 7
0
//Open files, Initialize grid memory, makes function calls to set flowDir, slope, and resolvflats, writes files
int setdird8(char* demfile, char* pointfile, char *slopefile, char *flowfile, int useflowfile)
{
    MPI_Init(NULL,NULL);

    int rank,size;
    MPI_Comm_rank(MCW,&rank);
    MPI_Comm_size(MCW,&size);

    if (rank==0) {
        printf("D8FlowDir version %s\n",TDVERSION);

        if (strlen(pointfile) == 0) {
            printf("WARNING: no output p file specified\n");
        }

        if (strlen(slopefile) == 0) {
            printf("WARNING: no output sd8 file specified\n");
        }

        fflush(stdout);
    }

    MPITimer t;

    t.start("Total");
    t.start("Header read");

    //Read DEM from file
    tiffIO dem(demfile, FLOAT_TYPE);

    long totalX = dem.getTotalX();
    long totalY = dem.getTotalY();
    double dx = dem.getdxA();
    double dy = dem.getdyA();

    linearpart<float> elevDEM(totalX, totalY, dx, dy, MPI_FLOAT, *(float*) dem.getNodata());

    int xstart, ystart;
    int nx = elevDEM.getnx();
    int ny = elevDEM.getny();
    elevDEM.localToGlobal(0, 0, xstart, ystart);
    elevDEM.savedxdyc(dem);

    t.end("Header read");

    if (rank==0) {
        float timeestimate=(2.8e-9*pow((double)(totalX*totalY),1.55)/pow((double) size,0.65))/60+1;  // Time estimate in minutes
        //fprintf(stderr,"%d %d %d\n",totalX,totalY,size);
        fprintf(stderr,"This run may take on the order of %.0f minutes to complete.\n",timeestimate);
        fprintf(stderr,"This estimate is very approximate. \nRun time is highly uncertain as it depends on the complexity of the input data \nand speed and memory of the computer. This estimate is based on our testing on \na dual quad core Dell Xeon E5405 2.0GHz PC with 16GB RAM.\n");
        fflush(stderr);
    }

    uint64_t bytes_to_read = (uint64_t) nx * ny * sizeof(float);
    if (rank == 0) { 
        fprintf(stderr, "Reading input data (%s)... ", humanReadableSize(bytes_to_read).c_str());
    }

    t.start("Data read");

    dem.read(xstart, ystart, ny, nx, elevDEM.getGridPointer(), elevDEM.getGridPointerStride());
    elevDEM.share();
    double data_read_time = t.end("Data read");
   
    if (rank == 0) {
        fprintf(stderr, "done (%s/s).\n", humanReadableSize(bytes_to_read / data_read_time).c_str());
    }

    //Creates empty partition to store new flow direction
    short flowDirNodata = MISSINGSHORT;

    linearpart<short> flowDir(totalX, totalY, dx, dy, MPI_SHORT, flowDirNodata);

    //If using a flowfile, read it in
    if (useflowfile == 1) {
        tiffIO flow(flowfile, SHORT_TYPE);

        linearpart<short> imposedflow(flow.getTotalX(), flow.getTotalY(),
                flow.getdxA(), flow.getdyA(), MPI_SHORT, *(short*) flow.getNodata());

        if (!dem.compareTiff(flow)) {
            printf("Error using imposed flow file.\n");
            return 1;
        }

        for (int j=0; j < elevDEM.getny(); j++) {
            for (int i=0; i < elevDEM.getnx(); i++ ) {
                short data = imposedflow.getData(i,j);

                if (imposedflow.isNodata(i,j) || !imposedflow.hasAccess(i-1,j) || !imposedflow.hasAccess(i+1,j) ||
                        !imposedflow.hasAccess(i,j-1) || !imposedflow.hasAccess(i,j+1)) {
                    //Do nothing
                } else if (data > 0 && data <= 8) {
                    flowDir.setData(i,j,data);
                }
            }
        }
    }

    if (rank == 0) fprintf(stderr, "Calculating flow directions... ");
    t.start("Calculate flow directions");
    uint64_t numFlat = setPosDir(elevDEM, flowDir);
    t.end("Calculate flow directions");
  
    flowDir.share();

    if (strlen(slopefile) > 0)
    {
        t.start("Calculate slope");
        
        //Creates empty partition to store new slopes
        float slopeNodata = -1.0f;
        linearpart<float> slope(totalX, totalY, dx, dy, MPI_FLOAT, slopeNodata);

        calcSlope(flowDir, elevDEM, slope);

        t.end("Calculate slope");

        t.start("Write slope");
        tiffIO slopeIO(slopefile, FLOAT_TYPE, &slopeNodata, dem);
        slopeIO.write(xstart, ystart, ny, nx, slope.getGridPointer(), slope.getGridPointerStride());
        t.end("Write slope");
    }

    uint64_t totalNumFlat = 0;
    MPI_Allreduce(&numFlat, &totalNumFlat, 1, MPI_UINT64_T, MPI_SUM, MCW);
   
    if (rank == 0) {
        fprintf(stderr, "done. %" PRIu64 " flats to resolve.\n", totalNumFlat);
        fflush(stderr);
    }

    t.start("Resolve flats");

    if (totalNumFlat > 0) {
        if (rank == 0) {
            fprintf(stderr, "Finding flat islands...\n");
        }

        std::vector<std::vector<node>> islands;
        std::vector<std::vector<node>> borderingIslands;

        t.start("Find islands");
        findIslands<D8>(flowDir, islands, borderingIslands);
        t.end("Find islands");

        uint64_t localSharedFlats = 0, sharedFlats = 0;
        for (auto& island : borderingIslands) {
            localSharedFlats += island.size();
        }

        t.start("Resolve shared flats");
        MPI_Allreduce(&localSharedFlats, &sharedFlats, 1, MPI_UINT64_T, MPI_SUM, MCW);

        if (rank == 0 && size > 1) {
            fprintf(stderr, "Processing partial flats\n");

            printf("PRL: %llu flats shared across processors (%llu local -> %.2f%% shared)\n",
                    sharedFlats, totalNumFlat - sharedFlats, 100. * sharedFlats / totalNumFlat);
        }

        if (sharedFlats > 0) {
            SparsePartition<int> inc(totalX, totalY, 0);
            size_t lastNumFlat = resolveFlats_parallel_async<D8>(elevDEM, inc, flowDir, borderingIslands);

            if (rank==0) {
                fprintf(stderr, "PRL: Iteration complete. Number of flats remaining: %zu\n", lastNumFlat);
                fflush(stderr);
            }

            // Repeatedly call resolve flats until there is no change across all processors
            while (lastNumFlat > 0) {
                SparsePartition<int> newInc(totalX, totalY, 0);

                lastNumFlat = resolveFlats_parallel_async<D8>(inc, newInc, flowDir, borderingIslands);
                inc = std::move(newInc);

                if (rank==0) {
                    fprintf(stderr, "PRL: Iteration complete. Number of flats remaining: %zu\n", lastNumFlat);
                    fflush(stderr);
                }
            }
        }
        t.end("Resolve shared flats");

        //printf("rank %d: Done, %d islands. Took %.2f seconds\n", rank, numIslands, MPI_Wtime() - flatFindStart);
        //printf("rank %d: %lu bordering islands with %d flats\n", rank, bordering_islands.size(), localSharedFlats);

        t.start("Resolve local flats");
        if (!islands.empty()) {
            SparsePartition<int> inc(totalX, totalY, 0);
            size_t lastNumFlat = resolveFlats<D8>(elevDEM, inc, flowDir, islands);

            if (rank==0) {
                fprintf(stderr, "Iteration complete. Number of flats remaining: %zu\n\n", lastNumFlat);
                fflush(stderr);
            }

            // Repeatedly call resolve flats until there is no change
            while (lastNumFlat > 0)
            {
                SparsePartition<int> newInc(totalX, totalY, 0);

                lastNumFlat = resolveFlats<D8>(inc, newInc, flowDir, islands); 
                inc = std::move(newInc);

                if (rank==0) {
                    fprintf(stderr, "Iteration complete. Number of flats remaining: %zu\n\n", lastNumFlat);
                    fflush(stderr);
                }
            } 
        }
        t.end("Resolve local flats");
    }

    t.end("Resolve flats");

    if (strlen(pointfile) > 0) {
        t.start("Write directions");
        tiffIO pointIO(pointfile, SHORT_TYPE, &flowDirNodata, dem);
        pointIO.write(xstart, ystart, ny, nx, flowDir.getGridPointer(), flowDir.getGridPointerStride());
        t.end("Write directions");
    }

    t.end("Total");
    t.stop();
    //t.save("timing_info");

    MPI_Finalize();
    return 0;
}
void initGapAid(char *gapFileName)
/* Initialize gap aid structure for faster gap
 * computations. */
{
int i, tableSize, startLong = -1;
char *sizeDesc[2];
char *words[128];

if (gapFileName != NULL)
    {
    struct lineFile *lf = lineFileOpen(gapFileName, TRUE);
    int count;

    lineFileNextRowTab(lf, sizeDesc, 2);
    tableSize = atoi(sizeDesc[1]);
    AllocArray(gapInitPos,tableSize);
    AllocArray(gapInitQGap,tableSize);
    AllocArray(gapInitTGap,tableSize);
    AllocArray(gapInitBothGap,tableSize);
    while (count = lineFileChopNext(lf, words, tableSize+1))
        {
        if (sameString(words[0],"smallSize"))
            {
            aid.smallSize = atoi(words[1]);
            }
        if (sameString(words[0],"position"))
            {
            for (i=0 ; i<count-1 ; i++)
                gapInitPos[i] = atoi(words[i+1]);
            }
        if (sameString(words[0],"qGap"))
            {
            for (i=0 ; i<count-1 ; i++)
                gapInitQGap[i] = atoi(words[i+1]);
            }
        if (sameString(words[0],"tGap"))
            {
            for (i=0 ; i<count-1 ; i++)
                gapInitTGap[i] = atoi(words[i+1]);
            }
        if (sameString(words[0],"bothGap"))
            {
            for (i=0 ; i<count-1 ; i++)
                gapInitBothGap[i] = atoi(words[i+1]);
            }
            
        }
    if (aid.smallSize == 0)
        errAbort("missing smallSize parameter in %s\n",gapFileName);
    lineFileClose(&lf);
    }
else
    {
    /* if no gap file, then setup default values */ 
    /* Set up to handle small values */
    aid.smallSize = 111;
    tableSize = 11;
    AllocArray(gapInitPos,tableSize);
    AllocArray(gapInitQGap,tableSize);
    AllocArray(gapInitTGap,tableSize);
    AllocArray(gapInitBothGap,tableSize);
    for (i = 0 ; i < tableSize ; i++)
        {
        gapInitPos[i] = gapInitPosDefault[i];
        gapInitTGap[i] = gapInitTGapDefault[i];
        gapInitQGap[i] = gapInitQGapDefault[i];
        gapInitBothGap[i] = gapInitBothGapDefault[i];
        }
    }
    AllocArray(aid.qSmall, aid.smallSize);
    AllocArray(aid.tSmall, aid.smallSize);
    AllocArray(aid.bSmall, aid.smallSize);
    for (i=1; i<aid.smallSize; ++i)
        {
        aid.qSmall[i] = 
            interpolate(i, gapInitPos, gapInitQGap, tableSize);
        aid.tSmall[i] = 
            interpolate(i, gapInitPos, gapInitTGap, tableSize);
        aid.bSmall[i] = interpolate(i, gapInitPos, 
            gapInitBothGap, tableSize);
        }

    /* Set up to handle intermediate values. */
    for (i=0; i<tableSize; ++i)
        {
        if (aid.smallSize == gapInitPos[i])
            {
            startLong = i;
            break;
            }
        }
    if (startLong < 0)
        errAbort("No position %d in initGapAid()\n", aid.smallSize);
    aid.longCount = tableSize - startLong;
    aid.qPosCount = tableSize - startLong;
    aid.tPosCount = tableSize - startLong;
    aid.bPosCount = tableSize - startLong;
    aid.longPos = cloneMem(gapInitPos + startLong, aid.longCount * sizeof(int));
    aid.qLong = cloneMem(gapInitQGap + startLong, aid.qPosCount * sizeof(double));
    aid.tLong = cloneMem(gapInitTGap + startLong, aid.tPosCount * sizeof(double));
    aid.bLong = cloneMem(gapInitBothGap + startLong, aid.bPosCount * sizeof(double));

    /* Set up to handle huge values. */
    aid.qLastPos = aid.longPos[aid.qPosCount-1];
    aid.tLastPos = aid.longPos[aid.tPosCount-1];
    aid.bLastPos = aid.longPos[aid.bPosCount-1];
    aid.qLastPosVal = aid.qLong[aid.qPosCount-1];
    aid.tLastPosVal = aid.tLong[aid.tPosCount-1];
    aid.bLastPosVal = aid.bLong[aid.bPosCount-1];
    aid.qLastSlope = calcSlope(aid.qLastPosVal, aid.qLong[aid.qPosCount-2],
                               aid.qLastPos, aid.longPos[aid.qPosCount-2]);
    aid.tLastSlope = calcSlope(aid.tLastPosVal, aid.tLong[aid.tPosCount-2],
                               aid.tLastPos, aid.longPos[aid.tPosCount-2]);
    aid.bLastSlope = calcSlope(aid.bLastPosVal, aid.bLong[aid.bPosCount-2],
                               aid.bLastPos, aid.longPos[aid.bPosCount-2]);
    // uglyf("qLastPos %d, qlastPosVal %f, qLastSlope %f\n", aid.qLastPos, aid.qLastPosVal, aid.qLastSlope);
    // uglyf("tLastPos %d, tlastPosVal %f, tLastSlope %f\n", aid.tLastPos, aid.tLastPosVal, aid.tLastSlope);
    // uglyf("bLastPos %d, blastPosVal %f, bLastSlope %f\n", aid.bLastPos, aid.bLastPosVal, aid.bLastSlope);
}
void WallFollowingStrategy::removeLines(std::vector< cv::Vec4i > lines) {
  // "bucket" for each of the group of "similar" lines
  std::vector< std::pair< cv::Vec4i, float > > temp;
  // sort the lines by the x coordinate of the starting point
  std::sort(lines.begin(), lines.end(), compareStart);

  bool pushed = true;

  int count = 0;
  // loop through all the lines that have been detected by HoughLinesP
  for (size_t i = 0; i < lines.size(); i++) {
    float slope = calcSlope(lines[i]);
    std::pair<cv::Vec4i, float> lastLine;
    if (!temp.empty()) {
      lastLine = temp.back();
    }
    // if the bucket is empty push the current line to be processed
    if (temp.empty()) {
      std::pair< cv::Vec4i, float > p = std::make_pair(lines[i], slope);
      temp.push_back(p);

      /* case 1 of similar line segments: the slopes are almost the same,
         starting position of the x-coordinate of the second line segment
         that is being processed lies between starting and ending
         points of first line segment. Taking into account that the line
         segments are not too far apart in y-direction
         (e.g. two  parallel walls) */
    } else if (lineCondition(lastLine, lines[i])) {
      std::pair< cv::Vec4i, float > p = std::make_pair(lines[i], slope);
      temp.push_back(p);

      /* case 2 and 3 of similar lines: the slopes are almost the same, but
         for the second line segment x coordinate of the starting point lies a
         bit farther from the endpoint of the first line segment */
    } else if (slope < 0 && fabs(lastLine.second - slope) < 0.3 &&
               abs(lastLine.first[2] - lines[i][0]) < 2) {
      std::pair< cv::Vec4i, float > p = std::make_pair(lines[i], slope);
      temp.push_back(p);
    } else if (slope > 0 && compareY(lastLine.first[3], lines[i][1]) < 2 &&
               fabs(lastLine.second - slope) < 0.3) {
      std::pair< cv::Vec4i, float > p = std::make_pair(lines[i], slope);
      temp.push_back(p);
    } else {
      /* all the similar line segments were pushed - find the average of them
         and push in a resulting vector of line segments */
      res.push_back(getAverLine(temp));
      temp.clear();
      /* as line segments sorted by x-coordinate of the starting point can be
         shuffle with respect to the wall they belong to we need to check before
         processing a new line segment whether the lines similar to it were
         processed before */
      for (int j = 0; j < res.size(); j++) {
        if (slope > 0 && fabs(calcSlope(res[j]) - slope) < 2 ||
            slope < 0 && fabs(calcSlope(res[j]) + slope) < 2) {
          pushed = false;
          break;
        }
      }

      if (pushed) {
        std::pair< cv::Vec4i, float > p = std::make_pair(lines[i], slope);
        temp.push_back(p);
        pushed = true;
      }
    }

    // always process the current bucket before the end of vector of line
    // segments
    if (!temp.empty() && i == lines.size() - 1) {
      res.push_back(getAverLine(temp));
      temp.clear();
    }
  }
}