void saveArrayAsImage( const Array2D< float >& array, QString prefix, float ss, float sr ) { Image4f im( array.width(), array.height() ); for( int y = 0; y < im.height(); ++y ) { for( int x = 0; x < im.width(); ++x ) { float v = array( x, y ); im.setPixel( x, y, Vector4f( v, v, v, 1 ) ); } } QString filename = QString( "%1_%2_%3.png" ).arg( prefix ).arg( ss ).arg( sr ); printf( "saving output: %s...", qPrintable( filename ) ); im.flipUD().save( filename ); printf( "done.\n\n" ); }

/* * @param s output stream * @param title plot title * @param names vector of variable names * @param data N x M data array. * data(n,m) is the m^th value of the n^th variable. */ void outputExcel(std::ostream &s, const std::string &title, const std::vector<std::string>& names, const Array2D& data) { int i,j; int npts = static_cast<int>(data.nColumns()); int nv = static_cast<int>(data.nRows()); s << title + "," << endl; for (i = 0; i < nv; i++) { s << names[i] << ","; } s << endl; for (i = 0; i < npts; i++) { for (j = 0; j < nv; j++) { s << data(j,i) << ","; } s << endl; } }

void RobotWithGeometry::GetSelfCollisionPairs(Array2D<bool>& collision) const { collision.resize(geometry.size(),geometry.size(),false); for(int i=0;i<collision.m;i++) for(int j=0;j<collision.n;j++) if(selfCollisions(i,j) != NULL) collision(i,j) = true; }

void FMSegView::setArray(const Array2D &X) { d->m_array=X; if (d->m_window_max==0) { d->m_window_min=0; d->m_window_max=X.max()*0.6; } d->m_array_filtered=d->compute_median_filter(d->m_array,d->m_median_filter_radius); refresh(); }

