int seg_number_of_tribs(int r, int c, SEGMENT *streams, SEGMENT *dirs) { int trib = 0; int i, j; int streams_cell = 0; int dirs_cell = 0; for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; j = DIAG(i); Segment_get(streams, &streams_cell, NR(i), NC(i)); Segment_get(dirs, &dirs_cell, NR(i), NC(i)); if (streams_cell && dirs_cell == j) trib++; } if (trib > 5) G_fatal_error(_("Error finding nodes. " "Stream and direction maps probably do not match.")); if (trib > 3) G_warning(_("Stream network may be too dense")); return trib; }
SpatialMarkup SpatialConvex::triangleTest(uint64 id) { SpatialMarkup mark; // // do the face test on the triangle mark = testNode(V(NV(0)),V(NV(1)),V(NV(2))); // do we have a final result code? // if rEJECT, fULL then return if(mark > fULL) return mark; if(mark == fULL) { fillChildren(id); // propagate final result to children return mark; } // if pARTIAL or dONTKNOW, then continue, test children, // but do not reach beyond the leaf nodes. // If Convex is fully contained within one (sWALLOWED), // we can stop looking further in another child if (NC(id,0)!=0) { triangleTest(NC(id,0)); triangleTest(NC(id,1)); triangleTest(NC(id,2)); triangleTest(NC(id,3)); // we are at the leafnodes // If we have to recurse further, calculate intersections one by one // If not, just set the proper bit in partial_ or append id to plist_. } else { if(addlevel_) { // from now on, continue to build the triangles dynamically. // until maxlevel_ levels depth. testPartial(addlevel_, N(id).id_, V(NV(0)), V(NV(1)), V(NV(2))); } else { if(bitresult_) partial_->set((uint32)index_->leafNumberById(N(id).id_),true); else plist_->append(N(id).id_); } } return mark; }
int seg_trib_nums(int r, int c, SEGMENT *streams, SEGMENT *dirs) { /* calculate number of tributaries */ int trib_num = 0; int i, j; int next_r, next_c; int streams_cell, streams_next_cell, dirs_next_cell; Segment_get(streams, &streams_cell, r, c); for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; j = DIAG(i); next_r = NR(i); next_c = NC(i); Segment_get(streams, &streams_next_cell, next_r, next_c); Segment_get(dirs, &dirs_next_cell, next_r, next_c); if (streams_next_cell > 0 && dirs_next_cell == j) trib_num++; } if (trib_num > 1) for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; j = DIAG(i); next_r = NR(i); next_c = NC(i); Segment_get(streams, &streams_next_cell, next_r, next_c); Segment_get(dirs, &dirs_next_cell, next_r, next_c); if (streams_next_cell == streams_cell && dirs_next_cell == j) trib_num--; } if (trib_num > 5) G_fatal_error(_("Error finding inits. Stream and direction maps probably do not match")); if (trib_num > 3) G_warning(_("Stream network may be too dense")); return trib_num; } /* end trib_num */
int ram_trib_nums(int r, int c, CELL ** streams, CELL ** dirs) { /* calculate number of tributaries */ int trib_num = 0; int i, j; int next_r, next_c; for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; j = DIAG(i); next_r = NR(i); next_c = NC(i); if (streams[next_r][next_c] > 0 && dirs[next_r][next_c] == j) trib_num++; } if (trib_num > 1) for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; j = DIAG(i); next_r = NR(i); next_c = NC(i); if (streams[next_r][next_c] == streams[r][c] && dirs[next_r][next_c] == j) trib_num--; } if (trib_num > 5) G_fatal_error(_("Error finding inits. Stream and direction maps probably do not match")); if (trib_num > 3) G_warning(_("Stream network may be too dense")); return trib_num; } /* end trib_num */
int ram_number_of_tribs(int r, int c, CELL **streams, CELL **dirs) { int trib = 0; int i, j; for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; j = DIAG(i); if (streams[NR(i)][NC(i)] && dirs[NR(i)][NC(i)] == j) trib++; } if (trib > 5) G_fatal_error(_("Error finding nodes. " "Stream and direction maps probably do not match.")); if (trib > 3) G_warning(_("Stream network may be too dense")); return trib; }
int seg_fill_basins(OUTLET outlet, SEGMENT * distance, SEGMENT * dirs) { /* fill empty spaces with zeros but leave -1 as a markers of NULL */ int r, c, i, j; int next_r, next_c; double stop, val; POINT n_cell; CELL dirs_cell; DCELL distance_cell; tail = 0; head = -1; r = outlet.r; c = outlet.c; val = 1; stop = 0; Segment_put(distance, &stop, r, c); while (tail != head) { for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; /* out of border */ j = DIAG(i); next_r = NR(i); next_c = NC(i); Segment_get(dirs, &dirs_cell, next_r, next_c); if (dirs_cell == j) { /* countributing cell */ Segment_get(distance, &distance_cell, next_r, next_c); distance_cell = (distance_cell == stop) ? stop : val; Segment_put(distance, &distance_cell, next_r, next_c); n_cell.r = next_r; n_cell.c = next_c; fifo_insert(n_cell); } } /* end for i... */ n_cell = fifo_return_del(); r = n_cell.r; c = n_cell.c; } return 0; }
double get_distance(int r, int c, int d) { double northing, easting, next_northing, next_easting; int next_r, next_c; next_r = NR(d); next_c = NC(d); northing = window.north - (r + .5) * window.ns_res; easting = window.west + (c + .5) * window.ew_res; next_northing = window.north - (next_r + .5) * window.ns_res; next_easting = window.west + (next_c + .5) * window.ew_res; return G_distance(easting, northing, next_easting, next_northing); }
/////////////FILLCHILDREN///////////////////////////////// // fillChildren: mark children as full // void SpatialConvex::fillChildren(uint64 id) { if(range_) plist_->append(N(id).id_); else { if(NC(id,0)!=0) { for(size_t i = 0; i < 4; i++) { fillChildren(NC(id,i)); } } else { // we are at the leaf. If we still have levels to recurse, // fill them. If not, just set the full_ bitlist's or flist_ list's // value correctly. if(addlevel_) setfull(N(id).id_,addlevel_); else { if(bitresult_) full_->set((uint32)index_->leafNumberById(N(id).id_), true); else flist_->append(N(id).id_); } } } }
int ram_fill_basins(OUTLET outlet, DCELL ** distance, CELL ** dirs) { /* fill empty spaces with zeros but leave -1 as a markers of NULL */ int r, c, i, j; int next_r, next_c; double stop, val; POINT n_cell; tail = 0; head = -1; r = outlet.r; c = outlet.c; val = 1; stop = 0; distance[r][c] = stop; while (tail != head) { for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; /* out of border */ j = DIAG(i); next_r = NR(i); next_c = NC(i); if (dirs[next_r][next_c] == j) { /* countributing cell */ distance[next_r][next_c] = (distance[next_r][next_c] == stop) ? stop : val; n_cell.r = next_r; n_cell.c = next_c; fifo_insert(n_cell); } } /* end for i... */ n_cell = fifo_return_del(); r = n_cell.r; c = n_cell.c; } return 0; }
int ram_find_contributing_cell(int r, int c, CELL **dirs, FCELL **elevation) { int i, j = 0; int next_r, next_c; float elev_min = 9999; for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; next_r = NR(i); next_c = NC(i); if (dirs[next_r][next_c] == DIAG(i) && elevation[next_r][next_c] < elev_min) { elev_min = elevation[next_r][next_c]; j = i; } } return j; }
int seg_find_contributing_cell(int r, int c, SEGMENT *dirs, SEGMENT *elevation) { int i, j = 0; int next_r, next_c; float elev_min = 9999; int dirs_next_cell; float elevation_next_cell; for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; next_r = NR(i); next_c = NC(i); Segment_get(elevation, &elevation_next_cell, next_r, next_c); Segment_get(dirs, &dirs_next_cell, next_r, next_c); if (dirs_next_cell == DIAG(i) && elevation_next_cell < elev_min) { elev_min = elevation_next_cell; j = i; } } return j; }
int seg_build_streamlines(SEGMENT *streams, SEGMENT *dirs, SEGMENT *elevation, int number_of_streams) { int r, c, i; int d, next_d; int prev_r, prev_c; int stream_num = 1, cell_num = 0; int contrib_cell; STREAM *SA; int border_dir; int streams_cell, dirs_cell; int dirs_prev_cell; float elevation_cell, elevation_prev_cell; stream_attributes = (STREAM *) G_malloc(number_of_streams * sizeof(STREAM)); G_message(_("Finding inits...")); SA = stream_attributes; /* finding inits */ for (r = 0; r < nrows; ++r) for (c = 0; c < ncols; ++c) { Segment_get(streams, &streams_cell, r, c); if (streams_cell) if (seg_trib_nums(r, c, streams, dirs) != 1) { /* adding inits */ if (stream_num > number_of_streams) G_fatal_error(_("Error finding inits. Stream and direction maps probably do not match")); SA[stream_num].stream = stream_num; SA[stream_num].init = INDEX(r, c); stream_num++; } } /* building streamline */ for (i = 1; i < stream_num; ++i) { r = (int)SA[i].init / ncols; c = (int)SA[i].init % ncols; Segment_get(streams, &streams_cell, r, c); SA[i].order = streams_cell; SA[i].number_of_cells = 0; do { SA[i].number_of_cells++; Segment_get(dirs, &dirs_cell, r, c); d = abs(dirs_cell); if (NOT_IN_REGION(d) || d == 0) break; r = NR(d); c = NC(d); Segment_get(streams, &streams_cell, r, c); } while (streams_cell == SA[i].order); SA[i].number_of_cells += 2; /* add two extra points for point before init and after outlet */ } for (i = 1; i < number_of_streams; ++i) { SA[i].points = (unsigned long int *) G_malloc((SA[i].number_of_cells) * sizeof(unsigned long int)); SA[i].elevation = (float *) G_malloc((SA[i].number_of_cells) * sizeof(float)); SA[i].distance = (double *) G_malloc((SA[i].number_of_cells) * sizeof(double)); r = (int)SA[i].init / ncols; c = (int)SA[i].init % ncols; contrib_cell = seg_find_contributing_cell(r, c, dirs, elevation); prev_r = NR(contrib_cell); prev_c = NC(contrib_cell); /* add one point contributing to init to calculate parameters */ /* what to do if there is no contributing points? */ Segment_get(dirs, &dirs_cell, r, c); Segment_get(dirs, &dirs_prev_cell, prev_r, prev_c); Segment_get(elevation, &elevation_prev_cell, prev_r, prev_c); Segment_get(elevation, &elevation_cell, r, c); SA[i].points[0] = (contrib_cell == 0) ? -1 : INDEX(prev_r, prev_c); SA[i].elevation[0] = (contrib_cell == 0) ? -99999 : elevation_prev_cell; d = (contrib_cell == 0) ? dirs_cell : dirs_prev_cell; SA[i].distance[0] = (contrib_cell == 0) ? get_distance(r, c, d) : get_distance(prev_r, prev_c, d); SA[i].points[1] = INDEX(r, c); SA[i].elevation[1] = elevation_cell; d = abs(dirs_cell); SA[i].distance[1] = get_distance(r, c, d); cell_num = 2; do { Segment_get(dirs, &dirs_cell, r, c); d = abs(dirs_cell); if (NOT_IN_REGION(d) || d == 0) { SA[i].points[cell_num] = -1; SA[i].distance[cell_num] = SA[i].distance[cell_num - 1]; SA[i].elevation[cell_num] = 2 * SA[i].elevation[cell_num - 1] - SA[i].elevation[cell_num - 2]; border_dir = convert_border_dir(r, c, dirs_cell); SA[i].last_cell_dir = border_dir; break; } r = NR(d); c = NC(d); Segment_get(dirs, &dirs_cell, r, c); SA[i].last_cell_dir = dirs_cell; SA[i].points[cell_num] = INDEX(r, c); Segment_get(elevation, &SA[i].elevation[cell_num], r, c); next_d = (abs(dirs_cell) == 0) ? d : abs(dirs_cell); SA[i].distance[cell_num] = get_distance(r, c, next_d); cell_num++; if (cell_num > SA[i].number_of_cells) G_fatal_error(_("To much points in stream line")); Segment_get(streams, &streams_cell, r, c); } while (streams_cell == SA[i].order); if (SA[i].elevation[0] == -99999) SA[i].elevation[0] = 2 * SA[i].elevation[1] - SA[i].elevation[2]; } return 0; }
int seg_stream_topology(SEGMENT *streams, SEGMENT *dirs, int number_of_streams) { int d, i, j; /* d: direction, i: iteration */ int r, c; int next_r, next_c; int trib_num, trib = 0; int next_stream = -1, cur_stream; int streams_cell, dirs_cell; int next_streams_cell, trib_dirs_cell, trib_stream_cell; STREAM *SA = stream_attributes; /* for better code readability */ init_num = 0, outlet_num = 0; G_message(_("Finding nodes...")); outlet_streams = (unsigned int *)G_malloc((number_of_streams) * sizeof(unsigned int)); init_streams = (unsigned int *)G_malloc((number_of_streams) * sizeof(unsigned int)); init_cells = (unsigned long int *)G_malloc((number_of_streams) * sizeof(unsigned long int)); for (r = 0; r < nrows; ++r) { G_percent(r, nrows, 2); for (c = 0; c < ncols; ++c) { Segment_get(streams, &streams_cell, r, c); Segment_get(dirs, &dirs_cell, r, c); if (streams_cell) { trib_num = seg_number_of_tribs(r, c, streams, dirs); trib = 0; d = abs(dirs_cell); /* r.watershed! */ if (NOT_IN_REGION(d)) next_stream = -1; else Segment_get(streams, &next_streams_cell, NR(d), NC(d)); if (d < 1 || NOT_IN_REGION(d) || !next_streams_cell) next_stream = -1; else Segment_get(streams, &next_stream, NR(d), NC(d)); cur_stream = streams_cell; if (cur_stream != next_stream) { /* junction: building topology */ if (outlet_num > (number_of_streams - 1)) G_fatal_error(_("Error finding nodes. " "Stream and direction maps probably do not match.")); SA[cur_stream].stream = cur_stream; SA[cur_stream].next_stream = next_stream; if (next_stream < 0) /* is outlet stream */ outlet_streams[outlet_num++] = cur_stream; } if (trib_num == 0) { /* is init */ if (init_num > (number_of_streams - 1)) G_fatal_error(_("Error finding nodes. " "Stream and direction maps probably do not match.")); SA[cur_stream].trib_num = 0; init_cells[init_num] = r * ncols + c; init_streams[init_num++] = cur_stream; /* collecting inits */ } if (trib_num > 1) { /* adding tributuaries */ SA[cur_stream].trib_num = trib_num; for (i = 1; i < 9; ++i) { if (trib > 4) G_fatal_error(_("Error finding nodes. " "Stream and direction maps probably do not match.")); if (NOT_IN_REGION(i)) continue; j = DIAG(i); next_r = NR(i); next_c = NC(i); Segment_get(streams, &trib_stream_cell, next_r, next_c); Segment_get(dirs, &trib_dirs_cell, next_r, next_c); if (trib_stream_cell && trib_dirs_cell == j) SA[cur_stream].trib[trib++] = trib_stream_cell; } /* end for i... */ } } /* end if streams */ } } /* end r, c */ G_percent(r, nrows, 2); return 0; }
int ram_stream_topology(CELL **streams, CELL **dirs, int number_of_streams) { int d, i, j; /* d: direction, i: iteration */ int r, c; int next_r, next_c; int trib_num, trib = 0; int next_stream = -1, cur_stream; STREAM *SA = stream_attributes; /* for better code readability */ init_num = 0, outlet_num = 0; G_message(_("Finding nodes...")); outlet_streams = (unsigned int *)G_malloc((number_of_streams) * sizeof(unsigned int)); init_streams = (unsigned int *)G_malloc((number_of_streams) * sizeof(unsigned int)); init_cells = (unsigned long int *)G_malloc((number_of_streams) * sizeof(unsigned long int)); /* free at the end */ for (r = 0; r < nrows; ++r) for (c = 0; c < ncols; ++c) if (streams[r][c]) { trib_num = ram_number_of_tribs(r, c, streams, dirs); trib = 0; d = abs(dirs[r][c]); /* r.watershed! */ if (d < 1 || NOT_IN_REGION(d) || !streams[NR(d)][NC(d)]) next_stream = -1; else next_stream = streams[NR(d)][NC(d)]; cur_stream = streams[r][c]; if (cur_stream != next_stream) { /* junction: building topology */ if (outlet_num > (number_of_streams - 1)) G_fatal_error(_("Error finding nodes. " "Stream and direction maps probably do not match.")); SA[cur_stream].stream = cur_stream; SA[cur_stream].next_stream = next_stream; if (next_stream < 0) /* is outlet stream */ outlet_streams[outlet_num++] = cur_stream; } if (trib_num == 0) { /* is init */ if (init_num > (number_of_streams - 1)) G_fatal_error(_("Error finding nodes. " "Stream and direction maps probably do not match.")); SA[cur_stream].trib_num = 0; init_cells[init_num] = r * ncols + c; init_streams[init_num++] = cur_stream; /* collecting inits */ } if (trib_num > 1) { /* adding tributuaries */ SA[cur_stream].trib_num = trib_num; for (i = 1; i < 9; ++i) { if (trib > 4) G_fatal_error(_("Error finding nodes. " "Stream and direction maps probably do not match.")); if (NOT_IN_REGION(i)) continue; j = DIAG(i); next_r = NR(i); next_c = NC(i); if (streams[next_r][next_c] && dirs[next_r][next_c] == j) SA[cur_stream].trib[trib++] = streams[next_r][next_c]; } /* end for i... */ } } /* end if streams */ return 0; }
template<typename Tin, typename Tout> static __host__ __device__ Tout _pixDist(Tin &pix1, Tin &pix2) { return __pixDist_CN<Tin, Tout, NC(Tin)>::_pixDist_CN(pix1, pix2); }
template<typename Tin, typename Tout, typename Tw> static __host__ __device__ Tout _pixScale(Tin &pix, Tw w) { return __pixScale_CN<Tin, Tout, Tw, NC(Tin)>::_pixScale_CN(pix, w); }
///' Calculate the network properties ///' ///' @details ///' \subsection{Input expectations:}{ ///' Note that this function expects all inputs to be sensible, as checked by ///' the R function 'checkUserInput' and processed by 'networkProperties'. ///' ///' These requirements are: ///' \itemize{ ///' \item{The ordering of node names across 'data' and 'net' is consistent.} ///' \item{The columns of 'data' are the nodes.} ///' \item{'net' is a square matrix, and its rownames are identical to its ///' column names.} ///' \item{'moduleAssigments' is a named character vector, where the names ///' represent node labels found in the discovery dataset. Unlike ///' 'PermutationProcedure', these may include nodes that are not ///' present in 'data' and 'net'.} ///' \item{The module labels specified in 'modules' must occur in ///' 'moduleAssignments'.} ///' } ///' } ///' ///' @param data data matrix from the dataset in which to calculate the network ///' properties. ///' @param net adjacency matrix of network edge weights between all pairs of ///' nodes in the dataset in which to calculate the network properties. ///' @param moduleAssignments a named character vector containing the module ///' each node belongs to in the discovery dataset. ///' @param modules a character vector of modules for which to calculate the ///' network properties for. ///' ///' @return a list containing the summary profile, node contribution, module ///' coherence, weighted degree, and average edge weight for each 'module'. ///' ///' @keywords internal // [[Rcpp::export]] Rcpp::List NetProps ( Rcpp::NumericMatrix data, Rcpp::NumericMatrix net, Rcpp::CharacterVector moduleAssignments, Rcpp::CharacterVector modules ) { // First, scale the matrix data unsigned int nSamples = data.nrow(); unsigned int nNodes = data.ncol(); arma::mat scaledData = Scale(data.begin(), nSamples, nNodes); R_CheckUserInterrupt(); // convert the colnames / rownames to C++ equivalents const std::vector<std::string> nodeNames (Rcpp::as<std::vector<std::string>>(colnames(net))); const std::vector<std::string> sampleNames (Rcpp::as<std::vector<std::string>>(rownames(data))); /* Next, we need to create two mappings: * - From node IDs to indices in the dataset of interest * - From modules to node IDs * - From modules to only node IDs present in the dataset of interest */ const namemap nodeIdxMap = MakeIdxMap(nodeNames); const stringmap modNodeMap = MakeModMap(moduleAssignments); const stringmap modNodePresentMap = MakeModMap(moduleAssignments, nodeIdxMap); // What modules do we actually want to analyse? const std::vector<std::string> mods (Rcpp::as<std::vector<std::string>>(modules)); R_CheckUserInterrupt(); // Calculate the network properties for each module std::string mod; // iterators unsigned int mNodesPresent, mNodes; arma::uvec nodeIdx, propIdx, nodeRank; namemap propIdxMap; std::vector<std::string> modNodeNames; arma::vec WD, SP, NC; // results containers double avgWeight, coherence; Rcpp::NumericVector degree, summary, contribution; // for casting to R equivalents Rcpp::List results; // final storage container for (auto mi = mods.begin(); mi != mods.end(); ++mi) { // What nodes are in this module? mod = *mi; modNodeNames = GetModNodeNames(mod, modNodeMap); // initialise results containers with NA values for nodes not present in // the dataset we're calculating the network properties in. degree = Rcpp::NumericVector(modNodeNames.size(), NA_REAL); contribution = Rcpp::NumericVector(modNodeNames.size(), NA_REAL); summary = Rcpp::NumericVector(nSamples, NA_REAL); avgWeight = NA_REAL; coherence = NA_REAL; degree.names() = modNodeNames; contribution.names() = modNodeNames; // Create a mapping between node names and the result vectors propIdxMap = MakeIdxMap(modNodeNames); // Get just the indices of nodes that are present in the requested dataset nodeIdx = GetNodeIdx(mod, modNodePresentMap, nodeIdxMap); mNodesPresent = nodeIdx.n_elem; // And a mapping of those nodes to the initialised vectors propIdx = GetNodeIdx(mod, modNodePresentMap, propIdxMap); mNodes = propIdx.n_elem; // Calculate the properties if the module has nodes in the test dataset if (nodeIdx.n_elem > 0) { // sort the node indices for sequential memory access nodeRank = SortNodes(nodeIdx.memptr(), mNodesPresent); WD = WeightedDegree(net.begin(), nNodes, nodeIdx.memptr(), mNodesPresent); WD = WD(nodeRank); // reorder results avgWeight = AverageEdgeWeight(WD.memptr(), WD.n_elem); R_CheckUserInterrupt(); SP = SummaryProfile(scaledData.memptr(), nSamples, nNodes, nodeIdx.memptr(), mNodesPresent); R_CheckUserInterrupt(); NC = NodeContribution(scaledData.memptr(), nSamples, nNodes, nodeIdx.memptr(), mNodesPresent, SP.memptr()); NC = NC(nodeRank); // reorder results coherence = ModuleCoherence(NC.memptr(), mNodesPresent); R_CheckUserInterrupt(); // Convert NaNs to NAs SP.elem(arma::find_nonfinite(SP)).fill(NA_REAL); NC.elem(arma::find_nonfinite(NC)).fill(NA_REAL); if (!arma::is_finite(coherence)) { coherence = NA_REAL; } // Fill results vectors Fill(degree, WD.memptr(), mNodesPresent, propIdx.memptr(), mNodes); Fill(contribution, NC.memptr(), mNodesPresent, propIdx.memptr(), mNodes); summary = Rcpp::NumericVector(SP.begin(), SP.end()); } summary.names() = sampleNames; results.push_back( Rcpp::List::create( Rcpp::Named("summary") = summary, Rcpp::Named("contribution") = contribution, Rcpp::Named("coherence") = coherence, Rcpp::Named("degree") = degree, Rcpp::Named("avgWeight") = avgWeight ) ); } results.names() = mods; return(results); }
int seg_calculate_upstream(SEGMENT * distance, SEGMENT * dirs, SEGMENT * elevation, SEGMENT * tmp_elevation, int near) { int r, c; int next_r, next_c; double easting, northing; double cell_easting, cell_northing; int i, j, k, d, d_next; DCELL minus_one_cell = -1; DCELL zero_cell = 0; int done; int counter; int n_inits = 0; double cur_dist; POINT *d_inits; double tmp_dist = 0; double target_elev = 0; CELL dirs_cell; DCELL distance_cell, elevation_cell, tmp_elevation_cell; /* size_t elevation_data_size; */ struct Cell_head window; Rast_get_window(&window); if (elevation) { /* elevation_data_size = Rast_cell_size(DCELL_TYPE); */ for (r = 0; r < nrows; ++r) for (c = 0; c < ncols; ++c) { Segment_get(elevation, &elevation_cell, r, c); Segment_put(tmp_elevation, &elevation_cell, r, c); } } for (r = 0; r < nrows; ++r) for (c = 0; c < ncols; ++c) { Segment_get(distance, &distance_cell, r, c); for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; /* out of border */ j = DIAG(i); next_r = NR(i); next_c = NC(i); Segment_get(dirs, &dirs_cell, next_r, next_c); if (dirs_cell == j && distance_cell != 0) { /* is contributing cell */ Segment_put(distance, &minus_one_cell, r, c); break; } } /* end for i */ Segment_get(distance, &distance_cell, r, c); Segment_get(dirs, &dirs_cell, r, c); if (distance_cell == 1) { if (distance_cell == 1 && dirs_cell > 0) n_inits++; else if (dirs_cell > 0) Segment_put(distance, &minus_one_cell, r, c); } } d_inits = (POINT *) G_malloc(n_inits * sizeof(POINT)); k = 0; for (r = 0; r < nrows; ++r) for (c = 0; c < ncols; ++c) { Segment_get(distance, &distance_cell, r, c); if (distance_cell == 1) { Segment_put(distance, &zero_cell, r, c); if (elevation) Segment_put(elevation, &zero_cell, r, c); Segment_get(dirs, &d, r, c); Segment_get(dirs, &d_next, NR(d), NR(d)); if (d_next < 0) continue; d_inits[k].r = r; d_inits[k].c = c; d_inits[k].cur_dist = 0; if (elevation) Segment_get(tmp_elevation, &(d_inits[k].target_elev), r, c); k++; } } counter = n_inits = k; G_message(_("Calculate upstream parameters...")); while (n_inits > 0) { k = 0; G_percent((counter - n_inits), counter, 10); for (i = 0; i < n_inits; ++i) { r = d_inits[i].r; c = d_inits[i].c; Segment_get(dirs, &d, r, c); next_r = NR(d); next_c = NC(d); tmp_dist = d_inits[i].cur_dist; if (elevation) target_elev = d_inits[i].target_elev; easting = window.west + (c + 0.5) * window.ew_res; northing = window.north - (r + 0.5) * window.ns_res; cell_easting = window.west + (next_c + 0.5) * window.ew_res; cell_northing = window.north - (next_r + 0.5) * window.ns_res; cur_dist = tmp_dist + G_distance(easting, northing, cell_easting, cell_northing); Segment_get(distance, &distance_cell, next_r, next_c); if (near) done = (distance_cell > cur_dist || distance_cell <= 0) ? 1 : 0; else done = (distance_cell < cur_dist || distance_cell <= 0) ? 1 : 0; if (done) { Segment_put(distance, &cur_dist, next_r, next_c); if (elevation) { Segment_get(tmp_elevation, &tmp_elevation_cell, next_r, next_c); tmp_elevation_cell = target_elev - tmp_elevation_cell; Segment_put(elevation, &tmp_elevation_cell, next_r, next_c); } Segment_get(dirs, &dirs_cell, NR(d), NC(d)); if (dirs_cell < 1) continue; d_inits[k].r = next_r; d_inits[k].c = next_c; d_inits[k].cur_dist = cur_dist; if (elevation) d_inits[k].target_elev = target_elev; k++; } /* end of if done */ } n_inits = k; } G_percent(1, 1, 1); return 0; }
int ram_calculate_upstream(DCELL ** distance, CELL ** dirs, DCELL ** elevation, DCELL ** tmp_elevation, int near) { int r, c; int next_r, next_c; double easting, northing; double cell_easting, cell_northing; int i, j, k, d; int done; int counter; int n_inits = 0; double cur_dist; POINT *d_inits; double tmp_dist = 0; double target_elev = 0; size_t elevation_data_size; struct Cell_head window; Rast_get_window(&window); if (elevation) { elevation_data_size = Rast_cell_size(DCELL_TYPE); for (r = 0; r < nrows; ++r) memcpy(tmp_elevation[r], elevation[r], ncols * elevation_data_size); } for (r = 0; r < nrows; ++r) for (c = 0; c < ncols; ++c) { for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; /* out of border */ j = DIAG(i); next_r = NR(i); next_c = NC(i); if (dirs[next_r][next_c] == j && distance[r][c] != 0) { /* is contributing cell */ distance[r][c] = -1; break; } } if (distance[r][c] == 1 && dirs[r][c] > 0) n_inits++; else if (dirs[r][c] > 0) distance[r][c] = -1; } d_inits = (POINT *) G_malloc(n_inits * sizeof(POINT)); k = 0; for (r = 0; r < nrows; ++r) for (c = 0; c < ncols; ++c) { if (distance[r][c] == 1) { distance[r][c] = 0; if (elevation) elevation[r][c] = 0; d = dirs[r][c]; if (dirs[NR(d)][NC(d)] < 0) continue; d_inits[k].r = r; d_inits[k].c = c; d_inits[k].cur_dist = 0; if (elevation) d_inits[k].target_elev = tmp_elevation[r][c]; k++; } } counter = n_inits = k; /* return 0; */ G_message(_("Calculate upstream parameters...")); while (n_inits > 0) { k = 0; G_percent((counter - n_inits), counter, 10); for (i = 0; i < n_inits; ++i) { r = d_inits[i].r; c = d_inits[i].c; d = dirs[r][c]; next_r = NR(d); next_c = NC(d); tmp_dist = d_inits[i].cur_dist; if (elevation) target_elev = d_inits[i].target_elev; easting = window.west + (c + 0.5) * window.ew_res; northing = window.north - (r + 0.5) * window.ns_res; cell_easting = window.west + (next_c + 0.5) * window.ew_res; cell_northing = window.north - (next_r + 0.5) * window.ns_res; cur_dist = tmp_dist + G_distance(easting, northing, cell_easting, cell_northing); if (near) done = (distance[next_r][next_c] > cur_dist || distance[next_r][next_c] <= 0) ? 1 : 0; else done = (distance[next_r][next_c] < cur_dist || distance[next_r][next_c] <= 0) ? 1 : 0; if (done) { distance[next_r][next_c] = cur_dist; if (elevation) { elevation[next_r][next_c] = target_elev - tmp_elevation[next_r][next_c]; } if (dirs[NR(d)][NC(d)] < 1) continue; d_inits[k].r = next_r; d_inits[k].c = next_c; d_inits[k].cur_dist = cur_dist; if (elevation) d_inits[k].target_elev = target_elev; k++; } /* end of if done */ } n_inits = k; } G_percent((counter - n_inits), counter, 10); return 0; }
int ram_calculate_downstream(CELL ** dirs, DCELL ** distance, DCELL ** elevation, OUTLET outlet, int outs) { int r, c, i, j; int next_r, next_c; POINT n_cell; double cur_dist = 0; double tmp_dist = 0; double target_elev; /* eleavation at stream or outlet */ double easting, northing; double cell_easting, cell_northing; struct Cell_head window; Rast_get_window(&window); tail = 0; head = -1; r = outlet.r; c = outlet.c; if (elevation) { target_elev = elevation[r][c]; elevation[r][c] = 0.; } while (tail != head) { easting = window.west + (c + .5) * window.ew_res; northing = window.north - (r + .5) * window.ns_res; for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; /* border */ j = DIAG(i); next_r = NR(i); next_c = NC(i); if (dirs[NR(i)][NC(i)] == j) { /* countributing cell, reset distance and elevation */ if (outs) { /* outlet mode */ if (distance[NR(i)][NC(i)] == 0) continue; /* continue loop, point is not added to the queue! */ else { cell_northing = window.north - (next_r + .5) * window.ns_res; cell_easting = window.west + (next_c + .5) * window.ew_res; cur_dist = tmp_dist + G_distance(easting, northing, cell_easting, cell_northing); distance[NR(i)][NC(i)] = cur_dist; } } else { /* stream mode */ if (distance[next_r][next_c] == 0) { cur_dist = 0; if (elevation) target_elev = elevation[next_r][next_c]; } else { cell_northing = window.north - (next_r + .5) * window.ns_res; cell_easting = window.west + (next_c + .5) * window.ew_res; cur_dist = tmp_dist + G_distance(easting, northing, cell_easting, cell_northing); distance[NR(i)][NC(i)] = cur_dist; } } /* end stream mode */ if (elevation) { elevation[next_r][next_c] = elevation[next_r][next_c] - target_elev; n_cell.target_elev = target_elev; } n_cell.r = next_r; n_cell.c = next_c; n_cell.cur_dist = cur_dist; fifo_insert(n_cell); } } /* end for i... */ n_cell = fifo_return_del(); r = n_cell.r; c = n_cell.c; tmp_dist = n_cell.cur_dist; target_elev = n_cell.target_elev; } /* end while */ return 0; }
int seg_stream_geometry(SEGMENT *streams, SEGMENT *dirs) { int i, s, d; /* s - streams index; d - direction */ int done = 1; int r, c; int next_r, next_c; int prev_r, prev_c; int cur_stream, next_stream, dirs_cell; float cur_northing, cur_easting; float next_northing, next_easting; float init_northing, init_easting; double cur_length = 0.; double cur_accum_length = 0.; STREAM *SA = stream_attributes; /* for better code readability */ struct Cell_head window; G_get_window(&window); G_message(_("Finding longest streams...")); G_begin_distance_calculations(); for (s = 0; s < init_num; ++s) { /* main loop on springs */ G_percent(s, init_num, 2); r = (int)init_cells[s] / ncols; c = (int)init_cells[s] % ncols; Segment_get(streams, &cur_stream, r, c); cur_length = 0; done = 1; SA[cur_stream].init = init_cells[s]; /* stored as index */ init_northing = window.north - (r + .5) * window.ns_res; init_easting = window.west + (c + .5) * window.ew_res; while (done) { cur_northing = window.north - (r + .5) * window.ns_res; cur_easting = window.west + (c + .5) * window.ew_res; Segment_get(dirs, &dirs_cell, r, c); d = abs(dirs_cell); next_r = NR(d); next_c = NC(d); if (NOT_IN_REGION(d)) Rast_set_c_null_value(&next_stream, 1); else Segment_get(streams, &next_stream, next_r, next_c); if (d < 1 || NOT_IN_REGION(d) || !next_stream) { cur_length = (window.ns_res + window.ew_res) / 2; SA[cur_stream].accum_length += cur_length; SA[cur_stream].length += cur_length; SA[cur_stream].stright = G_distance(cur_easting, cur_northing, init_easting, init_northing); SA[cur_stream].outlet = (r * ncols + c); /* add outlet to sorting */ break; } next_northing = window.north - (next_r + .5) * window.ns_res; next_easting = window.west + (next_c + .5) * window.ew_res; cur_length = G_distance(next_easting, next_northing, cur_easting, cur_northing); SA[cur_stream].accum_length += cur_length; SA[cur_stream].length += cur_length; prev_r = r; prev_c = c; r = next_r; c = next_c; if (next_stream != cur_stream) { SA[cur_stream].stright = G_distance(next_easting, next_northing, init_easting, init_northing); init_northing = cur_northing; init_easting = cur_easting; SA[cur_stream].outlet = (prev_r * ncols + prev_c); cur_stream = next_stream; cur_accum_length = 0; SA[cur_stream].init = (r * ncols + c); for (i = 0; i < SA[cur_stream].trib_num; ++i) { if (SA[SA[cur_stream].trib[i]].accum_length == 0) { done = 0; cur_accum_length = 0; break; /* do not pass accum */ } if (SA[SA[cur_stream].trib[i]].accum_length > cur_accum_length) cur_accum_length = SA[SA[cur_stream].trib[i]].accum_length; } /* end for i */ SA[cur_stream].accum_length = cur_accum_length; } /* end if */ } /* end while */ } /* end for s */ G_percent(1, 1, 1); return 0; }
int main(int argc, char* argv[]) { if (argc < 2) { STXXL_MSG("Usage: " << argv[0] << " #ins"); return -1; } const unsigned nins = atoi(argv[1]); STXXL_MSG("Data set size : " << nins * sizeof(std::pair<int, my_type>) << " bytes"); STXXL_MSG("Node cache size: " << node_cache_size << " bytes"); STXXL_MSG("Leaf cache size: " << leaf_cache_size << " bytes"); //stxxl::random_number32 rnd; std::vector<std::pair<int, my_type> > Data(nins); for (unsigned int i = 0; i < nins; ++i) { Data[i].first = i; Data[i].second.data = i; checksum += i; } { btree_type BTree1(Data.begin(), Data.end(), comp_type(), node_cache_size, leaf_cache_size, true); btree_type BTree2(Data.begin(), Data.end(), comp_type(), node_cache_size, leaf_cache_size, true); //STXXL_MSG(*stxxl::stats::get_instance()); C(BTree1); //STXXL_MSG(*stxxl::stats::get_instance()); NC(BTree2); //STXXL_MSG(*stxxl::stats::get_instance()); } { btree_type BTree1(Data.begin(), Data.end(), comp_type(), node_cache_size, leaf_cache_size, true); btree_type BTree2(Data.begin(), Data.end(), comp_type(), node_cache_size, leaf_cache_size, true); STXXL_MSG("Disabling prefetching"); BTree1.disable_prefetching(); BTree2.disable_prefetching(); //STXXL_MSG(*stxxl::stats::get_instance()); C(BTree1); //STXXL_MSG(*stxxl::stats::get_instance()); NC(BTree2); //STXXL_MSG(*stxxl::stats::get_instance()); } STXXL_MSG("All tests passed successfully"); return 0; }
int seg_calculate_downstream(SEGMENT *dirs, SEGMENT * distance, SEGMENT *elevation, OUTLET outlet, int outs) { int r, c, i, j; int next_r, next_c; POINT n_cell; double cur_dist = 0; double tmp_dist = 0; double target_elev; /* eleavation at stream or outlet */ double easting, northing; double cell_easting, cell_northing; CELL dirs_cell; DCELL distance_cell, elevation_cell; DCELL zero_cell = 0; struct Cell_head window; Rast_get_window(&window); tail = 0; head = -1; r = outlet.r; c = outlet.c; if (elevation) { Segment_get(elevation, &target_elev, r, c); Segment_put(elevation, &zero_cell, r, c); } while (tail != head) { easting = window.west + (c + .5) * window.ew_res; northing = window.north - (r + .5) * window.ns_res; for (i = 1; i < 9; ++i) { if (NOT_IN_REGION(i)) continue; /* border */ j = DIAG(i); next_r = NR(i); next_c = NC(i); Segment_get(dirs, &dirs_cell, next_r, next_c); if (dirs_cell == j) { /* countributing cell, reset distance and elevation */ if (outs) { /* outlet mode */ Segment_get(distance, &distance_cell, next_r, next_c); if (distance_cell == 0) continue; /* continue loop, point is not added to the queue! */ else { cell_northing = window.north - (next_r + .5) * window.ns_res; cell_easting = window.west + (next_c + .5) * window.ew_res; cur_dist = tmp_dist + G_distance(easting, northing, cell_easting, cell_northing); Segment_put(distance, &cur_dist, next_r, next_c); } } else { /* stream mode */ Segment_get(distance, &distance_cell, next_r, next_c); if (distance_cell == 0) { cur_dist = 0; if (elevation) Segment_get(elevation, &target_elev, next_r, next_c); } else { cell_northing = window.north - (next_r + .5) * window.ns_res; cell_easting = window.west + (next_c + .5) * window.ew_res; cur_dist = tmp_dist + G_distance(easting, northing, cell_easting, cell_northing); Segment_put(distance, &cur_dist, next_r, next_c); } } /* end stream mode */ if (elevation) { Segment_get(elevation, &elevation_cell, next_r, next_c); elevation_cell -= target_elev; Segment_put(elevation, &elevation_cell, next_r, next_c); n_cell.target_elev = target_elev; } n_cell.r = next_r; n_cell.c = next_c; n_cell.cur_dist = cur_dist; fifo_insert(n_cell); } } /* end for i... */ n_cell = fifo_return_del(); r = n_cell.r; c = n_cell.c; tmp_dist = n_cell.cur_dist; target_elev = n_cell.target_elev; } /* end while */ return 0; }
main(int argc, char **argv) { int sec, i, j, row,strip; int rcout = 1; int ccout = 1; int icout = 1; int lcout = 1; int n1, n2; char name[256]; double res_val, cap_val, ind_val; double I1, I2, I3, I4, I5; double voltage; double cur_var; FILE *fp; setbuf(stdout,0); printf("# row:"); scanf("%d",&row); printf("# RC/RLC sections in each row:"); scanf("%d",&sec); printf("# strips in each row:"); scanf("%d",&strip); printf("filename:"); scanf("%s", name); printf("voltage source:"); scanf("%lf",&voltage); printf("#sec: %d\n",sec); printf("#row: %d\n",row); printf("#vertical strip: %d\n",strip); printf("filename: %s\n",name); printf("voltage: %g\n",voltage); if(strip >= 2*sec) { printf("Invalid p/g strip number %d", strip); exit(-1); } /* first, the netlist file */ fp = fopen(name,"w"); if(!fp) { perror(name); exit(-1); } fprintf(fp,"\n** supply voltage: %g\n", voltage); fprintf(fp,"** #row: %d\n", row); fprintf(fp,"** #RC/RLC section per row: %d\n", sec); fprintf(fp,"** # of p/g strips per row: %d\n", strip); fprintf(fp,"** num_node %d\n",2*sec*row+1); fprintf(fp,"** This is a %d x %d power network\n",row,sec); for(j = 0; j < row; j++) { fprintf(fp,"** row: %d\n",j+1); /* inter-row (strip) connection */ if((row - j) > 1) { int interval = 2*sec/strip; if(interval >= 3) { fprintf(fp,"** p/g strip connection\n"); for( i = 0; i < strip; i++) { //p/g strip has smaller resistance as they are wider. res_val = 4*R_UNIT*(1 + ((rand()%10)/100.0)); // n1 and n2 must be odd number n1 = (j*2*sec + interval*(i+1)); n1 = n1%2?n1:n1-1; n2 = (j+1)*2*sec + interval*(i+1); n2 = n2%2?n2:n2-1; fprintf(fp,"R%d %d %d %g\n", rcout++, n1, n2, res_val); } } else { printf("P/G inseration is ignored as sec/strip is too small: %d\n", interval); } fprintf(fp,"** end of p/g strip connection\n"); } // connect row to the power supply res_val = 0.01*R_UNIT*(1 + ((rand()%10)/100.0)); fprintf(fp,"R%d %d %d %g\n", rcout++, j*2*(sec+1)+1, 2*(sec+1)*row+1, res_val ); for( i = 1; i < 2*sec; i = i + 2) { // time varying current sources I1 = I_UNIT*(((rand()%100)/100.0)); I2 = I_UNIT*(1.3 + ((rand()%100)/100.0)); I3 = I_UNIT*(1 + ((rand()%90)/100.0)); I4 = I_UNIT*(0.5 + ((rand()%80)/100.0)); I5 = I_UNIT*(((rand()%10)/100.0)); fprintf(fp,"I%d %d %d DC 0 PWL(0 0.0 1ns %gmA 2ns %gmA 3ns %gmA 4ns %gmA 5ns %gmA)\n", icout++, NC(i), 0, I1, I2, I3, I4, I5); // capacitance cap_val = C_UNIT*(1 + ((rand()%100)/100.0)); fprintf(fp,"C%d %d %d %g\n", ccout++, NC(i), 0, cap_val); // resistance res_val = R_UNIT*(1 + ((rand()%10)/100.0)); fprintf(fp,"R%d %d %d %g\n", rcout++, NC(i), NC(i+1),res_val); // inductance ind_val = L_UNIT*(1 + ((rand()%10)/100.0)); fprintf(fp,"L%d %d %d %g\n", lcout++, NC(i+1), NC(i+2), ind_val); } I1 = I_UNIT*(((rand()%100)/100.0)); I2 = I_UNIT*(1 + ((rand()%100)/100.0)); I3 = I_UNIT*(1 + ((rand()%90)/100.0)); I4 = I_UNIT*(0.5 + ((rand()%80)/100.0)); I5 = I_UNIT*(((rand()%10)/100.0)); fprintf(fp,"I%d %d %d DC 0 PWL(0 0.0 1ns %gmA 2ns %gmA 3ns %gmA 4ns %gmA 5ns %gmA)\n", icout++, NC(i), 0, I1, I2, I3, I4, I5); // capacitance at one end. cap_val = C_UNIT*(1 + ((rand()%100)/100.0)); fprintf(fp,"C%d %d %d %g\n", ccout++, NC(i), 0, cap_val); // connect to the power supply res_val = 0.01*R_UNIT*(1 + ((rand()%10)/100.0)); fprintf(fp,"R%d %d %d %g\n", rcout++, NC(i), 2*(sec+1)*row+1, res_val); } /* we put a voltage supply at each corner of the chip */ /* fprintf(fp,"V1 %d %d %g \n", 1, 0, voltage); // r = 0, c = 1 fprintf(fp,"V2 %d %d %g \n", 2*sec, 0, voltage); // r = 0 , c = sec fprintf(fp,"V3 %d %d %g \n", (row-2)*2*sec+1, 0, voltage); // r = row-2, c = 1 fprintf(fp,"V4 %d %d %g \n", (row-1)*2*sec, 0, voltage); // r = row-1, c = sec */ fprintf(fp,"\n** supply voltage \n"); fprintf(fp,"V1 %d %d %g \n", row*2*(sec+1)+1, 0, voltage); fprintf(fp,"\n.tran 0.01ns 6n\n"); fprintf(fp,"\n.end\n"); fclose(fp); }
template<typename Tin, typename Tout> static inline __host__ __device__ Tout _pixDemoteClampNN(Tin &pix) { return __pixDemoteClampNN_CN<Tin, Tout, NC(Tin)>::_pixDemoteClampNN_CN(pix); }
main(int argc, char **argv) { int sec, i, j, seg,strip; int rcout = 1; int icout = 1; char name[256]; char spname[256], csname[256]; double voltage, offset; double cur_base = 1.23684e-05, cur_var; double res_base = 1.6, res_var; double length,width = 0.8; FILE *fp; setbuf(stdout,0); printf("#segment:"); scanf("%d",&seg); printf("#R-I section in each segment:"); scanf("%d",&sec); printf("# strip in each segment:"); scanf("%d",&strip); printf("fileroot:"); scanf("%s", name); printf("voltage source:"); scanf("%lf",&voltage); printf("voltage offset:"); scanf("%lf",&offset); printf("#sec: %d\n",sec); printf("#seg: %d\n",seg); printf("#vertical strip: %d\n",strip); printf("filename: %s\n",name); printf("voltage: %g\n",voltage); printf("voltage offset: %g\n",offset); if(strip >= sec) { printf("Invalid p/g strip number %d", strip); exit(-1); } sprintf(spname,"%s.sp",name); sprintf(csname,"%s.cs",name); /* first, the netlist file */ fp = fopen(spname,"w"); if(!fp) { perror(spname); exit(-1); } fprintf(fp,"num_node %d\n",sec*seg+1); fprintf(fp,"matrix_size %d\n\n",sec*seg+2); fprintf(fp,"* %d x %d ground network\n",seg,sec); for(j = 0; j < seg; j++) { fprintf(fp,"*seg: %d\n",j+1); /* inter-segment (strip) connection */ if((seg - j) > 1) { int interval = sec/strip; if(interval < 3) { printf("Serise chain circuit is too small: %d", interval); exit(-1); } fprintf(fp,"* inter-segment connection\n"); for( i = 0; i < strip; i++) { fprintf(fp, "R%d %d %d 6.16 0.8 49.28 37\n",rcout++, j*sec+interval*(i+1), (j+1)*sec + interval*(i+1)); } } fprintf(fp, "R%d %d %d 0.4 20 80 37\n",rcout++, sec*seg+1, j*sec+1 ); for( i = 1; i < sec; i++) { cur_var = cur_base*((rand()%10)/100.0); fprintf(fp,"I%d %d %d %g\n",icout++, NC(i), 0, cur_base + cur_var); res_var = res_base*((rand()%10)/100.0); length = width*(res_var + res_base)*10.0; fprintf(fp,"R%d %d %d %g %g %g 37\n", rcout++, NC(i), NC(i+1),res_base+res_var, width, length); } fprintf(fp,"I%d %d %d 1.23684e-05\n",icout++, NC(i), 0); fprintf(fp,"R%d %d %d 0.5 10 50 37\n",rcout++, NC(i), sec*seg+1); } fprintf(fp,"V1 %d %d %g \n", seg*sec+1, 0, voltage); fprintf(fp,"\n.op"); fprintf(fp,"\n.end"); fclose(fp); /* the constraint file */ fp = fopen(csname,"w"); if(!fp) { perror(csname); exit(-1); } fprintf(fp,"*Layer Information\n"); fprintf(fp,"*Layer Index Unit_Res Min_Width Max_Current_Den\n"); fprintf(fp,"Layer 37 0.1 0.4 1.7\n"); fprintf(fp,"\n*Voltage Constraint\n"); for( i = 1; i <= seg*sec; i++) { fprintf(fp,"Const V(%D) >= %G\n",i,voltage-offset); } fclose(fp); }
int main(int argc, char **argv) { //----------------------- // Input float *h_First_Level_Results, *h_Mask; unsigned short int *h_Permutation_Matrix; float *h_Sign_Matrix; float *h_X_GLM, *h_xtxxt_GLM, *h_Contrasts, *h_ctxtxc_GLM; //----------------------- // Output int *h_Cluster_Indices, *h_Cluster_Indices_Out; float *h_Permutation_Distribution; float *h_Beta_Volumes, *h_Residuals, *h_Residual_Variances, *h_Statistical_Maps, *h_P_Values; float *h_Permuted_First_Level_Results; //-------------- void* allMemoryPointers[500]; for (int i = 0; i < 500; i++) { allMemoryPointers[i] = NULL; } nifti_image* allNiftiImages[500]; for (int i = 0; i < 500; i++) { allNiftiImages[i] = NULL; } int numberOfMemoryPointers = 0; int numberOfNiftiImages = 0; size_t allocatedHostMemory = 0; //-------------- // Default parameters int OPENCL_PLATFORM = 0; int OPENCL_DEVICE = 0; bool DEBUG = false; bool PRINT = true; bool VERBOS = false; bool CHANGE_OUTPUT_NAME = false; int NUMBER_OF_GLM_REGRESSORS = 1; int NUMBER_OF_CONTRASTS = 1; float CLUSTER_DEFINING_THRESHOLD = 2.5f; int NUMBER_OF_PERMUTATIONS = 10000; float SIGNIFICANCE_LEVEL = 0.05f; int TEST_STATISTICS = 0; int INFERENCE_MODE = 1; bool MASK = false; const char* MASK_NAME; const char* DESIGN_FILE; const char* CONTRASTS_FILE; const char* PERMUTATION_INPUT_FILE; const char* PERMUTATION_VALUES_FILE; const char* PERMUTATION_VECTORS_FILE; bool FOUND_DESIGN = false; bool FOUND_CONTRASTS = false; bool ANALYZE_GROUP_MEAN = false; bool USE_PERMUTATION_FILE = false; bool WRITE_PERMUTATION_VALUES = false; bool WRITE_PERMUTATION_VECTORS = false; bool DO_ALL_PERMUTATIONS = false; const char* outputFilename; // Size parameters int DATA_W, DATA_H, DATA_D, NUMBER_OF_SUBJECTS; //--------------------- /* Input arguments */ FILE *fp = NULL; // No inputs, so print help text if (argc == 1) { printf("\nThe function performs permutation testing for group analyses.\n\n"); printf("General usage:\n\n"); printf("RandomiseGroupLevel volumes.nii -design design.mat -contrasts design.con [options]\n\n"); printf("Testing a group mean:\n\n"); printf("RandomiseGroupLevel volumes.nii -groupmean [options]\n\n"); printf("Options:\n\n"); printf(" -platform The OpenCL platform to use (default 0) \n"); printf(" -device The OpenCL device to use for the specificed platform (default 0) \n"); printf(" -design The design matrix to apply in each permutation \n"); printf(" -contrasts The contrast vector(s) to apply to the estimated beta values \n"); printf(" -groupmean Test for group mean, using sign flipping (design and contrast not needed) \n"); printf(" -mask A mask that defines which voxels to permute (default none) \n"); printf(" -permutations Number of permutations to use (default 10,000) \n"); //printf(" -teststatistics Test statistics to use, 0 = GLM t-test, 1 = GLM F-test, 2 = CCA, 3 = Searchlight (default 0) \n"); printf(" -inferencemode Inference mode to use, 0 = voxel, 1 = cluster extent, 2 = cluster mass, 3 = TFCE (default 1) \n"); printf(" -cdt Cluster defining threshold for cluster inference (default 2.5) \n"); printf(" -significance The significance level to calculate the threshold for (default 0.05) \n"); printf(" -output Set output filename (default volumes_perm_tvalues.nii and volumes_perm_pvalues.nii) \n"); printf(" -writepermutationvalues Write all the permutation values to a text file \n"); printf(" -writepermutations Write all the random permutations (or sign flips) to a text file \n"); printf(" -permutationfile Use a specific permutation file or sign flipping file (e.g. from FSL) \n"); printf(" -quiet Don't print anything to the terminal (default false) \n"); printf(" -verbose Print extra stuff (default false) \n"); printf("\n\n"); return EXIT_SUCCESS; } // Try to open file else if (argc > 1) { fp = fopen(argv[1],"r"); if (fp == NULL) { printf("Could not open file %s !\n",argv[1]); return EXIT_FAILURE; } fclose(fp); } // Loop over additional inputs int i = 2; while (i < argc) { char *input = argv[i]; char *p; if (strcmp(input,"-platform") == 0) { if ( (i+1) >= argc ) { printf("Unable to read value after -platform !\n"); return EXIT_FAILURE; } OPENCL_PLATFORM = (int)strtol(argv[i+1], &p, 10); if (!isspace(*p) && *p != 0) { printf("OpenCL platform must be an integer! You provided %s \n",argv[i+1]); return EXIT_FAILURE; } else if (OPENCL_PLATFORM < 0) { printf("OpenCL platform must be >= 0!\n"); return EXIT_FAILURE; } i += 2; } else if (strcmp(input,"-device") == 0) { if ( (i+1) >= argc ) { printf("Unable to read value after -device !\n"); return EXIT_FAILURE; } OPENCL_DEVICE = (int)strtol(argv[i+1], &p, 10); if (!isspace(*p) && *p != 0) { printf("OpenCL device must be an integer! You provided %s \n",argv[i+1]); return EXIT_FAILURE; } else if (OPENCL_DEVICE < 0) { printf("OpenCL device must be >= 0!\n"); return EXIT_FAILURE; } i += 2; } else if (strcmp(input,"-design") == 0) { if ( (i+1) >= argc ) { printf("Unable to read value after -design !\n"); return EXIT_FAILURE; } DESIGN_FILE = argv[i+1]; FOUND_DESIGN = true; i += 2; } else if (strcmp(input,"-contrasts") == 0) { if ( (i+1) >= argc ) { printf("Unable to read value after -contrasts !\n"); return EXIT_FAILURE; } CONTRASTS_FILE = argv[i+1]; FOUND_CONTRASTS = true; i += 2; } else if (strcmp(input,"-groupmean") == 0) { ANALYZE_GROUP_MEAN = true; FOUND_DESIGN = true; FOUND_CONTRASTS = true; i += 1; } else if (strcmp(input,"-permutations") == 0) { if ( (i+1) >= argc ) { printf("Unable to read value after -permutations !\n"); return EXIT_FAILURE; } NUMBER_OF_PERMUTATIONS = (int)strtol(argv[i+1], &p, 10); if (!isspace(*p) && *p != 0) { printf("Number of permutations must be an integer! You provided %s \n",argv[i+1]); return EXIT_FAILURE; } else if (NUMBER_OF_PERMUTATIONS <= 0) { printf("Number of permutations must be > 0!\n"); return EXIT_FAILURE; } i += 2; } else if (strcmp(input,"-inferencemode") == 0) { if ( (i+1) >= argc ) { printf("Unable to read value after -inferencemode !\n"); return EXIT_FAILURE; } INFERENCE_MODE = (int)strtol(argv[i+1], &p, 10); if (!isspace(*p) && *p != 0) { printf("Inference mode must be an integer! You provided %s \n",argv[i+1]); return EXIT_FAILURE; } else if ( (INFERENCE_MODE != 0) && (INFERENCE_MODE != 1) && (INFERENCE_MODE != 2) && (INFERENCE_MODE != 3) ) { printf("Inference mode must be 0, 1, 2 or 3 !\n"); return EXIT_FAILURE; } i += 2; if (INFERENCE_MODE == 3) { printf("TFCE is currently turned off!\n"); return EXIT_FAILURE; } } else if (strcmp(input,"-cdt") == 0) { if ( (i+1) >= argc ) { printf("Unable to read value after -cdt !\n"); return EXIT_FAILURE; } CLUSTER_DEFINING_THRESHOLD = (float)strtod(argv[i+1], &p); if (!isspace(*p) && *p != 0) { printf("Cluster defining threshold must be a float! You provided %s \n",argv[i+1]); return EXIT_FAILURE; } i += 2; } else if (strcmp(input,"-significance") == 0) { if ( (i+1) >= argc ) { printf("Unable to read value after -significance !\n"); return EXIT_FAILURE; } SIGNIFICANCE_LEVEL = (float)strtod(argv[i+1], &p); if (!isspace(*p) && *p != 0) { printf("Significance level must be a float! You provided %s \n",argv[i+1]); return EXIT_FAILURE; } if ( (SIGNIFICANCE_LEVEL <= 0.0f) || (SIGNIFICANCE_LEVEL >= 1.0f) ) { float zero = 0.0f; float one = 1.0f; printf("Significance level must be between %f and %f ! You provided %f \n",zero,one,SIGNIFICANCE_LEVEL); return EXIT_FAILURE; } i += 2; } else if (strcmp(input,"-mask") == 0) { if ( (i+1) >= argc ) { printf("Unable to read name after -mask !\n"); return EXIT_FAILURE; } MASK = true; MASK_NAME = argv[i+1]; i += 2; } else if (strcmp(input,"-debug") == 0) { DEBUG = true; i += 1; } else if (strcmp(input,"-quiet") == 0) { PRINT = false; i += 1; } else if (strcmp(input,"-verbose") == 0) { VERBOS = true; i += 1; } else if (strcmp(input,"-output") == 0) { if ( (i+1) >= argc ) { printf("Unable to read name after -output !\n"); return EXIT_FAILURE; } CHANGE_OUTPUT_NAME = true; outputFilename = argv[i+1]; i += 2; } else if (strcmp(input,"-writepermutationvalues") == 0) { if ( (i+1) >= argc ) { printf("Unable to read name after -writepermutationvalues !\n"); return EXIT_FAILURE; } WRITE_PERMUTATION_VALUES = true; PERMUTATION_VALUES_FILE = argv[i+1]; i += 2; } else if (strcmp(input,"-writepermutations") == 0) { if ( (i+1) >= argc ) { printf("Unable to read name after -writepermutations !\n"); return EXIT_FAILURE; } WRITE_PERMUTATION_VECTORS = true; PERMUTATION_VECTORS_FILE = argv[i+1]; i += 2; } else if (strcmp(input,"-permutationfile") == 0) { if ( (i+1) >= argc ) { printf("Unable to read name after -permutationfile !\n"); return EXIT_FAILURE; } USE_PERMUTATION_FILE = true; PERMUTATION_INPUT_FILE = argv[i+1]; i += 2; } else { printf("Unrecognized option! %s \n",argv[i]); return EXIT_FAILURE; } } if (!FOUND_DESIGN) { printf("No design file detected, aborting! \n"); return EXIT_FAILURE; } if (!FOUND_CONTRASTS) { printf("No contrasts file detected, aborting! \n"); return EXIT_FAILURE; } // Check if BROCCOLI_DIR variable is set if (getenv("BROCCOLI_DIR") == NULL) { printf("The environment variable BROCCOLI_DIR is not set!\n"); return EXIT_FAILURE; } //CLUSTER_DEFINING_THRESHOLD = 2.3f; double startTime = GetWallTime(); // Read data nifti_image *inputData = nifti_image_read(argv[1],1); if (inputData == NULL) { printf("Could not open volumes!\n"); return EXIT_FAILURE; } allNiftiImages[numberOfNiftiImages] = inputData; numberOfNiftiImages++; nifti_image *inputMask; if (MASK) { inputMask = nifti_image_read(MASK_NAME,1); if (inputMask == NULL) { printf("Could not open mask volume!\n"); return EXIT_FAILURE; } allNiftiImages[numberOfNiftiImages] = inputMask; numberOfNiftiImages++; } else { printf("Warning: No mask being used, doing permutations for all voxels.\n"); } double endTime = GetWallTime(); if (VERBOS) { printf("It took %f seconds to read the nifti file(s)\n",(float)(endTime - startTime)); } // Get data dimensions from input data DATA_W = inputData->nx; DATA_H = inputData->ny; DATA_D = inputData->nz; NUMBER_OF_SUBJECTS = inputData->nt; // Check if there is more than one volume if (NUMBER_OF_SUBJECTS <= 1) { printf("Input data is a single volume, nothing to permute! \n"); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } // Check if requested number of permutations is larger than number of possible sign flips, for group mean only if (ANALYZE_GROUP_MEAN) { // Calculate maximum number of sign flips unsigned long int SIGN_FLIPS = (unsigned long int)pow(2.0, (double)NUMBER_OF_SUBJECTS); if ((unsigned long int)NUMBER_OF_PERMUTATIONS > SIGN_FLIPS) { printf("Warning: Number of possible sign flips for group mean is %lu, but %i permutations were requested. Lowering number of permutations to number of possible sign flips. \n",SIGN_FLIPS,NUMBER_OF_PERMUTATIONS); NUMBER_OF_PERMUTATIONS = (int)SIGN_FLIPS; DO_ALL_PERMUTATIONS = true; } else if ((unsigned long int)NUMBER_OF_PERMUTATIONS == SIGN_FLIPS) { DO_ALL_PERMUTATIONS = true; } } // Check if requested number of permutations is larger than number of possible permutations else { unsigned long int MAX_PERMS = factorial(NUMBER_OF_SUBJECTS); if ((unsigned long int)NUMBER_OF_PERMUTATIONS > MAX_PERMS) { printf("Warning: Number of possible permutations for your design is %lu, but %i permutations were requested. Lowering number of permutations to number of possible permutations. \n",MAX_PERMS,NUMBER_OF_PERMUTATIONS); NUMBER_OF_PERMUTATIONS = (int)MAX_PERMS; DO_ALL_PERMUTATIONS = true; } else if ((unsigned long int)NUMBER_OF_PERMUTATIONS == MAX_PERMS) { DO_ALL_PERMUTATIONS = true; } } // Check if mask volume has the same dimensions as the data if (MASK) { int TEMP_DATA_W = inputMask->nx; int TEMP_DATA_H = inputMask->ny; int TEMP_DATA_D = inputMask->nz; if ( (TEMP_DATA_W != DATA_W) || (TEMP_DATA_H != DATA_H) || (TEMP_DATA_D != DATA_D) ) { printf("Input data has the dimensions %i x %i x %i, while the mask volume has the dimensions %i x %i x %i. Aborting! \n",DATA_W,DATA_H,DATA_D,TEMP_DATA_W,TEMP_DATA_H,TEMP_DATA_D); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } } // ------------------------------------------------ // Read number of regressors and number of subjects from design matrix file std::ifstream design; std::ifstream contrasts; if (!ANALYZE_GROUP_MEAN) { design.open(DESIGN_FILE); if (!design.good()) { design.close(); printf("Unable to open design file %s. Aborting! \n",DESIGN_FILE); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } // Get number of regressors std::string tempString; int tempNumber; design >> tempString; // NumRegressors as string std::string NR("NumRegressors"); if (tempString.compare(NR) != 0) { design.close(); printf("First element of the design file should be the string 'NumRegressors', but it is %s. Aborting! \n",tempString.c_str()); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } design >> NUMBER_OF_GLM_REGRESSORS; if (NUMBER_OF_GLM_REGRESSORS <= 0) { design.close(); printf("Number of regressors must be > 0 ! You provided %i regressors in the design file. Aborting! \n",NUMBER_OF_GLM_REGRESSORS); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } else if (NUMBER_OF_GLM_REGRESSORS > 25) { design.close(); printf("Number of regressors must be <= 25 ! You provided %i regressors in the design file. Aborting! \n",NUMBER_OF_GLM_REGRESSORS); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } // Get number of subjects design >> tempString; // NumSubjects as string std::string NS("NumSubjects"); if (tempString.compare(NS) != 0) { design.close(); printf("Third element of the design file should be the string 'NumSubjects', but it is %s. Aborting! \n",tempString.c_str()); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } design >> tempNumber; if (tempNumber <= 0) { design.close(); printf("Number of subjects must be > 0 ! You provided %i in the design file. Aborting! \n",tempNumber); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } // Check for consistency if ( tempNumber != NUMBER_OF_SUBJECTS ) { design.close(); printf("Input data contains %i volumes, while the design file says %i subjects. Aborting! \n",NUMBER_OF_SUBJECTS,tempNumber); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } // ------------------------------------------------ // Read number of regressors and number of contrasts from contrasts file contrasts.open(CONTRASTS_FILE); if (!contrasts.good()) { contrasts.close(); printf("Unable to open contrasts file %s. Aborting! \n",CONTRASTS_FILE); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } // Get number of regressors and number of subjects contrasts >> tempString; // NumRegressors as string if (tempString.compare(NR) != 0) { contrasts.close(); printf("First element of the contrasts file should be the string 'NumRegressors', but it is %s. Aborting! \n",tempString.c_str()); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } contrasts >> tempNumber; // Check for consistency if ( tempNumber != NUMBER_OF_GLM_REGRESSORS ) { contrasts.close(); printf("Design file says that number of regressors is %i, while contrast file says there are %i regressors. Aborting! \n",NUMBER_OF_GLM_REGRESSORS,tempNumber); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } contrasts >> tempString; // NumContrasts as string std::string NC("NumContrasts"); if (tempString.compare(NC) != 0) { contrasts.close(); printf("Third element of the contrasts file should be the string 'NumContrasts', but it is %s. Aborting! \n",tempString.c_str()); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } contrasts >> NUMBER_OF_CONTRASTS; if (NUMBER_OF_CONTRASTS <= 0) { contrasts.close(); printf("Number of contrasts must be > 0 ! You provided %i in the contrasts file. Aborting! \n",NUMBER_OF_CONTRASTS); FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages); return EXIT_FAILURE; } }