repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/scripts/report.py
#!/usr/bin/env python """ Parse the output of an application into a csv file @section License Copyright (C) 2011, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. @author Donald Nguyen <ddn@cs.utexas.edu> """ from __future__ import print_function import sys import os import re import optparse import collections def main(options): class Row: def __init__(self): self.reset() def reset(self): self.r = collections.defaultdict(str) self.header = None def get(self, line, key): return line.split(',')[self.header.index(key)] cols = set() rows = [] row = Row() def add_stat(key, value): # 'Threads' key duplicated so just directly assign instead of accumulate if key != "Threads": try: if options.sum_duplicates: row.r[key] = int(row.r[key]) + int(value) else: row.r[key] = value except ValueError: row.r[key] = value except KeyError: row.r[key] = value else: row.r[key] = value cols.add(key) def add_stat_l(key, value, loop): add_stat(key, value) if loop != '(NULL)': add_stat("%s-%s" % (key, loop), value) def do_start_line(m): if row.r: rows.append(row.r) row.reset() def do_var_line(m): add_stat(m.group('key'), m.group('value')) def do_stat_header(m): row.header = m.group('value').split(',') def do_stat_line(m): v = m.group('value') add_stat_l(row.get(v, 'CATEGORY'), row.get(v, 'sum'), row.get(v, 'LOOP')) def do_old_stat_line(m): add_stat_l(m.group('key'), m.group('value'), m.group('loop')) def do_old_dist_line(m): add_stat_l(m.group('key'), m.group('value'), '%s-%s' % (m.group('loop'), m.group('loopn'))) table = { r'^RUN: Start': do_start_line, r'^RUN: Variable (?P<key>\S+) = (?P<value>\S+)': do_var_line, r'^(RUN|INFO): (?P<key>CommandLine) (?P<value>.*)': do_var_line, r'^INFO: (?P<key>Hostname) (?P<value>.*)': do_var_line, r'^STAT SINGLE (?P<key>\S+) (?P<loop>\S+) (?P<value>.*)': do_old_stat_line, r'^STAT DISTRIBUTION (?P<loopn>\d+) (?P<key>\S+) (?P<loop>\S+) (?P<value>.*)': do_old_dist_line, r'^(?P<value>STATTYPE.*)': do_stat_header, r'^(?P<value>STAT,.*)': do_stat_line } matcher = [(re.compile(s), fn) for (s,fn) in table.iteritems()] for line in sys.stdin: try: for (regex, fn) in matcher: m = regex.match(line) if m: fn(m) break except: sys.stderr.write('Error parsing line: %s' % line) raise if row.r: rows.append(row.r) if options.include: cols = cols.intersect(options.include) elif options.exclude: cols = cols.difference(options.exclude) cols = sorted(cols) print(','.join(cols)) for r in rows: print(','.join([str(r[c]) for c in cols])) if __name__ == '__main__': parser = optparse.OptionParser(usage='usage: %prog [options]') parser.add_option('-i', '--include', dest="include", default=[], action='append', help='column to include in output. Multiple columns can be specified ' + 'with multiple options or a comma separated list of columns.') parser.add_option('--sum-duplicates', dest="sum_duplicates", default=False, action='store_true', help='sum duplicate keys together') parser.add_option('-e', '--exclude', dest="exclude", default=[], action='append', help='column to include in output. Multiple columns can be specified ' + 'with multiple options or a comma separated list of columns.') (options, args) = parser.parse_args() if (not options.include and options.exclude) or (options.include and not options.exclude): parser.error('include and exclude are mutually exclusive') if args: parser.error('extra unknown arguments') main(options)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/scripts/run.py
#!/usr/bin/env python # # Run an application multiple times, varying parameters like # number of threads, etc from __future__ import print_function import sys import os import subprocess import optparse import shlex import signal def die(s): sys.stderr.write(s) sys.exit(1) def print_bright(s): red = '\033[1;31m' endc = '\033[0m' print(red + s + endc) def parse_range(s): """ Parses thread range s Grammar: R := R,R | S | N | N:N | N:N:N N := an integer S := a string """ # Parsing strategy: greedily parse integers with one character # lookahead to figure out exact category s = s + ' ' # append special end marker retval = [] cur = -1 curseq = [] for i in range(len(s)): if s[i] == ',' or s[i] == ' ': if cur < 0: break if len(curseq) == 0: retval.append(s[cur:i]) elif len(curseq) == 1: retval.extend(range(curseq[0], int(s[cur:i]) + 1)) elif len(curseq) == 2: retval.extend(range(curseq[0], curseq[1] + 1, int(s[cur:i]))) else: break cur = -1 curseq = [] elif s[i] == ':' and cur >= 0: curseq.append(int(s[cur:i])) cur = -1 elif cur < 0: cur = i else: pass else: return sorted(set(retval)) die('error parsing range: %s\n' % s) def product(args): """ Like itertools.product but for one iterable of iterables rather than an argument list of iterables """ pools = map(tuple, args) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) def run(cmd, values, envs, options): import subprocess, datetime, os, time, signal, socket new_env = dict(os.environ) new_env.update(envs) is_tty = sys.stdout.isatty() for R in range(options.runs): if is_tty: print_bright('RUN: Start') else: print('RUN: Start') print("RUN: CommandLine %s" % ' '.join(cmd)) print("RUN: Variable Hostname = %s" % socket.gethostname()) print("RUN: Variable Timestamp = %f" % time.time()) for (name, value) in values: print('RUN: Variable %s = %s' % (name, value)) if options.timeout: start = datetime.datetime.now() process = subprocess.Popen(cmd, env=new_env) while process.poll() is None: time.sleep(5) now = datetime.datetime.now() diff = (now-start).seconds if diff > options.timeout: os.kill(process.pid, signal.SIGKILL) #os.waitpid(-1, os.WNOHANG) os.waitpid(-1, 0) print("RUN: Variable Timeout = %d" % (diff*1000)) break retcode = process.returncode else: retcode = subprocess.call(cmd, env=new_env) if retcode != 0: # print command line just in case child process should be died before doing it print("RUN: Error %s" % retcode) if not options.ignore_errors: sys.exit(1) def parse_extra(extra): """ Parse extra command line option. Three cases: (1) <name>::<arg>::<range> (2) ::<arg>::<range> (3) <name>::<range> """ import re if extra.count('::') == 2: (name, arg, r) = extra.split('::') if not name: name = re.sub(r'^-*', '', arg) elif extra.count('::') == 1: (name, r) = extra.split('::') arg = None else: die('error parsing extra argument: %s\n' % extra) return (name, arg, r) def main(args, options): variables = [] ranges = [] extras = [(e, False) for e in options.extra] extras += [(e, True) for e in options.extra_env] for (extra, env) in extras: (name, arg, r) = parse_extra(extra) variables.append((name, arg, env)) ranges.append(parse_range(r)) for prod in product(ranges): params = [] values = [] envs = {} for ((name, arg, env), value) in zip(variables, prod): if env: if arg: envs[arg] = str(value) else: envs[str(value)] = '' else: if arg: params.extend([arg, str(value)]) else: params.extend([str(value)]) values.append((name, str(value))) if options.append_arguments: cmd = args + params else: cmd = [args[0]] + params + args[1:] run(cmd, values, envs, options) if __name__ == '__main__': signal.signal(signal.SIGQUIT, signal.SIG_IGN) sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) parser = optparse.OptionParser(usage='usage: %prog [options] <command line> ...') parser.add_option('--ignore-errors', dest='ignore_errors', default=False, action='store_true', help='ignore errors in subprocesses') parser.add_option('-t', '--threads', dest="threads", default="1", help='range of threads to use. A range is R := R,R | S | N | N:N | N:N:N where N is an integer and S is a string.') parser.add_option('-r', '--runs', default=1, type='int', help='set number of runs') parser.add_option('-x', '--extra', dest="extra", default=[], action='append', help='add commandline parameter to range over (format: <name>::<arg>::<range> or ::<arg>::<range> or <name>::<range>). E.g., delta::-delta::1,5 or ::-delta::1,5 or schedule::-useFIFO,-useLIFO') parser.add_option('-e', '--extra-env', dest="extra_env", default=[], action='append', help='add environment variable to range over (format: <name>::<arg>::<range> or ::<arg>::<range> or <name>::<range>). E.g., delta::-delta::1,5 or ::-delta::1,5 or schedule::-useFIFO,-useLIFO') parser.add_option('-o', '--timeout', dest="timeout", default=0, type='int', help="timeout a run after SEC seconds", metavar='SEC') parser.add_option('--no-default-thread', dest='no_default_thread', default=False, action='store_true', help='supress run command default thread argument') parser.add_option('--append-arguments', dest='append_arguments', default=False, action='store_true', help='append instead of prepend additional command line arguments') (options, args) = parser.parse_args() if not args: parser.error('need command to run') if not options.no_default_thread: options.extra.insert(0, '%s::%s::%s' % ('Threads', '-t', options.threads)) main(args, options)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/scripts/report.R
# Generate pretty graphs from csv # usage: Rscript report.R <report.csv> library(ggplot2) library(reshape2) Id.Vars <- c("Algo","Kind","Hostname","Threads","CommandLine") outputfile <- "" if (interactive()) { theme_grey() inputfile <- "~/report.csv" outputfile <- "" } else { theme_set(theme_bw(base_size=9)) arguments <- commandArgs(trailingOnly=TRUE) if (length(arguments) < 1) { cat("usage: Rscript report.R <report.csv> [output.json]\n") quit(save = "no", status=1) } inputfile <- arguments[1] if (length(arguments) > 1) { outputfile <- arguments[2] } } ### Replace orig[i] with repl[i] in x mreplace <- function(x, orig, repl, defaultIndex=1) { stopifnot(length(orig) == length(repl)) indices <- numeric(length(x)) for (i in 1:length(orig)) { indices[grep(orig[i], x, fixed=T)] <- i } if (sum(indices == 0) > 0) { warning("Some entries were unmatched, using default index") indices[indices == 0] <- defaultIndex } return(sapply(indices, function(x) { repl[x] })) } printMapping <- function(lhs, rhs) { cat("Using following mapping from command line to (Algo,Kind):\n") cat(paste(" ", paste(lhs, rhs, sep=" -> ")), sep="\n") } ### Generate unique and short set of Algo and Kind names from CommandLine parseAlgo <- function(res) { cmds.orig <- sub(" -t \\d+", "", res$CommandLine) cmds.uniq <- unique(cmds.orig) make <- function(rhs) { cmds.new <- mreplace(cmds.orig, cmds.uniq, rhs) printMapping(cmds.uniq, rhs) parts <- strsplit(cmds.new, "\\s+") res$Algo <- sapply(parts, function(x) { x[1] }) res$Kind <- sapply(parts, function(x) { ifelse(length(x) > 1, x[2], "") }) return(res) } # Try various uniquification patterns until one works # Case 1: Extract algo and give kinds unique within an algo algos <- sub("^\\S*?((?:\\w|-|\\.)+)\\s.*$", "\\1", cmds.uniq, perl=T) kinds <- numeric(length(algos)) dupes <- duplicated(algos) version <- 0 while (sum(dupes) > 0) { kinds[dupes] <- version dupes <- duplicated(paste(algos, kinds)) version <- version + 1 } rhs <- unique(paste(algos, kinds)) if (length(cmds.uniq) == length(rhs)) { return(make(rhs)) } # Case 2: XXX/XXX/algo ... kind rhs <- unique(sub("^\\S*?(\\w+)\\s.*?((?:\\w|\\.)+)$", "\\1 \\2", cmds.uniq, perl=T)) if (length(cmds.uniq) == length(rhs)) { return(make(rhs)) } # Case 3: Make all algos unique return(make(1:length(cmds.uniq))) } res.raw <- read.csv(inputfile, stringsAsFactors=F) res <- res.raw[res.raw$CommandLine != "",] cat(sprintf("Dropped %d empty rows\n", nrow(res.raw) - nrow(res))) res <- parseAlgo(res) # Timeouts if ("Timeout" %in% colnames(res)) { timeouts <- !is.na(res$Timeout) res[timeouts,]$Time <- res[timeouts,]$Timeout } else { timeouts <- FALSE } res$Timeout <- timeouts cat(sprintf("Timed out rows: %d\n", sum(timeouts))) # Process partial results partial <- is.na(res$Time) res <- res[!partial,] cat(sprintf("Dropped %d partial runs\n", sum(partial))) # Drop unused columns Columns <- sapply(res, is.numeric) | colnames(res) %in% Id.Vars Columns <- names(Columns)[Columns] Columns <- grep("\\.null\\.", Columns, value=T, invert=T) res <- res[,Columns] summarizeBy <- function(d, f, fun.aggregate=mean, suffix=".Y", merge.with=d, idvars=Id.Vars) { m <- dcast(melt(d[,Columns], id.vars=idvars), f, fun.aggregate) vars <- all.vars(f) merge(merge.with, m, by=vars[-length(vars)], all.x=T, suffixes=c("", suffix)) } # Replace NAs with zeros res[is.na(res)] <- 0 # Make factors res <- data.frame(lapply(res, function(x) if (is.character(x)) { factor(x) } else {x})) # Take mean of multiple runs #res <- recast(res, ... ~ variable, mean, id.var=Id.Vars) # Summarize res <- summarizeBy(subset(res, Threads==1), Algo + Hostname ~ variable, min, ".Ref", merge.with=res) res <- summarizeBy(res, Algo + Kind + Hostname + Threads + CommandLine ~ variable, mean, ".Mean") ggplot(res, aes(x=Threads, y=Time.Ref/Time.Mean, color=Kind)) + geom_point() + geom_line() + scale_y_continuous("Speedup (rel. to best at t=1)") + facet_grid(Hostname ~ Algo, scale="free") ggplot(res, aes(x=Threads, y=Time.Mean/1000, color=Kind)) + geom_point() + geom_line() + scale_y_continuous("Time (s)") + facet_grid(Hostname ~ Algo, scale="free") #ggplot(res, # aes(x=Threads, y=Iterations.Mean/Iterations.Ref, color=Kind)) + # geom_point() + # geom_line() + # scale_y_continuous("Iterations relative to serial") + # facet_grid(Hostname ~ Algo, scale="free") cat("Results in Rplots.pdf\n") ### # Might as well generate simplified json output ### if (outputfile != "") { library(plyr) library(rjson) idvars <- setdiff(Id.Vars, c("Threads","CommandLine")) json <- toJSON(dlply(res, idvars, function(x) { # Just pick representative command line cmd <- x[1,]$CommandLine cmd <- sub(" -t \\d+", "", cmd) # Drop columns being selected on because they are redundant d <- x[,setdiff(Columns, c("CommandLine", idvars))] # Sort by num threads d <- d[order(d$Threads),] list(command=cmd, data=d) })) cat(json, file=outputfile) cat(sprintf("Results in %s\n", outputfile)) }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/scripts/run_web_figures.sh
#!/bin/bash # # Larger test cases for each benchmark set -e BASE="$(cd $(dirname $0); cd ..; pwd)" if [[ -z "$BASEINPUT" ]]; then BASEINPUT="$(pwd)/inputs" fi if [[ -z "$NUMTHREADS" ]]; then NUMTHREADS="$(cat /proc/cpuinfo | grep processor | wc -l)" fi RESULTDIR="$(pwd)/weblogs" if [[ ! -e Makefile ]]; then echo "Execute this script from the base of your build directory" 1>&2 exit 1 fi SKIPPED=0 run() { cmd="$@ -noverify" name=$(echo "$1" | sed -e 's/\//_/g') logfile="$RESULTDIR/$name.log" if [[ ! -e "$logfile" && -x "$1" ]]; then echo -en '\033[1;31m' echo -n "$cmd" echo -e '\033[0m' $BASE/scripts/run.py --threads 1:$NUMTHREADS --timeout $((60*20)) -- $cmd 2>&1 | tee "$logfile" else echo -en '\033[1;31m' echo -n Skipping $1 echo -e '\033[0m' SKIPPED=$(($SKIPPED + 1)) fi } mkdir -p "$RESULTDIR" run apps/avi/AVIodgExplicitNoLock -d 2 -n 1 -e 0.1 -f "$BASEINPUT/avi/10x10_42k.NEU.gz" run apps/barneshut/barneshut -n 50000 -steps 1 -seed 0 run apps/betweennesscentrality/betweennesscentrality-outer "$BASEINPUT/scalefree/rmat8-2e14.gr" run apps/bfs/bfs "$BASEINPUT/random/r4-2e26.gr" run apps/boruvka/boruvka "$BASEINPUT/road/USA-road-d.USA.gr" run apps/clustering/clustering -numPoints 10000 run apps/delaunayrefinement/delaunayrefinement "$BASEINPUT/meshes/r5M" run apps/delaunaytriangulation/delaunaytriangulation "$BASEINPUT/meshes/r5M.node" run apps/des/DESunordered "$BASEINPUT/des/koggeStone64bit.net" run apps/gmetis/gmetis "$BASEINPUT/road/USA-road-d.USA.gr" 256 run apps/kruskal/KruskalHand -maxRounds 600 -lowThresh 16 -preAlloc 32 "$BASEINPUT/random/r4-2e24.gr" run apps/independentset/independentset "$BASEINPUT/random/r4-2e26.gr" run apps/matching/bipartite-mcm 1000000 100000000 10000 0 run apps/preflowpush/preflowpush "$BASEINPUT/random/r4-2e23.gr" 0 100 run apps/spanningtree/spanningtree "$BASEINPUT/random/r4-2e26.gr" run apps/sssp/sssp -delta 8 "$BASEINPUT/random/r4-2e26.gr" run apps/surveypropagation/surveypropagation 9 1000000 3000000 3 # Generate results #cat $RESULTDIR/*.log | python "$BASE/scripts/report.py" > report.csv #Rscript "$BASE/scripts/report.R" report.csv report.json if (($SKIPPED)); then echo -en '\033[1;32m' echo -n "SOME OK (skipped $SKIPPED)" echo -e '\033[0m' else echo -en '\033[1;32m' echo -n ALL OK echo -e '\033[0m' fi
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/scripts/make_dist.sh.in
#!/bin/bash # # Make distribution tarball NAME="Galois-@GALOIS_VERSION_MAJOR@.@GALOIS_VERSION_MINOR@.@GALOIS_VERSION_PATCH@" if [[ ! -e COPYRIGHT ]]; then echo "Run this from the root source directory" 1>&2 exit 1 fi touch "$NAME.tar.gz" # Prevent . from changing during tar (svn status | grep '^\?' | sed -e 's/^\? *//'; \ echo "*.swp"; \ echo "*~"; \ echo "exp"; \ echo "$NAME.tar.gz") | \ tar --exclude-from=- --exclude-vcs --transform "s,^\./,$NAME/," -cz -f "$NAME.tar.gz" .
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/scripts/find_ifdefs.sh
find $* -name '*.h' -o -name '*.cpp' \ | xargs grep --no-filename '#if' \ | awk '{print $2;}' | sort | uniq
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/scripts/run_small.sh
#!/bin/bash # # Small test cases for each benchmark # Die on first failed command set -e BASE="$(cd $(dirname $0); cd ..; pwd)" if [[ ! -e Makefile ]]; then echo "Execute this script from the base of your build directory" 1>&2 exit 1 fi SKIPPED=0 run() { cmd="$@ -t 2" if [[ -x $1 ]]; then echo -en '\033[1;31m' echo -n "$cmd" echo -e '\033[0m' $cmd else echo -en '\033[1;31m' echo -n Skipping $1 echo -e '\033[0m' SKIPPED=$(($SKIPPED + 1)) fi } run apps/avi/AVIodgExplicitNoLock -n 0 -d 2 -f "${BASE}/inputs/avi/squareCoarse.NEU.gz" run apps/barneshut/barneshut -n 1000 -steps 1 -seed 0 run apps/betweennesscentrality/betweennesscentrality-outer "${BASE}/inputs/structured/torus5.gr" -forceVerify run apps/bfs/bfs "${BASE}/inputs/structured/rome99.gr" run apps/boruvka/boruvka "${BASE}/inputs/structured/rome99.gr" run apps/clustering/clustering -numPoints 1000 run apps/delaunayrefinement/delaunayrefinement "${BASE}/inputs/meshes/r10k.1" run apps/delaunaytriangulation/delaunaytriangulation "${BASE}/inputs/meshes/r10k.node" run apps/des/DESunordered "${BASE}/inputs/des/multTree6bit.net" run apps/gmetis/gmetis "${BASE}/inputs/structured/rome99.gr" 4 run apps/kruskal/KruskalHand "${BASE}/inputs/structured/rome99.gr" run apps/independentset/independentset "${BASE}/inputs/structured/rome99.gr" run apps/matching/bipartite-mcm 100 1000 10 0 run apps/preflowpush/preflowpush "${BASE}/inputs/structured/srome99.gr" 0 100 run apps/sssp/sssp "${BASE}/inputs/structured/rome99.gr" run apps/surveypropagation/surveypropagation 9 100 300 3 run apps/tutorial/hello-world 2 10 run apps/tutorial/torus 2 100 run apps/tutorial/torus-improved 2 100 if (($SKIPPED)); then echo -en '\033[1;32m' echo -n "SOME OK (skipped $SKIPPED)" echo -e '\033[0m' else echo -en '\033[1;32m' echo -n ALL OK echo -e '\033[0m' fi
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/scripts/rcat.py
#!/usr/bin/env python """ Like cat but optionally add key-values after 'RUN: Start'. Useful with report.py. @section License Copyright (C) 2012, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. @author Donald Nguyen <ddn@cs.utexas.edu> """ from __future__ import print_function import sys import os import re import optparse import collections def process(fh, options): regex = re.compile(r'^RUN: Start') pairs = [kv.split('=') for kv in options.add] text = '\n'.join(['RUN: Variable %s = %s' % (k, v) for (k,v) in pairs]) for line in fh: print(line, end='') if regex.match(line): print(text) if __name__ == '__main__': parser = optparse.OptionParser(usage='usage: %prog [options]') parser.add_option('-a', '--add-column', dest="add", default=[], action='append', help='column to include in output. Multiple columns can be specified ' + 'with multiple options or a comma separated list of columns. ' + 'Example: --add-column Version=Good') (options, args) = parser.parse_args() if args: for f in args: with open(f) as fh: process(fh, options) else: process(sys.stdin, options)
0
rapidsai_public_repos/code-share/maxflow/galois/scripts
rapidsai_public_repos/code-share/maxflow/galois/scripts/visual/plotTimeStamps.m
data = dlmread('mesh.csv', ',', 1, 0); x = data (:,1); y = data (:,2); z = data (:,3); gridsize = 100; xlin = linspace (min(x), max(x), gridsize); ylin = linspace (min(y), max(y), gridsize); [X, Y] = meshgrid (xlin, ylin); f = TriScatteredInterp (x,y,z, 'nearest');; Z = f(X,Y); % bar3 (Z); hidden off mesh(X,Y,Z); figure() surf(X,Y,Z, 'EdgeColor', 'None'); % shading interp % lighting('phong')
0
rapidsai_public_repos/code-share/maxflow/galois/scripts
rapidsai_public_repos/code-share/maxflow/galois/scripts/visual/plotGraph.R
#!/usr/bin/Rscript library (rgl) args = commandArgs (trailingOnly=T); nodes = read.csv (args[1], header=T); edges = read.csv (args[2], header=T); nodes = nodes[rev (rownames (nodes)), ]; # order by nodeId rownames (nodes) = 1:nrow(nodes); edges = edges[rev (rownames (edges)), ]; # reverse like wise rownames (edges) = 1:nrow(edges); localMin = nodes[nodes$inDeg == 0, ] localMax = nodes[nodes$outDeg == 0, ] srcVec = edges$srcId + 1 dstVec = edges$dstId + 1 arrowCoord = cbind (nodes$centerX[srcVec], nodes$centerY[srcVec], nodes$centerX[dstVec], nodes$centerY[dstVec]); cex=2.5; pch=20 outfile = "adjgraph.pdf" pdf (outfile) plot (nodes$centerX, nodes$centerY, type="p", pch=pch, col="transparent", cex=cex, xlab="", ylab=""); arrows (arrowCoord[,1], arrowCoord[,2], arrowCoord[,3], arrowCoord[,4], length=0.1, angle=7, lwd=1); points (nodes$centerX, nodes$centerY, pch=pch, col="blue", cex=cex); points (localMin$centerX, localMin$centerY, pch=pch, col="red", cex=cex); points (localMax$centerX, localMax$centerY, pch=pch, col="green", cex=cex); dev.off ();
0
rapidsai_public_repos/code-share/maxflow/galois/scripts
rapidsai_public_repos/code-share/maxflow/galois/scripts/visual/plotGraph3d.R
#!/usr/bin/Rscript library (rgl) library (compositions) args = commandArgs (trailingOnly=T); nodes = read.csv (args[1], header=T); edges = read.csv (args[2], header=T); nodes = nodes[rev (rownames (nodes)), ]; # order by nodeId rownames (nodes) = 1:nrow(nodes); edges = edges[rev (rownames (edges)), ]; # reverse like wise rownames (edges) = 1:nrow(edges); # scale time stamps nodes$timeStamp = 500 * nodes$timeStamp; localMin = nodes[nodes$inDeg == 0, ] localMax = nodes[nodes$outDeg == 0, ] srcVec = edges$srcId + 1 dstVec = edges$dstId + 1 open3d (); # segX = nodes$centerX[rbind (srcVec, dstVec)] # segY = nodes$centerY[rbind (srcVec, dstVec)] # segZ = nodes$timeStamp[rbind (srcVec, dstVec)] # segments3d (segX, segY, segZ); arrowStart = cbind (nodes$centerX[srcVec], nodes$centerY[srcVec], nodes$timeStamp[srcVec]); arrowEnd = cbind (nodes$centerX[dstVec], nodes$centerY[dstVec], nodes$timeStamp[dstVec]); arrows3D (arrowStart, arrowEnd, angle=10, length=0.2, size=10, lwd=10); radius=0.15 spheres3d (nodes$centerX, nodes$centerY, nodes$timeStamp, radius=radius, color=c("blue")); spheres3d (localMin$centerX, localMin$centerY, localMin$timeStamp, radius=1.1*radius, color=c("red")); spheres3d (localMax$centerX, localMax$centerY, localMax$timeStamp, radius=1.1*radius, color=c("green")); # rgl.snapshot ("adjgraph3d.png")
0
rapidsai_public_repos/code-share/maxflow/galois/scripts
rapidsai_public_repos/code-share/maxflow/galois/scripts/visual/plot2Dmesh.m
poly = dlmread ('mesh-poly.csv', ',' , 1, 0); coord = dlmread ('mesh-coord.csv', ',', 1, 0); xcoord = coord(:, 1); ycoord = coord(:, 2); zcoord = coord(:, 3); t = poly (:, 1:4); t = t + 1; % triplot (t, x, y); timestamps = poly(:, 4); norm_ts = timestamps ./ max(timestamps); % scale relative to 1; norm_freq = min (timestamps) ./ timestamps; sz = size(t) % colormap Gray; colormap ('default'); cbar = colorbar ('location', 'EastOutside'); set( get(cbar, 'Ylabel'), 'String', 'Number of updates per element normalized to 1'); hold on; for i = 1 : sz(1) x = xcoord(t(i,:)); y = ycoord(t(i,:)); z = zcoord(t(i,:)); fill3 (x, y, z, norm_freq(i), 'LineWidth', 2); end set (get(gca, 'Xlabel'), 'String', 'Xpos of elements'); set (get(gca, 'Ylabel'), 'String', 'Ypos of elements'); title ('Mesh elements colored by number of updates');
0
rapidsai_public_repos/code-share/maxflow/galois/scripts
rapidsai_public_repos/code-share/maxflow/galois/scripts/visual/triplot.m
data = dlmread('mesh.csv', ',', 1, 0); x = data (:,1); y = data (:,2); z = data (:,3); gridsize = 50; xlin = linspace (min(x), max(x), gridsize); ylin = linspace (min(y), max(y), gridsize); [X, Y] = meshgrid (xlin, ylin); f = TriScatteredInterp (x,y,z);; Z = f(X,Y); hidden off mesh(X,Y,Z); figure() surf(X,Y,Z); color('interp') lighting('phong')
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/hi_pr.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +add_definitions(-DCUT_ONLY -DPRINT_STAT) +add_executable(hi_pr hi_pr.c) +install(TARGETS hi_pr DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/bfs-schardl.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 2.6) +add_executable(bfs-schardl bfs.cpp bag.cpp) +install(TARGETS bfs-schardl DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/CMakeLists.txt
add_subdirectory(generators) add_subdirectory(comparisons) add_subdirectory(graph-convert) add_subdirectory(graph-convert-standalone) add_subdirectory(graph-stats) include(ExternalProject) find_program(WGET wget) find_program(UNZIP unzip) ########################################## # Broken external projects ########################################## #ExternalProject_Add(cats-gens # PREFIX cats-gens # # LIST_SEPARATOR is replaced with ";" in generated Makefile # LIST_SEPARATOR | # # default is <prefix>/src # DOWNLOAD_DIR cats-gens/src/cats-gens # DOWNLOAD_COMMAND bash -c "if [ ! -e makefile ] | then ${WGET} --recursive --no-parent --no-host-directories --cut-dirs=3 --reject \"index.html*\" --quiet http://www.avglab.com/andrew/CATS/gens/ | fi" # PATCH_COMMAND bash -c "if [ ! -e CMakeLists.txt ] | then patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/cats-gens.patch | fi" # CMAKE_ARGS # -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} # -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS_RELEASE} # -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} # -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS_RELEASE} # -DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR} #) #ExternalProject_Add(snap # PREFIX snap # LIST_SEPARATOR | # DOWNLOAD_DIR snap/src/snap # DOWNLOAD_COMMAND bash -c "if [ ! -e Snap-11-12-31.zip ] | then ${WGET} --quiet http://snap.stanford.edu/snap/Snap-11-12-31.zip | fi" # UPDATE_COMMAND bash -c "if [ ! -e README ] | then ${UNZIP} Snap-11-12-31.zip | fi" # PATCH_COMMAND bash -c "if [ ! -e CMakeLists.txt ] | then patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/snap.patch | fi" # CMAKE_ARGS # -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} # -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS_RELEASE} # -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} # -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS_RELEASE} # -DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR} #) ########################################## # Working external projects ########################################## # NB(ddn): bash -c "if [ ! -e ... " is a hack to prevent reexecuting # commands when not needed # Manually specify steps because ExternalProject doesn't know about unzip ExternalProject_Add(triangle PREFIX triangle LIST_SEPARATOR | DOWNLOAD_DIR triangle/src/triangle DOWNLOAD_COMMAND bash -c "if [ ! -e triangle.zip ] | then ${WGET} --quiet http://www.netlib.org/voronoi/triangle.zip | fi" UPDATE_COMMAND bash -c "if [ ! -e makefile ] | then ${UNZIP} triangle.zip | fi" PATCH_COMMAND bash -c "if [ ! -e CMakeLists.txt ] | then patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/triangle.patch | fi" CMAKE_ARGS -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS_RELEASE} -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS_RELEASE} -DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR} ) #set(more_tools hi_pr triangle cats-gens snap GTgraph-rmat SSCA2) set(more_tools triangle GTgraph-rmat SSCA2) # Simple download and patch function(dl name url) ExternalProject_Add(${name} PREFIX ${name} LIST_SEPARATOR | DOWNLOAD_DIR ${name}/src/${name} URL ${url} PATCH_COMMAND bash -c "if [ ! -e CMakeLists.txt ] | then patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/${name}.patch | fi" CMAKE_ARGS -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS_RELEASE} -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS_RELEASE} -DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR} ) endfunction(dl) function(cilkdl name url) if(HAVE_CILK) dl(${name} ${url}) set(more_tools ${more_tools} ${name} PARENT_SCOPE) else() message(STATUS "Build of ${name} will be skipped because CILK is not available") endif() endfunction(cilkdl) #dl(hi_pr http://www.avglab.com/andrew/soft/hipr.tar) dl(GTgraph-rmat http://www.cse.psu.edu/~madduri/software/GTgraph/GTgraph.tar.gz) dl(SSCA2 http://www.graphanalysis.org/benchmark/SSCA2-2.2.tar.gz) cilkdl(bfs-schardl http://web.mit.edu/~neboat/www/code/bfs-icc-20120304.tar.gz) cilkdl(bfs-pbbs http://www.cs.cmu.edu/~pbbs/benchmarks/breadthFirstSearch.tar) cilkdl(delaunayrefinement-pbbs http://www.cs.cmu.edu/~pbbs/benchmarks/delaunayRefine.tar) cilkdl(delaunaytriangulation-pbbs http://www.cs.cmu.edu/~pbbs/benchmarks/delaunayTriangulation.tar) cilkdl(independentset-pbbs http://www.cs.cmu.edu/~pbbs/benchmarks/maximalIndependentSet.tar) cilkdl(kruskal-pbbs http://www.cs.cmu.edu/~pbbs/benchmarks/minSpanningTree.tar) add_custom_target(more-tools) set_target_properties(${more_tools} PROPERTIES EXCLUDE_FROM_ALL true) add_dependencies(more-tools ${more_tools})
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/SSCA2.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,24 @@ +cmake_minimum_required(VERSION 2.6) +add_definitions(-DAdd__ -DGALOIS_PATCH) +include_directories(sprng2.0/include sprng2.0/src) +set(sprng + sprng2.0/checkid.c + sprng2.0/cputime.c + sprng2.0/lcg64.c + sprng2.0/makeseed.c + sprng2.0/primes_32.c + sprng2.0/simple_mpi.c + sprng2.0/cmrg.c + sprng2.0/lcg.c + sprng2.0/memory.c + sprng2.0/primes_64.c + sprng2.0/sprng.c + sprng2.0/communicate.c + sprng2.0/fwrap_mpi.c + sprng2.0/lfg.c + sprng2.0/mlfg.c + sprng2.0/store.c) +file(GLOB ssca *.c) +add_executable(SSCA2 ${ssca} ${sprng}) +target_link_libraries(SSCA2 m) +install(TARGETS SSCA2 DESTINATION bin) diff -Naur SSCA2v2.2/init.c SSCA2/init.c --- src/init.c 2007-08-16 15:41:26.000000000 -0500 +++ src.patched/init.c 2012-03-02 11:34:31.086524574 -0600 @@ -35,6 +35,9 @@ MaxIntWeight = (1<<SCALE); SubGraphPathLength = 3; +#ifdef GALOIS_PATCH + K4approx = SCALE; +#else #ifndef VERIFYK4 if (SCALE < 10) K4approx = SCALE; @@ -43,4 +46,5 @@ #else K4approx = SCALE; #endif +#endif }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/triangle.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +add_executable(triangle triangle.c) +target_link_libraries(triangle m) +install(TARGETS triangle DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/independentset-pbbs.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 2.6) +include_directories(incrementalMIS common) +add_definitions(-DCILKP) +file(GLOB Sources incrementalMIS/*.C) +add_executable(independentset-pbbs ${Sources}) +install(TARGETS independentset-pbbs DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/cats-gens.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 2.6) +add_executable(gen_washington washington/washington.c) +add_executable(gen_ac ac_dense/ac.c) +add_executable(gen_ak ak/ak.c) +add_executable(gen_rmf genrmf/genrmf.c genrmf/genio.c genrmf/genmain.c) +install(TARGETS gen_washington gen_ac gen_ak gen_rmf DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/kruskal-pbbs.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 2.6) +include_directories(parallelKruskal common) +add_definitions(-DCILKP) +file(GLOB Sources parallelKruskal/*.C) +add_executable(kruskal-pbbs ${Sources}) +install(TARGETS kruskal-pbbs DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/delaunayrefinement-pbbs.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 2.6) +include_directories(incrementalRefine common) +add_definitions(-DCILKP) +file(GLOB Sources incrementalRefine/*.C) +add_executable(delaunayrefinement-pbbs ${Sources}) +install(TARGETS delaunayrefinement-pbbs DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/bfs-pbbs.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 2.6) +include_directories(deterministicBFS common) +add_definitions(-DCILKP) +file(GLOB Sources deterministicBFS/*.C) +add_executable(bfs-pbbs ${Sources}) +install(TARGETS bfs-pbbs DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/snap.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,5 @@ +cmake_minimum_required(VERSION 2.6) +include_directories(glib snap) +add_executable(graphgen snap/Snap.cpp examples/graphgen/graphgen.cpp) +target_link_libraries(graphgen rt) +install(TARGETS graphgen DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/delaunaytriangulation-pbbs.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 2.6) +include_directories(incrementalDelaunay common) +add_definitions(-DCILKP) +file(GLOB Sources incrementalDelaunay/*.C) +add_executable(delaunaytriangulation-pbbs ${Sources}) +install(TARGETS delaunaytriangulation-pbbs DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/tools/GTgraph-rmat.patch
diff -Naur src/CMakeLists.txt src.patched/CMakeLists.txt --- src/CMakeLists.txt 1969-12-31 18:00:00.000000000 -0600 +++ src.patched/CMakeLists.txt 2011-06-22 11:50:25.697422244 -0500 @@ -0,0 +1,24 @@ +cmake_minimum_required(VERSION 2.6) +add_definitions(-DAdd_) +include_directories(sprng2.0-lite/include sprng2.0-lite/src) +set(sprng sprng2.0-lite/src/primes_32.c + sprng2.0-lite/src/primes_64.c + sprng2.0-lite/src/fwrap_mpi.c + sprng2.0-lite/src/cputime.c + sprng2.0-lite/src/makeseed.c + sprng2.0-lite/src/store.c + sprng2.0-lite/src/simple_mpi.c + sprng2.0-lite/src/memory.c + sprng2.0-lite/src/communicate.c + sprng2.0-lite/src/checkid.c + sprng2.0-lite/src/simple_mpi.c + sprng2.0-lite/src/sprng/sprng.c + sprng2.0-lite/src/lcg/lcg.c + sprng2.0-lite/src/lfg/lfg.c + sprng2.0-lite/src/lcg64/lcg64.c + sprng2.0-lite/src/mlfg/mlfg.c + sprng2.0-lite/src/cmrg/cmrg.c) +file(GLOB rmat R-MAT/*.c) +add_executable(GTgraph-rmat ${rmat} ${sprng}) +target_link_libraries(GTgraph-rmat m) +install(TARGETS GTgraph-rmat DESTINATION bin)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/graph-stats/CMakeLists.txt
app(graph-stats)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/graph-stats/graph-stats.cpp
/** Graph converter -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Dimitrios Prountzos <dprountz@cs.utexas.edu> */ #include "Galois/Galois.h" #include "Galois/Graph/LCGraph.h" #include "llvm/Support/CommandLine.h" #include <iostream> #include <vector> namespace cll = llvm::cl; enum StatMode { summary, sortedoffsethist, degrees, degreehist, indegreehist }; static cll::opt<std::string> inputfilename(cll::Positional, cll::desc("<graph file>"), cll::Required); static cll::list<StatMode> statModeList(cll::desc("Available stats:"), cll::values( clEnumVal(summary, "Graph summary"), clEnumVal(degrees, "Node degrees"), clEnumVal(sortedoffsethist, "Histogram of node offsets with sorted edges"), clEnumVal(degreehist, "Histogram of degrees"), clEnumVal(indegreehist, "Histogram of indegrees"), clEnumValEnd)); typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph graph; void do_summary() { std::cout << "NumNodes: " << graph.size() << "\n"; std::cout << "NumEdges: " << graph.sizeEdges() << "\n"; std::cout << "SizeofEdge: " << graph.edgeSize() << "\n"; } void do_degrees() { for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { std::cout << std::distance(graph.neighbor_begin(*ii), graph.neighbor_end(*ii)) << "\n"; } } void do_hist() { unsigned numEdges = 0; std::map<unsigned, unsigned> hist; for (auto ii = graph.begin(), ee = graph.end(); ii != ee; ++ii) { unsigned val = std::distance(graph.neighbor_begin(*ii), graph.neighbor_end(*ii)); numEdges += val; ++hist[val]; } for (auto pp = hist.begin(), ep = hist.end(); pp != ep; ++pp) std::cout << pp->first << " , " << pp->second << "\n"; } void do_inhist() { std::map<GNode, unsigned> inv; std::map<unsigned, unsigned> hist; for (auto ii = graph.begin(), ee = graph.end(); ii != ee; ++ii) for (auto ei = graph.edge_begin(*ii), eie = graph.edge_end(*ii); ei != eie; ++ei) ++inv[graph.getEdgeDst(ei)]; for (auto pp = inv.begin(), ep = inv.end(); pp != ep; ++pp) ++hist[pp->second]; for (auto pp = hist.begin(), ep = hist.end(); pp != ep; ++pp) std::cout << pp->first << " , " << pp->second << "\n"; } struct EdgeComp { typedef Galois::Graph::EdgeSortValue<GNode, void> Edge; bool operator()(const Edge& a, const Edge& b) const { return a.dst < b.dst; } }; int getLogIndex(ptrdiff_t x) { int logvalue = 0; int sign = x < 0 ? -1 : 1; if (x < 0) x = -x; while (x >>= 1) ++logvalue; return sign * logvalue; } void do_sortedoffsethist() { Graph copy; { // Original FileGraph is immutable because it is backed by a file copy.cloneFrom(graph); } std::map<int, size_t> hist; for (auto ii = graph.begin(), ee = graph.end(); ii != ee; ++ii) { copy.sortEdges<void>(*ii, EdgeComp()); GNode last = *ii; for (auto jj = copy.edge_begin(*ii), ej = copy.edge_end(*ii); jj != ej; ++jj) { GNode dst = copy.getEdgeDst(jj); ptrdiff_t diff = dst - (ptrdiff_t) last; int index = getLogIndex(diff); ++hist[index]; last = dst; } } for (auto pp = hist.begin(), ep = hist.end(); pp != ep; ++pp) std::cout << pp->first << " , " << pp->second << "\n"; } int main(int argc, char** argv) { llvm::cl::ParseCommandLineOptions(argc, argv); graph.structureFromFile(inputfilename); for (unsigned i = 0; i != statModeList.size(); ++i) { switch (statModeList[i]) { case summary: do_summary(); break; case degrees: do_degrees(); break; case degreehist: do_hist(); break; case sortedoffsethist: do_sortedoffsethist(); break; case indegreehist: do_inhist(); break; default: abort(); break; } } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/CMakeLists.txt
# Copy over scripts because needed to generate inputs file(GLOB Sources *.py) file(COPY ${Sources} DESTINATION .)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/random-graph.py
#!/usr/bin/env python """ Generates random graphs @section License Copyright (C) 2011, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. @author Andrew Lenharth <andrewl@lenharth.org> """ from __future__ import print_function import sys import optparse import random import collections def main(num_nodes, seed, options): random.seed(seed) max_weight = int(options.max_weight) num_edges = int(options.density) * num_nodes adj = collections.defaultdict(set) print('p sp %d %d' % (num_nodes, num_edges)) def nextN(): return random.randint(1, num_nodes) def nextE(): return random.randint(1, max_weight) def addEdge(src, dst, w): if dst in adj[src]: return False print('a %d %d %d' % (src, dst, w)) adj[src].add(dst) return True # Form a connected graph for index in xrange(1, num_nodes): addEdge(index, index+1, nextE()) addEdge(num_nodes, 1, nextE()) for index in xrange(num_edges - num_nodes): while not addEdge(nextN(), nextN(), nextE()): pass if __name__ == '__main__': usage = 'usage: %prog [options] <num nodes> <seed>' parser = optparse.OptionParser(usage=usage) parser.add_option('--max-weight', dest="max_weight", default=10000, action='store', help='edge weights are uniformly selected from integers \ between (0, max-weight]') parser.add_option('--density', dest="density", default=4, action='store', help='total number of edges is numnodes * density') (options, args) = parser.parse_args() if len(args) != 2: parser.error('missing arguments') main(int(args[0]), int(args[1]), options)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/rmat.py
#!/usr/bin/env python """ Wrapper around GTgraph program. @section License Copyright (C) 2013, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. @author Donald Nguyen <ddn@cs.utexas.edu> """ from __future__ import print_function import optparse import random import tempfile import subprocess; def writeConfig(f, options): f.write('n %s\n' % options.num_nodes) f.write('m %s\n' % options.num_edges) f.write('a %s\n' % options.a) f.write('b %s\n' % options.b) f.write('c %s\n' % options.c) f.write('d %s\n' % options.d) f.write('MAX_WEIGHT %s\n' % options.max_weight) f.write('MIN_WEIGHT %s\n' % options.min_weight) f.write('SELF_LOOPS 0\n') f.write('STORE_IN_MEMORY 0\n') f.write('SORT_EDGELISTS 0\n') f.write('SORT_TYPE 1\n') f.write('WRITE_TO_FILE 1\n') f.flush() def main(GTgraph, output, options): with tempfile.NamedTemporaryFile(delete=False) as f: writeConfig(f, options) subprocess.check_call([GTgraph, '-c', f.name, '-o', output]) if __name__ == '__main__': usage = 'usage: %prog [options] <GTgraph binary> <output>' parser = optparse.OptionParser(usage=usage) parser.add_option('-n', '--num-nodes', dest="num_nodes", action='store', help='Number of nodes.') parser.add_option('-m', '--num-edges', dest="num_edges", action='store', help='Number of edges.') parser.add_option('-a', '--param-a', dest="a", action='store', default='0.45', help='Parameter a of rmat.') parser.add_option('-b', '--param-b', dest="b", action='store', default='0.15', help='Parameter b of rmat.') parser.add_option('-c', '--param-c', dest="c", action='store', default='0.15', help='Parameter c of rmat.') parser.add_option('-d', '--param-d', dest="d", action='store', default='0.25', help='Parameter d of rmat.') parser.add_option('--max-weight', dest="max_weight", default=100, action='store', help='edge weights are uniformly selected from integers between [min-weight, max-weight].') parser.add_option('--min-weight', dest="min_weight", default=0, action='store', help='edge weights are uniformly selected from integers between [min-weight, max-weight].') (options, args) = parser.parse_args() if not options.num_nodes: parser.error('missing num nodes') if not options.num_edges: parser.error('missing num edges') if len(args) != 2: parser.error('missing required arguments') main(args[0], args[1], options)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/2d-graph.py
#!/usr/bin/env python """ Generates 2D graphs @section License Copyright (C) 2011, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. @author Donald Nguyen <ddn@cs.utexas.edu> """ from __future__ import print_function import sys import optparse import random import collections class Random: def __init__(self, N, max_weight): self.N = N self.max_weight = max_weight self.indices = range(0, N*N) random.shuffle(self.indices) def addEdge(self, ax, ay, bx, by): da = self.xy2d(ax, ay) db = self.xy2d(bx, by) w = random.randint(1, self.max_weight) print('a %d %d %d' % (da+1, db+1, w)) def xy2d(self, x, y): return self.indices[y * self.N + x] # From Wikipedia: http://en.wikipedia.org/wiki/Hilbert_curve (7/9/12) def xy2d(n, x, y): rx = 0 ry = 0 d = 0 s = n / 2 while s > 0: rx = (x & s) > 0 ry = (y & s) > 0 d += s * s * ((3 * rx) ^ ry) (x, y) = rot(s, x, y, rx, ry) s /= 2 return d def d2xy(n, d): t = d s = 1 x = 0 y = 0 while s < n: rx = 1 & (t/2) ry = 1 & (t ^ rx) (x, y) = rot(s, x, y, rx, ry) x += s * rx y += s * ry t /= 4 s *= 2 return (x,y) def rot(n, x, y, rx, ry): if ry == 0: if rx == 1: x = n-1 - x y = n-1 - y t = x x = y y = t return (x,y) class Hilbert: def __init__(self, N, max_weight): self.N = N self.max_weight = max_weight def addEdge(self, ax, ay, bx, by): da = xy2d(self.N, ax, ay) db = xy2d(self.N, bx, by) w = random.randint(1, self.max_weight) print('a %d %d %d' % (da+1, db+1, w)) def main(N, seed, options): random.seed(seed) max_weight = int(options.max_weight) num_nodes = N * N num_edges = num_nodes * 2 - 2 * N print('p sp %d %d' % (num_nodes, num_edges)) if options.reorder: G = Hilbert(N, max_weight) else: G = Random(N, max_weight) for x in xrange(0, N): for y in xrange(0, N): if x != N - 1: G.addEdge(x, y, x+1, y) if y != N - 1: G.addEdge(x, y, x, y+1) if __name__ == '__main__': usage = 'usage: %prog [options] <N> <seed>' parser = optparse.OptionParser(usage=usage) parser.add_option('--max-weight', dest="max_weight", default=10000, action='store', help='edge weights are uniformly selected from integers \ between (0, max-weight]') parser.add_option('--reorder', dest="reorder", default=False, action="store_true", help="reorder nodes with space filling curve") (options, args) = parser.parse_args() if len(args) != 2: parser.error('missing arguments') main(int(args[0]), int(args[1]), options)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/clique.py
#!/usr/bin/env python """ Generates k-cliques @section License Copyright (C) 2013, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. @author Donald Nguyen <ddn@cs.utexas.edu> """ from __future__ import print_function import optparse import random def main(N, seed, options): random.seed(seed) max_weight = int(options.max_weight) for x in xrange(0, N): for y in xrange(0, N): if x == y: continue if max_weight: w = random.randint(1, max_weight) print('%d %d %d' % (x, y, w)) else: print('%d %d' % (x, y)) if __name__ == '__main__': usage = 'usage: %prog [options] <N> [seed]' parser = optparse.OptionParser(usage=usage) parser.add_option('--max-weight', dest="max_weight", default=0, action='store', help='edge weights are uniformly selected from integers between (0, max-weight]. \ If zero (default), generate unweighted graph.') (options, args) = parser.parse_args() if len(args) != 1: parser.error('missing arguments') if len(args) == 1: seed = 0 else: seed = int(args[1]) main(int(args[0]), seed, options)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/random-2d-points.py
#!/usr/bin/env python """ Generates random 2d points for use with Delaunay Triangulation. @section License Copyright (C) 2011, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. @author Donald Nguyen <ddn@cs.utexas.edu> """ from __future__ import print_function import sys import optparse import random def main(npoints, seed, options): random.seed(seed) print('%d 2 0 0' % npoints) if not options.realistic: for i in xrange(npoints): x = random.random() * npoints y = random.random() * npoints # repr to get maximum precision in ASCII'ed representation print('%d %s %s 0' % (i, repr(x), repr(y))) else: # produce spatially coherent bins of about 10000 points each pass if __name__ == '__main__': usage = 'usage: %prog [options] <num points> <seed>' parser = optparse.OptionParser(usage=usage) parser.add_option('-r', '--realistic', dest="realistic", default=False, action='store_true', help='use a more realistic strategy for generating points') (options, args) = parser.parse_args() if len(args) != 2: parser.error('missing arguments') if options.realistic: parser.error('not yet implemented') main(int(args[0]), int(args[1]), options)
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/grpXorNandArrayGen.pl
#!/usr/bin/perl use strict; use warnings; my $N = shift @ARGV; print "finish=100000\n\n"; foreach my $i ( 0..$N-1 ) { print "\ngroup\n"; print "\ninputs a$i, b$i end\n"; print "\noutputs o$i end \n"; print "\ninitlist a$i\n"; foreach my $j( 0..$N*$N-1 ) { print 5*$j, ", ", ($j%2),"\n"; # toggle value after every 5 } # 0,0 # 5,1 # 10,0 # 15,1 print "end\n"; print "\ninitlist b$i\n"; foreach my $j ( 0..$N*$N-1 ) { print 10*$j, ", ", ($j%2),"\n"; # toggle value after every 10 } print "end\n"; # the gate netlist print <<HERE; netlist nand2(x$i,a$i,b$i)#40 nand2(y$i,a$i,x$i)#40 nand2(z$i,b$i,x$i)#40 nand2(o$i,y$i,z$i)#40 end HERE #end of group i print "\nend\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/grpAdderGen.pl
#!/usr/bin/perl use strict; use warnings; require "../scripts/netlistLib.pl"; require "../scripts/devicelib.pl"; srand(time); my $MAX_TIME=100; my $FinishTime = 10000; my $NUM_THREADS = 4; my $DEBUG=0; my $numBits = shift @ARGV; $NUM_THREADS = (@ARGV) ? shift @ARGV : $NUM_THREADS; genAdderGrped("adder$numBits.grp", $numBits, 2**$numBits-1, 2**$numBits-1, 1); sub genAdderGrped { my ($fileName,$numBits,$a,$b,$cin)=@_; # open(OUTFILE, "> $fileName" ) or die "Could not open file $fileName for writing"; *OUTFILE = *STDOUT; print OUTFILE "\nfinish $FinishTime\n"; my $aInitArray = genInitListNbit($numBits, "a", $a); my $bInitArray = genInitListNbit($numBits, "b", $b); my $cinInit = genInitList1bit("cin", $cin); for my $i ( 0..$numBits-1 ) { print OUTFILE "\ngroup\n"; # input declaration print OUTFILE "\ninputs a$i, b$i"; if( $i == 0 ) { print OUTFILE ", cin "; } print OUTFILE " end\n"; #input initlist print OUTFILE $aInitArray->[$i]; print OUTFILE $bInitArray->[$i]; if( $i == 0 ) { print OUTFILE $cinInit; } print OUTFILE "outputs s$i"; if( $i == $numBits-1 ) { print OUTFILE ", cout "; } print " end\n"; # instantiate 1 bit adder here my $cinNet = ($i==0) ? "cin": "c".($i-1); my $coutNet = ($i==$numBits-1) ? "cout" : "c$i"; print OUTFILE "\nnetlist\n"; print OUTFILE (genAdder1bit( "s$i", $coutNet, "a$i", "b$i", $cinNet )); print OUTFILE "end\n"; print OUTFILE "\nend\n"; } } sub scanOutput { my ($lines , $numBits ) = @_; print "lines = $lines , numBits = $numBits\n" if $DEBUG; my $outNameIndex = 6; my $outValIndex = 8; my @sumArray = (1..$numBits); my $coutVal = 0; print "cout = $coutVal , sum = ", reverse( @sumArray ) ,"\n#\n" if $DEBUG; foreach my $l ( @$lines ) { my @a = split ' ', $l; my $outName = $a[$outNameIndex]; my $outVal = $a[$outValIndex]; if( $outName =~ /cout/ ) { $coutVal = $outVal; } elsif ( $numBits == 1 ) { $sumArray[0] = $outVal; } else { $outName =~ s/\D+//g; # extracting the index $sumArray[$outName] = $outVal; } } # DEBUG print "cout = $coutVal , sum = ", reverse (@sumArray) ,"\n" if $DEBUG; my $result = $coutVal; foreach my $i ( reverse @sumArray ) { # msb to lsb $result = $result*2; $result = $result + $i; } return $result; }
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/testTreeMult.pl
#!/usr/bin/perl # use strict; use warnings; require "../scripts/netlistlib.pl"; require "../scripts/devicelib.pl"; my $numBits = shift @ARGV; my $GaloisBin = '~/projects/Galois/trunk/bin'; my $testFile = "/tmp/mult$numBits.net"; my $cmd = "cd $GaloisBin && java eventdrivensimulation.SerialEventdrivensimulation $testFile"; foreach my $aVal ( 0..2**$numBits-1) { foreach my $bVal( 0..2**$numBits-1) { my $mVal = ($aVal*$bVal) ; print "============= aVal = $aVal, bVal = $bVal, | mVal = $mVal =============\n" if ( 1 ); open ( FH, "> $testFile") or die "could not open file $testFile"; # generate the test into the file genMultTest( *FH, $numBits, $mVal, $aVal, $bVal); close ( FH ); # exit status of the wait call my $exitStatus = system( $cmd ); # exit status of the cmd $exitStatus >>= 8; if( $exitStatus != 0 ) { system( "cp $testFile $testFile.bak"); print STDERR "Error in simulation, file backed up as $testFile.bak"; exit(1); } } }
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/genAdderRC.pl
#!/usr/bin/perl use strict; use warnings; require "../scripts/netlistlib.pl"; require "../scripts/devicelib.pl"; my $FinishTime = 10000; my $numBits = shift @ARGV; genAdderRC( $numBits, 2**$numBits-1, 1, 2**$numBits-1, 2**$numBits-1, 1 ); sub genAdderRC { my ($numBits, $sVal, $coutVal, $aVal, $bVal, $cinVal )=@_; *OUTFILE=*STDOUT; my $inputAList = genPortVector("a",$numBits); my $inputBList = genPortVector("b",$numBits); print OUTFILE "\nfinish $FinishTime\n"; print OUTFILE "\ninputs cin, $inputAList, $inputBList\nend\n"; my $outputList = genPortVector("s", $numBits ); print OUTFILE "\noutputs cout, $outputList \nend\n"; my $sOutValues = genOutValuesNbit( $numBits, "s", $sVal ); my $coutOutValues = genOutValues1bit ( "cout", $coutVal ); print "\noutvalues\n"; print "@$sOutValues\n"; print ", $coutOutValues\n"; print "end\n"; my $aInitList = genInitListNbit( $numBits, "a", $aVal ); my $bInitList = genInitListNbit( $numBits, "b", $bVal ); my $cinInitlist = genInitList1bit( "cin", $cinVal ); print "\n@$aInitList\n"; print "\n@$bInitList\n"; print "\n$cinInitlist\n"; if( $numBits == 1 ) { print OUTFILE "\nnetlist\n"; print OUTFILE genAdder1bit("s", "cout", "a", "b", "cin" ); print OUTFILE "\nend\n"; } else { print OUTFILE "\nnetlist\n"; print OUTFILE ( genAdder1bit("s0", "c0", "a0", "b0", "cin" ) ); print OUTFILE "\nend\n"; foreach my $i( 1..$numBits-2 ) { print OUTFILE "\nnetlist\n"; print OUTFILE ( genAdder1bit("s$i", "c$i", "a$i", "b$i", "c".($i-1) ) ); print OUTFILE "\nend\n"; } print OUTFILE "\nnetlist\n"; print OUTFILE ( genAdder1bit("s".($numBits-1), "cout", "a".($numBits-1), "b".($numBits-1), "c".($numBits-2) ) ); print OUTFILE "\nend\n"; } }
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/adder_1bit.m4
define(`adder_1bit',` inv($3n,$3)#4 inv($4n,$4)#4 inv($5n,$5)#4 and2($3n$4n,$3n,$4n)#2 and2($3n$4,$3n,$4)#2 and2($3$4n,$3,$4n)#2 and2($3$4,$3,$4)#3 and2($3$4$5,$3$4,$5)#2 and2($3n$4n$5,$3n$4n,$5)#2 and2($3n$4$5n,$3n$4,$5n)#2 and2($3$4n$5n,$3$4n,$5n)#2 and2($4$5,$4,$5)#2 and2($3$5,$5,$3)#2 or2($1w42,$3$4n$5n,$3n$4$5n)#3 or2($1w71,$3$4$5, $3n$4n$5)#3 or2($1,$1w42,$1w71)#3 or2($1w35, $4$5, $3$5)#3 or2($2,$1w35,$3$4)#5 ')
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/genCSA.pl
#!/usr/bin/perl # use strict; use warnings; require "../scripts/netlistlib.pl"; require "../scripts/devicelib.pl"; my $finishTime = 100000; my $numBits = shift @ARGV; my $numEvents = ( @ARGV ) ? shift @ARGV : 200 ; genCSAtest($numBits, 2**$numBits-1, 2**$numBits-1, 2**$numBits-1, 2**$numBits-1, 2**$numBits-1 ); sub genCSAtest { my ($numBits,$s, $t, $a,$b,$c)=@_; print "\nfinish $finishTime\n"; # generate the port declarations my $aInput = genPortVector("a",$numBits); my $bInput = genPortVector("b",$numBits); my $cInput = genPortVector("c",$numBits); print "\ninputs\n"; print "$aInput\n"; print "$bInput\n"; print "$cInput\n"; print "end\n"; # generate $numEvents events my $aInitArray = genInitListNbit($numBits, "a", $a, $numEvents); my $bInitArray = genInitListNbit($numBits, "b", $b, $numEvents); my $cInitArray = genInitListNbit($numBits, "c", $c, $numEvents); print "\n @$aInitArray \n"; print "\n @$bInitArray \n"; print "\n @$cInitArray \n"; my $sOutput = genPortVector("s", $numBits ); my $tOutput = genPortVector("t", $numBits ); print "\noutputs\n"; print "$sOutput\n"; print "$tOutput\n"; print "end\n"; my $sOutValList = genOutValuesNbit( $numBits, "s", $s ); my $tOutValList = genOutValuesNbit( $numBits, "t", $t ); print "\noutvalues\n"; print "@$sOutValList\n"; print "@$tOutValList\n"; print "\nend\n"; genCSA($numBits, "s", "t", "a", "b", "c" ); } sub genCSA { my ($numBits,$s,$t,$a,$b,$c) = @_; foreach my $i ( 0..$numBits-1 ) { print "\nnetlist\n"; print genAdder1bit( $s.$i, $t.$i, $a.$i, $b.$i, $c.$i ); print "\nend\n"; } }
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/tryOut.pl
#!/usr/bin/perl # use strict; use warnings; my $v = [ map { "a_".$_; } (0..10) ]; print "@$v[0..3]\n";
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/testKoggeStone.pl
#!/usr/bin/perl # use strict; use warnings; require "../scripts/netlistlib.pl"; require "../scripts/devicelib.pl"; my $numBits = 8; my $FinishTime = 100000; $numBits = shift @ARGV; my $GaloisBin = '~/projects/Galois/trunk/bin'; my $testFile = "/tmp/ks$numBits.net"; my $cmd = "cd $GaloisBin && java eventdrivensimulation.SerialEventdrivensimulation $testFile"; foreach my $aVal ( 0..2**$numBits-1) { foreach my $bVal( 0..2**$numBits-1) { foreach my $cinVal( 0..1) { my $coutVal = ($aVal+$bVal+$cinVal) / (2**$numBits); my $sVal = ($aVal+$bVal+$cinVal) % (2**$numBits); $coutVal = int($coutVal); print "============= aVal = $aVal, bVal = $bVal, cinVal = $cinVal | sVal = $sVal, coutVal = $coutVal ============\n" if ( 1 ); open ( FH, "> $testFile") or die "could not open file $testFile"; # generate the test into the file genKoggeStoneTest( *FH, $numBits, $sVal, $coutVal, $aVal, $bVal, $cinVal ); close ( FH ); # exit status of the wait call my $exitStatus = system( $cmd ); # exit status of the cmd $exitStatus >>= 8; if( $exitStatus != 0 ) { system( "cp $testFile $testFile.bak"); print STDERR "Error in simulation, file backed up as $testFile.bak"; exit(1); } } } }
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/genKoggeStone.pl
#!/usr/bin/perl # use strict; use warnings; require "netlistlib.pl"; require "devicelib.pl"; my $numBits = 8; my $FinishTime = 10000; $numBits = shift @ARGV; genKoggeStoneTest( *STDOUT, $numBits, 2**$numBits-1, 1, 2**$numBits-1, 2**$numBits-1, 1 );
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/netlistlib.pl
my $MAX_INTER = 100; my $FinishTime = 100000; sub genPortVector { my ($prefix,$numBits) = @_; my $str=""; my $sep = ""; if( $numBits == 1 ) { $str = $prefix; } else { foreach my $i ( 0..$numBits-1 ) { $str = $str.$sep."${prefix}$i"; $sep=", "; } } return $str; } sub genInitList1bit { my ($sigName, $val) = @_; my $t = int( rand()*$MAX_INTER + 1 ) ; # preventing time to be zero return "initlist $sigName 0, 0 $t, $val end\n"; } # params # # numBits # prefix string that is prefix of a vector e.g. for a0,a1,a2,...,a7 'a' is the prefix # val integer value the vector is to be initialized to # numEvents the number of events/changes to the input before the final event assigning val occurs # maxInter max interval between changes to the input sub genInitListNbit { my ( $numBits, $prefix, $val) = @_[0..2]; # first 3 args # shift 3 times now shift @_; shift @_; shift @_; my $numEvents = ( @_ != 0 ) ? shift @_ : 0 ; # by default my $maxInter = (@_) ? shift @_ : $MAX_INTER ; my $binStr = sprintf("%0${numBits}b",$val); if( $DEBUG ) { print "$binStr\n"; } my @initList; foreach my $i( 0..$numBits-1 ) { my $bit = substr( $binStr , length($binStr)-$i-1 , 1 ); my $init = "initlist ${prefix}$i 0,0 "; my $prevVal = 0; my $prevTime = 0; foreach (1..$numEvents) { $prevVal = 1 - $prevVal ; # toggle value b/w 1 and 0 $prevTime = int( rand()*$MAX_INTER + 1 ) + $prevTime; $init = $init." $prevTime,$prevVal \n"; } # now add the actual final time,value pair my $rt = int( rand()*$MAX_INTER + 1 ) + $prevTime ; # preventing time to be zero $init = $init." $rt,$bit end\n"; push @initList , $init; } return \@initList; } sub genOutValuesNbit { my ($numBits,$outPre,$outVal) = @_; my $binStr = sprintf("%0${numBits}b",$outVal); if( 0 ) { print "$binStr\n"; } my @outValList; foreach my $i ( 0..$numBits-1 ) { my $bit = substr( $binStr , length($binStr)-$i-1 , 1 ); my $str = $outPre.$i." ".$bit. ", "; push @outValList, $str; } return \@outValList; } sub genOutValues1bit { my ($outName,$outVal)= @_; my $str = "$outName $outVal, "; return $str; } sub genKoggeStoneTest { my ($FH, $numBits,$s,$cout,$a,$b,$cin)=@_; print $FH "\nfinish $FinishTime\n"; my $inputAList = genPortVector("a",$numBits); my $inputBList = genPortVector("b",$numBits); print $FH "\ninputs cin, $inputAList, $inputBList\nend\n"; my $outputList = genPortVector("s", $numBits ); print $FH "\noutputs cout, $outputList \nend\n"; my $initListA = genInitListNbit($numBits, "a", $a, 256 ); my $initListB = genInitListNbit($numBits, "b", $b, 256 ); my $initListCin = genInitList1bit("cin", $cin); print $FH "\n@$initListA\n"; print $FH "\n@$initListB\n"; print $FH "\n$initListCin\n"; my $sOutValues = genOutValuesNbit( $numBits, "s", $s ); my $coutOutValues = genOutValues1bit( "cout", $cout ); print $FH "\noutvalues\n"; print $FH "@$sOutValues\n"; print $FH ", $coutOutValues\n"; print $FH "end\n"; genKoggeStoneNetlist($FH, $numBits); } sub genMultTest { my ($FH, $numBits, $mVal, $aVal, $bVal ) = @_; print $FH "\nfinish $FinishTime\n"; # declare the inputs print $FH "\ninputs\n"; foreach ( 0..$numBits-1 ) { print $FH "a$_, "; } print $FH "\n"; foreach ( 0..$numBits-1 ) { print $FH "b$_, "; } # declare the special input GND print $FH "\nGND"; print $FH "\nend\n"; # declare the outputs print $FH "\noutputs\n"; foreach ( 0..2*$numBits-1 ) { print $FH "m$_, "; } print $FH "\nend\n"; # declare the outvalues my $outVals = genOutValuesNbit( 2*$numBits, "m", $mVal ); print $FH "\noutvalues\n"; print $FH "@$outVals\n"; print $FH "end\n"; # declare the initlist # for GND print $FH "\ninitlist GND 0 0 end\n"; my $aInitArray = genInitListNbit( $numBits, "a", $aVal ); my $bInitArray = genInitListNbit( $numBits, "b", $bVal ); print $FH "@$aInitArray\n"; print $FH "@$bInitArray\n"; genTreeMultUnsigned( $FH, $numBits); } 1; # return value good
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/forloop.m4
divert(-1) # forloop(i, from, to, stmt) define(`forloop', `pushdef(`$1', `$2')_forloop($@)popdef(`$1')') define(`_forloop', `$4`'ifelse($1, `$3',`', `define(`$1', incr($1))$0($@)')') divert`'dnl
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/devicelib.pl
my $Delay=5; sub genAdder1bit { my ($s,$cout,$a,$b,$cin)=@_; my $adder1Bit = <<END_HERE; inv(${a}n,${a})#4 inv(${b}n,${b})#4 inv(${cin}n,${cin})#4 and2(${a}n${b}n,${a}n,${b}n)#2 and2(${a}n${b},${a}n,${b})#2 and2(${a}${b}n,${a},${b}n)#2 and2(${a}${b},${a},${b})#3 and2(${a}${b}${cin},${a}${b},${cin})#2 and2(${a}n${b}n${cin},${a}n${b}n,${cin})#2 and2(${a}n${b}${cin}n,${a}n${b},${cin}n)#2 and2(${a}${b}n${cin}n,${a}${b}n,${cin}n)#2 and2(${b}${cin},${b},${cin})#2 and2(${a}${cin},${cin},${a})#2 or2(${s}w42,${a}${b}n${cin}n,${a}n${b}${cin}n)#3 or2(${s}w71,${a}${b}${cin}, ${a}n${b}n${cin})#3 or2(${s},${s}w42,${s}w71)#3 or2(${s}w35, ${b}${cin}, ${a}${cin})#3 or2(${cout},${s}w35,${a}${b})#5 END_HERE return $adder1Bit; } sub genAdder1bitInst { my ($inst, $s, $cout, $a, $b, $cin ) = @_; my $str = <<END_HERE; // adder1bit $inst( $s, $cout, $a, $b, $cin) // sum nand2( w0.$inst, $a, $b )#$Delay nand2( w1.$inst, $a, w0.$inst )#$Delay nand2( w2.$inst, $b, w0.$inst )#$Delay nand2( w3.$inst, w1.$inst, w2.$inst )#$Delay nand2( w4.$inst, $cin, w3.$inst )#$Delay nand2( w5.$inst, $cin, w4.$inst )#$Delay nand2( w6.$inst, w3.$inst, w4.$inst )#$Delay nand2( $s, w5.$inst, w6.$inst )#$Delay //cout and2( w7.$inst, $a, $b )#$Delay and2( w8.$inst, $a, $cin )#$Delay and2( w9.$inst, $cin, $b )#$Delay or2( w10.$inst, w7.$inst, w8.$inst )#$Delay or2( $cout, w9.$inst, w10.$inst )#$Delay // end adder1bit END_HERE return $str; } sub genAdder1bitSimple { my ($inst, $s, $cout, $a, $b, $cin ) = @_; my $str = <<END_HERE; // adder1bit $inst( $s, $cout, $a, $b, $cin) // sum xor2( w0.$inst, $a, $b )#$Delay xor2( $s, w0.$inst, $cin )#$Delay //cout and2( w1.$inst, $a, $b )#$Delay and2( w2.$inst, w0.$inst, $cin )#$Delay or2( $cout, w1.$inst, w2.$inst )#$Delay // end adder1bit END_HERE return $str; } sub genKoggeStoneNetlist { my ($FH, $numBits) = @_; my $aVec = [ map { "a$_"; } (0..$numBits-1) ]; my $bVec = [ map { "b$_"; } (0..$numBits-1) ]; my $sVec = [ map { "s$_"; } (0..$numBits-1) ]; genKoggeStoneVec( $FH, $numBits, $sVec, "cout", $aVec, $bVec, "cin" ); } sub genKoggeStoneVec { my ($FH, $numBits, $sVec,$cout,$aVec,$bVec,$cin) = @_; foreach my $i (0..$numBits-1) { print $FH "\nnetlist\n"; print $FH (PGgen("g$i", "p$i", $aVec->[$i], $bVec->[$i] )); print $FH "\nend\n"; } my $M = 1; while( $M < $numBits ) { #Gcombine foreach ( my $j = 0; $j < $M && ($j+$M) < $numBits ; ++$j ) { my $i = $j+$M-1; my $k = $j; my $g_i_j = "g_${i}_$cin"; my $g_i_k = "g_${i}_${k}"; my $g_k_1_j = "g_".($k-1)."_$cin"; my $p_i_k = "p_${i}_${k}"; if( $j == 0 ) { $g_k_1_j = "$cin"; } if( $M == 1 ) { $g_i_k = "g0"; $p_i_k = "p0"; } print $FH "\nnetlist\n"; print $FH (Gcombine( $g_i_j, $g_i_k, $g_k_1_j, $p_i_k ) ); print $FH "\nend\n"; } #PGcombine for (my $j=0; ($j <= $numBits-2*$M) && (2*$M <= $numBits) ; ++$j) { my $i = $j+2*$M-1; my $k = $j+$M; my $g_i_j = "g_${i}_${j}"; my $p_i_j = "p_${i}_${j}"; my $g_i_k = "g_${i}_${k}"; my $p_i_k = "p_${i}_${k}"; my $g_k_1_j = "g_".($k-1)."_$j"; my $p_k_1_j = "p_".($k-1)."_$j"; if( $M==1 ) { $g_i_k = "g$i"; $p_i_k = "p$i"; $g_k_1_j = "g$j"; $p_k_1_j = "p$j"; } print $FH "\nnetlist\n"; print $FH (PGcombine( $g_i_j, $p_i_j, $g_i_k, $g_k_1_j, $p_i_k, $p_k_1_j) ); print $FH "\nend\n"; } # update M $M = 2*$M; } # when $numBits is not a power of 2, $M exceeds it in the # while loop above if( $M > $numBits ) { $M = $M/2; } # cout logic my $g_i_k = "g_".($numBits-1)."_".($numBits-$M); my $p_i_k = "p_".($numBits-1)."_".($numBits-$M); my $g_k_1_j = "g_".($numBits-$M-1)."_$cin"; if( $numBits == $M ) { $g_k_1_j = "$cin"; } print $FH "\nnetlist\n"; print $FH ( Gcombine( $cout, $g_i_k, $g_k_1_j, $p_i_k, ) ); print $FH "\nend\n"; # sum array print $FH "\nnetlist\n"; foreach my $i( 0..$numBits-1 ) { if( $i == 0 ) { print $FH "\nxor2( $sVec->[$i], p$i,$cin )#$Delay \n"; } else { print $FH "\nxor2( $sVec->[$i], p$i,g_".($i-1)."_$cin )#$Delay\n"; } } print $FH "\nend\n"; } sub PGgen { my ($g,$p,$a,$b) = @_; my $str = <<HERE; // PGgen ($g,$p,$a,$b) xor2($p,$a,$b)#$Delay and2($g,$a,$b)#$Delay HERE return $str; } sub Gcombine { my ($g_i_j, $g_i_k, $g_k_1_j, $p_i_k ) = @_; my $str = <<HERE; // Gcombine ($g_i_j, $g_i_k, $g_k_1_j, $p_i_k ) and2(w0$g_i_j, $p_i_k, $g_k_1_j )#$Delay or2( $g_i_j, w0$g_i_j, $g_i_k )#$Delay HERE return $str; } sub PGcombine { my ($g_i_j,$p_i_j,$g_i_k,$g_k_1_j,$p_i_k,$p_k_1_j) = @_; my $str = <<HERE; // PGcombine ($g_i_j,$p_i_j,$g_i_k,$p_i_k,$g_k_1_j,$p_k_1_j) and2( w0$g_i_j, $p_i_k, $g_k_1_j )#$Delay or2( $g_i_j, w0$g_i_j, $g_i_k )#$Delay and2( $p_i_j, $p_i_k, $p_k_1_j)#$Delay HERE return $str; } sub xor2x1 { my ($inst,$z,$a,$b) = @_; my $str = <<END_HERE; // xor2x1 $inst( $z, $a, $b ) inv( ${a}_n.$inst, $a )#$Delay inv( ${b}_n.$inst, $b )#$Delay nand2( w0.$inst, ${a}_n.$inst, $b )#$Delay nand2( w1.$inst, ${b}_n.$inst, $a )#$Delay nand2( $z, w0.$inst, w1.$inst ); // end xor2x1 END_HERE return $str; } sub genTreeMultUnsigned { my ($FH, $numBits) = @_; my $aVec = [ map { "a$_"; } (0..$numBits-1) ]; my $bVec = [ map { "b$_"; } (0..$numBits-1) ]; my $zeroVec = [ map { 'GND'; } (0..2*$numBits-1) ]; # twice the numBits to be used in muxes my $shiftedVecList = []; # create the shifted-concatenated aVec list foreach my $j ( 0..$numBits-1 ) { push @$shiftedVecList, concatShift( $numBits, $aVec, $j ); } # mux the shiftedVecList to generate partial products my @partProdList = (); foreach my $i ( 0..$#$shiftedVecList ) { my $shiftedVec = $shiftedVecList->[$i]; my $zVec = [ map { "PP_${i}_$_"; } (0..2*$numBits-1) ]; my $muxInstVec = mux2x1Vec( "Bth$i", $zVec, $zeroVec, $shiftedVec, $bVec->[$i] ); foreach my $m ( @$muxInstVec ) { print $FH "\nnetlist\n"; print $FH "$m"; print $FH "\nend\n"; } push @partProdList, $zVec; } my $outVec = [ map { "m$_"; } (0..2*$numBits-1) ]; csaTree4x2( $FH, $numBits, \@partProdList, $outVec ); } sub mux2x1 { my ($inst, $z,$i0,$i1,$s) = @_; my $str = <<END_HERE; // mux2x1 $inst( $z, $i0, $i1, $s ) inv(${s}_n.$inst, $s )#$Delay and2(w0.$inst, ${s}_n.$inst, $i0 )#$Delay and2(w1.$inst, $s, $i1 )#$Delay or2($z, w0.$inst, w1.$inst )#$Delay // end mux2x1 $inst END_HERE return $str; } sub mux2x1Nbit { my ($numBits, $inst, $z, $i0, $i1, $s ) = @_; my @array=(); foreach my $i( 0..$numBits-1 ) { my $str = mux2x1( "$inst.$i", $z.$i, $i0.$i, $i1.$i, $s ); push @array, $str; } return \@array; } sub mux2x1Vec { my ( $inst, $zVec, $i0Vec, $i1Vec, $s ) = @_; my @strVec = (); foreach my $i ( 0..$#$zVec ) { my $str = mux2x1( "$inst.$i", $zVec->[$i], $i0Vec->[$i], $i1Vec->[$i] , $s ); push @strVec, $str; } return \@strVec; } sub concatShift { my ($numBits, $inVec, $shift ) = @_; my $outVec = [ @$inVec ]; foreach ( 1..$shift ) { unshift @$outVec, 'GND'; } foreach ( 1..$numBits-$shift ) { push @$outVec, 'GND'; } return $outVec; } sub csa4x2 { my ( $inst, $s,$t,$cout,$a,$b,$c,$d,$cin) = @_; my $str1 = genAdder1bitSimple( "Adder0.$inst", "sint".$inst, $cout, $a,$b,$c ); my $str2 = genAdder1bitSimple( "Adder1.$inst", $s, $t, "sint".$inst, $d, $cin ); my $str = <<END_HERE; // csa4x2 ($inst, $s,$t,$cout,$a,$b,$c,$d,$cin) ; $str1 $str2 // end csa4x2 END_HERE return $str; } sub csa4x2Vec { my ( $instPre, $sVec, $tVec, $aVec, $bVec, $cVec, $dVec ) = @_; my @outputVec = (); for my $i ( 0..$#$aVec ) { my $cin; my $coutPre = "cout_$instPre."; if( $i == 0 ) { $cin = 'GND'; } else { $cin = $coutPre.($i-1); } my $str = csa4x2( $instPre.".".$i, $sVec->[$i], $tVec->[$i], $coutPre.$i, $aVec->[$i], $bVec->[$i], $cVec->[$i], $dVec->[$i], $cin, ); $outputVec[$i] = $str; } return \@outputVec; } # # generate a csa4x2 tree for partial products for example # # inputs # # numBits # list of partial product vectors # a vector of output names # # # sub csaTree4x2 { my ($FH, $numBits, $partProdList, $outVec) = @_; my $j = $numBits; # number of partial products my $currRow = $partProdList; my $lvl = 0; while( $#$currRow+1 >= 4 ) { # keep instantiating rows of csa4x2 my $newRow = []; print $FH "\n// instantiating csa4x2Vec at lvl $lvl \n"; for ( my $i = 0; $#$currRow+1 >= 4 ; $i+=4 ) { my $tVec = [ map { "t${i}_lvl".$lvl."_$_"; } (0..2*$numBits-1) ]; my $sVec = [ map { "s${i}_lvl".$lvl."_$_"; } (0..2*$numBits-1) ]; my $instList = csa4x2Vec( "csa4x2_${i}_lvl${lvl}", $sVec, $tVec, $currRow->[0], $currRow->[1], $currRow->[2], $currRow->[3] ); foreach my $inst ( @$instList ) { print $FH "\nnetlist\n"; print $FH "$inst"; print $FH "\nend\n"; } # remove 4 elements from currRow @$currRow = @$currRow[4..$#$currRow]; # shift the tVec by 1 to the left for( my $k = $#$tVec; $k > 0; --$k ) { $tVec->[$k] = $tVec->[$k-1]; } $tVec->[0] = 'GND'; push @$newRow , $sVec; push @$newRow , $tVec; } # add elements from newRow to currRow push @$currRow, @$newRow; $j = $j/2; ++$lvl; } # currRow contains the final sVec and shifted tVec # feed into a tree adder. print $FH qq{\n// genKoggeStoneVec(2*numBits, outVec, "cout", currRow->[0], currRow->[1], 'GND' );\n}; genKoggeStoneVec( $FH, 2*$numBits, $outVec, "cout", $currRow->[0], $currRow->[1], 'GND' ); # cin as 0 } 1; # return a true value
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/genTreeMult.pl
#!/usr/bin/perl # use strict; use warnings; require "devicelib.pl"; require "netlistlib.pl"; my $numBits = shift @ARGV; my $aVal = 2**$numBits-1; my $bVal = 2**$numBits-1; my $mVal = $aVal*$bVal ; genMultTest(*STDOUT, $numBits, $mVal, $aVal, $bVal );
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/testAdderRC.pl
#!/usr/bin/perl use strict; use warnings; require "../scripts/netlistLib.pl"; require "../scripts/devicelib.pl"; srand(time); my $MAX_TIME=100; my $FinishTime = 10000; my $NUM_THREADS = 4; my $DEBUG=0; my $numBits = shift @ARGV; $NUM_THREADS = (@ARGV) ? shift @ARGV : $NUM_THREADS; testAdderRC($numBits); sub testAdderRC { my ($numBits) = @_; foreach my $a ( 0..(2**$numBits-1) ) { foreach my $b ( 0..(2**$numBits-1) ) { foreach my $cin( 0,1 ) { my $initAList = genInitList( $a, $numBits, "a" ); my $initBList = genInitList( $b, $numBits, "b" ); my $initCinList = genInitList( $cin, 1 , "cin" ); my $fileName = "../testInputs/adder$numBits.net"; my @initListArray = ($initAList, $initBList, $initCinList); genAdderRC( $fileName , $numBits, \@initListArray ); my $output=`cd ../bin/ && java -ea main/Main $fileName $NUM_THREADS`; my @lines = split /\n/, $output; @lines = grep /^OUTPUT/, @lines; if($DEBUG) { print "no. of lines = $#lines\n" } if($DEBUG) { print "lines = @lines\n"; } my $result = scanOutput( \@lines , $numBits ); print "TEST: a = $a , b = $b, cin = $cin, result = $result, perl calculated = " , ($a+$b+$cin) , "\n"; if( ($a + $b + $cin) != $result ) { print STDERR "Test failed with a = $a , b = $b , cin = $cin , result = $result \n"; print STDERR "output = \n"; print STDERR $output; system("cp $fileName $fileName.faulty"); die "TEST FAILED"; } } } } } sub genAdderRC { my ($fileName,$numBits, $initListArray )=@_; open(OUTFILE, "> $fileName" ) or die "Could not open file $fileName for writing"; print OUTFILE "\nfinish $FinishTime\n"; my $inputAList = genPortVector("a",$numBits); my $inputBList = genPortVector("b",$numBits); print OUTFILE "\ninputs cin, $inputAList, $inputBList\nend\n"; my $outputList = genPortVector("s", $numBits ); print OUTFILE "\noutputs cout, $outputList \nend\n"; foreach my $i ( @$initListArray ) { print OUTFILE "\n@$i\n"; } if( $numBits == 1 ) { print OUTFILE "\nnetlist\n"; print OUTFILE genAdder1bit("s", "cout", "a", "b", "cin" ); print OUTFILE "\nend\n"; } else { print OUTFILE "\nnetlist\n"; print OUTFILE genAdder1bit("s0", "c0", "a0", "b0", "cin" ); print OUTFILE "\nend\n"; foreach my $i( 1..$numBits-2 ) { print OUTFILE "\nnetlist\n"; print OUTFILE genAdder1bit("s$i", "c$i", "a$i", "b$i", "c".($i-1) ); print OUTFILE "\nend\n"; } print OUTFILE "\nnetlist\n"; print OUTFILE genAdder1bit("s".($numBits-1), "cout", "a".($numBits-1), "b".($numBits-1), "c".($numBits-2) ); print OUTFILE "\nend\n"; } } sub genPortVector { my ($prefix,$numBits) = @_; my $str=""; my $sep = ""; if( $numBits == 1 ) { $str = $prefix; } else { foreach my $i ( 0..$numBits-1 ) { $str = $str.$sep."${prefix}$i"; $sep=", "; } } return $str; } sub genInitList { my ($val, $numBits,$prefix) = @_; my $binStr = sprintf("%0${numBits}b",$val); if( $DEBUG ) { print "$binStr\n"; } my @initList; if( $numBits == 1 ) { my $rt = int( rand()*$MAX_TIME + 1 ) ; # preventing time to be zero push @initList , "initlist $prefix 0,0 $rt, $val end \n"; } else { foreach my $i( 0..$numBits-1 ) { my $bit = substr( $binStr , length($binStr)-$i-1 , 1 ); my $rt = int( rand()*$MAX_TIME + 1 ) ; # preventing time to be zero push @initList , "initlist ${prefix}$i 0,0 $rt, $bit end \n"; } } return \@initList; } sub scanOutput { my ($lines , $numBits ) = @_; print "lines = $lines , numBits = $numBits\n" if $DEBUG; my $outNameIndex = 6; my $outValIndex = 8; my @sumArray = (1..$numBits); my $coutVal = 0; print "cout = $coutVal , sum = ", reverse( @sumArray ) ,"\n#\n" if $DEBUG; foreach my $l ( @$lines ) { my @a = split ' ', $l; my $outName = $a[$outNameIndex]; my $outVal = $a[$outValIndex]; if( $outName =~ /cout/ ) { $coutVal = $outVal; } elsif ( $numBits == 1 ) { $sumArray[0] = $outVal; } else { $outName =~ s/\D+//g; # extracting the index $sumArray[$outName] = $outVal; } } # DEBUG print "cout = $coutVal , sum = ", reverse (@sumArray) ,"\n" if $DEBUG; my $result = $coutVal; foreach my $i ( reverse @sumArray ) { # msb to lsb $result = $result*2; $result = $result + $i; } return $result; }
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/xorNandArrayGen.pl
#!/usr/bin/perl use strict; use warnings; my $N = shift @ARGV; print "inputs "; foreach my $i( 0..$N-1 ) { print "a$i, b$i, "; } print "\nend\n\n"; print "outputs "; foreach my $i( 0..$N-1 ) { print "o$i, "; } print "\nend\n\n"; print "finish=10000\n\n"; foreach my $i( 0..$N-1 ) { print "initlist a$i\n"; foreach my $j ( 0..$N*$N-1 ) { print 5*$j, ", ", ($j%2),"\n"; # toggle value after every 5 } # 0,0 # 5,1 # 10,0 # 15,1 print "end\n"; } foreach my $i( 0..$N-1 ) { print "initlist b$i\n"; foreach my $j ( 0..$N*$N-1 ) { print 10*$j, ", ", ($j%2),"\n"; # toggle value after every 10 } print "end\n"; } # generate the outvalues print "\noutvalues\n"; foreach my $i (0..$N-1) { print "o$i 0,\n"; } print "end\n"; foreach my $i( 0..$N-1 ) { print <<HERE; netlist nand2(x$i,a$i,b$i)#40 nand2(y$i,a$i,x$i)#40 nand2(z$i,b$i,x$i)#40 nand2(o$i,y$i,z$i)#40 end HERE }
0
rapidsai_public_repos/code-share/maxflow/galois/tools/generators
rapidsai_public_repos/code-share/maxflow/galois/tools/generators/desNetlistGen/adder_Nbit.m4
include(`forloop.m4') include(`adder_1bit.m4') define(N,1) finish=2000 inputs cin, forloop(`i',`0',N, ``a'i, ') end inputs forloop(`i',`0',N, ``b'i, ') end outputs `r'N forloop(`i',`0',N, ``s'i, ') end initlist cin 0,0 21,1 end forloop(`i',`0', N, `initlist `a'i 0,1 end ') forloop(`i',`0', N, `initlist `b'i 0,0 end ') netlist adder_1bit(s0,r0,a0,b0,cin) end forloop(`i',`1', N,` netlist adder_1bit(`s'i,`r'i,`a'i,`b'i,`r'eval(i-1)) end ')
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/comparisons/bfs.sh
#!/bin/bash # # Compare performance with Schardl BFS program BASE="$(cd $(dirname $0); cd ../..; pwd)" if [[ ! -e Makefile ]]; then echo "Execute this script from the base of your build directory" 1>&2 exit 1 fi if [[ ! -e "${BASE}/tools/bin/bfs-schardl" ]]; then echo "Execute make more-tools before running this script" 1>&2 exit 1 fi F=$1 if [[ -z "$F" ]]; then echo "usage: $(basename $0) <graph.gr> [args]" 1>&2 echo "args are passed to Galois programs. A useful example: -t 2" 1>&2 exit 1 fi shift run() { cmd="$@" echo -en '\033[1;31m' echo -n "$cmd" echo -e '\033[0m' $cmd } SF=$(dirname $F)/$(basename $F .gr).bsml if [[ ! -e "$SF" ]]; then "${BASE}/tools/graph-convert/graph-convert" -gr2bsml "$F" "$SF" fi run "${BASE}/tools/bin/bfs-schardl" -f "$SF" run "${BASE}/apps/bfs/bfs" $* "$F" if [[ ! -e "${BASE}/tools/bin/bfs-pbbs" ]]; then exit fi PBBSF=$(dirname $F)/$(basename $F .gr).pbbs if [[ ! -e "$PBBSF" ]]; then "${BASE}/tools/graph-convert/graph-convert" -gr2pbbs "$F" "$PBBSF" fi run "${BASE}/tools/bin/bfs-pbbs" "$PBBSF"
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/comparisons/kruskal.sh
#!/bin/bash # # Compare performance with PBBS minimal spanning tree program BASE="$(cd $(dirname $0); cd ../..; pwd)" if [[ ! -e Makefile ]]; then echo "Execute this script from the base of your build directory" 1>&2 exit 1 fi if [[ ! -e "${BASE}/tools/bin/kruskal-pbbs" ]]; then echo "Execute make more-tools before running this script" 1>&2 exit 1 fi F=$1 if [[ -z "$F" ]]; then echo "usage: $(basename $0) <graph.gr> [args]" 1>&2 echo "args are passed to Galois programs. A useful example: -t 2" 1>&2 exit 1 fi shift run() { cmd="$@" echo -en '\033[1;31m' echo -n "$cmd" echo -e '\033[0m' $cmd } PBBSF=$(dirname $F)/$(basename $F .gr).pbbs if [[ ! -e "$PBBSF" ]]; then "${BASE}/tools/graph-convert/graph-convert" -gr2intpbbs "$F" "$PBBSF" fi run "${BASE}/tools/bin/kruskal-pbbs" "$PBBSF" run "${BASE}/apps/kruskal/KruskalHand" $* "$F"
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/comparisons/CMakeLists.txt
set(sources hi_pr.sh SSCA2.sh triangle.sh bfs.sh independentset.sh kruskal.sh) file(COPY ${sources} DESTINATION .)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/comparisons/independentset.sh
#!/bin/bash # # Compare performance with PBBS maximal independent set program BASE="$(cd $(dirname $0); cd ../..; pwd)" if [[ ! -e Makefile ]]; then echo "Execute this script from the base of your build directory" 1>&2 exit 1 fi if [[ ! -e "${BASE}/tools/bin/independentset-pbbs" ]]; then echo "Execute make more-tools before running this script" 1>&2 exit 1 fi F=$1 if [[ -z "$F" ]]; then echo "usage: $(basename $0) <graph.gr> [args]" 1>&2 echo "args are passed to Galois programs. A useful example: -t 2" 1>&2 exit 1 fi shift run() { cmd="$@" echo -en '\033[1;31m' echo -n "$cmd" echo -e '\033[0m' $cmd } PBBSF=$(dirname $F)/$(basename $F .gr).pbbs if [[ ! -e "$PBBSF" ]]; then "${BASE}/tools/graph-convert/graph-convert" -gr2pbbs "$F" "$PBBSF" fi run "${BASE}/tools/bin/independentset-pbbs" "$PBBSF" run "${BASE}/apps/independentset/independentset" $* "$F"
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/comparisons/triangle.sh
#!/bin/bash # # Compare performance with triangle program BASE="$(cd $(dirname $0); cd ../..; pwd)" if [[ ! -e Makefile ]]; then echo "Execute this script from the base of your build directory" 1>&2 exit 1 fi if [[ ! -e "${BASE}/tools/bin/triangle" ]]; then echo "Execute make more-tools before running this script" 1>&2 exit 1 fi F=$1 if [[ -z "$F" ]]; then echo "usage: $(basename $0) <points.node> [args]" 1>&2 echo "args are passed to Galois programs. A useful example: -t 2" 1>&2 exit 1 fi run() { cmd="$@" echo -en '\033[1;31m' echo -n "$cmd" echo -e '\033[0m' $cmd } shift run "${BASE}/tools/bin/triangle" -i -P -N -E -q30 "$F" run "${BASE}/apps/delaunaytriangulation/delaunaytriangulation" $* "$F" M=$(dirname $F)/$(basename $F .node) if [[ ! -e "$M.ele" ]]; then "${BASE}/apps/delaunaytriangulation/delaunaytriangulation" $F -writemesh "$M" fi run "${BASE}/apps/delaunayrefinement/delaunayrefinement" $* "$M" if [[ ! -e "${BASE}/tools/bin/delaunaytriangulation-pbbs" || ! -e "${BASE}/tools/bin/delaunayrefinement-pbbs" ]]; then exit fi PBBSF=$(dirname $F)/$(basename $F .node).pbbs.dt if [[ ! -e "$PBBSF" ]]; then echo "Generating PBBS triangulation input from Galois." echo "TODO randomize points for best PBBS performance" (echo "pbbs_sequencePoint2d"; cat $F | sed '1d' | awk '{print $2,$3;}') > "$PBBSF" fi run "${BASE}/tools/bin/delaunaytriangulation-pbbs" "$PBBSF" PBBSM=$(dirname $F)/$(basename $F .node).pbbs.dmr if [[ ! -e "$PBBSM" ]]; then "${BASE}/tools/bin/delaunaytriangulation-pbbs" -o "$PBBSM" "$PBBSF" fi run "${BASE}/tools/bin/delaunayrefinement-pbbs" "$PBBSM"
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/comparisons/SSCA2.sh
#!/bin/bash # # Compare performance with SSCA2 program BASE="$(cd $(dirname $0); cd ../..; pwd)" if [[ ! -e Makefile ]]; then echo "Execute this script from the base of your build directory" 1>&2 exit 1 fi if [[ ! -e ${BASE}/tools/bin/SSCA2 ]]; then echo "Execute make more-tools before running this script" 1>&2 exit 1 fi F=$1 S=$2 if [[ -z "$S" ]]; then echo "usage: $(basename $0) <graph.gr> <scale> [args]" 1>&2 echo "For a useful comparison, graph file and scale must be the same." echo "args are passed to Galois programs. A useful example: -t 2" 1>&2 exit 1 fi shift shift run() { cmd="$@" echo -en '\033[1;31m' echo -n "$cmd" echo -e '\033[0m' $cmd } run ${BASE}/tools/bin/SSCA2 $S run ${BASE}/apps/betweennesscentrality/betweennesscentrality $* $F
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/comparisons/hi_pr.sh
#!/bin/bash # # Compare performance with triangle program BASE="$(cd $(dirname $0); cd ../..; pwd)" if [[ ! -e ${BASE}/tools/bin/hi_pr ]]; then echo "Execute make more-tools before running this script" 1>&2 exit 1 fi G=$1 SOURCE=$2 SINK=$3 if [[ -z "$SINK" ]]; then echo "usage: $(basename $0) <graph.gr> <source node> <sink node> [args]" 1>&2 echo "args are passed to Galois programs. A useful example: -t 2" 1>&2 exit 1 fi D="$(dirname $G)/$(basename $G .gr).dimacs" if [[ ! -e "$G" || ! -e "$D" ]]; then echo "Missing gr file or dimacs file." 1>&2 echo "Use graph-convert to make one from the other." 1>&2 exit 1 fi run() { cmd="$@" echo -en '\033[1;31m' echo -n "$cmd" echo -e '\033[0m' $@ } shift 3 run echo hi_pr HSOURCE=$(($SOURCE + 1)) HSINK=$(($SINK + 1)) # Bash tokenizing rules are complicated :( perl -p -e "s/p sp (\d+) (\d+)/p max \1 \2\nn $HSOURCE s\nn $HSINK t/;" $D \ | ${BASE}/tools/bin/hi_pr if [[ -e ${BASE}/apps/preflowpush/preflowpush ]]; then run ${BASE}/apps/preflowpush/preflowpush $* $G $SOURCE $SINK fi
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/graph-convert-standalone/CMakeLists.txt
add_executable(graph-convert-standalone ../graph-convert/graph-convert.cpp) target_link_libraries(graph-convert-standalone galois-nothreads) install(TARGETS graph-convert-standalone EXPORT GaloisTargets RUNTIME DESTINATION "${INSTALL_BIN_DIR}" COMPONENT bin)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/graph-convert/CMakeLists.txt
app(graph-convert graph-convert.cpp) install(TARGETS graph-convert EXPORT GaloisTargets RUNTIME DESTINATION "${INSTALL_BIN_DIR}" COMPONENT bin)
0
rapidsai_public_repos/code-share/maxflow/galois/tools
rapidsai_public_repos/code-share/maxflow/galois/tools/graph-convert/graph-convert.cpp
/** Graph converter -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Dimitrios Prountzos <dprountz@cs.utexas.edu> * @author Donald Nguyen <ddn@cs.utexas.edu> */ #include "Galois/config.h" #include "Galois/LargeArray.h" #include "Galois/Graph/FileGraph.h" #include "llvm/Support/CommandLine.h" #include <iostream> #include <fstream> #include <vector> #include <set> #include <stdint.h> #include GALOIS_CXX11_STD_HEADER(random) #include <fcntl.h> #include <cstdlib> namespace cll = llvm::cl; enum ConvertMode { dimacs2gr, edgelist2vgr, floatedgelist2gr, doubleedgelist2gr, gr2bsml, gr2cintgr, gr2dimacs, gr2doublemtx, gr2floatmtx, gr2floatpbbsedges, gr2intpbbs, gr2intpbbsedges, gr2lowdegreeintgr, gr2partdstintgr, gr2partsrcintgr, gr2randintgr, gr2sorteddstintgr, gr2sortedweightintgr, gr2ringintgr, gr2rmat, gr2sintgr, gr2tintgr, gr2treeintgr, gr2orderdeg, intedgelist2gr, mtx2doublegr, mtx2floatgr, nodelist2vgr, pbbs2vgr, vgr2bsml, vgr2cvgr, vgr2edgelist, vgr2intgr, vgr2lowdegreevgr, vgr2pbbs, vgr2ringvgr, vgr2svgr, vgr2treevgr, vgr2trivgr, vgr2tvgr, vgr2vbinpbbs32, vgr2vbinpbbs64 }; static cll::opt<std::string> inputfilename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<std::string> outputfilename(cll::Positional, cll::desc("<output file>"), cll::Required); static cll::opt<ConvertMode> convertMode(cll::desc("Choose a conversion mode:"), cll::values( clEnumVal(dimacs2gr, "Convert dimacs to binary gr"), clEnumVal(edgelist2vgr, "Convert edge list to binary void gr"), clEnumVal(floatedgelist2gr, "Convert weighted (float) edge list to binary gr"), clEnumVal(doubleedgelist2gr, "Convert weighted (double) edge list to binary gr"), clEnumVal(gr2bsml, "Convert binary gr to binary sparse MATLAB matrix"), clEnumVal(gr2cintgr, "Clean up binary weighted (int) gr: remove self edges and multi-edges"), clEnumVal(gr2dimacs, "Convert binary gr to dimacs"), clEnumVal(gr2doublemtx, "Convert binary gr to matrix market format"), clEnumVal(gr2floatmtx, "Convert binary gr to matrix market format"), clEnumVal(gr2floatpbbsedges, "Convert binary gr to weighted (float) pbbs edge list"), clEnumVal(gr2intpbbs, "Convert binary gr to weighted (int) pbbs graph"), clEnumVal(gr2intpbbsedges, "Convert binary gr to weighted (int) pbbs edge list"), clEnumVal(gr2lowdegreeintgr, "Remove high degree nodes from binary gr"), clEnumVal(gr2partdstintgr, "Partition binary weighted (int) gr by destination nodes into N pieces"), clEnumVal(gr2partsrcintgr, "Partition binary weighted (int) gr by source nodes into N pieces"), clEnumVal(gr2randintgr, "Randomize binary weighted (int) gr"), clEnumVal(gr2ringintgr, "Convert binary gr to strongly connected graph by adding ring overlay"), clEnumVal(gr2rmat, "Convert binary gr to RMAT graph"), clEnumVal(gr2sintgr, "Convert binary gr to symmetric graph by adding reverse edges"), clEnumVal(gr2sorteddstintgr, "Sort outgoing edges of binary weighted (int) gr by edge destination"), clEnumVal(gr2sortedweightintgr, "Sort outgoing edges of binary weighted (int) gr by edge weight"), clEnumVal(gr2tintgr, "Transpose binary weighted (int) gr"), clEnumVal(gr2treeintgr, "Convert binary gr to strongly connected graph by adding tree overlay"), clEnumVal(gr2orderdeg, "Order by neighbor degree"), clEnumVal(intedgelist2gr, "Convert weighted (int) edge list to binary gr"), clEnumVal(mtx2doublegr, "Convert matrix market format to binary gr"), clEnumVal(mtx2floatgr, "Convert matrix market format to binary gr"), clEnumVal(nodelist2vgr, "Convert node list to binary gr"), clEnumVal(pbbs2vgr, "Convert pbbs graph to binary void gr"), clEnumVal(vgr2bsml, "Convert binary void gr to binary sparse MATLAB matrix"), clEnumVal(vgr2cvgr, "Clean up binary void gr: remove self edges and multi-edges"), clEnumVal(vgr2edgelist, "Convert binary void gr to edgelist"), clEnumVal(vgr2intgr, "Convert void binary gr to weighted (int) gr by adding random edge weights"), clEnumVal(vgr2lowdegreevgr, "Remove high degree nodes from binary gr"), clEnumVal(vgr2pbbs, "Convert binary gr to unweighted pbbs graph"), clEnumVal(vgr2ringvgr, "Convert binary gr to strongly connected graph by adding ring overlay"), clEnumVal(vgr2svgr, "Convert binary void gr to symmetric graph by adding reverse edges"), clEnumVal(vgr2treevgr, "Convert binary gr to strongly connected graph by adding tree overlay"), clEnumVal(vgr2trivgr, "Convert symmetric binary void gr to triangular form by removing reverse edges"), clEnumVal(vgr2tvgr, "Transpose binary gr"), clEnumVal(vgr2vbinpbbs32, "Convert binary gr to unweighted binary pbbs graph"), clEnumVal(vgr2vbinpbbs64, "Convert binary gr to unweighted binary pbbs graph"), clEnumValEnd), cll::Required); static cll::opt<int> numParts("numParts", cll::desc("number of parts to partition graph into"), cll::init(64)); static cll::opt<int> maxValue("maxValue", cll::desc("maximum weight to add (tree/ring edges are maxValue + 1)"), cll::init(100)); static cll::opt<int> maxDegree("maxDegree", cll::desc("maximum degree to keep"), cll::init(2*1024)); static void printStatus(size_t in_nodes, size_t in_edges, size_t out_nodes, size_t out_edges) { std::cout << "InGraph : |V| = " << in_nodes << ", |E| = " << in_edges << "\n"; std::cout << "OutGraph: |V| = " << out_nodes << ", |E| = " << out_edges << "\n"; } static void printStatus(size_t in_nodes, size_t in_edges) { printStatus(in_nodes, in_edges, in_nodes, in_edges); } /** * Just a bunch of pairs or triples: * src dst weight? */ template<typename EdgeTy> void convert_edgelist2gr(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Writer p; EdgeData edgeData; std::ifstream infile(infilename.c_str()); size_t numNodes = 0; size_t numEdges = 0; while (infile) { size_t src; size_t dst; edge_value_type data; infile >> src >> dst; if (EdgeData::has_value) infile >> data; if (infile) { ++numEdges; if (src > numNodes) numNodes = src; if (dst > numNodes) numNodes = dst; } } numNodes++; p.setNumNodes(numNodes); p.setNumEdges(numEdges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(numEdges); infile.clear(); infile.seekg(0, std::ios::beg); p.phase1(); while (infile) { size_t src; size_t dst; edge_value_type data; infile >> src >> dst; if (EdgeData::has_value) infile >> data; if (infile) { p.incrementDegree(src); } } infile.clear(); infile.seekg(0, std::ios::beg); p.phase2(); while (infile) { size_t src; size_t dst; edge_value_type data = 0; infile >> src >> dst; if (EdgeData::has_value) infile >> data; if (infile) { edgeData.set(p.addNeighbor(src, dst), data); } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(numNodes, numEdges); } /** * Convert matrix market matrix to binary graph. * * %% comments * % ... * <num nodes> <num nodes> <num edges> * <src> <dst> <float> * * src and dst start at 1. */ template<typename EdgeTy> void convert_mtx2gr(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Writer p; EdgeData edgeData; uint32_t nnodes; size_t nedges; for (int phase = 0; phase < 2; ++phase) { std::ifstream infile(infilename.c_str()); // Skip comments while (infile) { if (infile.peek() != '%') { break; } infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } // Read header char header[256]; infile.getline(header, 256, '\n'); std::istringstream line(header, std::istringstream::in); std::vector<std::string> tokens; while (line) { std::string tmp; line >> tmp; if (line) { tokens.push_back(tmp); } } if (tokens.size() != 3) { GALOIS_DIE("Unknown problem specification line: ", line.str()); } // Prefer C functions for maximum compatibility //nnodes = std::stoull(tokens[0]); //nedges = std::stoull(tokens[2]); nnodes = strtoull(tokens[0].c_str(), NULL, 0); nedges = strtoull(tokens[2].c_str(), NULL, 0); // Parse edges if (phase == 0) { p.setNumNodes(nnodes); p.setNumEdges(nedges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(nedges); p.phase1(); } else { p.phase2(); } for (size_t edge_num = 0; edge_num < nedges; ++edge_num) { uint32_t cur_id, neighbor_id; edge_value_type weight = 1; infile >> cur_id >> neighbor_id >> weight; if (cur_id == 0 || cur_id > nnodes) { GALOIS_DIE("Error: node id out of range: ", cur_id); } if (neighbor_id == 0 || neighbor_id > nnodes) { GALOIS_DIE("Error: neighbor id out of range: ", neighbor_id); } // 1 indexed if (phase == 0) { p.incrementDegree(cur_id - 1); //p.incrementDegree(neighbor_id - 1); } else { edgeData.set(p.addNeighbor(cur_id - 1, neighbor_id - 1), weight); //edgeData.set(p.addNeighbor(neighbor_id - 1, cur_id - 1), weight); } infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } infile.peek(); if (!infile.eof()) { GALOIS_DIE("Error: additional lines in file"); } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(p.size(), p.sizeEdges()); } template<typename EdgeTy> void convert_gr2mtx(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph graph; graph.structureFromFile(infilename); std::ofstream file(outfilename.c_str()); file << graph.size() << " " << graph.size() << " " << graph.sizeEdges() << "\n"; for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); EdgeTy& weight = graph.getEdgeData<EdgeTy>(jj); file << src + 1 << " " << dst + 1 << " " << weight << "\n"; } } file.close(); printStatus(graph.size(), graph.sizeEdges()); } /** * List of node adjacencies: * * <node id> <num neighbors> <neighbor id>* * ... */ void convert_nodelist2vgr(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraphWriter Writer; Writer p; std::ifstream infile(infilename.c_str()); size_t numNodes = 0; size_t numEdges = 0; while (infile) { size_t src; size_t numNeighbors; infile >> src >> numNeighbors; if (infile) { if (src > numNodes) numNodes = src; numEdges += numNeighbors; } infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } numNodes++; p.setNumNodes(numNodes); p.setNumEdges(numEdges); infile.clear(); infile.seekg(0, std::ios::beg); p.phase1(); while (infile) { size_t src; size_t numNeighbors; infile >> src >> numNeighbors; if (infile) { p.incrementDegree(src, numNeighbors); } infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } infile.clear(); infile.seekg(0, std::ios::beg); p.phase2(); while (infile) { size_t src; size_t numNeighbors; infile >> src >> numNeighbors; for (; infile && numNeighbors > 0; --numNeighbors) { size_t dst; infile >> dst; if (infile) p.addNeighbor(src, dst); } infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } p.finish<void>(); p.structureToFile(outfilename); printStatus(numNodes, numEdges); } template<typename EdgeTy> void convert_gr2edgelist(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Graph graph; graph.structureFromFile(infilename); std::ofstream file(outfilename.c_str()); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (EdgeData::has_value) { file << src << " " << dst << " " << graph.getEdgeData<edge_value_type>(jj) << "\n"; } else { file << src << " " << dst << "\n"; } } } file.close(); printStatus(graph.size(), graph.sizeEdges()); } //! Wrap generator into form form std::random_shuffle template<typename T,typename Gen,template<typename> class Dist> struct UniformDist { Gen& gen; UniformDist(Gen& g): gen(g) { } T operator()(T m) { Dist<T> r(0, m - 1); return r(gen); } }; template<typename EdgeTy> void convert_gr2rand(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; typedef Galois::LargeArray<GNode> Permutation; typedef typename std::iterator_traits<typename Permutation::iterator>::difference_type difference_type; Graph graph; graph.structureFromFile(infilename); Permutation perm; perm.create(graph.size()); std::copy(boost::counting_iterator<GNode>(0), boost::counting_iterator<GNode>(graph.size()), perm.begin()); std::mt19937 gen; #if __cplusplus >= 201103L || defined(HAVE_CXX11_UNIFORM_INT_DISTRIBUTION) UniformDist<difference_type,std::mt19937,std::uniform_int_distribution> dist(gen); #else UniformDist<difference_type,std::mt19937,std::uniform_int> dist(gen); #endif std::random_shuffle(perm.begin(), perm.end(), dist); Graph out; Galois::Graph::permute<EdgeTy>(graph, perm, out); out.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges()); } template<typename InEdgeTy,typename OutEdgeTy> void add_weights(const std::string& infilename, const std::string& outfilename, int maxvalue) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph graph, outgraph; graph.structureFromFile(infilename); OutEdgeTy* edgeData = outgraph.structureFromGraph<OutEdgeTy>(graph); OutEdgeTy* edgeDataEnd = edgeData + graph.sizeEdges(); std::mt19937 gen; #if __cplusplus >= 201103L || defined(HAVE_CXX11_UNIFORM_INT_DISTRIBUTION) std::uniform_int_distribution<OutEdgeTy> dist(1, maxvalue); #else std::uniform_int<OutEdgeTy> dist(1, maxvalue); #endif for (; edgeData != edgeDataEnd; ++edgeData) { *edgeData = dist(gen); } outgraph.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges(), outgraph.size(), outgraph.sizeEdges()); } template<typename EdgeValue,bool Enable> void setEdgeValue(EdgeValue& edgeValue, int maxvalue, typename std::enable_if<Enable>::type* = 0) { edgeValue.set(0, maxvalue + 1); } template<typename EdgeValue,bool Enable> void setEdgeValue(EdgeValue& edgeValue, int maxvalue, typename std::enable_if<!Enable>::type* = 0) { } /** * Add edges (i, i-1) for all i \in V. */ template<typename EdgeTy> void add_ring(const std::string& infilename, const std::string& outfilename, int maxvalue) { typedef Galois::Graph::FileGraph Graph; typedef Galois::Graph::FileGraphWriter Writer; typedef Graph::GraphNode GNode; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Graph graph; graph.structureFromFile(infilename); Writer p; EdgeData edgeData; EdgeData edgeValue; uint64_t size = graph.size(); p.setNumNodes(size); p.setNumEdges(graph.sizeEdges() + size); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(graph.sizeEdges() + size); edgeValue.create(1); //edgeValue.set(0, maxValue + 1); setEdgeValue<EdgeData,EdgeData::has_value>(edgeValue, maxvalue); p.phase1(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; p.incrementDegree(src, std::distance(graph.edge_begin(src), graph.edge_end(src)) + 1); } p.phase2(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (EdgeData::has_value) { edgeData.set(p.addNeighbor(src, dst), graph.getEdgeData<edge_value_type>(jj)); } else { p.addNeighbor(src, dst); } } GNode dst = src == 0 ? size - 1 : src - 1; if (EdgeData::has_value) { edgeData.set(p.addNeighbor(src, dst), edgeValue.at(0)); } else { p.addNeighbor(src, dst); } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges(), p.size(), p.sizeEdges()); } /** * Add edges (i, i*2+1), (i, i*2+2) and their complement. */ template<typename EdgeTy> void add_tree(const std::string& infilename, const std::string& outfilename, int maxvalue) { typedef Galois::Graph::FileGraph Graph; typedef Galois::Graph::FileGraphWriter Writer; typedef Graph::GraphNode GNode; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Graph graph; graph.structureFromFile(infilename); Writer p; EdgeData edgeData; EdgeData edgeValue; uint64_t size = graph.size(); uint64_t newEdges = 0; if (size >= 2) { // Closed form counts for the loop below newEdges = (size - 1 + (2 - 1)) / 2; // (1) rounded up newEdges += (size - 2 + (2 - 1)) / 2; // (2) rounded up } else if (size >= 1) newEdges = 1; newEdges *= 2; // reverse edges p.setNumNodes(size); p.setNumEdges(graph.sizeEdges() + newEdges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(graph.sizeEdges() + newEdges); edgeValue.create(1); //edgeValue.set(0, maxValue + 1); setEdgeValue<EdgeData,EdgeData::has_value>(edgeValue, maxvalue); p.phase1(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; p.incrementDegree(src, std::distance(graph.edge_begin(src), graph.edge_end(src))); if (src * 2 + 1 < size) { // (1) p.incrementDegree(src); p.incrementDegree(src * 2 + 1); } if (src * 2 + 2 < size) { // (2) p.incrementDegree(src); p.incrementDegree(src * 2 + 2); } } p.phase2(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (EdgeData::has_value) { edgeData.set(p.addNeighbor(src, dst), graph.getEdgeData<edge_value_type>(jj)); } else { p.addNeighbor(src, dst); } } if (src * 2 + 1 < size) { if (EdgeData::has_value) { edgeData.set(p.addNeighbor(src, src * 2 + 1), edgeValue.at(0)); edgeData.set(p.addNeighbor(src * 2 + 1, src), edgeValue.at(0)); } else { p.addNeighbor(src, src * 2 + 1); p.addNeighbor(src * 2 + 1, src); } } if (src * 2 + 2 < size) { if (EdgeData::has_value) { edgeData.set(p.addNeighbor(src, src * 2 + 2), edgeValue.at(0)); edgeData.set(p.addNeighbor(src * 2 + 2, src), edgeValue.at(0)); } else { p.addNeighbor(src, src * 2 + 2); p.addNeighbor(src * 2 + 2, src); } } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges(), p.size(), p.sizeEdges()); } //! Make graph symmetric by blindly adding reverse entries template<typename EdgeTy> void convert_gr2sgr(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; Graph ingraph; Graph outgraph; ingraph.structureFromFile(infilename); Galois::Graph::makeSymmetric<EdgeTy>(ingraph, outgraph); outgraph.structureToFile(outfilename); printStatus(ingraph.size(), ingraph.sizeEdges(), outgraph.size(), outgraph.sizeEdges()); } template<typename GNode, typename Weights> struct order_by_degree { Weights& weights; bool operator()(const GNode& a, const GNode& b) { uint64_t wa = weights.count(a) ? weights[a] : ~0; uint64_t wb = weights.count(b) ? weights[b] : ~0; return wa < wb; } }; template<typename EdgeTy> void order_by_high_degree(const std::string& infilename, const std::string& outfilename, int numSort) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; typedef Galois::LargeArray<GNode> Permutation; typedef typename std::iterator_traits<typename Permutation::iterator>::difference_type difference_type; Graph graph; graph.structureFromFile(infilename); Permutation perm; perm.create(graph.size()); std::copy(boost::counting_iterator<GNode>(0), boost::counting_iterator<GNode>(graph.size()), perm.begin()); typedef std::map<GNode,uint64_t> Weights; Weights weights; std::set<GNode> done; for (int z = 0; z < numSort; ++z) { //find the next biggest node unsigned deg = 0; GNode n; for (Graph::iterator ii = graph.begin(), ee = graph.end(); ii != ee; ++ii) { unsigned d = std::distance(graph.edge_begin(*ii), graph.edge_end(*ii)); if (d >= deg && !done.count(*ii)) { deg = d; n = *ii; } } done.insert(n); std::cout << "First " << n << " deg " << deg << "\n"; //shift all keys for (Weights::iterator ii = weights.begin(), ee = weights.end(); ii != ee; ++ii) { ii->second <<= 1; } //add to sort keys for (Graph::edge_iterator ii = graph.edge_begin(n), ee = graph.edge_end(n); ii != ee; ++ii) { weights[graph.getEdgeDst(ii)] |= 1; } weights[n] |= 1; } order_by_degree<GNode,Weights> fn = { weights }; //compute inverse std::stable_sort(perm.begin(), perm.end(), fn); Permutation perm2; perm2.create(graph.size()); //compute permutation for (unsigned x = 0; x < perm.size(); ++x) perm2[perm[x]] = x; for (unsigned x = 0; x < perm2.size(); ++x) if (perm2[x] == 0) std::cout << "Zero is at " << x << "\n"; Graph out; Galois::Graph::permute<EdgeTy>(graph, perm2, out); out.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges()); } template<typename EdgeTy> void remove_high_degree(const std::string& infilename, const std::string& outfilename, int degree) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Graph graph; graph.structureFromFile(infilename); Writer p; EdgeData edgeData; std::vector<GNode> nodeTable; nodeTable.resize(graph.size()); uint64_t numNodes = 0; uint64_t numEdges = 0; for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); if (std::distance(jj, ej) > degree) continue; nodeTable[src] = numNodes++; for (; jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (std::distance(graph.edge_begin(dst), graph.edge_end(dst)) > degree) continue; ++numEdges; } } if (numEdges == graph.sizeEdges() && numNodes == graph.size()) { std::cout << "Graph already simplified; copy input to output\n"; printStatus(graph.size(), graph.sizeEdges()); graph.structureToFile(outfilename); return; } p.setNumNodes(numNodes); p.setNumEdges(numEdges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(numEdges); p.phase1(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); if (std::distance(jj, ej) > degree) continue; for (; jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (std::distance(graph.edge_begin(dst), graph.edge_end(dst)) > degree) continue; p.incrementDegree(nodeTable[src]); } } p.phase2(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); if (std::distance(jj, ej) > degree) continue; for (; jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (std::distance(graph.edge_begin(dst), graph.edge_end(dst)) > degree) continue; if (EdgeData::has_value) { edgeData.set(p.addNeighbor(nodeTable[src], nodeTable[dst]), graph.getEdgeData<edge_value_type>(jj)); } else { p.addNeighbor(nodeTable[src], nodeTable[dst]); } } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges(), p.size(), p.sizeEdges()); } //! Partition graph into balanced number of edges by source node template<typename EdgeTy> void partition_by_source(const std::string& infilename, const std::string& outfilename, int parts) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Graph graph; graph.structureFromFile(infilename); for (int i = 0; i < parts; ++i) { Writer p; EdgeData edgeData; auto r = graph.divideBy(0, 1, i, parts); size_t numEdges = 0; if (r.first != r.second) numEdges = std::distance(graph.edge_begin(*r.first), graph.edge_end(*(r.second - 1))); p.setNumNodes(graph.size()); p.setNumEdges(numEdges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(numEdges); p.phase1(); for (Graph::iterator ii = r.first, ei = r.second; ii != ei; ++ii) { GNode src = *ii; p.incrementDegree(src, std::distance(graph.edge_begin(src), graph.edge_end(src))); } p.phase2(); for (Graph::iterator ii = r.first, ei = r.second; ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (EdgeData::has_value) edgeData.set(p.addNeighbor(src, dst), graph.getEdgeData<edge_value_type>(jj)); else p.addNeighbor(src, dst); } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); std::ostringstream partname; partname << outfilename << "." << i << ".of." << parts; p.structureToFile(partname.str()); printStatus(graph.size(), graph.sizeEdges(), p.size(), p.sizeEdges()); } } template<typename InDegree, typename It = typename InDegree::iterator> static std::pair<It,It> divide_by_destination(InDegree& inDegree, int id, int total) { if (inDegree.begin() == inDegree.end()) return std::make_pair(inDegree.begin(), inDegree.end()); size_t size = inDegree[inDegree.size() - 1]; size_t block = (size + total - 1) / total; It bb = std::lower_bound(inDegree.begin(), inDegree.end(), id * block); It eb; if (id + 1 == total) eb = inDegree.end(); else eb = std::upper_bound(bb, inDegree.end(), (id + 1) * block); return std::make_pair(bb, eb); } template<typename GraphTy, typename InDegree> static void compute_indegree(GraphTy& graph, InDegree& inDegree) { inDegree.create(graph.size()); for (auto nn = graph.begin(), en = graph.end(); nn != en; ++nn) { for (auto jj = graph.edge_begin(*nn), ej = graph.edge_end(*nn); jj != ej; ++jj) { auto dst = graph.getEdgeDst(jj); inDegree[dst] += 1; } } for (size_t i = 1; i < inDegree.size(); ++i) inDegree[i] = inDegree[i-1] + inDegree[i]; } //! Partition graph into balanced number of edges by destination node template<typename EdgeTy> void partition_by_destination(const std::string& infilename, const std::string& outfilename, int parts) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef Galois::LargeArray<size_t> InDegree; typedef typename EdgeData::value_type edge_value_type; Graph graph; graph.structureFromFile(infilename); InDegree inDegree; compute_indegree(graph, inDegree); for (int i = 0; i < parts; ++i) { Writer p; EdgeData edgeData; auto r = divide_by_destination(inDegree, i, parts); size_t bb = std::distance(inDegree.begin(), r.first); size_t eb = std::distance(inDegree.begin(), r.second); size_t numEdges = 0; if (bb != eb) { size_t begin = bb == 0 ? 0 : inDegree[bb - 1]; size_t end = eb == 0 ? 0 : inDegree[eb - 1]; numEdges = end - begin; } p.setNumNodes(graph.size()); p.setNumEdges(numEdges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(numEdges); p.phase1(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (dst < bb) continue; if (dst >= eb) continue; p.incrementDegree(src); } } p.phase2(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (dst < bb) continue; if (dst >= eb) continue; if (EdgeData::has_value) edgeData.set(p.addNeighbor(src, dst), graph.getEdgeData<edge_value_type>(jj)); else p.addNeighbor(src, dst); } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); std::ostringstream partname; partname << outfilename << "." << i << ".of." << parts; p.structureToFile(partname.str()); printStatus(graph.size(), graph.sizeEdges(), p.size(), p.sizeEdges()); } } //! Transpose graph template<typename EdgeTy> void transpose(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Graph graph; graph.structureFromFile(infilename); Writer p; EdgeData edgeData; p.setNumNodes(graph.size()); p.setNumEdges(graph.sizeEdges()); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(graph.sizeEdges()); p.phase1(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); p.incrementDegree(dst); } } p.phase2(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (EdgeData::has_value) { edgeData.set(p.addNeighbor(dst, src), graph.getEdgeData<edge_value_type>(jj)); } else { p.addNeighbor(dst, src); } } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges(), p.size(), p.sizeEdges()); } template<typename GraphNode,typename EdgeTy> struct IdLess { bool operator()(const Galois::Graph::EdgeSortValue<GraphNode,EdgeTy>& e1, const Galois::Graph::EdgeSortValue<GraphNode,EdgeTy>& e2) const { return e1.dst < e2.dst; } }; template<typename GraphNode,typename EdgeTy> struct WeightLess { bool operator()(const Galois::Graph::EdgeSortValue<GraphNode,EdgeTy>& e1, const Galois::Graph::EdgeSortValue<GraphNode,EdgeTy>& e2) const { return e1.get() < e2.get(); } }; /** * Removes self and multi-edges from a graph. */ template<typename EdgeTy> void convert_gr2cgr(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph orig, graph; { // Original FileGraph is immutable because it is backed by a file orig.structureFromFile(infilename); graph.cloneFrom(orig); } size_t numEdges = 0; for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; graph.sortEdges<EdgeTy>(src, IdLess<GNode,EdgeTy>()); Graph::edge_iterator prev = graph.edge_end(src); for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (src == dst) { } else if (prev != ej && graph.getEdgeDst(prev) == dst) { } else { numEdges += 1; } prev = jj; } } if (numEdges == graph.sizeEdges()) { std::cout << "Graph already simplified; copy input to output\n"; printStatus(graph.size(), graph.sizeEdges()); graph.structureToFile(outfilename); return; } typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Writer p; EdgeData edgeData; p.setNumNodes(graph.size()); p.setNumEdges(numEdges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(numEdges); p.phase1(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; Graph::edge_iterator prev = graph.edge_end(src); for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (src == dst) { } else if (prev != ej && graph.getEdgeDst(prev) == dst) { } else { p.incrementDegree(src); } prev = jj; } } p.phase2(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; Graph::edge_iterator prev = graph.edge_end(src); for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (src == dst) { } else if (prev != ej && graph.getEdgeDst(prev) == dst) { } else if (EdgeData::has_value) { edgeData.set(p.addNeighbor(src, dst), graph.getEdgeData<edge_value_type>(jj)); } else { p.addNeighbor(src, dst); } prev = jj; } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges(), p.size(), p.sizeEdges()); } template<typename EdgeTy,template<typename,typename> class SortBy> void sort_edges(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Graph orig, graph; { // Original FileGraph is immutable because it is backed by a file orig.structureFromFile(infilename); graph.cloneFrom(orig); } for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; graph.sortEdges<EdgeTy>(src, SortBy<GNode,EdgeTy>()); } graph.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges()); } /** * Removes edges such that src > dst */ template<typename EdgeTy> void convert_sgr2gr(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph graph; graph.structureFromFile(infilename); size_t numEdges = 0; for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (src > dst) { } else { numEdges += 1; } } } if (numEdges == graph.sizeEdges()) { std::cout << "Graph already simplified; copy input to output\n"; printStatus(graph.size(), graph.sizeEdges()); graph.structureToFile(outfilename); return; } typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Writer p; EdgeData edgeData; p.setNumNodes(graph.size()); p.setNumEdges(numEdges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(numEdges); p.phase1(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (src > dst) { } else { p.incrementDegree(src); } } } p.phase2(); for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); if (src > dst) { } else if (EdgeData::has_value) { edgeData.set(p.addNeighbor(src, dst), graph.getEdgeData<edge_value_type>(jj)); } else { p.addNeighbor(src, dst); } } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(graph.size(), graph.sizeEdges(), p.size(), p.sizeEdges()); } // Example: // c Some file // c Comments // p XXX* <num nodes> <num edges> // a <src id> <dst id> <weight> // .... void convert_dimacs2gr(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<int32_t> EdgeData; typedef EdgeData::value_type edge_value_type; Writer p; EdgeData edgeData; uint32_t nnodes; size_t nedges; for (int phase = 0; phase < 2; ++phase) { std::ifstream infile(infilename.c_str()); // Skip comments while (infile) { if (infile.peek() == 'p') { break; } infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } // Read header char header[256]; infile.getline(header, 256, '\n'); std::istringstream line(header, std::istringstream::in); std::vector<std::string> tokens; while (line) { std::string tmp; line >> tmp; if (line) { tokens.push_back(tmp); } } if (tokens.size() < 3 || tokens[0].compare("p") != 0) { GALOIS_DIE("Unknown problem specification line: ", line.str()); } // Prefer C functions for maximum compatibility //nnodes = std::stoull(tokens[tokens.size() - 2]); //nedges = std::stoull(tokens[tokens.size() - 1]); nnodes = strtoull(tokens[tokens.size() - 2].c_str(), NULL, 0); nedges = strtoull(tokens[tokens.size() - 1].c_str(), NULL, 0); // Parse edges if (phase == 0) { p.setNumNodes(nnodes); p.setNumEdges(nedges); p.setSizeofEdgeData(EdgeData::size_of::value); edgeData.create(nedges); p.phase1(); } else { p.phase2(); } for (size_t edge_num = 0; edge_num < nedges; ++edge_num) { uint32_t cur_id, neighbor_id; int32_t weight; std::string tmp; infile >> tmp; if (tmp.compare("a") != 0) { --edge_num; infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); continue; } infile >> cur_id >> neighbor_id >> weight; if (cur_id == 0 || cur_id > nnodes) { GALOIS_DIE("Error: node id out of range: ", cur_id); } if (neighbor_id == 0 || neighbor_id > nnodes) { GALOIS_DIE("Error: neighbor id out of range: ", neighbor_id); } // 1 indexed if (phase == 0) { p.incrementDegree(cur_id - 1); } else { edgeData.set(p.addNeighbor(cur_id - 1, neighbor_id - 1), weight); } infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } infile.peek(); if (!infile.eof()) { GALOIS_DIE("Error: additional lines in file"); } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); if (EdgeData::has_value) std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outfilename); printStatus(p.size(), p.sizeEdges()); } /** * PBBS input is an ASCII file of tokens that serialize a CSR graph. I.e., * elements in brackets are non-literals: * * AdjacencyGraph * <num nodes> * <num edges> * <offset node 0> * <offset node 1> * ... * <edge 0> * <edge 1> * ... */ void convert_pbbs2vgr(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraphWriter Writer; Writer p; std::ifstream infile(infilename.c_str()); std::string header; uint32_t nnodes; size_t nedges; infile >> header >> nnodes >> nedges; if (header != "AdjacencyGraph") { GALOIS_DIE("Error: unknown file format"); } p.setNumNodes(nnodes); p.setNumEdges(nedges); size_t* offsets = new size_t[nnodes]; for (size_t i = 0; i < nnodes; ++i) { infile >> offsets[i]; } size_t* edges = new size_t[nedges]; for (size_t i = 0; i < nedges; ++i) { infile >> edges[i]; } p.phase1(); for (uint32_t i = 0; i < nnodes; ++i) { size_t begin = offsets[i]; size_t end = (i == nnodes - 1) ? nedges : offsets[i+1]; p.incrementDegree(i, end - begin); } p.phase2(); for (uint32_t i = 0; i < nnodes; ++i) { size_t begin = offsets[i]; size_t end = (i == nnodes - 1) ? nedges : offsets[i+1]; for (size_t j = begin; j < end; ++j) { size_t dst = edges[j]; p.addNeighbor(i, dst); } } p.finish<void>(); p.structureToFile(outfilename); printStatus(p.size(), p.sizeEdges()); } template<typename EdgeTy> void convert_gr2pbbsedges(const std::string& infilename, const std::string& outfilename) { // Use FileGraph because it is basically in CSR format needed for pbbs typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph graph; graph.structureFromFile(infilename); std::ofstream file(outfilename.c_str()); file << "WeightedEdgeArray\n"; for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); EdgeTy& weight = graph.getEdgeData<EdgeTy>(jj); file << src << " " << dst << " " << weight << "\n"; //file << src << "," << dst << "," << weight << "\n"; } } file.close(); printStatus(graph.size(), graph.sizeEdges()); } /** * PBBS input is an ASCII file of tokens that serialize a CSR graph. I.e., * elements in brackets are non-literals: * * [Weighted]AdjacencyGraph * <num nodes> * <num edges> * <offset node 0> * <offset node 1> * ... * <edge 0> * <edge 1> * ... * [ * <edge weight 0> * <edge weight 1> * ... * ] */ template<typename InEdgeTy,typename OutEdgeTy> void convert_gr2pbbs(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Galois::LargeArray<OutEdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Graph graph; graph.structureFromFile(infilename); std::ofstream file(outfilename.c_str()); if (EdgeData::has_value) file << "Weighted"; file << "AdjacencyGraph\n" << graph.size() << "\n" << graph.sizeEdges() << "\n"; // edgeid[i] is the end of i in FileGraph while it is the beginning of i in pbbs graph size_t last = std::distance(graph.edge_id_begin(), graph.edge_id_end()); size_t count = 0; file << "0\n"; for (Graph::edge_id_iterator ii = graph.edge_id_begin(), ei = graph.edge_id_end(); ii != ei; ++ii, ++count) { if (count < last - 1) file << *ii << "\n"; } for (Graph::node_id_iterator ii = graph.node_id_begin(), ei = graph.node_id_end(); ii != ei; ++ii) { file << *ii << "\n"; } if (EdgeData::has_value) { for (edge_value_type* ii = graph.edge_data_begin<edge_value_type>(), *ei = graph.edge_data_end<edge_value_type>(); ii != ei; ++ii) { file << *ii << "\n"; } } file.close(); printStatus(graph.size(), graph.sizeEdges()); } /** * Binary PBBS format is three files. * * <base>.config - ASCII file with number of vertices * <base>.adj - Binary adjacencies * <base>.idx - Binary offsets for adjacencies */ template<typename NodeIdx,typename Offset> void convert_gr2vbinpbbs(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph graph; graph.structureFromFile(infilename); { std::string configName = outfilename + ".config"; std::ofstream configFile(configName.c_str()); configFile << graph.size() << "\n"; } { std::string idxName = outfilename + ".idx"; std::ofstream idxFile(idxName.c_str()); // edgeid[i] is the end of i in FileGraph while it is the beginning of i in pbbs graph size_t last = std::distance(graph.edge_id_begin(), graph.edge_id_end()); size_t count = 0; Offset offset = 0; idxFile.write(reinterpret_cast<char*>(&offset), sizeof(offset)); for (Graph::edge_id_iterator ii = graph.edge_id_begin(), ei = graph.edge_id_end(); ii != ei; ++ii, ++count) { offset = *ii; if (count < last - 1) idxFile.write(reinterpret_cast<char*>(&offset), sizeof(offset)); } idxFile.close(); } { std::string adjName = outfilename + ".adj"; std::ofstream adjFile(adjName.c_str()); for (Graph::node_id_iterator ii = graph.node_id_begin(), ei = graph.node_id_end(); ii != ei; ++ii) { NodeIdx nodeIdx = *ii; adjFile.write(reinterpret_cast<char*>(&nodeIdx), sizeof(nodeIdx)); } adjFile.close(); } printStatus(graph.size(), graph.sizeEdges()); } template<typename EdgeTy> void convert_gr2dimacs(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph graph; graph.structureFromFile(infilename); std::ofstream file(outfilename.c_str()); file << "p sp " << graph.size() << " " << graph.sizeEdges() << "\n"; for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); EdgeTy& weight = graph.getEdgeData<EdgeTy>(jj); file << "a " << src + 1 << " " << dst + 1 << " " << weight << "\n"; } } file.close(); printStatus(graph.size(), graph.sizeEdges()); } /** * RMAT format (zero indexed): * %%% Comment1 * %%% Comment2 * %%% Comment3 * <num nodes> <num edges> * <node id> <num edges> [<neighbor id> <neighbor weight>]* * ... */ template<typename InEdgeTy,typename OutEdgeTy> void convert_gr2rmat(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef Graph::GraphNode GNode; Graph graph; graph.structureFromFile(infilename); std::ofstream file(outfilename.c_str()); file << "%%%\n"; file << "%%%\n"; file << "%%%\n"; file << graph.size() << " " << graph.sizeEdges() << "\n"; for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; file << *ii << " " << std::distance(graph.edge_begin(src), graph.edge_end(src)); for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); OutEdgeTy weight = graph.getEdgeData<InEdgeTy>(jj); file << " " << dst << " " << weight; } file << "\n"; } file.close(); printStatus(graph.size(), graph.sizeEdges()); } template<typename EdgeTy> struct GetEdgeData { double operator()(Galois::Graph::FileGraph& g, Galois::Graph::FileGraph::edge_iterator ii) const { return g.getEdgeData<EdgeTy>(ii); } }; template<> struct GetEdgeData<void> { double operator()(Galois::Graph::FileGraph& g, Galois::Graph::FileGraph::edge_iterator ii) const { return 1; } }; /** * GR to Binary Sparse MATLAB matrix. * [i, j, v] = find(A); * fwrite(f, size(A,1), 'uint32'); * fwrite(f, size(A,2), 'uint32'); * fwrite(f, nnz(A), 'uint32'); * fwrite(f, (i-1), 'uint32'); % zero-indexed * fwrite(f, (j-1), 'uint32'); * fwrite(f, v, 'double'); */ template<typename EdgeTy> void convert_gr2bsml(const std::string& infilename, const std::string& outfilename) { typedef Galois::Graph::FileGraph Graph; typedef typename Graph::GraphNode GNode; Graph graph; graph.structureFromFile(infilename); uint32_t nnodes = graph.size(); uint32_t nedges = graph.sizeEdges(); mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int fd = open(outfilename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, mode); if (fd == -1) { GALOIS_SYS_DIE(""); } int retval; // Write header retval = write(fd, &nnodes, sizeof(nnodes)); if (retval == -1) { GALOIS_SYS_DIE(""); } retval = write(fd, &nnodes, sizeof(nnodes)); if (retval == -1) { GALOIS_SYS_DIE(""); } retval = write(fd, &nedges, sizeof(nedges)); if (retval == -1) { GALOIS_SYS_DIE(""); } // Write row adjacency for (typename Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; uint32_t sid = src; for (typename Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { retval = write(fd, &sid, sizeof(sid)); if (retval == -1) { GALOIS_SYS_DIE(""); } } } // Write column adjacency for (typename Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (typename Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { GNode dst = graph.getEdgeDst(jj); uint32_t did = dst; retval = write(fd, &did, sizeof(did)); if (retval == -1) { GALOIS_SYS_DIE(""); } } } // Write data GetEdgeData<EdgeTy> convert; for (typename Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { GNode src = *ii; for (typename Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) { double weight = convert(graph, jj); retval = write(fd, &weight, sizeof(weight)); if (retval == -1) { GALOIS_SYS_DIE(""); } } } close(fd); printStatus(nnodes, nedges); } int main(int argc, char** argv) { llvm::cl::ParseCommandLineOptions(argc, argv); switch (convertMode) { case dimacs2gr: convert_dimacs2gr(inputfilename, outputfilename); break; case edgelist2vgr: convert_edgelist2gr<void>(inputfilename, outputfilename); break; case floatedgelist2gr: convert_edgelist2gr<float>(inputfilename, outputfilename); break; case doubleedgelist2gr: convert_edgelist2gr<double>(inputfilename, outputfilename); break; case gr2bsml: convert_gr2bsml<int32_t>(inputfilename, outputfilename); break; case gr2cintgr: convert_gr2cgr<int32_t>(inputfilename, outputfilename); break; case gr2dimacs: convert_gr2dimacs<int32_t>(inputfilename, outputfilename); break; case gr2doublemtx: convert_gr2mtx<double>(inputfilename, outputfilename); break; case gr2floatmtx: convert_gr2mtx<float>(inputfilename, outputfilename); break; case gr2floatpbbsedges: convert_gr2pbbsedges<float>(inputfilename, outputfilename); break; #if !defined(__IBMCPP__) || __IBMCPP__ > 1210 case gr2intpbbs: convert_gr2pbbs<int32_t,int32_t>(inputfilename, outputfilename); break; #endif case gr2intpbbsedges: convert_gr2pbbsedges<int32_t>(inputfilename, outputfilename); break; case gr2lowdegreeintgr: remove_high_degree<int32_t>(inputfilename, outputfilename, maxDegree); break; // XXX(ddn): The below triggers some internal XLC bug #if !defined(__IBMCPP__) || __IBMCPP__ > 1210 case gr2partdstintgr: partition_by_destination<int32_t>(inputfilename, outputfilename, numParts); break; #endif case gr2partsrcintgr: partition_by_source<int32_t>(inputfilename, outputfilename, numParts); break; case gr2randintgr: convert_gr2rand<int32_t>(inputfilename, outputfilename); break; case gr2sorteddstintgr: sort_edges<int32_t,IdLess>(inputfilename, outputfilename); break; case gr2sortedweightintgr: sort_edges<int32_t,WeightLess>(inputfilename, outputfilename); break; case gr2ringintgr: add_ring<int32_t>(inputfilename, outputfilename, maxValue); break; case gr2rmat: convert_gr2rmat<int32_t,int32_t>(inputfilename, outputfilename); break; case gr2sintgr: convert_gr2sgr<int32_t>(inputfilename, outputfilename); break; case gr2tintgr: transpose<int32_t>(inputfilename, outputfilename); break; case gr2treeintgr: add_tree<int32_t>(inputfilename, outputfilename, maxValue); break; case gr2orderdeg: order_by_high_degree<void>(inputfilename, outputfilename, maxValue); break; case intedgelist2gr: convert_edgelist2gr<int>(inputfilename, outputfilename); break; case mtx2doublegr: convert_mtx2gr<double>(inputfilename, outputfilename); break; case mtx2floatgr: convert_mtx2gr<float>(inputfilename, outputfilename); break; case nodelist2vgr: convert_nodelist2vgr(inputfilename, outputfilename); break; case pbbs2vgr: convert_pbbs2vgr(inputfilename, outputfilename); break; case vgr2bsml: convert_gr2bsml<void>(inputfilename, outputfilename); break; case vgr2cvgr: convert_gr2cgr<void>(inputfilename, outputfilename); break; case vgr2edgelist: convert_gr2edgelist<void>(inputfilename, outputfilename); break; case vgr2intgr: add_weights<void,int32_t>(inputfilename, outputfilename, maxValue); break; case vgr2lowdegreevgr: remove_high_degree<void>(inputfilename, outputfilename, maxDegree); break; #if !defined(__IBMCPP__) || __IBMCPP__ > 1210 case vgr2pbbs: convert_gr2pbbs<void,void>(inputfilename, outputfilename); break; #endif case vgr2ringvgr: add_ring<void>(inputfilename, outputfilename, maxValue); break; case vgr2svgr: convert_gr2sgr<void>(inputfilename, outputfilename); break; case vgr2treevgr: add_tree<void>(inputfilename, outputfilename, maxValue); break; case vgr2trivgr: convert_sgr2gr<void>(inputfilename, outputfilename); break; case vgr2tvgr: transpose<void>(inputfilename, outputfilename); break; #if !defined(__IBMCPP__) || __IBMCPP__ > 1210 case vgr2vbinpbbs32: convert_gr2vbinpbbs<uint32_t,uint32_t>(inputfilename, outputfilename); break; case vgr2vbinpbbs64: convert_gr2vbinpbbs<uint32_t,uint64_t>(inputfilename, outputfilename); break; #endif default: abort(); } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindTBB.cmake
# Locate Intel Threading Building Blocks include paths and libraries # FindTBB.cmake can be found at https://code.google.com/p/findtbb/ # Written by Hannes Hofmann <hannes.hofmann _at_ informatik.uni-erlangen.de> # Improvements by Gino van den Bergen <gino _at_ dtecta.com>, # Florian Uhlig <F.Uhlig _at_ gsi.de>, # Jiri Marsik <jiri.marsik89 _at_ gmail.com> # The MIT License # # Copyright (c) 2011 Hannes Hofmann # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # GvdB: This module uses the environment variable TBB_ARCH_PLATFORM which defines architecture and compiler. # e.g. "ia32/vc8" or "em64t/cc4.1.0_libc2.4_kernel2.6.16.21" # TBB_ARCH_PLATFORM is set by the build script tbbvars[.bat|.sh|.csh], which can be found # in the TBB installation directory (TBB_INSTALL_DIR). # # GvdB: Mac OS X distribution places libraries directly in lib directory. # # For backwards compatibility, you may explicitely set the CMake variables TBB_ARCHITECTURE and TBB_COMPILER. # TBB_ARCHITECTURE [ ia32 | em64t | itanium ] # which architecture to use # TBB_COMPILER e.g. vc9 or cc3.2.3_libc2.3.2_kernel2.4.21 or cc4.0.1_os10.4.9 # which compiler to use (detected automatically on Windows) # This module respects # TBB_INSTALL_DIR or $ENV{TBB21_INSTALL_DIR} or $ENV{TBB_INSTALL_DIR} # This module defines # TBB_INCLUDE_DIRS, where to find task_scheduler_init.h, etc. # TBB_LIBRARY_DIRS, where to find libtbb, libtbbmalloc # TBB_DEBUG_LIBRARY_DIRS, where to find libtbb_debug, libtbbmalloc_debug # TBB_INSTALL_DIR, the base TBB install directory # TBB_LIBRARIES, the libraries to link against to use TBB. # TBB_DEBUG_LIBRARIES, the libraries to link against to use TBB with debug symbols. # TBB_FOUND, If false, don't try to use TBB. # TBB_INTERFACE_VERSION, as defined in tbb/tbb_stddef.h if (WIN32) # has em64t/vc8 em64t/vc9 # has ia32/vc7.1 ia32/vc8 ia32/vc9 set(_TBB_DEFAULT_INSTALL_DIR "C:/Program Files/Intel/TBB" "C:/Program Files (x86)/Intel/TBB") set(_TBB_LIB_NAME "tbb") set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") if (MSVC71) set (_TBB_COMPILER "vc7.1") endif(MSVC71) if (MSVC80) set(_TBB_COMPILER "vc8") endif(MSVC80) if (MSVC90) set(_TBB_COMPILER "vc9") endif(MSVC90) if(MSVC10) set(_TBB_COMPILER "vc10") endif(MSVC10) # Todo: add other Windows compilers such as ICL. set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) endif (WIN32) if (UNIX) if (APPLE) # MAC set(_TBB_DEFAULT_INSTALL_DIR "/Library/Frameworks/Intel_TBB.framework/Versions") # libs: libtbb.dylib, libtbbmalloc.dylib, *_debug set(_TBB_LIB_NAME "tbb") set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") # default flavor on apple: ia32/cc4.0.1_os10.4.9 # Jiri: There is no reason to presume there is only one flavor and # that user's setting of variables should be ignored. if(NOT TBB_COMPILER) set(_TBB_COMPILER "cc4.0.1_os10.4.9") elseif (NOT TBB_COMPILER) set(_TBB_COMPILER ${TBB_COMPILER}) endif(NOT TBB_COMPILER) if(NOT TBB_ARCHITECTURE) set(_TBB_ARCHITECTURE "ia32") elseif(NOT TBB_ARCHITECTURE) set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) endif(NOT TBB_ARCHITECTURE) else (APPLE) # LINUX set(_TBB_DEFAULT_INSTALL_DIR "/opt/intel/tbb" "/usr/local/include" "/usr/include") set(_TBB_LIB_NAME "tbb") set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") # has em64t/cc3.2.3_libc2.3.2_kernel2.4.21 em64t/cc3.3.3_libc2.3.3_kernel2.6.5 em64t/cc3.4.3_libc2.3.4_kernel2.6.9 em64t/cc4.1.0_libc2.4_kernel2.6.16.21 # has ia32/* # has itanium/* set(_TBB_COMPILER ${TBB_COMPILER}) set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) endif (APPLE) endif (UNIX) if (CMAKE_SYSTEM MATCHES "SunOS.*") # SUN # not yet supported # has em64t/cc3.4.3_kernel5.10 # has ia32/* endif (CMAKE_SYSTEM MATCHES "SunOS.*") #-- Clear the public variables set (TBB_FOUND "NO") #-- Find TBB install dir and set ${_TBB_INSTALL_DIR} and cached ${TBB_INSTALL_DIR} # first: use CMake variable TBB_INSTALL_DIR if (TBB_INSTALL_DIR) set (_TBB_INSTALL_DIR ${TBB_INSTALL_DIR}) endif (TBB_INSTALL_DIR) # second: use environment variable if (NOT _TBB_INSTALL_DIR) if (NOT "$ENV{TBBROOT}" STREQUAL "") set (_TBB_INSTALL_DIR $ENV{TBBROOT}) endif() if (NOT "$ENV{TBB_INSTALL_DIR}" STREQUAL "") set (_TBB_INSTALL_DIR $ENV{TBB_INSTALL_DIR}) endif (NOT "$ENV{TBB_INSTALL_DIR}" STREQUAL "") # Intel recommends setting TBB21_INSTALL_DIR if (NOT "$ENV{TBB21_INSTALL_DIR}" STREQUAL "") set (_TBB_INSTALL_DIR $ENV{TBB21_INSTALL_DIR}) endif (NOT "$ENV{TBB21_INSTALL_DIR}" STREQUAL "") if (NOT "$ENV{TBB22_INSTALL_DIR}" STREQUAL "") set (_TBB_INSTALL_DIR $ENV{TBB22_INSTALL_DIR}) endif (NOT "$ENV{TBB22_INSTALL_DIR}" STREQUAL "") if (NOT "$ENV{TBB30_INSTALL_DIR}" STREQUAL "") set (_TBB_INSTALL_DIR $ENV{TBB30_INSTALL_DIR}) endif (NOT "$ENV{TBB30_INSTALL_DIR}" STREQUAL "") endif (NOT _TBB_INSTALL_DIR) # third: try to find path automatically if (NOT _TBB_INSTALL_DIR) if (_TBB_DEFAULT_INSTALL_DIR) set (_TBB_INSTALL_DIR ${_TBB_DEFAULT_INSTALL_DIR}) endif (_TBB_DEFAULT_INSTALL_DIR) endif (NOT _TBB_INSTALL_DIR) # sanity check if (NOT _TBB_INSTALL_DIR) message ("ERROR: Unable to find Intel TBB install directory. ${_TBB_INSTALL_DIR}") else (NOT _TBB_INSTALL_DIR) # finally: set the cached CMake variable TBB_INSTALL_DIR if (NOT TBB_INSTALL_DIR) set (TBB_INSTALL_DIR ${_TBB_INSTALL_DIR} CACHE PATH "Intel TBB install directory") mark_as_advanced(TBB_INSTALL_DIR) endif (NOT TBB_INSTALL_DIR) #-- A macro to rewrite the paths of the library. This is necessary, because # find_library() always found the em64t/vc9 version of the TBB libs macro(TBB_CORRECT_LIB_DIR var_name) # if (NOT "${_TBB_ARCHITECTURE}" STREQUAL "em64t") string(REPLACE em64t "${_TBB_ARCHITECTURE}" ${var_name} ${${var_name}}) # endif (NOT "${_TBB_ARCHITECTURE}" STREQUAL "em64t") string(REPLACE ia32 "${_TBB_ARCHITECTURE}" ${var_name} ${${var_name}}) string(REPLACE vc7.1 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) string(REPLACE vc8 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) string(REPLACE vc9 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) string(REPLACE vc10 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) endmacro(TBB_CORRECT_LIB_DIR var_content) #-- Look for include directory and set ${TBB_INCLUDE_DIR} set (TBB_INC_SEARCH_DIR ${_TBB_INSTALL_DIR}/include) # Jiri: tbbvars now sets the CPATH environment variable to the directory # containing the headers. find_path(TBB_INCLUDE_DIR tbb/task_scheduler_init.h PATHS ${TBB_INC_SEARCH_DIR} ENV CPATH ) mark_as_advanced(TBB_INCLUDE_DIR) #-- Look for libraries # GvdB: $ENV{TBB_ARCH_PLATFORM} is set by the build script tbbvars[.bat|.sh|.csh] if (NOT $ENV{TBB_ARCH_PLATFORM} STREQUAL "") set (_TBB_LIBRARY_DIR ${_TBB_INSTALL_DIR}/lib/$ENV{TBB_ARCH_PLATFORM} ${_TBB_INSTALL_DIR}/$ENV{TBB_ARCH_PLATFORM}/lib ) endif (NOT $ENV{TBB_ARCH_PLATFORM} STREQUAL "") # Jiri: This block isn't mutually exclusive with the previous one # (hence no else), instead I test if the user really specified # the variables in question. if ((NOT ${TBB_ARCHITECTURE} STREQUAL "") AND (NOT ${TBB_COMPILER} STREQUAL "")) # HH: deprecated message(STATUS "[Warning] FindTBB.cmake: The use of TBB_ARCHITECTURE and TBB_COMPILER is deprecated and may not be supported in future versions. Please set \$ENV{TBB_ARCH_PLATFORM} (using tbbvars.[bat|csh|sh]).") # Jiri: It doesn't hurt to look in more places, so I store the hints from # ENV{TBB_ARCH_PLATFORM} and the TBB_ARCHITECTURE and TBB_COMPILER # variables and search them both. set (_TBB_LIBRARY_DIR "${_TBB_INSTALL_DIR}/${_TBB_ARCHITECTURE}/${_TBB_COMPILER}/lib" ${_TBB_LIBRARY_DIR}) endif ((NOT ${TBB_ARCHITECTURE} STREQUAL "") AND (NOT ${TBB_COMPILER} STREQUAL "")) # GvdB: Mac OS X distribution places libraries directly in lib directory. list(APPEND _TBB_LIBRARY_DIR ${_TBB_INSTALL_DIR}/lib) # Jiri: No reason not to check the default paths. From recent versions, # tbbvars has started exporting the LIBRARY_PATH and LD_LIBRARY_PATH # variables, which now point to the directories of the lib files. # It all makes more sense to use the ${_TBB_LIBRARY_DIR} as a HINTS # argument instead of the implicit PATHS as it isn't hard-coded # but computed by system introspection. Searching the LIBRARY_PATH # and LD_LIBRARY_PATH environment variables is now even more important # that tbbvars doesn't export TBB_ARCH_PLATFORM and it facilitates # the use of TBB built from sources. find_library(TBB_LIBRARY ${_TBB_LIB_NAME} HINTS ${_TBB_LIBRARY_DIR} PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) find_library(TBB_MALLOC_LIBRARY ${_TBB_LIB_MALLOC_NAME} HINTS ${_TBB_LIBRARY_DIR} PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) #Extract path from TBB_LIBRARY name get_filename_component(TBB_LIBRARY_DIR ${TBB_LIBRARY} PATH) #TBB_CORRECT_LIB_DIR(TBB_LIBRARY) #TBB_CORRECT_LIB_DIR(TBB_MALLOC_LIBRARY) mark_as_advanced(TBB_LIBRARY TBB_MALLOC_LIBRARY) #-- Look for debug libraries # Jiri: Changed the same way as for the release libraries. find_library(TBB_LIBRARY_DEBUG ${_TBB_LIB_DEBUG_NAME} HINTS ${_TBB_LIBRARY_DIR} PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) find_library(TBB_MALLOC_LIBRARY_DEBUG ${_TBB_LIB_MALLOC_DEBUG_NAME} HINTS ${_TBB_LIBRARY_DIR} PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) # Jiri: Self-built TBB stores the debug libraries in a separate directory. # Extract path from TBB_LIBRARY_DEBUG name get_filename_component(TBB_LIBRARY_DEBUG_DIR ${TBB_LIBRARY_DEBUG} PATH) #TBB_CORRECT_LIB_DIR(TBB_LIBRARY_DEBUG) #TBB_CORRECT_LIB_DIR(TBB_MALLOC_LIBRARY_DEBUG) mark_as_advanced(TBB_LIBRARY_DEBUG TBB_MALLOC_LIBRARY_DEBUG) if (TBB_INCLUDE_DIR) if (TBB_LIBRARY) set (TBB_FOUND "YES") set (TBB_LIBRARIES ${TBB_LIBRARY} ${TBB_MALLOC_LIBRARY} ${TBB_LIBRARIES}) set (TBB_DEBUG_LIBRARIES ${TBB_LIBRARY_DEBUG} ${TBB_MALLOC_LIBRARY_DEBUG} ${TBB_DEBUG_LIBRARIES}) set (TBB_INCLUDE_DIRS ${TBB_INCLUDE_DIR} CACHE PATH "TBB include directory" FORCE) set (TBB_LIBRARY_DIRS ${TBB_LIBRARY_DIR} CACHE PATH "TBB library directory" FORCE) # Jiri: Self-built TBB stores the debug libraries in a separate directory. set (TBB_DEBUG_LIBRARY_DIRS ${TBB_LIBRARY_DEBUG_DIR} CACHE PATH "TBB debug library directory" FORCE) mark_as_advanced(TBB_INCLUDE_DIRS TBB_LIBRARY_DIRS TBB_DEBUG_LIBRARY_DIRS TBB_LIBRARIES TBB_DEBUG_LIBRARIES) message(STATUS "Found Intel TBB") endif (TBB_LIBRARY) endif (TBB_INCLUDE_DIR) if (NOT TBB_FOUND) message("ERROR: Intel TBB NOT found!") message(STATUS "Looked for Threading Building Blocks in ${_TBB_INSTALL_DIR}") # do only throw fatal, if this pkg is REQUIRED if (TBB_FIND_REQUIRED) message(FATAL_ERROR "Could NOT find TBB library.") endif (TBB_FIND_REQUIRED) endif (NOT TBB_FOUND) endif (NOT _TBB_INSTALL_DIR) if (TBB_FOUND) set(TBB_INTERFACE_VERSION 0) FILE(READ "${TBB_INCLUDE_DIRS}/tbb/tbb_stddef.h" _TBB_VERSION_CONTENTS) STRING(REGEX REPLACE ".*#define TBB_INTERFACE_VERSION ([0-9]+).*" "\\1" TBB_INTERFACE_VERSION "${_TBB_VERSION_CONTENTS}") set(TBB_INTERFACE_VERSION "${TBB_INTERFACE_VERSION}") endif (TBB_FOUND)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/UseDoxygen.cmake
# - Run Doxygen # # Adds a doxygen target that runs doxygen to generate the html # and optionally the LaTeX API documentation. # The doxygen target is added to the doc target as a dependency. # i.e.: the API documentation is built with: # make doc # # USAGE: GLOBAL INSTALL # # Install it with: # cmake ./ && sudo make install # Add the following to the CMakeLists.txt of your project: # include(UseDoxygen OPTIONAL) # Optionally copy Doxyfile.in in the directory of CMakeLists.txt and edit it. # # USAGE: INCLUDE IN PROJECT # # set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) # include(UseDoxygen) # Add the Doxyfile.in and UseDoxygen.cmake files to the projects source directory. # # # Variables you may define are: # DOXYFILE_SOURCE_DIR - Path where the Doxygen input files are. # Defaults to the current source and binary directory. # DOXYFILE_OUTPUT_DIR - Path where the Doxygen output is stored. Defaults to "doc". # # DOXYFILE_LATEX - Set to "NO" if you do not want the LaTeX documentation # to be built. # DOXYFILE_LATEX_DIR - Directory relative to DOXYFILE_OUTPUT_DIR where # the Doxygen LaTeX output is stored. Defaults to "latex". # # DOXYFILE_HTML_DIR - Directory relative to DOXYFILE_OUTPUT_DIR where # the Doxygen html output is stored. Defaults to "html". # # # Copyright (c) 2009, 2010 Tobias Rautenkranz <tobias@rautenkranz.ch> # # Redistribution and use is allowed according to the terms of the New # BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # macro(usedoxygen_set_default name value) if(NOT DEFINED "${name}") set("${name}" "${value}") endif() endmacro() find_package(Doxygen) if(DOXYGEN_FOUND) find_file(DOXYFILE_IN "Doxyfile.in" PATHS "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_ROOT}/Modules/" NO_DEFAULT_PATH) set(DOXYFILE "${CMAKE_CURRENT_BINARY_DIR}/Doxyfile") include(FindPackageHandleStandardArgs) find_package_handle_standard_args(DOXYFILE_IN DEFAULT_MSG "DOXYFILE_IN") endif() if(DOXYGEN_FOUND AND DOXYFILE_IN_FOUND) usedoxygen_set_default(DOXYFILE_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/doc") usedoxygen_set_default(DOXYFILE_HTML_DIR "html") usedoxygen_set_default(DOXYFILE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}\" \"${CMAKE_CURRENT_BINARY_DIR}") set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES "${DOXYFILE_OUTPUT_DIR}/${DOXYFILE_HTML_DIR}") add_custom_target(doxygen COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYFILE} COMMENT "Writing documentation to ${DOXYFILE_OUTPUT_DIR}..." WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) ## LaTeX set(DOXYFILE_PDFLATEX "NO") set(DOXYFILE_DOT "NO") find_package(LATEX) find_program(MAKE_PROGRAM make) if(NOT DEFINED DOXYFILE_LATEX) set(DOXFILE_LATEX, "YES") endif() if(LATEX_COMPILER AND MAKEINDEX_COMPILER AND MAKE_PROGRAM AND DOXYFILE_LATEX STREQUAL "YES") set(DOXYFILE_LATEX "YES") usedoxygen_set_default(DOXYFILE_LATEX_DIR "latex") set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES "${DOXYFILE_OUTPUT_DIR}/${DOXYFILE_LATEX_DIR}") if(PDFLATEX_COMPILER) set(DOXYFILE_PDFLATEX "YES") endif() if(DOXYGEN_DOT_EXECUTABLE) set(DOXYFILE_DOT "YES") endif() add_custom_command(TARGET doxygen POST_BUILD COMMAND ${MAKE_PROGRAM} COMMENT "Running LaTeX for Doxygen documentation in ${DOXYFILE_OUTPUT_DIR}/${DOXYFILE_LATEX_DIR}..." WORKING_DIRECTORY "${DOXYFILE_OUTPUT_DIR}/${DOXYFILE_LATEX_DIR}") else() set(DOXYGEN_LATEX "NO") endif() configure_file(${DOXYFILE_IN} Doxyfile IMMEDIATE @ONLY) get_target_property(DOC_TARGET doc TYPE) if(NOT DOC_TARGET) add_custom_target(doc) endif() add_dependencies(doc doxygen) endif()
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/HandleLLVMOptions.cmake
include(AddLLVMDefinitions) if( CMAKE_COMPILER_IS_GNUCXX ) set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON) elseif( "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" ) set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON) endif() # Run-time build mode; It is used for unittests. if(MSVC_IDE) # Expect "$(Configuration)", "$(OutDir)", etc. # It is expanded by msbuild or similar. set(RUNTIME_BUILD_MODE "${CMAKE_CFG_INTDIR}") elseif(NOT CMAKE_BUILD_TYPE STREQUAL "") # Expect "Release" "Debug", etc. # Or unittests could not run. set(RUNTIME_BUILD_MODE ${CMAKE_BUILD_TYPE}) else() # It might be "." set(RUNTIME_BUILD_MODE "${CMAKE_CFG_INTDIR}") endif() set(LIT_ARGS_DEFAULT "-sv") if (MSVC OR XCODE) set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --no-progress-bar") endif() set(LLVM_LIT_ARGS "${LIT_ARGS_DEFAULT}" CACHE STRING "Default options for lit") #XXX(ddn): Don't pollute with extra definitions if(0) if( LLVM_ENABLE_ASSERTIONS ) # MSVC doesn't like _DEBUG on release builds. See PR 4379. if( NOT MSVC ) add_definitions( -D_DEBUG ) endif() # On Release builds cmake automatically defines NDEBUG, so we # explicitly undefine it: if( uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE" ) add_definitions( -UNDEBUG ) endif() else() if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE" ) if( NOT MSVC_IDE AND NOT XCODE ) add_definitions( -DNDEBUG ) endif() endif() endif() endif() if(WIN32) if(CYGWIN) set(LLVM_ON_WIN32 0) set(LLVM_ON_UNIX 1) else(CYGWIN) set(LLVM_ON_WIN32 1) set(LLVM_ON_UNIX 0) # This is effective only on Win32 hosts to use gnuwin32 tools. set(LLVM_LIT_TOOLS_DIR "" CACHE PATH "Path to GnuWin32 tools") endif(CYGWIN) set(LTDL_SHLIB_EXT ".dll") set(EXEEXT ".exe") # Maximum path length is 160 for non-unicode paths set(MAXPATHLEN 160) else(WIN32) if(UNIX) set(LLVM_ON_WIN32 0) set(LLVM_ON_UNIX 1) if(APPLE) set(LTDL_SHLIB_EXT ".dylib") else(APPLE) set(LTDL_SHLIB_EXT ".so") endif(APPLE) set(EXEEXT "") # FIXME: Maximum path length is currently set to 'safe' fixed value set(MAXPATHLEN 2024) else(UNIX) MESSAGE(SEND_ERROR "Unable to determine platform") endif(UNIX) endif(WIN32) if( LLVM_ENABLE_PIC ) if( XCODE ) # Xcode has -mdynamic-no-pic on by default, which overrides -fPIC. I don't # know how to disable this, so just force ENABLE_PIC off for now. message(WARNING "-fPIC not supported with Xcode.") elseif( WIN32 ) # On Windows all code is PIC. MinGW warns if -fPIC is used. else() include(CheckCXXCompilerFlag) check_cxx_compiler_flag("-fPIC" SUPPORTS_FPIC_FLAG) if( SUPPORTS_FPIC_FLAG ) message(STATUS "Building with -fPIC") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC") else( SUPPORTS_FPIC_FLAG ) message(WARNING "-fPIC not supported.") endif() endif() endif() if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 ) # TODO: support other platforms and toolchains. option(LLVM_BUILD_32_BITS "Build 32 bits executables and libraries." OFF) if( LLVM_BUILD_32_BITS ) message(STATUS "Building 32 bits executables and libraries.") add_llvm_definitions( -m32 ) list(APPEND CMAKE_EXE_LINKER_FLAGS -m32) list(APPEND CMAKE_SHARED_LINKER_FLAGS -m32) endif( LLVM_BUILD_32_BITS ) endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 ) if( MSVC_IDE AND ( MSVC90 OR MSVC10 ) ) # Only Visual Studio 2008 and 2010 officially supports /MP. # Visual Studio 2005 do support it but it's experimental there. set(LLVM_COMPILER_JOBS "0" CACHE STRING "Number of parallel compiler jobs. 0 means use all processors. Default is 0.") if( NOT LLVM_COMPILER_JOBS STREQUAL "1" ) if( LLVM_COMPILER_JOBS STREQUAL "0" ) add_llvm_definitions( /MP ) else() if (MSVC10) message(FATAL_ERROR "Due to a bug in CMake only 0 and 1 is supported for " "LLVM_COMPILER_JOBS when generating for Visual Studio 2010") else() message(STATUS "Number of parallel compiler jobs set to " ${LLVM_COMPILER_JOBS}) add_llvm_definitions( /MP${LLVM_COMPILER_JOBS} ) endif() endif() else() message(STATUS "Parallel compilation disabled") endif() endif() if( MSVC ) include(ChooseMSVCCRT) # Add definitions that make MSVC much less annoying. add_llvm_definitions( # For some reason MS wants to deprecate a bunch of standard functions... -D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_NONSTDC_NO_WARNINGS -D_SCL_SECURE_NO_DEPRECATE -D_SCL_SECURE_NO_WARNINGS -wd4146 # Suppress 'unary minus operator applied to unsigned type, result still unsigned' -wd4180 # Suppress 'qualifier applied to function type has no meaning; ignored' -wd4224 # Suppress 'nonstandard extension used : formal parameter 'identifier' was previously defined as a type' -wd4244 # Suppress ''argument' : conversion from 'type1' to 'type2', possible loss of data' -wd4267 # Suppress ''var' : conversion from 'size_t' to 'type', possible loss of data' -wd4275 # Suppress 'An exported class was derived from a class that was not exported.' -wd4291 # Suppress ''declaration' : no matching operator delete found; memory will not be freed if initialization throws an exception' -wd4345 # Suppress 'behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized' -wd4351 # Suppress 'new behavior: elements of array 'array' will be default initialized' -wd4355 # Suppress ''this' : used in base member initializer list' -wd4503 # Suppress ''identifier' : decorated name length exceeded, name was truncated' -wd4551 # Suppress 'function call missing argument list' -wd4624 # Suppress ''derived class' : destructor could not be generated because a base class destructor is inaccessible' -wd4715 # Suppress ''function' : not all control paths return a value' -wd4800 # Suppress ''type' : forcing value to bool 'true' or 'false' (performance warning)' -wd4065 # Suppress 'switch statement contains 'default' but no 'case' labels' -wd4181 # Suppress 'qualifier applied to reference type; ignored' -w14062 # Promote "enumerator in switch of enum is not handled" to level 1 warning. ) # Enable warnings if (LLVM_ENABLE_WARNINGS) add_llvm_definitions( /W4 /Wall ) if (LLVM_ENABLE_PEDANTIC) # No MSVC equivalent available endif (LLVM_ENABLE_PEDANTIC) endif (LLVM_ENABLE_WARNINGS) if (LLVM_ENABLE_WERROR) add_llvm_definitions( /WX ) endif (LLVM_ENABLE_WERROR) elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE ) if (LLVM_ENABLE_WARNINGS) add_llvm_definitions( -Wall -W -Wno-unused-parameter -Wwrite-strings ) if (LLVM_ENABLE_PEDANTIC) add_llvm_definitions( -pedantic -Wno-long-long ) endif (LLVM_ENABLE_PEDANTIC) endif (LLVM_ENABLE_WARNINGS) if (LLVM_ENABLE_WERROR) add_llvm_definitions( -Werror ) endif (LLVM_ENABLE_WERROR) endif( MSVC ) add_llvm_definitions( -D__STDC_LIMIT_MACROS ) add_llvm_definitions( -D__STDC_CONSTANT_MACROS ) option(LLVM_INCLUDE_TESTS "Generate build targets for the LLVM unit tests." ON)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindPAPI.cmake
# Find PAPI libraries # Once done this will define # PAPI_FOUND - System has PAPI # PAPI_INCLUDE_DIRS - The PAPI include directories # PAPI_LIBRARIES - The libraries needed to use PAPI if(PAPI_INCLUDE_DIRS AND PAPI_LIBRARIES) set(PAPI_FIND_QUIETLY TRUE) endif() find_path(PAPI_INCLUDE_DIRS papi.h PATHS ${PAPI_ROOT} PATH_SUFFIXES include) find_library(PAPI_LIBRARY NAMES papi PATHS ${PAPI_ROOT} PATH_SUFFIXES lib lib64) find_library(PAPI_LIBRARIES NAMES rt PATH_SUFFIXES lib lib64) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(PAPI DEFAULT_MSG PAPI_LIBRARY PAPI_LIBRARIES PAPI_INCLUDE_DIRS) if(PAPI_FOUND) set(PAPI_LIBRARIES ${PAPI_LIBRARY} ${PAPI_LIBRARIES}) endif() mark_as_advanced(PAPI_INCLUDE_DIRS PAPI_LIBRARIES)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/AddLLVMDefinitions.cmake
# There is no clear way of keeping track of compiler command-line # options chosen via `add_definitions', so we need our own method for # using it on tools/llvm-config/CMakeLists.txt. # Beware that there is no implementation of remove_llvm_definitions. macro(add_llvm_definitions) # We don't want no semicolons on LLVM_DEFINITIONS: foreach(arg ${ARGN}) set(LLVM_DEFINITIONS "${LLVM_DEFINITIONS} ${arg}") endforeach(arg) add_definitions( ${ARGN} ) endmacro(add_llvm_definitions)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/llvm-extras.cmake
include(HandleLLVMOptions) if( WIN32 AND NOT CYGWIN ) # We consider Cygwin as another Unix set(PURE_WINDOWS 1) endif() include(CheckIncludeFile) include(CheckLibraryExists) include(CheckSymbolExists) include(CheckFunctionExists) include(CheckCXXSourceCompiles) include(TestBigEndian) if( UNIX AND NOT BEOS ) # Used by check_symbol_exists: set(CMAKE_REQUIRED_LIBRARIES m) endif() # Helper macros and functions macro(add_cxx_include result files) set(${result} "") foreach (file_name ${files}) set(${result} "${${result}}#include<${file_name}>\n") endforeach() endmacro(add_cxx_include files result) function(check_type_exists type files variable) add_cxx_include(includes "${files}") CHECK_CXX_SOURCE_COMPILES(" ${includes} ${type} typeVar; int main() { return 0; } " ${variable}) endfunction() # include checks check_include_file(argz.h HAVE_ARGZ_H) check_include_file(assert.h HAVE_ASSERT_H) check_include_file(ctype.h HAVE_CTYPE_H) check_include_file(dirent.h HAVE_DIRENT_H) check_include_file(dl.h HAVE_DL_H) check_include_file(dld.h HAVE_DLD_H) check_include_file(dlfcn.h HAVE_DLFCN_H) check_include_file(errno.h HAVE_ERRNO_H) check_include_file(execinfo.h HAVE_EXECINFO_H) check_include_file(fcntl.h HAVE_FCNTL_H) check_include_file(inttypes.h HAVE_INTTYPES_H) check_include_file(limits.h HAVE_LIMITS_H) check_include_file(link.h HAVE_LINK_H) check_include_file(malloc.h HAVE_MALLOC_H) check_include_file(malloc/malloc.h HAVE_MALLOC_MALLOC_H) check_include_file(memory.h HAVE_MEMORY_H) check_include_file(ndir.h HAVE_NDIR_H) if( NOT PURE_WINDOWS ) check_include_file(pthread.h HAVE_PTHREAD_H) endif() check_include_file(setjmp.h HAVE_SETJMP_H) check_include_file(signal.h HAVE_SIGNAL_H) check_include_file(stdint.h HAVE_STDINT_H) check_include_file(stdio.h HAVE_STDIO_H) check_include_file(stdlib.h HAVE_STDLIB_H) check_include_file(string.h HAVE_STRING_H) check_include_file(strings.h HAVE_STRINGS_H) check_include_file(sys/dir.h HAVE_SYS_DIR_H) check_include_file(sys/dl.h HAVE_SYS_DL_H) check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H) check_include_file(sys/mman.h HAVE_SYS_MMAN_H) check_include_file(sys/ndir.h HAVE_SYS_NDIR_H) check_include_file(sys/param.h HAVE_SYS_PARAM_H) check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H) check_include_file(sys/stat.h HAVE_SYS_STAT_H) check_include_file(sys/time.h HAVE_SYS_TIME_H) check_include_file(sys/types.h HAVE_SYS_TYPES_H) check_include_file(sys/uio.h HAVE_SYS_UIO_H) check_include_file(sys/wait.h HAVE_SYS_WAIT_H) check_include_file(termios.h HAVE_TERMIOS_H) check_include_file(unistd.h HAVE_UNISTD_H) check_include_file(utime.h HAVE_UTIME_H) check_include_file(valgrind/valgrind.h HAVE_VALGRIND_VALGRIND_H) check_include_file(windows.h HAVE_WINDOWS_H) check_include_file(fenv.h HAVE_FENV_H) check_include_file(mach/mach.h HAVE_MACH_MACH_H) check_include_file(mach-o/dyld.h HAVE_MACH_O_DYLD_H) # library checks if( NOT PURE_WINDOWS ) check_library_exists(pthread pthread_create "" HAVE_LIBPTHREAD) check_library_exists(pthread pthread_getspecific "" HAVE_PTHREAD_GETSPECIFIC) check_library_exists(pthread pthread_rwlock_init "" HAVE_PTHREAD_RWLOCK_INIT) check_library_exists(dl dlopen "" HAVE_LIBDL) endif() # function checks check_symbol_exists(getpagesize unistd.h HAVE_GETPAGESIZE) check_symbol_exists(getrusage sys/resource.h HAVE_GETRUSAGE) check_symbol_exists(setrlimit sys/resource.h HAVE_SETRLIMIT) check_function_exists(isatty HAVE_ISATTY) check_symbol_exists(index strings.h HAVE_INDEX) check_symbol_exists(isinf cmath HAVE_ISINF_IN_CMATH) check_symbol_exists(isinf math.h HAVE_ISINF_IN_MATH_H) check_symbol_exists(finite ieeefp.h HAVE_FINITE_IN_IEEEFP_H) check_symbol_exists(isnan cmath HAVE_ISNAN_IN_CMATH) check_symbol_exists(isnan math.h HAVE_ISNAN_IN_MATH_H) check_symbol_exists(ceilf math.h HAVE_CEILF) check_symbol_exists(floorf math.h HAVE_FLOORF) check_symbol_exists(fmodf math.h HAVE_FMODF) if( HAVE_SETJMP_H ) check_symbol_exists(longjmp setjmp.h HAVE_LONGJMP) check_symbol_exists(setjmp setjmp.h HAVE_SETJMP) check_symbol_exists(siglongjmp setjmp.h HAVE_SIGLONGJMP) check_symbol_exists(sigsetjmp setjmp.h HAVE_SIGSETJMP) endif() if( HAVE_SYS_UIO_H ) check_symbol_exists(writev sys/uio.h HAVE_WRITEV) endif() check_symbol_exists(nearbyintf math.h HAVE_NEARBYINTF) check_symbol_exists(mallinfo malloc.h HAVE_MALLINFO) check_symbol_exists(malloc_zone_statistics malloc/malloc.h HAVE_MALLOC_ZONE_STATISTICS) check_symbol_exists(mkdtemp "stdlib.h;unistd.h" HAVE_MKDTEMP) check_symbol_exists(mkstemp "stdlib.h;unistd.h" HAVE_MKSTEMP) check_symbol_exists(mktemp "stdlib.h;unistd.h" HAVE_MKTEMP) check_symbol_exists(closedir "sys/types.h;dirent.h" HAVE_CLOSEDIR) check_symbol_exists(opendir "sys/types.h;dirent.h" HAVE_OPENDIR) check_symbol_exists(readdir "sys/types.h;dirent.h" HAVE_READDIR) check_symbol_exists(getcwd unistd.h HAVE_GETCWD) check_symbol_exists(gettimeofday sys/time.h HAVE_GETTIMEOFDAY) check_symbol_exists(getrlimit "sys/types.h;sys/time.h;sys/resource.h" HAVE_GETRLIMIT) check_symbol_exists(rindex strings.h HAVE_RINDEX) check_symbol_exists(strchr string.h HAVE_STRCHR) check_symbol_exists(strcmp string.h HAVE_STRCMP) check_symbol_exists(strdup string.h HAVE_STRDUP) check_symbol_exists(strrchr string.h HAVE_STRRCHR) if( NOT PURE_WINDOWS ) check_symbol_exists(pthread_mutex_lock pthread.h HAVE_PTHREAD_MUTEX_LOCK) endif() check_symbol_exists(sbrk unistd.h HAVE_SBRK) check_symbol_exists(srand48 stdlib.h HAVE_RAND48_SRAND48) if( HAVE_RAND48_SRAND48 ) check_symbol_exists(lrand48 stdlib.h HAVE_RAND48_LRAND48) if( HAVE_RAND48_LRAND48 ) check_symbol_exists(drand48 stdlib.h HAVE_RAND48_DRAND48) if( HAVE_RAND48_DRAND48 ) set(HAVE_RAND48 1 CACHE INTERNAL "are srand48/lrand48/drand48 available?") endif() endif() endif() check_symbol_exists(strtoll stdlib.h HAVE_STRTOLL) check_symbol_exists(strtoq stdlib.h HAVE_STRTOQ) check_symbol_exists(strerror string.h HAVE_STRERROR) check_symbol_exists(strerror_r string.h HAVE_STRERROR_R) check_symbol_exists(strerror_s string.h HAVE_DECL_STRERROR_S) check_symbol_exists(memcpy string.h HAVE_MEMCPY) check_symbol_exists(memmove string.h HAVE_MEMMOVE) check_symbol_exists(setenv stdlib.h HAVE_SETENV) if( PURE_WINDOWS ) check_symbol_exists(_chsize_s io.h HAVE__CHSIZE_S) check_function_exists(_alloca HAVE__ALLOCA) check_function_exists(__alloca HAVE___ALLOCA) check_function_exists(__chkstk HAVE___CHKSTK) check_function_exists(___chkstk HAVE____CHKSTK) check_function_exists(__ashldi3 HAVE___ASHLDI3) check_function_exists(__ashrdi3 HAVE___ASHRDI3) check_function_exists(__divdi3 HAVE___DIVDI3) check_function_exists(__fixdfdi HAVE___FIXDFDI) check_function_exists(__fixsfdi HAVE___FIXSFDI) check_function_exists(__floatdidf HAVE___FLOATDIDF) check_function_exists(__lshrdi3 HAVE___LSHRDI3) check_function_exists(__moddi3 HAVE___MODDI3) check_function_exists(__udivdi3 HAVE___UDIVDI3) check_function_exists(__umoddi3 HAVE___UMODDI3) check_function_exists(__main HAVE___MAIN) check_function_exists(__cmpdi2 HAVE___CMPDI2) endif() if( HAVE_ARGZ_H ) check_symbol_exists(argz_append argz.h HAVE_ARGZ_APPEND) check_symbol_exists(argz_create_sep argz.h HAVE_ARGZ_CREATE_SEP) check_symbol_exists(argz_insert argz.h HAVE_ARGZ_INSERT) check_symbol_exists(argz_next argz.h HAVE_ARGZ_NEXT) check_symbol_exists(argz_stringify argz.h HAVE_ARGZ_STRINGIFY) endif() if( HAVE_DLFCN_H ) if( HAVE_LIBDL ) list(APPEND CMAKE_REQUIRED_LIBRARIES dl) endif() check_symbol_exists(dlerror dlfcn.h HAVE_DLERROR) check_symbol_exists(dlopen dlfcn.h HAVE_DLOPEN) if( HAVE_LIBDL ) list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES dl) endif() endif() #check_symbol_exists(__GLIBC__ stdio.h LLVM_USING_GLIBC) #if( LLVM_USING_GLIBC ) # add_llvm_definitions( -D_GNU_SOURCE ) #endif() set(headers "") if (HAVE_SYS_TYPES_H) set(headers ${headers} "sys/types.h") endif() if (HAVE_INTTYPES_H) set(headers ${headers} "inttypes.h") endif() if (HAVE_STDINT_H) set(headers ${headers} "stdint.h") endif() check_type_exists(int64_t "${headers}" HAVE_INT64_T) check_type_exists(uint64_t "${headers}" HAVE_UINT64_T) check_type_exists(u_int64_t "${headers}" HAVE_U_INT64_T) check_type_exists(error_t errno.h HAVE_ERROR_T) # available programs checks #function(llvm_find_program name) # string(TOUPPER ${name} NAME) # string(REGEX REPLACE "\\." "_" NAME ${NAME}) # find_program(LLVM_PATH_${NAME} ${name}) # mark_as_advanced(LLVM_PATH_${NAME}) # if(LLVM_PATH_${NAME}) # set(HAVE_${NAME} 1 CACHE INTERNAL "Is ${name} available ?") # mark_as_advanced(HAVE_${NAME}) # else(LLVM_PATH_${NAME}) # set(HAVE_${NAME} "" CACHE INTERNAL "Is ${name} available ?") # endif(LLVM_PATH_${NAME}) #endfunction() # #llvm_find_program(gv) #llvm_find_program(circo) #llvm_find_program(twopi) #llvm_find_program(neato) #llvm_find_program(fdp) #llvm_find_program(dot) #llvm_find_program(dotty) #llvm_find_program(xdot.py) # #if( LLVM_ENABLE_FFI ) # find_path(FFI_INCLUDE_PATH ffi.h PATHS ${FFI_INCLUDE_DIR}) # if( FFI_INCLUDE_PATH ) # set(FFI_HEADER ffi.h CACHE INTERNAL "") # set(HAVE_FFI_H 1 CACHE INTERNAL "") # else() # find_path(FFI_INCLUDE_PATH ffi/ffi.h PATHS ${FFI_INCLUDE_DIR}) # if( FFI_INCLUDE_PATH ) # set(FFI_HEADER ffi/ffi.h CACHE INTERNAL "") # set(HAVE_FFI_FFI_H 1 CACHE INTERNAL "") # endif() # endif() # # if( NOT FFI_HEADER ) # message(FATAL_ERROR "libffi includes are not found.") # endif() # # find_library(FFI_LIBRARY_PATH ffi PATHS ${FFI_LIBRARY_DIR}) # if( NOT FFI_LIBRARY_PATH ) # message(FATAL_ERROR "libffi is not found.") # endif() # # list(APPEND CMAKE_REQUIRED_LIBRARIES ${FFI_LIBRARY_PATH}) # list(APPEND CMAKE_REQUIRED_INCLUDES ${FFI_INCLUDE_PATH}) # check_symbol_exists(ffi_call ${FFI_HEADER} HAVE_FFI_CALL) # list(REMOVE_ITEM CMAKE_REQUIRED_INCLUDES ${FFI_INCLUDE_PATH}) # list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES ${FFI_LIBRARY_PATH}) #else() # unset(HAVE_FFI_FFI_H CACHE) # unset(HAVE_FFI_H CACHE) # unset(HAVE_FFI_CALL CACHE) #endif( LLVM_ENABLE_FFI ) # # Define LLVM_HAS_ATOMICS if gcc or MSVC atomic builtins are supported. #include(CheckAtomic) # #if( LLVM_ENABLE_PIC ) # set(ENABLE_PIC 1) #else() # set(ENABLE_PIC 0) #endif() # #include(CheckCXXCompilerFlag) # #check_cxx_compiler_flag("-Wno-variadic-macros" SUPPORTS_NO_VARIADIC_MACROS_FLAG) # #include(GetTargetTriple) #get_target_triple(LLVM_HOSTTRIPLE) # ## FIXME: We don't distinguish the target and the host. :( #set(TARGET_TRIPLE "${LLVM_HOSTTRIPLE}") # ## Determine the native architecture. #string(TOLOWER "${LLVM_TARGET_ARCH}" LLVM_NATIVE_ARCH) #if( LLVM_NATIVE_ARCH STREQUAL "host" ) # string(REGEX MATCH "^[^-]*" LLVM_NATIVE_ARCH ${LLVM_HOSTTRIPLE}) #endif () # #if (LLVM_NATIVE_ARCH MATCHES "i[2-6]86") # set(LLVM_NATIVE_ARCH X86) #elseif (LLVM_NATIVE_ARCH STREQUAL "x86") # set(LLVM_NATIVE_ARCH X86) #elseif (LLVM_NATIVE_ARCH STREQUAL "amd64") # set(LLVM_NATIVE_ARCH X86) #elseif (LLVM_NATIVE_ARCH STREQUAL "x86_64") # set(LLVM_NATIVE_ARCH X86) #elseif (LLVM_NATIVE_ARCH MATCHES "sparc") # set(LLVM_NATIVE_ARCH Sparc) #elseif (LLVM_NATIVE_ARCH MATCHES "powerpc") # set(LLVM_NATIVE_ARCH PowerPC) #elseif (LLVM_NATIVE_ARCH MATCHES "alpha") # set(LLVM_NATIVE_ARCH Alpha) #elseif (LLVM_NATIVE_ARCH MATCHES "arm") # set(LLVM_NATIVE_ARCH ARM) #elseif (LLVM_NATIVE_ARCH MATCHES "mips") # set(LLVM_NATIVE_ARCH Mips) #elseif (LLVM_NATIVE_ARCH MATCHES "xcore") # set(LLVM_NATIVE_ARCH XCore) #elseif (LLVM_NATIVE_ARCH MATCHES "msp430") # set(LLVM_NATIVE_ARCH MSP430) #else () # message(FATAL_ERROR "Unknown architecture ${LLVM_NATIVE_ARCH}") #endif () # #list(FIND LLVM_TARGETS_TO_BUILD ${LLVM_NATIVE_ARCH} NATIVE_ARCH_IDX) #if (NATIVE_ARCH_IDX EQUAL -1) # message(STATUS # "Native target ${LLVM_NATIVE_ARCH} is not selected; lli will not JIT code") #else () # message(STATUS "Native target architecture is ${LLVM_NATIVE_ARCH}") # set(LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target) # set(LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo) # set(LLVM_NATIVE_TARGETMC LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC) # set(LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter) #endif () # #if( MINGW ) # set(HAVE_LIBIMAGEHLP 1) # set(HAVE_LIBPSAPI 1) # # TODO: Check existence of libraries. # # include(CheckLibraryExists) # # CHECK_LIBRARY_EXISTS(imagehlp ??? . HAVE_LIBIMAGEHLP) #endif( MINGW ) # #if( MSVC ) # set(error_t int) # set(LTDL_SHLIBPATH_VAR "PATH") # set(LTDL_SYSSEARCHPATH "") # set(LTDL_DLOPEN_DEPLIBS 1) # set(SHLIBEXT ".lib") # set(LTDL_OBJDIR "_libs") # set(HAVE_STRTOLL 1) # set(strtoll "_strtoi64") # set(strtoull "_strtoui64") # set(stricmp "_stricmp") # set(strdup "_strdup") #else( MSVC ) # set(LTDL_SHLIBPATH_VAR "LD_LIBRARY_PATH") # set(LTDL_SYSSEARCHPATH "") # TODO # set(LTDL_DLOPEN_DEPLIBS 0) # TODO #endif( MSVC ) # #if( PURE_WINDOWS ) # CHECK_CXX_SOURCE_COMPILES(" # #include <windows.h> # #include <imagehlp.h> # extern \"C\" void foo(PENUMLOADED_MODULES_CALLBACK); # extern \"C\" void foo(BOOL(CALLBACK*)(PCSTR,ULONG_PTR,ULONG,PVOID)); # int main(){return 0;}" # HAVE_ELMCB_PCSTR) # if( HAVE_ELMCB_PCSTR ) # set(WIN32_ELMCB_PCSTR "PCSTR") # else() # set(WIN32_ELMCB_PCSTR "PSTR") # endif() #endif( PURE_WINDOWS ) # ## FIXME: Signal handler return type, currently hardcoded to 'void' #set(RETSIGTYPE void) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/include/llvm/Support/DataTypes.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/include/llvm/Support/DataTypes.h) #configure_file( # ${CMAKE_CURRENT_SOURCE_DIR}/include/llvm/Config/config.h.cmake # ${CMAKE_CURRENT_BINARY_DIR}/include/llvm/Config/config.h) include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/GetSVNVersion.cmake
# DUMMY is a non-existent file to force regeneration of svn header every build add_custom_target(svnversion ALL DEPENDS DUMMY ${PROJECT_BINARY_DIR}/include/Galois/svnversion.h) find_file(_MODULE "GetSVNVersion-write.cmake" PATHS ${CMAKE_MODULE_PATH}) add_custom_command(OUTPUT DUMMY ${PROJECT_BINARY_DIR}/include/Galois/svnversion.h COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_SOURCE_DIR} -DCMAKE_MODULE_PATH="${CMAKE_SOURCE_DIR}/cmake/Modules/" -P ${_MODULE}) set(_MODULE off) set_source_files_properties(${PROJECT_BINARY_DIR}/include/Galois/svnversion.h PROPERTIES GENERATED TRUE HEADER_FILE_ONLY TRUE)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/UseStdMacro.cmake
add_definitions(-D__STDC_LIMIT_MACROS) add_definitions(-D__STDC_CONSTANT_MACROS)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/CheckHugePages.cmake
include(CheckCSourceRuns) set(HugePages_C_TEST_SOURCE " #ifdef __linux__ #include <linux/mman.h> #endif #include <sys/mman.h> int main(int c, char** argv) { void *ptr = mmap(0, 2*1024*1024, PROT_READ|PROT_WRITE, MAP_HUGETLB, -1, 0); return ptr != MAP_FAILED; } ") CHECK_C_SOURCE_RUNS("${HugePages_C_TEST_SOURCE}" HAVE_HUGEPAGES) if(HAVE_HUGEPAGES) message(STATUS "Huge pages found") endif()
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/GetSVNVersion-write.cmake
### Don't include directly, for use by GetSVNVersion.cmake find_package(Subversion) # Extract svn info into MY_XXX variables if(Subversion_FOUND) Subversion_WC_INFO(${SOURCE_DIR} MY) if (Subversion_FOUND) file(WRITE include/Galois/svnversion.h.txt "#define GALOIS_SVNVERSION ${MY_WC_REVISION}\n") else() file(WRITE include/Galois/svnversion.h.txt "#define GALOIS_SVNVERSION 0\n") endif() else() file(WRITE include/Galois/svnversion.h.txt "#define GALOIS_SVNVERSION 0\n") endif() execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different include/Galois/svnversion.h.txt include/Galois/svnversion.h)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindEigen.cmake
# Find Eigen library # Once done this will define # Eigen_FOUND - System has Eigen # Eigen_INCLUDE_DIRS - The Eigen include directories # Eigen_LIBRARIES - The libraries needed to use Eigen set(Eigen_LIBRARIES) # Include-only library if(Eigen_INCLUDE_DIR) set(Eigen_FIND_QUIETLY TRUE) endif() find_path(Eigen_INCLUDE_DIRS NAMES Eigen/Eigen PATHS ENV EIGEN_HOME) include(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set Eigen_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args(Eigen DEFAULT_MSG Eigen_INCLUDE_DIRS) if(EIGEN_FOUND) set(Eigen_FOUND TRUE) endif() mark_as_advanced(Eigen_INCLUDE_DIRS)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/CheckCilk.cmake
include(CheckCXXSourceCompiles) set(Cilk_CXX_TEST_SOURCE " #include <cilk/cilk.h> int main(){ cilk_for(int i=0;i<1; ++i); } ") CHECK_CXX_SOURCE_COMPILES("${Cilk_CXX_TEST_SOURCE}" HAVE_CILK) if(HAVE_CILK) message(STATUS "A compiler with CILK support found") endif()
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindSubversion.cmake
# - Extract information from a subversion working copy # The module defines the following variables: # Subversion_SVN_EXECUTABLE - path to svn command line client # Subversion_VERSION_SVN - version of svn command line client # Subversion_FOUND - true if the command line client was found # If the command line client executable is found the macro # Subversion_WC_INFO(<dir> <var-prefix>) # is defined to extract information of a subversion working copy at # a given location. The macro defines the following variables: # <var-prefix>_WC_URL - url of the repository (at <dir>) # <var-prefix>_WC_ROOT - root url of the repository # <var-prefix>_WC_REVISION - current revision # <var-prefix>_WC_LAST_CHANGED_AUTHOR - author of last commit # <var-prefix>_WC_LAST_CHANGED_DATE - date of last commit # <var-prefix>_WC_LAST_CHANGED_REV - revision of last commit # <var-prefix>_WC_LAST_CHANGED_LOG - last log of base revision # <var-prefix>_WC_INFO - output of command `svn info <dir>' # Example usage: # FIND_PACKAGE(Subversion) # IF(Subversion_FOUND) # Subversion_WC_INFO(${PROJECT_SOURCE_DIR} Project) # MESSAGE("Current revision is ${Project_WC_REVISION}") # Subversion_WC_LOG(${PROJECT_SOURCE_DIR} Project) # MESSAGE("Last changed log is ${Project_LAST_CHANGED_LOG}") # ENDIF(Subversion_FOUND) # Copyright (c) 2006, Tristan Carel # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the University of California, Berkeley nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # $Id: FindSubversion.cmake,v 1.2.2.3 2008-05-23 20:09:34 hoffman Exp $ SET(Subversion_FOUND FALSE) SET(Subversion_SVN_FOUND FALSE) FIND_PROGRAM(Subversion_SVN_EXECUTABLE svn DOC "subversion command line client") MARK_AS_ADVANCED(Subversion_SVN_EXECUTABLE) IF(Subversion_SVN_EXECUTABLE) SET(Subversion_SVN_FOUND TRUE) SET(Subversion_FOUND TRUE) MACRO(Subversion_WC_INFO dir prefix) # the subversion commands should be executed with the C locale, otherwise # the message (which are parsed) may be translated, Alex SET(_Subversion_SAVED_LC_ALL "$ENV{LC_ALL}") SET(ENV{LC_ALL} C) EXECUTE_PROCESS(COMMAND ${Subversion_SVN_EXECUTABLE} --version WORKING_DIRECTORY ${dir} OUTPUT_VARIABLE Subversion_VERSION_SVN OUTPUT_STRIP_TRAILING_WHITESPACE) EXECUTE_PROCESS(COMMAND ${Subversion_SVN_EXECUTABLE} info ${dir} OUTPUT_VARIABLE ${prefix}_WC_INFO ERROR_VARIABLE Subversion_svn_info_error RESULT_VARIABLE Subversion_svn_info_result OUTPUT_STRIP_TRAILING_WHITESPACE) IF(NOT ${Subversion_svn_info_result} EQUAL 0) MESSAGE(STATUS "Command \"${Subversion_SVN_EXECUTABLE} info ${dir}\" failed with output:\n${Subversion_svn_info_error}") set(Subversion_SVN_FOUND FALSE) set(Subversion_FOUND FALSE) ELSE(NOT ${Subversion_svn_info_result} EQUAL 0) STRING(REGEX REPLACE "^(.*\n)?svn, version ([.0-9]+).*" "\\2" Subversion_VERSION_SVN "${Subversion_VERSION_SVN}") STRING(REGEX REPLACE "^(.*\n)?URL: ([^\n]+).*" "\\2" ${prefix}_WC_URL "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Revision: ([^\n]+).*" "\\2" ${prefix}_WC_REVISION "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Last Changed Author: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_AUTHOR "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Last Changed Rev: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_REV "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Last Changed Date: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_DATE "${${prefix}_WC_INFO}") ENDIF(NOT ${Subversion_svn_info_result} EQUAL 0) # restore the previous LC_ALL SET(ENV{LC_ALL} ${_Subversion_SAVED_LC_ALL}) ENDMACRO(Subversion_WC_INFO) MACRO(Subversion_WC_LOG dir prefix) # This macro can block if the certificate is not signed: # svn ask you to accept the certificate and wait for your answer # This macro requires a svn server network access (Internet most of the time) # and can also be slow since it access the svn server EXECUTE_PROCESS(COMMAND ${Subversion_SVN_EXECUTABLE} log -r BASE ${dir} OUTPUT_VARIABLE ${prefix}_LAST_CHANGED_LOG ERROR_VARIABLE Subversion_svn_log_error RESULT_VARIABLE Subversion_svn_log_result OUTPUT_STRIP_TRAILING_WHITESPACE) IF(NOT ${Subversion_svn_log_result} EQUAL 0) MESSAGE(SEND_ERROR "Command \"${Subversion_SVN_EXECUTABLE} log -r BASE ${dir}\" failed with output:\n${Subversion_svn_log_error}") ENDIF(NOT ${Subversion_svn_log_result} EQUAL 0) ENDMACRO(Subversion_WC_LOG) ENDIF(Subversion_SVN_EXECUTABLE) IF(NOT Subversion_FOUND) IF(NOT Subversion_FIND_QUIETLY) MESSAGE(STATUS "Subversion was not found.") ELSE(NOT Subversion_FIND_QUIETLY) IF(Subversion_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Subversion was not found.") ENDIF(Subversion_FIND_REQUIRED) ENDIF(NOT Subversion_FIND_QUIETLY) ENDIF(NOT Subversion_FOUND) # FindSubversion.cmake ends here.
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/CheckEndian.cmake
include(TestBigEndian) TEST_BIG_ENDIAN(HAVE_BIG_ENDIAN) include(CheckIncludeFiles) CHECK_INCLUDE_FILES(endian.h HAVE_ENDIAN_H) include(CheckSymbolExists) CHECK_SYMBOL_EXISTS(le64toh "endian.h" HAVE_LE64TOH) CHECK_SYMBOL_EXISTS(le32toh "endian.h" HAVE_LE32TOH)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/CheckCXX11Features.cmake
include(CheckCXXSourceCompiles) include(CMakePushCheckState) set(CheckUniformIntDistribution " #include <random> int main(){ std::mt19937 gen; std::uniform_int_distribution<int> r(0, 6); return r(gen); } ") set(CheckUniformRealDistribution " #include <random> int main(){ std::mt19937 gen; std::uniform_real_distribution<float> r(0, 1); return r(gen) < 0.5 ? 0 : 1; } ") set(CheckChrono " #include <chrono> int main(){ typedef std::chrono::steady_clock Clock; std::chrono::time_point<Clock> start, stop; start = Clock::now(); stop = Clock::now(); unsigned long res = std::chrono::duration_cast<std::chrono::milliseconds>(stop-start).count(); return res < 1000 ? 0 : 1; } ") set(CheckAlignof " int main(){ return alignof(int) != 0; } ") cmake_push_check_state() set(CMAKE_REQUIRED_FLAGS ${CXX11_FLAGS}) CHECK_CXX_SOURCE_COMPILES("${CheckUniformIntDistribution}" HAVE_CXX11_UNIFORM_INT_DISTRIBUTION) CHECK_CXX_SOURCE_COMPILES("${CheckUniformRealDistribution}" HAVE_CXX11_UNIFORM_REAL_DISTRIBUTION) CHECK_CXX_SOURCE_COMPILES("${CheckChrono}" HAVE_CXX11_CHRONO) CHECK_CXX_SOURCE_COMPILES("${CheckAlignof}" HAVE_CXX11_ALIGNOF) cmake_pop_check_state()
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindHPCToolKit.cmake
# Find HPCToolKit libraries # Once done this will define # HPCToolKit_FOUND - System has lib # HPCToolKit_INCLUDE_DIRS - The include directories # HPCToolKit_LIBRARIES - The libraries needed to use if(HPCToolKit_INCLUDE_DIRS AND HPCToolKit_LIBRARIES) set(HPCToolKit_FIND_QUIETLY TRUE) endif() find_path(HPCToolKit_INCLUDE_DIRS hpctoolkit.h PATHS ${HPCToolKit_ROOT} PATH_SUFFIXES include) find_library(HPCToolKit_LIBRARY NAMES libhpctoolkit.a hpctoolkit PATHS ${HPCToolKit_ROOT} PATH_SUFFIXES lib lib64 lib32 lib/hpctoolkit) set(HPCToolKit_LIBRARIES ${HPCToolKit_LIBRARY}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(HPCToolKit DEFAULT_MSG HPCToolKit_LIBRARIES HPCToolKit_INCLUDE_DIRS) if(HPCTOOLKIT_FOUND) set(HPCToolKit_FOUND on) endif() mark_as_advanced(HPCToolKit_INCLUDE_DIRS HPCToolKit_LIBRARIES)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindNUMA.cmake
# Find numa library # Once done this will define # NUMA_FOUND - libnuma found # NUMA_OLD - old libnuma API if(NOT NUMA_FOUND) find_library(NUMA_LIBRARIES NAMES numa PATH_SUFFIXES lib lib64) if(NUMA_LIBRARIES) include(CheckLibraryExists) check_library_exists(${NUMA_LIBRARIES} numa_available "" NUMA_FOUND_INTERNAL) if(NUMA_FOUND_INTERNAL) check_library_exists(${NUMA_LIBRARIES} numa_allocate_nodemask "" NUMA_NEW_INTERNAL) if(NOT NUMA_NEW_INTERNAL) set(NUMA_OLD "yes" CACHE) endif() endif() include(FindPackageHandleStandardArgs) find_package_handle_standard_args(NUMA DEFAULT_MSG NUMA_LIBRARIES) mark_as_advanced(NUMA_FOUND) endif() endif()
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindVTune.cmake
# Find VTune libraries # Once done this will define # VTune_FOUND - System has VTune # VTune_INCLUDE_DIRS - The VTune include directories # VTune_LIBRARIES - The libraries needed to use VTune if(VTune_INCLUDE_DIRS AND VTune_LIBRARIES) set(VTune_FIND_QUIETLY TRUE) endif() find_path(VTune_INCLUDE_DIRS ittnotify.h PATHS ${VTune_ROOT} PATH_SUFFIXES include) find_library(VTune_LIBRARY NAMES ittnotify PATHS ${VTune_ROOT} PATH_SUFFIXES lib lib64 lib32) find_library(VTune_LIBRARIES NAMES dl PATH_SUFFIXES lib lib64 lib32) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(VTune DEFAULT_MSG VTune_LIBRARY VTune_LIBRARIES VTune_INCLUDE_DIRS) if(VTUNE_FOUND) set(VTune_FOUND on) set(VTune_LIBRARIES ${VTune_LIBRARY} ${VTune_LIBRARIES}) endif() mark_as_advanced(VTune_INCLUDE_DIRS VTune_LIBRARIES)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/GaloisConfig.cmake.in
# Config file for the Galois package # It defines the following variables # Galois_INCLUDE_DIRS # Galois_LIBRARIES # Galois_CXX_COMPILER # Galois_CXX_FLAGS get_filename_component(GALOIS_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) set(Galois_INCLUDE_DIRS "@GALOIS_INCLUDE_DIR@") set(Galois_INCLUDE_DIRS ${Galois_INCLUDE_DIRS} "@GALOIS_INCLUDE_DIRS@") if(NOT TARGET galois AND NOT Galois_BINARY_DIR) include("${GALOIS_CMAKE_DIR}/GaloisTargets.cmake") endif() set(Galois_LIBRARIES galois) set(Galois_CXX_COMPILER "@GALOIS_CXX_COMPILER@") set(Galois_CXX_FLAGS "@GALOIS_FLAGS@")
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/GaloisConfigVersion.cmake.in
set(PACKAGE_VERSION "@GALOIS_VERSION@") # Check whether the requested PACKAGE_FIND_VERSION is compatible if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_EXACT TRUE) endif() endif()
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindCXX11.cmake
# Find C++11 flags # Once done this will define # CXX11_FLAGS - Compiler flags to enable C++11 include(CheckCXXCompilerFlag) # This covers gcc, icc, clang, xlc # Place xlc (-qlanglvl=extended0x) first because xlc parses -std but does not # halt even with -qhalt=i set(CXX11_FLAG_CANDIDATES -qlanglvl=extended0x -std=c++11 -std=c++0x) # some versions of cmake don't recognize clang's rejection of unknown flags if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") set(CXX11_FLAG_CANDIDATES -std=c++11 -std=c++0x) endif() # Don't do anything when already set if(CXX11_FLAGS) set(CXX11_FLAG_CANDIDATES) set(CXX11_FOUND_INTERNAL "YES") endif() foreach(FLAG ${CXX11_FLAG_CANDIDATES}) unset(CXX11_FLAG_DETECTED CACHE) message(STATUS "Try C++11 flag = [${FLAG}]") check_cxx_compiler_flag("${FLAG}" CXX11_FLAG_DETECTED) if(CXX11_FLAG_DETECTED) set(CXX11_FOUND_INTERNAL "YES") set(CXX11_FLAGS "${FLAG}" CACHE STRING "C++ compiler flags for C++11 features") break() endif() endforeach() include(FindPackageHandleStandardArgs) find_package_handle_standard_args(CXX11 DEFAULT_MSG CXX11_FOUND_INTERNAL CXX11_FLAGS) mark_as_advanced(CXX11_FLAGS) include(CheckCXX11Features)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindGMP.cmake
# Find the GMP librairies # GMP_FOUND - system has GMP lib # GMP_INCLUDE_DIR - the GMP include directory # GMP_LIBRARIES - Libraries needed to use GMP # Copyright (c) 2006, Laurent Montel, <montel@kde.org> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. if(GMP_INCLUDE_DIRS AND GMP_LIBRARIES AND GMPXX_LIBRARIES) set(GMP_FIND_QUIETLY TRUE) endif() find_path(GMP_INCLUDE_DIRS NAMES gmp.h) find_library(GMP_LIBRARIES NAMES gmp libgmp) find_library(GMPXX_LIBRARIES NAMES gmpxx libgmpxx) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GMP DEFAULT_MSG GMP_INCLUDE_DIRS GMP_LIBRARIES) mark_as_advanced(GMP_INCLUDE_DIRS GMP_LIBRARIES GMPXX_LIBRARIES)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindFortran.cmake
# Check if Fortran is possibly around before using enable_lanauge because # enable_language(... OPTIONAL) does not fail gracefully if language is not # found: # http://public.kitware.com/Bug/view.php?id=9220 set(Fortran_EXECUTABLE) if(Fortran_EXECUTABLE) set(Fortran_FIND_QUIETLY TRUE) endif() find_program(Fortran_EXECUTABLE NAMES gfortran ifort g77 f77 g90 f90) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Fortran DEFAULT_MSG Fortran_EXECUTABLE) if(FORTRAN_FOUND) set(Fortran_FOUND TRUE) endif()
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/FindQGLViewer.cmake
# Find QGLViewer libraries # Once done this will define # QGLViewer_FOUND - System has QGLViewer # QGLViewer_INCLUDE_DIRS - The QGLViewer include directories # QGLViewer_LIBRARIES - The libraries needed to use QGLViewer if(QGLViewer_INCLUDE_DIRS AND QGLVIEWER_LIBRARIES) set(QGLViewer_FIND_QUIETLY TRUE) endif() find_path(QGLViewer_INCLUDE_DIRS NAMES QGLViewer/qglviewer.h) find_library(QGLViewer_LIBRARIES NAMES QGLViewer PATH_SUFFIXES lib lib64) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(QGLViewer DEFAULT_MSG QGLViewer_INCLUDE_DIRS QGLViewer_LIBRARIES) if(QGLVIEWER_FOUND) set(QGLViewer_FOUND TRUE) endif() mark_as_advanced(QGLViewer_INCLUDE_DIRS QGLViewer_LIBRARIES)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Modules/ParseArguments.cmake
# Parse arguments passed to a function into several lists separated by # upper-case identifiers and options that do not have an associated list e.g.: # # SET(arguments # hello OPTION3 world # LIST3 foo bar # OPTION2 # LIST1 fuz baz # ) # PARSE_ARGUMENTS(ARG "LIST1;LIST2;LIST3" "OPTION1;OPTION2;OPTION3" ${arguments}) # # results in 7 distinct variables: # * ARG_DEFAULT_ARGS: hello;world # * ARG_LIST1: fuz;baz # * ARG_LIST2: # * ARG_LIST3: foo;bar # * ARG_OPTION1: FALSE # * ARG_OPTION2: TRUE # * ARG_OPTION3: TRUE # # taken from http://www.cmake.org/Wiki/CMakeMacroParseArguments MACRO(PARSE_ARGUMENTS prefix arg_names option_names) SET(DEFAULT_ARGS) FOREACH(arg_name ${arg_names}) SET(${prefix}_${arg_name}) ENDFOREACH(arg_name) FOREACH(option ${option_names}) SET(${prefix}_${option} FALSE) ENDFOREACH(option) SET(current_arg_name DEFAULT_ARGS) SET(current_arg_list) FOREACH(arg ${ARGN}) SET(larg_names ${arg_names}) LIST(FIND larg_names "${arg}" is_arg_name) IF (is_arg_name GREATER -1) SET(${prefix}_${current_arg_name} ${current_arg_list}) SET(current_arg_name ${arg}) SET(current_arg_list) ELSE (is_arg_name GREATER -1) SET(loption_names ${option_names}) LIST(FIND loption_names "${arg}" is_option) IF (is_option GREATER -1) SET(${prefix}_${arg} TRUE) ELSE (is_option GREATER -1) SET(current_arg_list ${current_arg_list} ${arg}) ENDIF (is_option GREATER -1) ENDIF (is_arg_name GREATER -1) ENDFOREACH(arg) SET(${prefix}_${current_arg_name} ${current_arg_list}) ENDMACRO(PARSE_ARGUMENTS)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Toolchain/ppc64-bgq-linux-clang.cmake
set(CMAKE_SYSTEM_NAME BlueGeneQ-static) set(CMAKE_SYSTEM_VERSION 1) set(CMAKE_C_COMPILER bgclang) set(CMAKE_CXX_COMPILER bgclang++11) set(CMAKE_FIND_ROOT_PATH) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(USE_BGQ on)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Toolchain/ppc64-bgq-linux-tryrunresults.cmake
# This file was generated by CMake because it detected TRY_RUN() commands # in crosscompiling mode. It will be overwritten by the next CMake run. # Copy it to a safe location, set the variables to appropriate values # and use it then to preset the CMake cache (using -C). # HAVE_HUGEPAGES_EXITCODE # indicates whether the executable would have been able to run on its # target platform. If so, set HAVE_HUGEPAGES_EXITCODE to # the exit code (in many cases 0 for success), otherwise enter "FAILED_TO_RUN". # The HAVE_HUGEPAGES_COMPILED variable holds the build result for this TRY_RUN(). # # Source file : /g/g14/nguyen91/build/default/CMakeFiles/CMakeTmp/src.c # Executable : /g/g14/nguyen91/build/default/CMakeFiles/cmTryCompileExec124295678-HAVE_HUGEPAGES_EXITCODE # Run arguments : # Called from: [2] /g/g14/nguyen91/w/GaloisDefault/cmake/Modules/CheckHugePages.cmake # [1] /g/g14/nguyen91/w/GaloisDefault/CMakeLists.txt SET( HAVE_HUGEPAGES_EXITCODE 0 CACHE STRING "Result from TRY_RUN" FORCE)
0
rapidsai_public_repos/code-share/maxflow/galois/cmake
rapidsai_public_repos/code-share/maxflow/galois/cmake/Toolchain/ppc64-bgq-linux-xlc.cmake
set(CMAKE_SYSTEM_NAME BlueGeneQ-static) set(CMAKE_SYSTEM_VERSION 1) set(CMAKE_C_COMPILER bgxlc_r) set(CMAKE_CXX_COMPILER bgxlc++_r) set(CMAKE_FIND_ROOT_PATH) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(USE_BGQ on) set(GALOIS_USE_CXX11_COMPAT on)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/OCFileGraph.cpp
/** OCFilegraph -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Andrew Lenharth <andrewl@lenharth.org> * @author Donald Nguyen <ddn@cs.utexas.edu> */ #include "Galois/Graph/OCGraph.h" #include "Galois/Runtime/ll/gio.h" #include <cassert> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> using namespace Galois::Graph; //File format V1: //version (1) {uint64_t LE} //EdgeType size {uint64_t LE} //numNodes {uint64_t LE} //numEdges {uint64_t LE} //outindexs[numNodes] {uint64_t LE} (outindex[nodeid] is index of first edge for nodeid + 1 (end interator. node 0 has an implicit start iterator of 0. //outedges[numEdges] {uint32_t LE} //potential padding (32bit max) to Re-Align to 64bits //EdgeType[numEdges] {EdgeType size} OCFileGraph::~OCFileGraph() { if (masterMapping) munmap(masterMapping, masterLength); if (masterFD != -1) close(masterFD); } void OCFileGraph::Block::unload() { if (!m_mapping) return; if (munmap(m_mapping, m_length) != 0) { GALOIS_SYS_DIE("failed unallocating"); } m_mapping = 0; } struct PageSizeConf { const off64_t pagesize; PageSizeConf(): #ifdef _POSIX_PAGESIZE pagesize(_POSIX_PAGESIZE) #else pagesize(sysconf(_SC_PAGESIZE)) #endif { } }; void OCFileGraph::Block::load(int fd, off64_t offset, size_t begin, size_t len, size_t sizeof_data) { static PageSizeConf conf; assert(m_mapping == 0); off64_t start = offset + begin * sizeof_data; off64_t aligned = start & ~(conf.pagesize - 1); int _MAP_BASE = MAP_PRIVATE; #ifdef MAP_POPULATE _MAP_BASE |= MAP_POPULATE; #endif m_length = len * sizeof_data + conf.pagesize; // account for round off due to alignment m_mapping = mmap64(0, m_length, PROT_READ, _MAP_BASE, fd, aligned); if (m_mapping == MAP_FAILED) { GALOIS_SYS_DIE("failed allocating ", fd); } m_data = reinterpret_cast<char*>(m_mapping); assert(aligned <= start); assert(start - aligned <= (off64_t) conf.pagesize); m_data += start - aligned; m_begin = begin; m_sizeof_data = sizeof_data; } void OCFileGraph::load(segment_type& s, edge_iterator begin, edge_iterator end, size_t sizeof_data) { size_t bb = *begin; size_t len = *end - *begin; off64_t outs = (4 + numNodes) * sizeof(uint64_t); off64_t data = outs + (numEdges + (numEdges & 1)) * sizeof(uint32_t); s.outs.load(masterFD, outs, bb, len, sizeof(uint32_t)); if (sizeof_data) s.edgeData.load(masterFD, data, bb, len, sizeof_data); s.loaded = true; } static void readHeader(int fd, uint64_t& numNodes, uint64_t& numEdges) { void* m = mmap(0, 4 * sizeof(uint64_t), PROT_READ, MAP_PRIVATE, fd, 0); if (m == MAP_FAILED) { GALOIS_SYS_DIE("failed reading ", fd); } uint64_t* ptr = reinterpret_cast<uint64_t*>(m); assert(ptr[0] == 1); numNodes = ptr[2]; numEdges = ptr[3]; if (munmap(m, 4 * sizeof(uint64_t))) { GALOIS_SYS_DIE("failed reading ", fd); } } void OCFileGraph::structureFromFile(const std::string& filename) { masterFD = open(filename.c_str(), O_RDONLY); if (masterFD == -1) { GALOIS_SYS_DIE("failed opening ", filename); } readHeader(masterFD, numNodes, numEdges); masterLength = 4 * sizeof(uint64_t) + numNodes * sizeof(uint64_t); int _MAP_BASE = MAP_PRIVATE; #ifdef MAP_POPULATE _MAP_BASE |= MAP_POPULATE; #endif masterMapping = mmap(0, masterLength, PROT_READ, _MAP_BASE, masterFD, 0); if (masterMapping == MAP_FAILED) { GALOIS_SYS_DIE("failed reading ", filename); } outIdx = reinterpret_cast<uint64_t*>(masterMapping); outIdx += 4; }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/Support.cpp
/** Support functions -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Andrew Lenharth <andrewl@lenharth.org> */ #include "Galois/Statistic.h" #include "Galois/Runtime/PerThreadStorage.h" #include "Galois/Runtime/Support.h" #include "Galois/Runtime/ll/StaticInstance.h" #include "Galois/Runtime/ll/gio.h" #include "Galois/Runtime/mm/Mem.h" #include <set> #include <map> #include <vector> #include <string> #include <cmath> using Galois::Runtime::LL::gPrint; namespace { class StatManager { typedef std::pair<std::string, std::string> KeyTy; Galois::Runtime::PerThreadStorage<std::map<KeyTy, unsigned long> > Stats; volatile unsigned maxID; void updateMax(unsigned n) { unsigned c; while (n > (c = maxID)) __sync_bool_compare_and_swap(&maxID, c, n); } KeyTy mkKey(const std::string& loop, const std::string& category) { return std::make_pair(loop,category); } void gather(const std::string& s1, const std::string& s2, unsigned m, std::vector<unsigned long>& v) { for (unsigned x = 0; x < m; ++x) v.push_back((*Stats.getRemote(x))[mkKey(s1,s2)]); } unsigned long getSum(std::vector<unsigned long>& Values, unsigned maxThreadID) { unsigned long R = 0; for (unsigned x = 0; x < maxThreadID; ++x) R += Values[x]; return R; } public: StatManager() :maxID(0) {} void addToStat(const std::string& loop, const std::string& category, size_t value) { (*Stats.getLocal())[mkKey(loop, category)] += value; updateMax(Galois::Runtime::activeThreads); } void addToStat(Galois::Statistic* value) { for (unsigned x = 0; x < Galois::Runtime::activeThreads; ++x) (*Stats.getRemote(x))[mkKey(value->getLoopname(), value->getStatname())] += value->getValue(x); updateMax(Galois::Runtime::activeThreads); } void addPageAllocToStat(const std::string& loop, const std::string& category) { for (unsigned x = 0; x < Galois::Runtime::activeThreads; ++x) (*Stats.getRemote(x))[mkKey(loop, category)] += Galois::Runtime::MM::numPageAllocForThread(x); updateMax(Galois::Runtime::activeThreads); } void addNumaAllocToStat(const std::string& loop, const std::string& category) { int nodes = Galois::Runtime::MM::numNumaNodes(); for (int x = 0; x < nodes; ++x) (*Stats.getRemote(x))[mkKey(loop, category)] += Galois::Runtime::MM::numNumaAllocForNode(x); updateMax(nodes); } //Assume called serially void printStats() { std::set<KeyTy> LKs; unsigned maxThreadID = maxID; //Find all loops and keys for (unsigned x = 0; x < maxThreadID; ++x) { std::map<KeyTy, unsigned long>& M = *Stats.getRemote(x); for (std::map<KeyTy, unsigned long>::iterator ii = M.begin(), ee = M.end(); ii != ee; ++ii) { LKs.insert(ii->first); } } //print header gPrint("STATTYPE,LOOP,CATEGORY,n,sum"); for (unsigned x = 0; x < maxThreadID; ++x) gPrint(",T", x); gPrint("\n"); //print all values for (std::set<KeyTy>::iterator ii = LKs.begin(), ee = LKs.end(); ii != ee; ++ii) { std::vector<unsigned long> Values; gather(ii->first, ii->second, maxThreadID, Values); gPrint("STAT,", ii->first.c_str(), ",", ii->second.c_str(), ",", maxThreadID, ",", getSum(Values, maxThreadID) ); for (unsigned x = 0; x < maxThreadID; ++x) { gPrint(",", Values[x]); } gPrint("\n"); } } }; static Galois::Runtime::LL::StaticInstance<StatManager> SM; } bool Galois::Runtime::inGaloisForEach = false; void Galois::Runtime::reportStat(const char* loopname, const char* category, unsigned long value) { SM.get()->addToStat(std::string(loopname ? loopname : "(NULL)"), std::string(category ? category : "(NULL)"), value); } void Galois::Runtime::reportStat(const std::string& loopname, const std::string& category, unsigned long value) { SM.get()->addToStat(loopname, category, value); } void Galois::Runtime::reportStat(Galois::Statistic* value) { SM.get()->addToStat(value); } void Galois::Runtime::printStats() { SM.get()->printStats(); } void Galois::Runtime::reportPageAlloc(const char* category) { SM.get()->addPageAllocToStat(std::string("(NULL)"), std::string(category ? category : "(NULL)")); } void Galois::Runtime::reportNumaAlloc(const char* category) { SM.get()->addNumaAllocToStat(std::string("(NULL)"), std::string(category ? category : "(NULL)")); }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/FileGraph.cpp
/** File graph -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Graph serialized to a file. * * @author Andrew Lenharth <andrewl@lenharth.org> */ #include "Galois/Graph/FileGraph.h" #include "Galois/Runtime/mm/Mem.h" #include <cassert> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> using namespace Galois::Graph; //File format V1: //version (1) {uint64_t LE} //EdgeType size {uint64_t LE} //numNodes {uint64_t LE} //numEdges {uint64_t LE} //outindexs[numNodes] {uint64_t LE} (outindex[nodeid] is index of first edge for nodeid + 1 (end interator. node 0 has an implicit start iterator of 0. //outedges[numEdges] {uint32_t LE} //potential padding (32bit max) to Re-Align to 64bits //EdgeType[numEdges] {EdgeType size} FileGraph::FileGraph() : masterMapping(0), masterLength(0), masterFD(0), outIdx(0), outs(0), edgeData(0), numEdges(0), numNodes(0) { } FileGraph::~FileGraph() { if (masterMapping) munmap(masterMapping, masterLength); if (masterFD) close(masterFD); } void FileGraph::parse(void* m) { //parse file uint64_t* fptr = (uint64_t*)m; uint64_t version = convert_le64(*fptr++); if (version != 1) GALOIS_DIE("unknown file version ", version); sizeofEdge = convert_le64(*fptr++); numNodes = convert_le64(*fptr++); numEdges = convert_le64(*fptr++); outIdx = fptr; fptr += numNodes; uint32_t* fptr32 = (uint32_t*)fptr; outs = fptr32; fptr32 += numEdges; if (numEdges % 2) fptr32 += 1; edgeData = (char*)fptr32; } void FileGraph::structureFromMem(void* mem, size_t len, bool clone) { masterLength = len; if (clone) { int _MAP_BASE = MAP_ANONYMOUS | MAP_PRIVATE; #ifdef MAP_POPULATE _MAP_BASE |= MAP_POPULATE; #endif void* m = mmap(0, masterLength, PROT_READ | PROT_WRITE, _MAP_BASE, -1, 0); if (m == MAP_FAILED) { GALOIS_SYS_DIE("failed copying graph"); } memcpy(m, mem, len); parse(m); masterMapping = m; } else { parse(mem); masterMapping = mem; } } void* FileGraph::structureFromGraph(FileGraph& g, size_t sizeof_edge_data) { // Allocate size_t common = g.masterLength - (g.sizeofEdge * g.numEdges); size_t len = common + (sizeof_edge_data * g.numEdges); int _MAP_BASE = MAP_ANONYMOUS | MAP_PRIVATE; #ifdef MAP_POPULATE _MAP_BASE |= MAP_POPULATE; #endif void* m = mmap(0, len, PROT_READ | PROT_WRITE, _MAP_BASE, -1, 0); if (m == MAP_FAILED) { GALOIS_SYS_DIE("failed copying graph"); } memcpy(m, g.masterMapping, common); uint64_t* fptr = (uint64_t*)m; fptr[1] = convert_le64(sizeof_edge_data); structureFromMem(m, len, false); return edgeData; } void* FileGraph::structureFromArrays(uint64_t* out_idx, uint64_t num_nodes, uint32_t* outs, uint64_t num_edges, size_t sizeof_edge_data) { uint64_t nBytes = sizeof(uint64_t) * 4; // version, sizeof_edge_data, numNodes, numEdges nBytes += sizeof(uint64_t) * num_nodes; nBytes += sizeof(uint32_t) * num_edges; if (num_edges % 2) nBytes += sizeof(uint32_t); // padding nBytes += sizeof_edge_data * num_edges; int _MAP_BASE = MAP_ANONYMOUS | MAP_PRIVATE; #ifdef MAP_POPULATE _MAP_BASE |= MAP_POPULATE; #endif char* base = (char*) mmap(0, nBytes, PROT_READ | PROT_WRITE, _MAP_BASE, -1, 0); if (base == MAP_FAILED) { base = 0; GALOIS_SYS_DIE("failed allocating graph"); } uint64_t* fptr = (uint64_t*) base; *fptr++ = convert_le64(1); *fptr++ = convert_le64(sizeof_edge_data); *fptr++ = convert_le64(num_nodes); *fptr++ = convert_le64(num_edges); for (size_t i = 0; i < num_nodes; ++i) *fptr++ = convert_le64(out_idx[i]); uint32_t* fptr32 = (uint32_t*) fptr; for (size_t i = 0; i < num_edges; ++i) *fptr32++ = convert_le32(outs[i]); structureFromMem(base, nBytes, false); return edgeData; } void FileGraph::structureFromFile(const std::string& filename, bool preFault) { masterFD = open(filename.c_str(), O_RDONLY); if (masterFD == -1) { GALOIS_SYS_DIE("failed opening ", filename); } struct stat buf; int f = fstat(masterFD, &buf); if (f == -1) { GALOIS_SYS_DIE("failed reading ", filename); } masterLength = buf.st_size; int _MAP_BASE = MAP_PRIVATE; #ifdef MAP_POPULATE if (preFault) _MAP_BASE |= MAP_POPULATE; #endif void* m = mmap(0, masterLength, PROT_READ, _MAP_BASE, masterFD, 0); if (m == MAP_FAILED) { m = 0; GALOIS_SYS_DIE("failed reading ", filename); } parse(m); masterMapping = m; #ifndef MAP_POPULATE if (preFault) { Runtime::MM::pageIn(m, masterLength); } #endif } size_t FileGraph::findIndex(size_t nodeSize, size_t edgeSize, size_t targetSize, size_t lb, size_t ub) { while (lb < ub) { size_t mid = lb + (ub - lb) / 2; size_t num_edges = *edge_end(mid); size_t size = num_edges * edgeSize + (mid+1) * nodeSize; if (size < targetSize) lb = mid + 1; else ub = mid; } return lb; } auto FileGraph::divideBy(size_t nodeSize, size_t edgeSize, unsigned id, unsigned total) -> std::pair<iterator,iterator> { size_t size = numNodes * nodeSize + numEdges * edgeSize; size_t block = (size + total - 1) / total; size_t bb = findIndex(nodeSize, edgeSize, block * id, 0, numNodes); size_t eb; if (id + 1 == total) eb = numNodes; else eb = findIndex(nodeSize, edgeSize, block * (id + 1), bb, numNodes); //Runtime::LL::gInfo("(", id, "/", total, ") ", bb, " ", eb, " ", numNodes); return std::make_pair(iterator(bb), iterator(eb)); } //FIXME: perform host -> le on data void FileGraph::structureToFile(const std::string& file) { ssize_t retval; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int fd = open(file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, mode); size_t total = masterLength; char* ptr = (char*) masterMapping; while (total) { retval = write(fd, ptr, total); if (retval == -1) { GALOIS_SYS_DIE("failed writing to ", file); } else if (retval == 0) { GALOIS_DIE("ran out of space writing to ", file); } total -= retval; ptr += retval; } close(fd); } void FileGraph::swap(FileGraph& other) { std::swap(masterMapping, other.masterMapping); std::swap(masterLength, other.masterLength); std::swap(sizeofEdge, other.sizeofEdge); std::swap(masterFD, other.masterFD); std::swap(outIdx, other.outIdx); std::swap(outs, other.outs); std::swap(edgeData, other.edgeData); std::swap(numEdges, other.numEdges); std::swap(numNodes, other.numNodes); } void FileGraph::cloneFrom(FileGraph& other) { structureFromMem(other.masterMapping, other.masterLength, true); } uint64_t FileGraph::getEdgeIdx(GraphNode src, GraphNode dst) const { for (uint32_t* ii = raw_neighbor_begin(src), *ee = raw_neighbor_end(src); ii != ee; ++ii) if (convert_le32(*ii) == dst) return std::distance(outs, ii); return ~static_cast<uint64_t>(0); } uint32_t* FileGraph::raw_neighbor_begin(GraphNode N) const { return (N == 0) ? &outs[0] : &outs[convert_le64(outIdx[N-1])]; } uint32_t* FileGraph::raw_neighbor_end(GraphNode N) const { return &outs[convert_le64(outIdx[N])]; } FileGraph::edge_iterator FileGraph::edge_begin(GraphNode N) const { return edge_iterator(N == 0 ? 0 : convert_le64(outIdx[N-1])); } FileGraph::edge_iterator FileGraph::edge_end(GraphNode N) const { return edge_iterator(convert_le64(outIdx[N])); } FileGraph::GraphNode FileGraph::getEdgeDst(edge_iterator it) const { return convert_le32(outs[*it]); } FileGraph::node_id_iterator FileGraph::node_id_begin() const { return boost::make_transform_iterator(&outs[0], Convert32()); } FileGraph::node_id_iterator FileGraph::node_id_end() const { return boost::make_transform_iterator(&outs[numEdges], Convert32()); } FileGraph::edge_id_iterator FileGraph::edge_id_begin() const { return boost::make_transform_iterator(&outIdx[0], Convert64()); } FileGraph::edge_id_iterator FileGraph::edge_id_end() const { return boost::make_transform_iterator(&outIdx[numNodes], Convert64()); } bool FileGraph::hasNeighbor(GraphNode N1, GraphNode N2) const { return getEdgeIdx(N1,N2) != ~static_cast<uint64_t>(0); } FileGraph::iterator FileGraph::begin() const { return iterator(0); } FileGraph::iterator FileGraph::end() const { return iterator(numNodes); }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/CMakeLists.txt
set(sources Barrier.cpp Context.cpp FileGraph.cpp FileGraphParallel.cpp OCFileGraph.cpp PerThreadStorage.cpp PreAlloc.cpp Sampling.cpp Support.cpp Termination.cpp Threads.cpp ThreadPool_pthread.cpp Timer.cpp) set(include_dirs "${PROJECT_SOURCE_DIR}/include/") if(USE_EXP) file(GLOB exp_sources ../exp/src/*.cpp) set(include_dirs ${include_dirs} "${PROJECT_SOURCE_DIR}/exp/include/") set(sources ${sources} ${exp_sources}) endif() set(include_dirs ${include_dirs} "${PROJECT_BINARY_DIR}/include/") include(ParseArguments) if(CMAKE_VERSION VERSION_GREATER 2.8.8 OR CMAKE_VERSION VERSION_EQUAL 2.8.8) function(add_internal_library name) add_library(${name} OBJECT ${ARGN}) endfunction() function(add_galois_library name) PARSE_ARGUMENTS(X "LIBS" "" ${ARGN}) set(objects) foreach(lib ${X_LIBS}) list(APPEND objects "$<TARGET_OBJECTS:${lib}>") endforeach() add_library(${name} ${X_DEFAULT_ARGS} ${objects}) endfunction() else() function(add_internal_library name) add_library(${name} ${ARGN}) install(TARGETS ${name} EXPORT GaloisTargets RUNTIME DESTINATION "${INSTALL_BIN_DIR}" COMPONENT bin LIBRARY DESTINATION "${INSTALL_LIB_DIR}" COMPONENT shlib ARCHIVE DESTINATION "${INSTALL_LIB_DIR}" COMPONENT dev ) export(TARGETS ${name} APPEND FILE "${PROJECT_BINARY_DIR}/GaloisTargets.cmake") endfunction() function(add_galois_library name) PARSE_ARGUMENTS(X "LIBS" "" ${ARGN}) add_library(${name} ${X_DEFAULT_ARGS}) foreach(lib ${X_LIBS}) target_link_libraries(${name} ${lib}) endforeach() endfunction() endif() add_galois_library(galois ${sources} LIBS llvm mm ll) add_galois_library(galois-nothreads FileGraph.cpp LIBS llvm mm-nonuma ll) add_subdirectory(ll) add_subdirectory(llvm) add_subdirectory(mm) add_subdirectory(mm-nonuma) target_link_libraries(galois ${CMAKE_THREAD_LIBS_INIT}) if(NUMA_FOUND) target_link_libraries(galois ${NUMA_LIBRARIES}) endif() if(USE_VTUNE) set(VTune_ROOT "/opt/intel/vtune_amplifier_xe_2013;/opt/intel/vtune_amplifier_xe_2011") find_package(VTune) if(VTune_FOUND) set(GALOIS_USE_VTUNE on) include_directories(${VTune_INCLUDE_DIRS}) target_link_libraries(galois ${VTune_LIBRARIES}) target_link_libraries(galois dl) else() message(WARNING "VTUNE required but not found") endif() endif() if(USE_HPCTOOLKIT) if(NOT "$ENV{HPCTOOLKIT_HOME}" STREQUAL "") set(HPCToolKit_ROOT $ENV{HPCTOOLKIT_HOME}) endif() find_package(HPCToolKit) if(HPCToolKit_FOUND) set(GALOIS_USE_HPCTOOLKIT on) include_directories(${HPCToolKit_INCLUDE_DIRS}) target_link_libraries(galois ${HPCToolKit_LIBRARIES}) else() message(WARNING "HPCToolKit required but not found") endif() endif() if(USE_PAPI) # Sadly, none of our machines places papi in a well-known place or provides # a method for finding papi automatically. Hardcode some constants. set(PAPI_ROOT "/h1/lenharth/papi;/usr/global/tools/papi/bgqos_0/papi-5.0.1-V1R1M2") find_package(PAPI) if (PAPI_FOUND) set(GALOIS_USE_PAPI on) include_directories(${PAPI_INCLUDE_DIRS}) target_link_libraries(galois ${PAPI_LIBRARIES}) else() message(WARNING "PAPI required but not found") endif() endif() if(USE_SUBVERSION_REVISION) add_dependencies(galois svnversion) endif() configure_file("${PROJECT_SOURCE_DIR}/include/Galois/config.h.in" "${PROJECT_BINARY_DIR}/include/Galois/config.h") ###### Installation ###### install(TARGETS galois EXPORT GaloisTargets RUNTIME DESTINATION "${INSTALL_BIN_DIR}" COMPONENT bin LIBRARY DESTINATION "${INSTALL_LIB_DIR}" COMPONENT shlib ARCHIVE DESTINATION "${INSTALL_LIB_DIR}" COMPONENT dev ) install(DIRECTORY ${include_dirs} DESTINATION "${INSTALL_INCLUDE_DIR}" COMPONENT dev FILES_MATCHING PATTERN "*.h" PATTERN ".svn" EXCLUDE)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/Termination.cpp
/** Dikstra style termination detection -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in * irregular programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights * reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES * CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY * WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, * NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY * THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF * TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO * THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, * direct or consequential damages or loss of profits, interruption of * business, or related expenses which may arise from use of Software * or Documentation, including but not limited to those resulting from * defects in Software and/or Documentation, or loss or inaccuracy of * data of any kind. * * @section Description * * Implementation of Dikstra dual-ring Termination Detection * * @author Andrew Lenharth <andrewl@lenharth.org> */ #include "Galois/Runtime/ActiveThreads.h" #include "Galois/Runtime/Termination.h" #include "Galois/Runtime/ll/CompilerSpecific.h" using namespace Galois::Runtime; namespace { //Dijkstra style 2-pass ring termination detection class LocalTerminationDetection : public TerminationDetection { struct TokenHolder { friend class TerminationDetection; volatile long tokenIsBlack; volatile long hasToken; long processIsBlack; bool lastWasWhite; // only used by the master }; PerThreadStorage<TokenHolder> data; //send token onwards void propToken(bool isBlack) { unsigned id = LL::getTID(); TokenHolder& th = *data.getRemote((id + 1) % activeThreads); th.tokenIsBlack = isBlack; LL::compilerBarrier(); th.hasToken = true; } void propGlobalTerm() { globalTerm.data = true; } bool isSysMaster() const { return LL::getTID() == 0; } public: LocalTerminationDetection() {} virtual void initializeThread() { TokenHolder& th = *data.getLocal(); th.hasToken = false; th.tokenIsBlack = false; th.processIsBlack = true; th.lastWasWhite = true; globalTerm.data = false; if (isSysMaster()) { th.hasToken = true; } } virtual void localTermination(bool workHappened) { assert(!(workHappened && globalTerm.data)); TokenHolder& th = *data.getLocal(); th.processIsBlack |= workHappened; if (th.hasToken) { if (isSysMaster()) { bool failed = th.tokenIsBlack || th.processIsBlack; th.tokenIsBlack = th.processIsBlack = false; if (th.lastWasWhite && !failed) { //This was the second success propGlobalTerm(); return; } th.lastWasWhite = !failed; } //Normal thread or recirc by master assert (!globalTerm.data && "no token should be in progress after globalTerm"); bool taint = th.processIsBlack || th.tokenIsBlack; th.processIsBlack = th.tokenIsBlack = false; th.hasToken = false; propToken(taint); } } }; static LocalTerminationDetection& getLocalTermination() { static LocalTerminationDetection term; return term; } //Dijkstra style 2-pass tree termination detection class TreeTerminationDetection : public TerminationDetection { static const int num = 2; struct TokenHolder { friend class TerminationDetection; //incoming from above volatile long down_token; //incoming from below volatile long up_token[num]; //my state long processIsBlack; bool hasToken; bool lastWasWhite; // only used by the master int parent; int parent_offset; TokenHolder* child[num]; }; PerThreadStorage<TokenHolder> data; void processToken() { TokenHolder& th = *data.getLocal(); //int myid = LL::getTID(); //have all up tokens? bool haveAll = th.hasToken; bool black = th.processIsBlack; for (int i = 0; i < num; ++i) { if (th.child[i]) { if( th.up_token[i] == -1 ) haveAll = false; else black |= th.up_token[i]; } } //Have the tokens, propagate if (haveAll) { th.processIsBlack = false; th.hasToken = false; if (isSysMaster()) { if (th.lastWasWhite && !black) { //This was the second success propGlobalTerm(); return; } th.lastWasWhite = !black; th.down_token = true; } else { data.getRemote(th.parent)->up_token[th.parent_offset] = black; } } //recieved a down token, propagate if (th.down_token) { th.down_token = false; th.hasToken = true; for (int i = 0; i < num; ++i) { th.up_token[i] = -1; if (th.child[i]) th.child[i]->down_token = true; } } } void propGlobalTerm() { globalTerm.data = true; } bool isSysMaster() const { return LL::getTID() == 0; } public: TreeTerminationDetection() {} virtual void initializeThread() { TokenHolder& th = *data.getLocal(); th.down_token = false; for (int i = 0; i < num; ++i) th.up_token[i] = false; th.processIsBlack = true; th.hasToken = false; th.lastWasWhite = false; globalTerm.data = false; th.parent = (LL::getTID() - 1) / num; th.parent_offset = (LL::getTID() - 1) % num; for (int i = 0; i < num; ++i) { int cn = LL::getTID() * num + i + 1; if (cn < (int) activeThreads) th.child[i] = data.getRemote(cn); else th.child[i] = 0; } if (isSysMaster()) { th.down_token = true; } } virtual void localTermination(bool workHappened) { assert(!(workHappened && globalTerm.data)); TokenHolder& th = *data.getLocal(); th.processIsBlack |= workHappened; processToken(); } }; __attribute__((unused)) static TreeTerminationDetection& getTreeTermination() { static TreeTerminationDetection term; return term; } } // namespace Galois::Runtime::TerminationDetection& Galois::Runtime::getSystemTermination() { return getLocalTermination(); //return getTreeTermination(); }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/Sampling.cpp
/** Sampling implementation -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Andrew Lenharth <andrewl@lenharth.org> */ #include "Galois/config.h" #include "Galois/Runtime/Sampling.h" #include "Galois/Runtime/Support.h" #include "Galois/Runtime/ll/EnvCheck.h" #include "Galois/Runtime/ll/TID.h" #include "Galois/Runtime/ll/gio.h" #include <cstdlib> static void endPeriod() { int val; if (Galois::Runtime::LL::EnvCheck("GALOIS_EXIT_AFTER_SAMPLING", val)) { exit(val); } } static void beginPeriod() { int val; if (Galois::Runtime::LL::EnvCheck("GALOIS_EXIT_BEFORE_SAMPLING", val)) { exit(val); } } #ifdef GALOIS_USE_VTUNE #include "ittnotify.h" #include "Galois/Runtime/ll/TID.h" namespace vtune { static bool isOn; static void begin() { if (!isOn && Galois::Runtime::LL::getTID() == 0) __itt_resume(); isOn = true; } static void end() { if (isOn && Galois::Runtime::LL::getTID() == 0) __itt_pause(); isOn = false; } } #else namespace vtune { static void begin() {} static void end() {} } #endif #ifdef GALOIS_USE_HPCTOOLKIT #include <hpctoolkit.h> #include "Galois/Runtime/ll/TID.h" namespace hpctoolkit { static bool isOn; static void begin() { if (!isOn && Galois::Runtime::LL::getTID() == 0) hpctoolkit_sampling_start(); isOn = true; } static void end() { if (isOn && Galois::Runtime::LL::getTID() == 0) hpctoolkit_sampling_stop(); isOn = false; } } #else namespace hpctoolkit { static void begin() {} static void end() {} } #endif #ifdef GALOIS_USE_PAPI extern "C" { #include <papi.h> #include <papiStdEventDefs.h> } #include <iostream> namespace papi { static bool isInit; static bool isSampling; static __thread int papiEventSet = PAPI_NULL; //static int papiEvents[2] = {PAPI_L3_TCA,PAPI_L3_TCM}; //static const char* papiNames[2] = {"L3_ACCESSES","L3_MISSES"}; static int papiEvents[2] = {PAPI_TOT_INS, PAPI_TOT_CYC}; static const char* papiNames[2] = {"Instructions", "Cycles"}; //static int papiEvents[2] = {PAPI_L1_DCM, PAPI_TOT_CYC}; //static const char* papiNames[2] = {"L1DCMCounter", "CyclesCounter"}; static_assert(sizeof(papiEvents)/sizeof(*papiEvents) == sizeof(papiNames)/sizeof(*papiNames), "PAPI Events != PAPI Names"); static unsigned long galois_get_thread_id() { return Galois::Runtime::LL::getTID(); } static void begin(bool mainThread) { if (mainThread) { if (isSampling) GALOIS_DIE("Sampling already begun"); isSampling = true; } else if (!isSampling) { return; } int rv; // Init library if (!isInit) { rv = PAPI_library_init(PAPI_VER_CURRENT); if (rv != PAPI_VER_CURRENT && rv < 0) { GALOIS_DIE("PAPI library version mismatch!"); } if (rv < 0) GALOIS_DIE(PAPI_strerror(rv)); if ((rv = PAPI_thread_init(galois_get_thread_id)) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); isInit = true; } // Register thread if ((rv = PAPI_register_thread()) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); // Create the Event Set if ((rv = PAPI_create_eventset(&papiEventSet)) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); if ((rv = PAPI_add_events(papiEventSet, papiEvents, sizeof(papiEvents)/sizeof(*papiEvents))) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); // Start counting events in the event set if ((rv = PAPI_start(papiEventSet)) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); } static void end(bool mainThread) { if (mainThread) { if (!isSampling) GALOIS_DIE("Sampling not yet begun"); isSampling = false; } else if (!isSampling) { return; } int rv; long_long papiResults[sizeof(papiNames)/sizeof(*papiNames)]; // Get the values if ((rv = PAPI_stop(papiEventSet, papiResults)) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); // Remove all events in the eventset if ((rv = PAPI_cleanup_eventset(papiEventSet)) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); // Free all memory and data structures, EventSet must be empty. if ((rv = PAPI_destroy_eventset(&papiEventSet)) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); // Unregister thread if ((rv = PAPI_unregister_thread()) != PAPI_OK) GALOIS_DIE(PAPI_strerror(rv)); for (unsigned i = 0; i < sizeof(papiNames)/sizeof(*papiNames); ++i) Galois::Runtime::reportStat(NULL, papiNames[i], papiResults[i]); } } #else namespace papi { static void begin(bool) {} static void end(bool) {} } #endif void Galois::Runtime::beginThreadSampling() { papi::begin(false); } void Galois::Runtime::endThreadSampling() { papi::end(false); } void Galois::Runtime::beginSampling() { beginPeriod(); papi::begin(true); vtune::begin(); hpctoolkit::begin(); } void Galois::Runtime::endSampling() { hpctoolkit::end(); vtune::end(); papi::end(true); endPeriod(); }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/ThreadPool_cray.cpp
/* Galois, a framework to exploit amorphous data-parallelism in irregular programs. Copyright (C) 2011, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. */ /*! \file * \brief cray thread pool implementation */ #ifdef GALOIS_CRAY #include "Galois/Runtime/ThreadPool.h" using namespace Galois::Runtime; namespace { class ThreadPool_cray : public ThreadPool { int tmax; int num; Executable* work; int mkID() { return int_fetch_add(&tmax, 1); } void launch(void) { int myID = mkID(); (*work)(myID, num); } public: ThreadPool_cray() :tmax(0), num(1) {} virtual void run(Executable* E) { work = E; work->preRun(num); #pragma mta assert parallel for (int i = 0; i < num; ++i) { launch(); } work->postRun(); } virtual void resize(int num) { this->num = num; } virtual int size() { return num; } }; } //! Implement the global threadpool static ThreadPool_cray pool; ThreadPool& Galois::Runtime::getSystemThreadPool() { return pool; } #endif
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/FileGraphParallel.cpp
/** Parallel implementations for FileGraph -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Donald Nguyen <ddn@cs.utexas.edu> */ #include "Galois/Runtime/ParallelWork.h" #include "Galois/Graph/FileGraph.h" #include <pthread.h> namespace Galois { namespace Graph { class FileGraphAllocator { pthread_mutex_t& lock; pthread_cond_t& cond; FileGraph* self; size_t sizeofEdgeData; unsigned maxPackages; volatile unsigned& count; public: FileGraphAllocator(pthread_mutex_t& l, pthread_cond_t& c, FileGraph* s, size_t ss, unsigned m, volatile unsigned& cc): lock(l), cond(c), self(s), sizeofEdgeData(ss), maxPackages(m), count(cc) { } void operator()(unsigned tid, unsigned total) { int pret_t; if ((pret_t = pthread_mutex_lock(&lock))) GALOIS_DIE("pthread error: ", pret_t); if (Galois::Runtime::LL::isPackageLeaderForSelf(tid)) { auto r = self->divideBy( sizeof(uint64_t), sizeofEdgeData + sizeof(uint32_t), Galois::Runtime::LL::getPackageForThread(tid), maxPackages); size_t edge_begin = *self->edge_begin(*r.first); size_t edge_end = edge_begin; if (r.first != r.second) edge_end = *self->edge_end(*r.second - 1); Galois::Runtime::MM::pageIn(self->outIdx + *r.first, std::distance(r.first, r.second) * sizeof(*self->outIdx)); Galois::Runtime::MM::pageIn(self->outs + edge_begin, (edge_end - edge_begin) * sizeof(*self->outs)); Galois::Runtime::MM::pageIn(self->edgeData + edge_begin * sizeofEdgeData, (edge_end - edge_begin) * sizeofEdgeData); if (--count == 0) { if ((pret_t = pthread_cond_broadcast(&cond))) GALOIS_DIE("pthread error: ", pret_t); } } else { while (count > 0) { if ((pret_t = pthread_cond_wait(&cond, &lock))) GALOIS_DIE("pthread error: ", pret_t); } } if ((pret_t = pthread_mutex_unlock(&lock))) GALOIS_DIE("pthread error: ", pret_t); } }; void FileGraph::structureFromFileInterleaved(const std::string& filename, size_t sizeofEdgeData) { structureFromFile(filename, false); // Interleave across all NUMA nodes unsigned oldActive = getActiveThreads(); setActiveThreads(std::numeric_limits<unsigned int>::max()); // Manually coarsen synchronization granularity, otherwise it would be at page granularity int pret; unsigned maxPackages = Runtime::LL::getMaxPackages(); volatile unsigned count = maxPackages; pthread_mutex_t lock; if ((pret = pthread_mutex_init(&lock, NULL))) GALOIS_DIE("pthread error: ", pret); pthread_cond_t cond; if ((pret = pthread_cond_init(&cond, NULL))) GALOIS_DIE("pthread error: ", pret); // NB(ddn): Use on_each_simple_impl because we are fiddling with the // number of active threads after this loop. Otherwise, the main // thread might change the number of active threads while some threads // are still in on_each_impl. Galois::Runtime::on_each_simple_impl(FileGraphAllocator(lock, cond, this, sizeofEdgeData, maxPackages, count)); if ((pret = pthread_mutex_destroy(&lock))) GALOIS_DIE("pthread error: ", pret); if ((pret = pthread_cond_destroy(&cond))) GALOIS_DIE("pthread error: ", pret); setActiveThreads(oldActive); } } }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/ThreadPool_pthread.cpp
/** pthread thread pool implementation -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Andrew Lenharth <andrewl@lenharth.org> */ #include "Galois/Runtime/Sampling.h" #include "Galois/Runtime/ThreadPool.h" #include "Galois/Runtime/ll/EnvCheck.h" #include "Galois/Runtime/ll/HWTopo.h" #include "Galois/Runtime/ll/TID.h" #include "boost/utility.hpp" #include <algorithm> #include <cstdlib> #include <cstdio> #include <cerrno> #include <cassert> #include <semaphore.h> #include <pthread.h> // Forward declare this to avoid including PerThreadStorage. // We avoid this to stress that the thread Pool MUST NOT depend on PTS. namespace Galois { namespace Runtime { extern void initPTS(); } } using namespace Galois::Runtime; //! Generic check for pthread functions static void checkResults(int val) { if (val) { perror("PTHREAD: "); assert(0 && "PThread check"); abort(); } } namespace { class Semaphore: private boost::noncopyable { sem_t sem; public: explicit Semaphore(int val = 0) { checkResults(sem_init(&sem, 0, val)); } ~Semaphore() { checkResults(sem_destroy(&sem)); } void release(int n = 1) { while (n) { --n; checkResults(sem_post(&sem)); } } void acquire(int n = 1) { while (n) { --n; int rc; while (((rc = sem_wait(&sem)) < 0) && (errno == EINTR)) { } checkResults(rc); } } }; class ThinBarrier: private boost::noncopyable { volatile int started; public: ThinBarrier(int v) { } void release(int n = 1) { __sync_fetch_and_add(&started, 1); } void acquire(int n = 1) { while (started < n) { } } }; class ThreadPool_pthread : public ThreadPool { pthread_t* threads; // Set of threads Semaphore* starts; // Signal to release threads to run ThinBarrier started; volatile bool shutdown; // Set and start threads to have them exit volatile unsigned starting; // Each run call uses this to control num threads volatile RunCommand* workBegin; // Begin iterator for work commands volatile RunCommand* workEnd; // End iterator for work commands void initThread() { // Initialize TID Galois::Runtime::LL::initTID(); unsigned id = Galois::Runtime::LL::getTID(); Galois::Runtime::initPTS(); if (!LL::EnvCheck("GALOIS_DO_NOT_BIND_THREADS")) if (id != 0 || !LL::EnvCheck("GALOIS_DO_NOT_BIND_MAIN_THREAD")) Galois::Runtime::LL::bindThreadToProcessor(id); // Use a simple pthread or atomic to avoid depending on Galois // too early in the initialization process started.release(); } void cascade(int tid) { const unsigned multiple = 2; for (unsigned i = 1; i <= multiple; ++i) { unsigned n = tid * multiple + i; if (n < starting) starts[n].release(); } } void doWork(unsigned tid) { cascade(tid); RunCommand* workPtr = (RunCommand*)workBegin; RunCommand* workEndL = (RunCommand*)workEnd; prefixThreadWork(tid); while (workPtr != workEndL) { (*workPtr)(); ++workPtr; } suffixThreadWork(tid); } void prefixThreadWork(unsigned tid) { if (tid) Galois::Runtime::beginThreadSampling(); } void suffixThreadWork(unsigned tid) { if (tid) Galois::Runtime::endThreadSampling(); } void launch() { unsigned tid = Galois::Runtime::LL::getTID(); while (!shutdown) { starts[tid].acquire(); doWork(tid); } } static void* slaunch(void* V) { ThreadPool_pthread* TP = (ThreadPool_pthread*)V; TP->initThread(); TP->launch(); return 0; } public: ThreadPool_pthread(): ThreadPool(Galois::Runtime::LL::getMaxThreads()), started(0), shutdown(false), workBegin(0), workEnd(0) { initThread(); starts = new Semaphore[maxThreads]; threads = new pthread_t[maxThreads]; for (unsigned i = 1; i < maxThreads; ++i) { int rc = pthread_create(&threads[i], 0, &slaunch, this); checkResults(rc); } started.acquire(maxThreads); } virtual ~ThreadPool_pthread() { shutdown = true; workBegin = workEnd = 0; __sync_synchronize(); for (unsigned i = 1; i < maxThreads; ++i) starts[i].release(); for (unsigned i = 1; i < maxThreads; ++i) { int rc = pthread_join(threads[i], NULL); checkResults(rc); } delete [] starts; delete [] threads; } virtual void run(RunCommand* begin, RunCommand* end, unsigned num) { // Sanitize num num = std::min(num, maxThreads); num = std::max(num, 1U); starting = num; // Setup work workBegin = begin; workEnd = end; // Ensure stores happen before children are spawned __sync_synchronize(); // Do master thread work doWork(0); // Clean up workBegin = workEnd = 0; } }; } // end namespace //! Implement the global threadpool ThreadPool& Galois::Runtime::getSystemThreadPool() { static ThreadPool_pthread pool; return pool; }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/Context.cpp
/** simple galois context and contention manager -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Andrew Lenharth <andrewl@lenharth.org> */ #include "Galois/Runtime/Context.h" #include "Galois/Runtime/MethodFlags.h" #include "Galois/Runtime/ll/SimpleLock.h" #include "Galois/Runtime/ll/CacheLineStorage.h" #include <stdio.h> #ifdef GALOIS_USE_LONGJMP #include <setjmp.h> __thread jmp_buf Galois::Runtime::hackjmp; static __thread Galois::Runtime::Releasable* releasableHead = 0; Galois::Runtime::Releasable::Releasable() { this->next = releasableHead; releasableHead = this; } void Galois::Runtime::Releasable::releaseAll() { Galois::Runtime::Releasable* head = this; while (head) { head->release(); Galois::Runtime::Releasable* next = head->next; head->~Releasable(); head = next; } } void Galois::Runtime::clearReleasable() { releasableHead = 0; } #endif //! Global thread context for each active thread static __thread Galois::Runtime::SimpleRuntimeContext* thread_ctx = 0; namespace { struct PendingStatus { Galois::Runtime::LL::CacheLineStorage<Galois::Runtime::PendingFlag> flag; PendingStatus(): flag(Galois::Runtime::NON_DET) { } }; PendingStatus pendingStatus; } void Galois::Runtime::setPending(Galois::Runtime::PendingFlag value) { pendingStatus.flag.data = value; } Galois::Runtime::PendingFlag Galois::Runtime::getPending() { return pendingStatus.flag.data; } void Galois::Runtime::doCheckWrite() { if (Galois::Runtime::getPending() == Galois::Runtime::PENDING) { #ifdef GALOIS_USE_LONGJMP if (releasableHead) releasableHead->releaseAll(); longjmp(hackjmp, Galois::Runtime::REACHED_FAILSAFE); #else throw Galois::Runtime::REACHED_FAILSAFE; #endif } } void Galois::Runtime::setThreadContext(Galois::Runtime::SimpleRuntimeContext* ctx) { thread_ctx = ctx; } Galois::Runtime::SimpleRuntimeContext* Galois::Runtime::getThreadContext() { return thread_ctx; } void Galois::Runtime::signalConflict(Lockable* lockable) { #ifdef GALOIS_USE_LONGJMP if (releasableHead) releasableHead->releaseAll(); longjmp(hackjmp, Galois::Runtime::CONFLICT); #else throw Galois::Runtime::CONFLICT; // Conflict #endif } void Galois::Runtime::forceAbort() { signalConflict(NULL); } //////////////////////////////////////////////////////////////////////////////// // LockManagerBase & SimpleRuntimeContext //////////////////////////////////////////////////////////////////////////////// #if !defined(GALOIS_USE_SEQ_ONLY) Galois::Runtime::LockManagerBase::AcquireStatus Galois::Runtime::LockManagerBase::tryAcquire(Galois::Runtime::Lockable* lockable) { assert(lockable); // XXX(ddn): Hand inlining this code makes a difference on // delaunaytriangulation (GCC 4.7.2) #if 0 if (tryLock(lockable)) { assert(!getOwner(lockable)); ownByForce(lockable); return NEW_OWNER; #else if (lockable->owner.try_lock()) { lockable->owner.setValue(this); return NEW_OWNER; #endif } else if (getOwner(lockable) == this) { return ALREADY_OWNER; } return FAIL; } void Galois::Runtime::SimpleRuntimeContext::acquire(Galois::Runtime::Lockable* lockable) { AcquireStatus i; if (customAcquire) { subAcquire(lockable); } else if ((i = tryAcquire(lockable)) != AcquireStatus::FAIL) { if (i == AcquireStatus::NEW_OWNER) { addToNhood(lockable); } } else { Galois::Runtime::signalConflict(lockable); } } void Galois::Runtime::SimpleRuntimeContext::release(Galois::Runtime::Lockable* lockable) { assert(lockable); // The deterministic executor, for instance, steals locks from other // iterations assert(customAcquire || getOwner(lockable) == this); assert(!lockable->next); lockable->owner.unlock_and_clear(); } unsigned Galois::Runtime::SimpleRuntimeContext::commitIteration() { unsigned numLocks = 0; while (locks) { //ORDER MATTERS! Lockable* lockable = locks; locks = lockable->next; lockable->next = 0; LL::compilerBarrier(); release(lockable); ++numLocks; } return numLocks; } unsigned Galois::Runtime::SimpleRuntimeContext::cancelIteration() { return commitIteration(); } #endif void Galois::Runtime::SimpleRuntimeContext::subAcquire(Galois::Runtime::Lockable* lockable) { GALOIS_DIE("Shouldn't get here"); }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/Timer.cpp
/** Simple timer support -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Andrew Lenharth <andrewl@lenharth.org> */ #include "Galois/Timer.h" #ifndef HAVE_CXX11_CHRONO // This is linux/bsd specific #include <sys/time.h> #endif using namespace Galois; #ifndef HAVE_CXX11_CHRONO Timer::Timer() :_start_hi(0), _start_low(0), _stop_hi(0), _stop_low(0) {} void Timer::start() { timeval start; gettimeofday(&start, 0); _start_hi = start.tv_sec; _start_low = start.tv_usec; } void Timer::stop() { timeval stop; gettimeofday(&stop, 0); _stop_hi = stop.tv_sec; _stop_low = stop.tv_usec; } unsigned long Timer::get() const { unsigned long msec = _stop_hi - _start_hi; msec *= 1000; if (_stop_low > _start_low) msec += (_stop_low - _start_low) / 1000; else { msec -= 1000; //borrow msec += (_stop_low + 1000000 - _start_low) / 1000; } return msec; } unsigned long Timer::get_usec() const { unsigned long usec = _stop_hi - _start_hi; usec *= 1000000; if (_stop_low > _start_low) usec += (_stop_low - _start_low); else { usec -= 1000000; //borrow usec += (_stop_low + 1000000 - _start_low); } return usec; } #endif TimeAccumulator::TimeAccumulator() :ltimer(), acc(0) {} void TimeAccumulator::start() { ltimer.start(); } void TimeAccumulator::stop() { ltimer.stop(); acc += ltimer.get_usec(); } unsigned long TimeAccumulator::get() const { return acc / 1000; } TimeAccumulator& TimeAccumulator::operator+=(const TimeAccumulator& rhs) { acc += rhs.acc; return *this; } TimeAccumulator& TimeAccumulator::operator+=(const Timer& rhs) { acc += rhs.get_usec(); return *this; }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/mainpage.dox
/** \mainpage @section Description Galois API documentation. Example programs can be found in the apps/tutorial directory. High-level descriptions of irregular algorithms can be found at the <a href="http://iss.ices.utexas.edu/galois">Galois webpage</a>. @section License Galois, a framework to exploit amorphous data-parallelism in irregular programs. Copyright (C) 2013, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. This software is released under the terms of the University of Texas at Austin Research License available at http://www.otc.utexas.edu/Forms/ResearchLicense_SourceCode_11142005.doc , which makes this software available without charge to anyone for academic, research, experimental, or personal use. For all other uses, please contact the University of Texas at Austin's Office of Technology Commercialization http://www.otc.utexas.edu/ */
0