void adjust_data(Array2D<double>& d, Array1D<double>& means) { for (int i=0; i<d.dim2(); ++i) { double mean = 0; for (int j=0; j<d.dim1(); ++j) { mean += d[j][i]; } mean /= d.dim1(); // store the mean means[i] = mean; // subtract the mean for (int j=0; j<d.dim1(); ++j) { d[j][i] -= mean; } } }

ImageData::ImageData(const string & filename, Array2D<Color4f> & rgbaBuffer) : filename(filename) { totalXRes = xRes = rgbaBuffer.getSizeX(); totalYRes = yRes = rgbaBuffer.getSizeY(); xOffset = yOffset = 0; gTable = GammaTable(1,1); color = new float[xRes*yRes*3]; alpha = NULL; for (int x = 0; x < xRes; x++) { for (int y = 0; y < yRes; y++) { for (int i = 0; i < 3; i++) color[3*(y*xRes+x)+i] = rgbaBuffer(x,yRes-y-1)[i]; } } }

// Quantise a subband in in-place transform order // This version of quantise_subbands assumes multiple quantisers per subband. // It may be used for either quantising slices or for quantising subbands with codeblocks const Array2D quantise_subbands(const Array2D& coefficients, const BlockVector& qIndices) { const Index transformHeight = coefficients.shape()[0]; const Index transformWidth = coefficients.shape()[1]; // TO DO: Check numberOfSubbands=3n+1 ? const int numberOfSubbands = qIndices.size(); const int waveletDepth = (numberOfSubbands-1)/3; Index stride, offset; // stride is subsampling factor, offset is subsampling phase Array2D result(coefficients.ranges()); // Create a view of the coefficients, representing the LL subband, quantise it, // then assign the result a view of the results array. This puts the quantised // LL subband into the result array in in-place transform order. // ArrayIndices2D objects specify the subset of array elements within a view, // that is they specify the subsampling factor and subsampling phase. stride = pow(2, waveletDepth); const ArrayIndices2D LLindices = // LLindices specifies the samples in the LL subband indices[Range(0,transformHeight,stride)][Range(0,transformWidth,stride)]; result[LLindices] = quantise_LLSubband(coefficients[LLindices], qIndices[0]); // Next quantise the other subbands // Note: Level numbers go from zero for the lowest ("DC") frequencies to depth for // the high frequencies. This corresponds to the convention in the VC-2 specification. // Subands go from zero ("DC") to numberOfSubbands-1 for HH at the highest level for (char level=1, band=1; level<=waveletDepth; ++level) { stride = pow(2, waveletDepth+1-level); offset = stride/2; // Create a view of coefficients corresponding to a subband, then quantise it //Quantise HL subband const ArrayIndices2D HLindices = // HLindices specifies the samples in the HL subband indices[Range(0,transformHeight,stride)][Range(offset,transformWidth,stride)]; result[HLindices] = quantise_block(coefficients[HLindices], qIndices[band++]); //Quantise LH subband const ArrayIndices2D LHindices = // LHindices specifies the samples in the LH subband indices[Range(offset,transformHeight,stride)][Range(0,transformWidth,stride)]; result[LHindices] = quantise_block(coefficients[LHindices], qIndices[band++]); //Quantise HH subband const ArrayIndices2D HHindices = // HHindices specifies the samples in the HH subband indices[Range(offset,transformHeight,stride)][Range(offset,transformWidth,stride)]; result[HHindices] = quantise_block(coefficients[HHindices], qIndices[band++]); } return result; }

static void readRgba1(const std::string& filename, Array2D<Rgba>& pixels, int& width, int& height) { RgbaInputFile file{filename.c_str()}; Box2i dw = file.dataWindow(); width = dw.max.x - dw.min.x + 1; height = dw.max.y - dw.min.y + 1; pixels.resizeErase(height, width); file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y * width, 1, width); file.readPixels(dw.min.y, dw.max.y); }

void Exr::readRgba(const string inf, Array2D<Rgba> &pix, int &w, int &h) { RgbaInputFile file (inf.c_str()); Box2i dw = file.dataWindow(); w = dw.max.x - dw.min.x + 1; h = dw.max.y - dw.min.y + 1; pix.resizeErase (h, w); file.setFrameBuffer (&pix[0][0] - dw.min.x - dw.min.y * w, 1, w); file.readPixels (dw.min.y, dw.max.y); }

// This function finds the next change in matrix int SBic::bicChangeSearch(const Array2D<Real>& matrix, int inc, int current) const { int nFeatures = matrix.dim1(); int nFrames = matrix.dim2(); Real d, dmin, penalty; Real s, s1, s2; Array2D<Real> half; int n1, n2, seg = 0, shift = inc-1; // according to the paper the penalty coefficient should be the following: // penalty = 0.5*(3*nFeatures + nFeatures*nFeatures); penalty = _cpw * _cp * log(Real(nFrames)); dmin = numeric_limits<Real>::max(); // log-determinant for the entire window s = logDet(matrix); // loop on all mid positions while (shift < nFrames - inc) { // first part n1 = shift + 1; half = subarray(matrix, 0, nFeatures-1, 0, shift); s1 = logDet(half); // second part n2 = nFrames - n1; half = subarray(matrix, 0, nFeatures-1, shift+1, nFrames-1); s2 = logDet(half); d = 0.5 * (n1*s1 + n2*s2 - nFrames*s + penalty); if (d < dmin) { seg = shift; dmin = d; } shift += inc; } if (dmin > 0) return 0; return current + seg; }

FitchLikelihooder(int numNodes,int numAlpha,Alphabet &alpha, MultSeqAlignment &A,int column,RootNode *root,int order) : A(A), numNodes(numNodes), numAlpha(numAlpha), alpha(alpha), L(numNodes,numAlpha), column(column), order(order), root(root), likelihood(NEGATIVE_INFINITY), gapSymbols(A.getGapSymbols()), V(numAlpha) { L.setAllTo(NEGATIVE_INFINITY); V.setAllTo(NEGATIVE_INFINITY); }

void compute_covariance_matrix(const Array2D<double> & d, Array2D<double> & covar_matrix) { int dim = d.dim2(); assert(dim == covar_matrix.dim1()); assert(dim == covar_matrix.dim2()); for (int i=0; i<dim; ++i) { for (int j=i; j<dim; ++j) { covar_matrix[i][j] = compute_covariance(d, i, j); } } // fill the Left triangular matrix for (int i=1; i<dim; i++) { for (int j=0; j<i; ++j) { covar_matrix[i][j] = covar_matrix[j][i]; } } }

// Splits a large 2D array into an array of smaller 2D arrays (blocks) // Note that if the number of blocks is not a sub-multiple of the input array dimensions then // the blocks will have different sizes! // yBlocks and xBlocks are the number of blocks in the vertical and horizontal dimension respectively. // Splits a picture into slices or a subband into codeblocks. const BlockArray split_into_blocks(const Array2D& picture, int yBlocks, int xBlocks) { // Define array of yBlocks by xBlocks BlockArray blocks(extents[yBlocks][xBlocks]); const int pictureHeight = picture.shape()[0]; const int pictureWidth = picture.shape()[1]; // Note Range(left, right) defines the half open range [left, right), // i.e. the rightmost element is not included for (int y=0, top=0, bottom=pictureHeight/yBlocks; y<yBlocks; ++y, top=bottom, bottom=((y+1)*pictureHeight/yBlocks) ) { for (int x=0, left=0, right=pictureWidth/xBlocks; x<xBlocks; ++x, left=right, right=((x+1)*pictureWidth/xBlocks) ) { // Assign region of picture to block blocks[y][x] = picture[indices[Range(top,bottom)][Range(left,right)]]; } } return blocks; }

Array2D ComputeIDX(const Mat& IDX) { assert(IDX.type() == CV_32S); assert(IDX.rows > 0 && IDX.cols > 0); std::unordered_map<int, Array1D> hash; std::vector<int> hash_keys; int idx_num = 0; for (int i = 0; i < IDX.cols; i++) { if (!hash.count(IDX.at<int>(i))) { hash_keys.push_back(IDX.at<int>(i)); } hash[IDX.at<int>(i)].push_back(i + 1); } std::sort(hash_keys.begin(), hash_keys.end()); Array2D result; for (int i = 0; i < hash_keys.size(); i++) { result.push_back(hash[hash_keys[i]]); } return result; }

// This function computes the delta bic. It is actually used to determine // whether two consecutive segments have the same probability distribution // or not. In such case, these segments are joined. Real SBic::delta_bic(const Array2D<Real>& matrix, Real segPoint) const{ int nFeatures = matrix.dim1(); int nFrames = matrix.dim2(); Array2D<Real> half; Real s, s1, s2; // entire segment s = logDet(matrix); // first half half = subarray(matrix, 0, nFeatures-1, 0, int(segPoint)); s1 = logDet(half); // second half half = subarray(matrix, 0, nFeatures-1, int(segPoint + 1), nFrames-1); s2 = logDet(half); return 0.5 * ( segPoint*s1 + (nFrames - segPoint)*s2 - nFrames*s + _cpw*_cp*log(Real(nFrames)) ); }

static bool vert_line(double _x0, double _y0, double _x1, double _y1, int NX, vector<int>& imin, vector<int>& imax, bool draw, npy_uint32 col, Array2D<npy_uint32>& D) { int x0 = lrint(_x0); int y0 = lrint(_y0); int x1 = lrint(_x1); int y1 = lrint(_y1); int dx = abs(x1-x0); int dy = abs(y1-y0); int sx, sy; int NY=imin.size()-1; int err, e2; bool visible=false; NX = NX-1; if (x0 < x1) sx = 1; else sx = -1; if (y0 < y1) sy = 1; else sy = -1; err = dx-dy; do { if (y0>=0 && y0<=NY) { int _min = min(imin[y0],x0); int _max = max(imax[y0],x0); if (draw) { if (x0>=0 && x0<=NX) { D.value(x0,y0) = col; } } imin[y0] = max( 0,_min); imax[y0] = min(NX,_max); if (_min<=NX && _max>=0) { visible=true; } } if ((x0 == x1) && (y0 == y1)) break; e2 = 2*err; if (e2 > -dy) { err = err - dy; x0 = x0 + sx; } if (e2 < dx) { err = err + dx; y0 = y0 + sy; } } while(true); return visible; }

ACO_Likelihooder(int numNodes,int numAlpha,Alphabet &alpha, MultSeqAlignment &A,int firstCol,int lastCol, RootNode *root,AlphabetMap &alphabetMap, MolecularSequenceType seqType) : A(A), numNodes(numNodes), numAlpha(numAlpha),alpha(alpha), firstCol(firstCol), lastCol(lastCol), alphabetMap(alphabetMap), seqType(seqType), gapSymbols(A.getGapSymbols()) { numCols=lastCol-firstCol+1; numNmers=pow((float)alphabetMap.getRangeSize(),(float)numCols); L.resize(numNodes,numNmers); }

static void PermutationHelper(Array1D &array, int index, Array2D &result) { if (index == array.size()) { result.push_back(array); return; } for (int i = index; i < array.size(); ++i) { std::swap(array[index], array[i]); PermutationHelper(array, index + 1, result); std::swap(array[index], array[i]); } }

KDE_EXPORT void kimgio_exr_read( TQImageIO *io ) { try { int width, height; // This won't work if io is not TQFile ! RgbaInputFile file (TQFile::encodeName(io->fileName())); Imath::Box2i dw = file.dataWindow(); width = dw.max.x - dw.min.x + 1; height = dw.max.y - dw.min.y + 1; Array2D<Rgba> pixels; pixels.resizeErase (height, width); file.setFrameBuffer (&pixels[0][0] - dw.min.x - dw.min.y * width, 1, width); file.readPixels (dw.min.y, dw.max.y); TQImage image(width, height, 32, 0, TQImage::BigEndian); if( image.isNull()) return; // somehow copy pixels into image for ( int y=0; y < height; y++ ) { for ( int x=0; x < width; x++ ) { // copy pixels(x,y) into image(x,y) image.setPixel( x, y, RgbaToQrgba( pixels[y][x] ) ); } } io->setImage( image ); io->setStatus( 0 ); } catch (const std::exception &exc) { kdDebug(399) << exc.what() << endl; return; } }

Array2D FMSegViewPrivate::compute_median_filter(const Array2D &array,int radius) { Array2D ret; ret.allocate(array.N1(),array.N2()); for (int y=0; y<array.N2(); y++) for (int x=0; x<array.N1(); x++) { QList<float> list; for (int dy=-radius; dy<=radius; dy++) for (int dx=-radius; dx<=radius; dx++) { list << array.getValue(x+dx,y+dy); } qSort(list); ret.setValue(list[list.count()/2],x,y); } return ret; }

void RawParameters::autoWB(const Array2D<uint16_t> & image) { Timer t("AutoWB"); double dsum[4] = { 0.0, 0.0, 0.0, 0.0 }; size_t dcount[4] = { 0, 0, 0, 0 }; for (size_t row = 0; row < image.getHeight(); row += 8) { for (size_t col = 0; col < image.getWidth() ; col += 8) { double sum[4] = { 0.0, 0.0, 0.0, 0.0 }; size_t count[4] = { 0, 0, 0, 0 }; size_t ymax = std::min(row + 8, image.getHeight()); size_t xmax = std::min(col + 8, image.getWidth()); bool skipBlock = false; for (size_t y = row; y < ymax && !skipBlock; y++) { for (size_t x = col; x < xmax; x++) { int c = FC(x, y); uint16_t val = image(x, y); if (val > max - 25) { skipBlock = true; break; } sum[c] += val; count[c]++; } } if (!skipBlock) { for (int c = 0; c < 4; ++c) { dsum[c] += sum[c]; dcount[c] += count[c]; } } } } for (int c = 0; c < 4; ++c) { if (dsum[c] > 0.0) { camMul[c] = dcount[c] / dsum[c]; } else { copy_n(preMul, 4, camMul); break; } } }

void Garbrecht_GradientAwayFromHigher(const Array2D<T> &elevations, const Array2D<d8_flowdir_t> &flowdirs, garbrecht_flat_type &flats, Array2D<int32_t> &inc2){ int loops = 0; int number_incremented = 0; std::cerr<<"Setting up the inc2 matrix..."<<std::endl; inc2.resize(elevations); inc2.setAll(0); while(number_incremented<(int)flats.size()){ for(int i=0;i<(int)flats.size();i++){ int x=flats[i].x; int y=flats[i].y; if(inc2(x,y)>0){ inc2(x,y)++; continue; } } for(int i=0;i<(int)flats.size();i++){ bool has_higher=false,has_lower=false; int x=flats[i].x; int y=flats[i].y; if(inc2(x,y)>0) continue; for(int n=1;n<=8;n++){ if( !has_higher && (elevations(x+dx[n],y+dy[n])>elevations(x,y) || inc2(x+dx[n],y+dy[n])==2) ) has_higher=true; else if( !has_lower && elevations(x+dx[n],y+dy[n])<elevations(x,y) ) has_lower=true; } if(has_higher && !has_lower){ inc2(x,y)++; number_incremented++; } } loops++; } }

Array2D CombinationByNonRecursion(Array1D array, int K) { Array2D result; if (array.empty() || K <= 0) { return result; } if (array.size() < K) { result.push_back(array); /** @warning maybe exclude it */ return result; } Array1D cur(1); for (int i = 1; i <= array.size(); i++) { Array1D::size_type size = cur.size(); Array1D temp; /** @bug has some problems */ for (int j = 0; j < size; j++) { temp.push_back(cur[j]); temp.push_back(array[i]); if (temp.size() == K) { result.push_back(temp); } else { cur.push_back(array[i]); } } } return result; }

void EOTColumn(Array2D& a, int count, int columnNumber, int direction) { int numOfRepeats = (int)ceil((double)count / 2); int i, chunk; chunk = CHUNKSIZE; int repeat1 = 2 * (count / 2) - 1; //pocet opakovani prvniho cyklu int repeat2 = 2 * (int)floor((double)((count - 1) / 2)); //opakuj numOfRepeats x for (int j = 0; j < numOfRepeats; j++) { //paralelni blok s polem A a promennou chunk #pragma omp parallel num_threads(NUM_OF_THREAD) shared(a,count,chunk,repeat1,repeat2) private(i) { //licho-sude dvojce #pragma omp for schedule(dynamic,chunk) for (i = 0; i < repeat1; i += 2) { //compare and exchange int val1 = a.getValueAt(i, columnNumber); int val2 = a.getValueAt(i + 1, columnNumber); if (compare(val1, val2, direction) == false) { //pokud poradni neni spravne swap(a, i, columnNumber, i + 1, columnNumber); } } //sudo-liche dvojce #pragma omp for schedule(dynamic,chunk) for (i = 1; i < repeat2; i += 2) { //compare and exchange int val1 = a.getValueAt(i, columnNumber); int val2 = a.getValueAt(i + 1, columnNumber); if (compare(val1, val2, direction) == false) { //pokud poradni neni spravne swap(a, i, columnNumber, i + 1, columnNumber); } } } //end of paralel region } }

void submatrix(const Array2D<E> &obj,int a,int b,int c,int d,Array2D<E> &obj2) { int row=c-a+1,col=d-b+1; //constructor used obj2.init(0,row-1,0,col-1); for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { obj2(i,j)=obj(i+a,j+b); } } }

// static bool PNGIO::write( const std::string& filename, Array2DReadView< uint8x4 > image ) { Array2D< uint8x4 > tmpImage; const uint8_t* srcPointer; if( !image.packed() ) { tmpImage.resize( image.size() ); copy< uint8x4 >( image, tmpImage ); srcPointer = reinterpret_cast< const uint8_t* >( tmpImage.pointer() ); } else { srcPointer = reinterpret_cast< const uint8_t* >( image.pointer() ); } unsigned int errVal = lodepng::encode( filename, srcPointer, image.width(), image.height(), LCT_RGBA ); bool succeeded = ( errVal == 0 ); return succeeded; }

Array2D CombinationByBinary(Array1D array, int K) { Array2D result; if (array.empty() || K <= 0) { return result; } if (array.size() < K) { result.push_back(array); /** @warning maybe exclude it */ return result; } /** @warning sort or not */ Array1D temp; int begin = (1 << K) - 1, end = (1 << array.size()) - (1 << (array.size() - K)); for (int bit = begin; bit <= end; bit = NextBit(bit)) { temp.clear(); for (int i = 0; i < array.size(); i++) { if (bit & (1 << i)) { temp.push_back(array[i]); } } result.push_back(temp); } return result; }

static void CombinationByIncreaseHelper(Array1D &array, int left, int count, Array1D &temp, Array2D &result) { for (int i = left; i < array.size() + 1 - count; i++) { temp[count - 1] = array[i]; if (count - 1 == 0) { result.push_back(temp); } else { CombinationByIncreaseHelper(array, i + 1, count - 1, temp, result); } } }

static void CombinationByDecreaseHelper(Array1D &array, int left, int count, Array1D &temp, Array2D &result) { for (int i = left; i >= count; i--) { temp[count - 1] = array[i - 1]; if (count > 1) { CombinationByDecreaseHelper(array, i - 1, count - 1, temp, result); } else { result.push_back(temp); } } }

void testCrossBilateralFilter( const Array2D< float >& data, const Array2D< float >& edge, float ss, float sr, Array2D< float >& output ) { BilateralFilter cbf( data.width(), data.height(), ss, sr, 0.f, 1.f, true ); int nIterations = 100; StopWatch sw; for( int i = 0; i < nIterations; ++i ) { cbf.applyCross( data, edge, output ); cudaDeviceSynchronize(); } float ms = sw.millisecondsElapsed(); printf( "image size: %d x %d\n", data.width(), data.height() ); printf( "ss = %f, sr = %f\n", ss, sr ); printf( "Total time = %f ms, ms on average: %f\n", ms, ms / nIterations ); }