rrepair, eval: more flexibility in the scale plots

#! /usr/bin/gnuplot
# USED PARAMS
#	colDefFile -> file with column definitions
#	srcFile1 -> source file 1 path
#	srcFile1_title -> prepend this to titles of lines from srcFile1
#	srcFile2 -> source file 2 path (optional)
#	srcFile2_title -> prepend this to titles of lines from srcFile2 (optional unless srcFile2 given)
#	srcFile3 -> source file 3 path (optional)
#	srcFile3_title -> prepend this to titles of lines from srcFile3 (optional unless srcFile3 given)
#	srcFile4 -> source file 4 path (optional)
#	srcFile4_title -> prepend this to titles of lines from srcFile4 (optional unless srcFile4 given)
#	srcFile5 -> source file 5 path (optional)
#	srcFile5_title -> prepend this to titles of lines from srcFile5 (optional unless srcFile5 given)
#	destDir -> destination path for pdfs
#	regenAccInPercent -> whether to show the regen accuracy in percent instead of absolute values (useful for bloom)
#	absoluteRedundancy -> whether to show the absolute redundancy or a relative one

set macro

load colDefFile

plotCount = exists("srcFile5") ? 5 : exists("srcFile4") ? 4 : exists("srcFile3") ? 3 : exists("srcFile2") ? 2 : 1
files = srcFile1 . (plotCount >= 2 ? " " . srcFile2 : "") . (plotCount >= 3 ? " " . srcFile3 : "") . (plotCount >= 4 ? " " . srcFile4 : "") . (plotCount >= 5 ? " " . srcFile5 : "")
get_file(i) = (i == 5) ? srcFile5 : (i == 4) ? srcFile4 : (i == 3) ? srcFile3 : (i == 2) ? srcFile2 : srcFile1
get_title(i) = (i == 5) ? srcFile5_title : (i == 4) ? srcFile4_title : (i == 3) ? srcFile3_title : (i == 2) ? srcFile2_title : srcFile1_title

# http://colorbrewer2.org/?type=qualitative&scheme=Set1&n=5
# (#e41a1c, #377eb8, #4daf4a, #984ea3, #ff7f00)
# -> a little brighter version:
set style line 1 lw 2 lt 1 lc rgb '#ff191b' pt 5 # dark red
set style line 2 lw 2 lt 1 lc rgb '#2d8ede' pt 9 # dark blue
set style line 3 lw 2 lt 1 lc rgb '#59c955' pt 7 # dark green
set style line 4 lw 2 lt 1 lc rgb '#b05abd' pt 4 # dark purple
set style line 5 lw 2 lt 1 lc rgb '#ff7f00' pt 10 # dark orange
set style line 6 lw 3 lc rgb "#777777" pt 8 lt 3 # gray (for the naive line)

set style line 101 lw 3 lt 1 lc rgb '#ff191b' pt 0 # dark red
set style line 102 lw 3 lt 1 lc rgb '#2d8ede' pt 0 # dark blue
set style line 103 lw 3 lt 1 lc rgb '#59c955' pt 0 # dark green
set style line 104 lw 3 lt 1 lc rgb '#b05abd' pt 0 # dark purple
set style line 105 lw 3 lt 1 lc rgb '#ff7f00' pt 0 # dark orange

if (plotCount == 5) {
  plotShift(x, i) = (i == 5) ? (x + (x / 1.6)) : (i == 4) ? (x + (x / 3.7)) : (i == 3) ? (x) : (i == 2) ? (x - (x / 4.6)) : (x - (x / 2.6))
} else {
  if (plotCount == 4) {
    plotShift(x, i) = (i == 4) ? (x + (x / 1.9)) : (i == 3) ? (x + (x / 6.5)) : (i == 2) ? (x - (x / 7.9)) : (x - (x / 2.95))
  } else {
    if (plotCount == 3) {
      plotShift(x, i) = (i == 3) ? (x + (x / 2.3)) : (i == 2) ? (x) : (x - (x / 3.2))
    } else {
      if (plotCount == 2) {
        plotShift(x, i) = (i == 2) ? (x + (x / 3)) : (x - (x / 4))
      } else {
        plotShift(x, i) = x
      }
    }
  }
}
if (exists("regenAccInPercent") && regenAccInPercent == 1) {
  regenAcc(found, existing) = 100 - 100 * found / existing
  regenAccErr(found1, found2, existingSum) = stderrSum(found1, found2) * (100 / existingSum)
} else {
  regenAccInPercent = 0
  regenAcc(found, existing) = existing - found
  regenAccErr(found1, found2, existingSum) = stderrSum(found1, found2)
}
if (exists("absoluteRedundancy") && absoluteRedundancy == 1) {
  redundancy(transferred, updated, regen) = transferred - (updated + regen)
  redundancyStderr(transferred, updated, regen) = sqrt(transferred**2 - updated**2 - regen**2)
} else {
  absoluteRedundancy = 0
  redundancy(transferred, updated, regen) = transferred / (updated + regen)
  redundancyStderr(transferred, updated, regen) = "-"
}
if (!exists("systemSize")) {
  systemSize = 4000
}
plot_boxwidth = (0.8 / plotCount)

# OUTPUT
set terminal pdfcairo dashed enhanced font ",15" fontscale 0.5 size 6,4.5
fileEx = "pdf"

system "echo 'PLOT " . files . "'"
system "mkdir -p " .destDir

filename = "file"

# --OPTION
kvvSize0 = 16+4 # key+version size in bytes
kvvSize1 = kvvSize0+10 # key+version+value size in byte

# Helper
stderrSum(x,y) = sqrt(x**2 + y**2)	# sum of std. errors is root of sum of square errors
kB(x) = x / 1024
min(x,y) = (x < y) ? x : y
min3(x,y,z) = min(min(x,y),z)
max(x,y) = (x > y) ? x : y
max3(x,y,z) = max(max(x,y),z)

acc_upd_max=0.5
if (regenAccInPercent == 1) {
  do for [i=1:plotCount] {
    stats "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) u (column(col_missing)+column(col_outdated) - column(col_regen)-column(col_updated)+stderrSum(column(col_sd_regen),column(col_sd_updated))) nooutput
    if (STATS_max > acc_upd_max) {acc_upd_max = STATS_max}
  }
  acc_reg_max=50.5
  acc_reg_min=49.5
  do for [i=1:plotCount] {
    stats "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) u (regenAcc(column(col_regen)+column(col_updated), column(col_missing)+column(col_outdated))+regenAccErr(column(col_sd_regen),column(col_sd_updated),(column(col_missing)+column(col_outdated)))):(regenAcc(column(col_regen)+column(col_updated), column(col_missing)+column(col_outdated))-regenAccErr(column(col_sd_regen),column(col_sd_updated),(column(col_missing)+column(col_outdated)))) nooutput
    if (STATS_min_y < acc_reg_min) {acc_reg_min = STATS_min_y}
    if (STATS_max_x > acc_reg_max) {acc_reg_max = STATS_max_x}
  }
  acc_reg_avg=(acc_reg_max+acc_reg_min)/2.0
  acc_reg_max=max(abs(acc_reg_avg-acc_reg_min), abs(acc_reg_max-acc_reg_avg))
} else {
  do for [i=1:plotCount] {
    stats "<awk '$" . col_ftype . " == \"update\" || $" . col_ftype . " == \"regen\"' " . get_file(i) u (column(col_missing)+column(col_outdated) - column(col_regen)-column(col_updated)+stderrSum(column(col_sd_regen),column(col_sd_updated))) nooutput
    if (STATS_max > acc_upd_max) {acc_upd_max = STATS_max}
  }
  acc_reg_max = acc_upd_max
}
if (acc_upd_max > 0.5) {acc_upd_max=acc_upd_max*1.05}
if (acc_reg_max > 0.5) {acc_reg_max=acc_reg_max*1.05}

red_max=0.5
do for [i=1:plotCount] {
  stats get_file(i) using (redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))+redundancyStderr(column(col_sd_bw_rs_kvv), column(col_sd_updated), column(col_sd_regen))) nooutput
  if (STATS_max > red_max) {red_max = STATS_max}
}
if (red_max > 0.5) {red_max=red_max*1.05}
if (red_max >= 1.5 && red_max < 2) {red_max=2}

bw_max=1
bw_min=1
do for [i=1:plotCount] {
  stats get_file(i) using (kB(column(col_bw_rc_size)+column(col_bw_rc2_size)+stderrSum(column(col_sd_bw_rc_size), column(col_sd_bw_rc2_size)))) nooutput
  if (STATS_max > bw_max) {bw_max = STATS_max}
  if (STATS_min < bw_min) {bw_min = STATS_min}
}
# is naive solution more expensive?
stats get_file(1) using (kB(column(col_dbsize)/4*(128+32)/8)) nooutput
if (STATS_max > bw_max) {bw_max = STATS_max}
if (STATS_min < bw_min) {bw_min = STATS_min}
bw_min = 2.0**floor(log(bw_min) / log(2))

key_width_fun(i) = min(-0.5, (6-strstrt(get_title(i), "_")) - (strlen(get_title(i)) - strstrt(get_title(i), "_")) * 0.15)
key_width = min(key_width_fun(1),key_width_fun(plotCount))
#print "key_width: ",key_width

# Solid Background
# set object 1 rect from screen 0, 0, 0 to screen 1, 1, 0 behind
# set object 1 rect fc  rgb "white"  fillstyle solid 1.0

# Style
if (plotCount == 1) {
  set style data yerrorlines
} else {
  set style data yerrorbars
}
set logscale x 2
set xrange [((systemSize/1000.0)/2):((systemSize/1000.0)*4**5*2)] # TODO: adapt if number of data points changes!
set grid layerdefault linetype 0 linewidth 1.000,  linetype 0 linewidth 1.000
set pointsize (plotCount >= 4) ? 0.7 : (plotCount == 3) ? 0.8 : 1
arrow_dx=.166666666667 # grid spacing in x
arrow_di=0 # added to each i in loop - arrows drawn at (i+arrow_di)*arrow_dx
arrow_xpoints=6 # TODO: adapt if number of data points changes!

set style line 100 lw 2 lc -1 pt 0 lt 1

#--------------------------------- ALL
set boxwidth plot_boxwidth relative
set style fill solid 1 border -1
systemSizeScaled = systemSize / 1000.0
set xtics scale 0.1 systemSizeScaled,4
set ytics scale 0.8
set grid noxtics nomxtics layerdefault linetype 0 linewidth 1.000,  linetype 0 linewidth 1.000
set for [i=1:arrow_xpoints] arrow from graph (i+arrow_di)*arrow_dx,graph 0 to graph (i+arrow_di)*arrow_dx,graph 1 nohead back linetype 0 linewidth 1.000

set o destDir. "all_" .filename. "." .fileEx
set multiplot

all_width_r = 0.545
all_width_l = all_width_r
bw_height_full = 0.700
bw_height = 0.023 + ((plotCount > 1) ? (bw_height_full - 0.018) : bw_height_full)
red_height = (plotCount > 1) ? 0.170 : 0.174
red_pos_y = (plotCount > 1) ? bw_height_full - 0.033 : bw_height_full - 0.035
acc_height_full = (plotCount > 1) ? 0.200 : 0.204
acc_height = (plotCount > 1) ? (acc_height_full - 0.012) : acc_height_full
acc_pos_y = (plotCount > 1) ? (red_pos_y + red_height - 0.007) : (red_pos_y + red_height - 0.025)

# accuracy

set size all_width_l,acc_height
set origin -0.002,acc_pos_y
unset xlabel
set format x ""
set ylabel "|Δ| missed " font ",16"
set yrange [0:acc_upd_max]
set format y " %4.1f"
if (plotCount > 1) {
  set key at screen 0.512,(acc_pos_y + 0.001) center center vertical Left reverse opaque enhanced autotitles nobox maxrows 1 width (plotCount >= 5 ? (key_width-2.2) : plotCount >= 4 ? (key_width+1) : (key_width+3)) samplen 1.75 font ",14" spacing 1.3
} else {
  set key top left horizontal Left reverse opaque enhanced autotitles box maxcols 1 width key_width samplen 1.5 font ",13"
}

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(column(col_missing)+column(col_outdated) - column(col_regen)-column(col_updated)):(stderrSum(column(col_sd_regen),column(col_sd_updated))) t get_title(i) ls i

set origin 0.49,acc_pos_y
unset key
unset ylabel
unset ytics
set grid y2tics
set size all_width_r,acc_height
if (regenAccInPercent == 1) {
  set y2tics mirror format "%-3.0f_{ }%%" offset 0 scale 0.8
  set y2range [(acc_reg_avg-acc_reg_max):(acc_reg_avg+acc_reg_max)]
} else {
  set y2tics mirror format "%-4.1f " scale 0.8
  set y2range [0:acc_reg_max]
}

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(regenAcc(column(col_regen)+column(col_updated), column(col_missing)+column(col_outdated))):(regenAccErr(column(col_sd_regen),column(col_sd_updated),(column(col_missing)+column(col_outdated)))) axes x1y2 t get_title(i) ls (plotCount > 1 ? i : 2)

set ytics scale 0.8
unset y2tics
set grid noy2tics

# redundancy

set ytics autofreq
set size all_width_l,red_height
set origin -0.002,red_pos_y
if (absoluteRedundancy == 1) {
set ylabel "Red." font ",16" # transferred / updated
} else {
set ylabel "rel. Red." font ",16" # transferred / updated
}
set yrange [0:red_max]
set y2range [0:red_max]
if (red_max > 10) {
  set format y "  %3.0f"
  set format y2 "%-3.0f "
} else {
  set format y " %4.1f"
  set format y2 "%-4.1f "
}
unset key

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))) with boxes t get_title(i) ls i, \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))):(redundancyStderr(column(col_sd_bw_rs_kvv), column(col_sd_updated), column(col_sd_regen))) with yerrorbars notitle ls (plotCount > 1 ? (100+i) : 100)

set size all_width_r,red_height
set origin 0.49,red_pos_y
if (plotCount == 1) {
  set key bottom right horizontal Right noreverse opaque enhanced autotitles box maxcols 1 width key_width samplen 1.5 font ",13"
}
unset ylabel
unset ytics
set grid y2tics
set y2tics mirror scale 0.8

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))) axes x1y2 with boxes t get_title(i) ls (plotCount > 1 ? i : 2), \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))):(redundancyStderr(column(col_sd_bw_rs_kvv), column(col_sd_updated), column(col_sd_regen))) with yerrorbars notitle ls (plotCount > 1 ? (100+i) : 100)

set ytics scale 0.8
unset y2tics
set grid noy2tics

# bandwidth

set size all_width_l,bw_height
set origin -0.002,-0.025
set xlabel "n in 10^3, update" font ",16"
set ylabel "RC costs (phase 1+2) in KiB" font ",16"
set yrange [bw_min:bw_max*1.2]
set y2range [bw_min:bw_max*1.2]
set logscale y 2
set logscale y2 2
if (bw_min < 1) {
  if (bw_min < 0.5) {
set format y "   2^{%L}"
  } else {
set format y "%4.1f"
  }
} else {
set format y "%5.0f"
}
set format x
if (plotCount > 1) {
  set key at screen 0.512,(red_pos_y + 0.0065) center center vertical Left reverse opaque enhanced autotitles nobox maxrows 1 width (plotCount >= 5 ? (key_width-2.2) : plotCount >= 4 ? (key_width+1) : (key_width+3)) samplen 1.75 font ",14" spacing 1.3
} else {
  set key top left horizontal Left reverse opaque enhanced autotitles box maxcols 1 width key_width samplen 1.5 font ",13"
}

LABELu = "n × (128+32) bits\n_{(≥ naïve approach)}"
set label 10 at systemSizeScaled*1.5,systemSize*66*(128+32)/8/1024 LABELu front left font ",12" textcolor rgb "#777777"

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))) with boxes notitle ls i fs solid 0.4, \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size))) with boxes t get_title(i) ls i, \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))):(kB(stderrSum(column(col_sd_bw_rc_size),column(col_sd_bw_rc2_size)))) with lines notitle ls (plotCount > 1 ? (100+i) : 100), \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))):(kB(stderrSum(column(col_sd_bw_rc_size),column(col_sd_bw_rc2_size)))) with yerrorbars notitle ls 100, \
     "<awk '$" . col_ftype . " == \"update\"' " . get_file(1) \
 u (plotShift(column(col_dbsize)/4/1000, 1)):(kB(column(col_dbsize)/4*(128+32)/8)) with linespoints notitle ls 6

set size all_width_r,bw_height
set origin 0.49,-0.025
set xlabel "n in 10^3, regen" font ",16"
unset key
unset ylabel
unset ytics
set grid y2tics
set y2tics mirror scale 0.8
if (bw_min < 1) {
  if (bw_min < 0.5) {
set format y2 "   2^{%L}"
  } else {
set format y2 "%4.1f"
  }
} else {
set format y2 "%5.0f"
}

unset label 10
LABELr = "n × (1-δ) × (128+32) bits\n_{(≥ naïve approach)}"
set label 10 at systemSizeScaled,128*systemSize*(128+32)/8/1024 LABELr front left font ",12" textcolor rgb "#777777"

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))) axes x1y2 with boxes notitle ls (plotCount > 1 ? i : 2) fs solid 0.4, \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size))) axes x1y2 with boxes t get_title(i) ls (plotCount > 1 ? i : 2), \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))):(kB(stderrSum(column(col_sd_bw_rc_size),column(col_sd_bw_rc2_size)))) axes x1y2 with lines notitle ls (plotCount > 1 ? (100+i) : 100), \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))):(kB(stderrSum(column(col_sd_bw_rc_size),column(col_sd_bw_rc2_size)))) axes x1y2 with yerrorbars notitle ls 100, \
     "<awk '$" . col_ftype . " == \"update\"' " . get_file(1) \
 u (plotShift(column(col_dbsize)/4/1000, 1)):(kB(column(col_dbsize)*(1-column(col_fprob)/100.0)/4*(128+32)/8)) with linespoints notitle ls 6

#! /usr/bin/gnuplot
# USED PARAMS
#	colDefFile -> file with column definitions
#	srcFile1 -> source file 1 path
#	srcFile1_title -> prepend this to titles of lines from srcFile1
#	srcFile2 -> source file 2 path (optional)
#	srcFile2_title -> prepend this to titles of lines from srcFile2 (optional unless srcFile2 given)
#	srcFile3 -> source file 3 path (optional)
#	srcFile3_title -> prepend this to titles of lines from srcFile3 (optional unless srcFile3 given)
#	srcFile4 -> source file 4 path (optional)
#	srcFile4_title -> prepend this to titles of lines from srcFile4 (optional unless srcFile4 given)
#	srcFile5 -> source file 5 path (optional)
#	srcFile5_title -> prepend this to titles of lines from srcFile5 (optional unless srcFile5 given)
#	destDir -> destination path for pdfs
#	regenAccInPercent -> whether to show the regen accuracy in percent instead of absolute values (useful for bloom)
#	absoluteRedundancy -> whether to show the absolute redundancy or a relative one

set macro

load colDefFile

plotCount = exists("srcFile5") ? 5 : exists("srcFile4") ? 4 : exists("srcFile3") ? 3 : exists("srcFile2") ? 2 : 1
files = srcFile1 . (plotCount >= 2 ? " " . srcFile2 : "") . (plotCount >= 3 ? " " . srcFile3 : "") . (plotCount >= 4 ? " " . srcFile4 : "") . (plotCount >= 5 ? " " . srcFile5 : "")
get_file(i) = (i == 5) ? srcFile5 : (i == 4) ? srcFile4 : (i == 3) ? srcFile3 : (i == 2) ? srcFile2 : srcFile1
get_title(i) = (i == 5) ? srcFile5_title : (i == 4) ? srcFile4_title : (i == 3) ? srcFile3_title : (i == 2) ? srcFile2_title : srcFile1_title

# http://colorbrewer2.org/?type=qualitative&scheme=Set1&n=5
# (#e41a1c, #377eb8, #4daf4a, #984ea3, #ff7f00)
# -> a little brighter version:
set style line 1 lw 2 lt 1 lc rgb '#ff191b' pt 5 # dark red
set style line 2 lw 2 lt 1 lc rgb '#2d8ede' pt 9 # dark blue
set style line 3 lw 2 lt 1 lc rgb '#59c955' pt 7 # dark green
set style line 4 lw 2 lt 1 lc rgb '#b05abd' pt 4 # dark purple
set style line 5 lw 2 lt 1 lc rgb '#ff7f00' pt 10 # dark orange
set style line 6 lw 3 lc rgb "#777777" pt 8 lt 3 # gray (for the naive line)

set style line 101 lw 3 lt 1 lc rgb '#ff191b' pt 0 # dark red
set style line 102 lw 3 lt 1 lc rgb '#2d8ede' pt 0 # dark blue
set style line 103 lw 3 lt 1 lc rgb '#59c955' pt 0 # dark green
set style line 104 lw 3 lt 1 lc rgb '#b05abd' pt 0 # dark purple
set style line 105 lw 3 lt 1 lc rgb '#ff7f00' pt 0 # dark orange

if (plotCount == 5) {
  plotShift(x, i) = (i == 5) ? (x + (x / 1.6)) : (i == 4) ? (x + (x / 3.7)) : (i == 3) ? (x) : (i == 2) ? (x - (x / 4.6)) : (x - (x / 2.6))
} else {
  if (plotCount == 4) {
    plotShift(x, i) = (i == 4) ? (x + (x / 1.9)) : (i == 3) ? (x + (x / 6.5)) : (i == 2) ? (x - (x / 7.9)) : (x - (x / 2.95))
  } else {
    if (plotCount == 3) {
      plotShift(x, i) = (i == 3) ? (x + (x / 2.3)) : (i == 2) ? (x) : (x - (x / 3.2))
    } else {
      if (plotCount == 2) {
        plotShift(x, i) = (i == 2) ? (x + (x / 3)) : (x - (x / 4))
      } else {
        plotShift(x, i) = x
      }
    }
  }
}
if (exists("regenAccInPercent") && regenAccInPercent == 1) {
  regenAcc(found, existing) = 100 - 100 * found / existing
  regenAccErr(found1, found2, existingSum) = stderrSum(found1, found2) * (100 / existingSum)
} else {
  regenAccInPercent = 0
  regenAcc(found, existing) = existing - found
  regenAccErr(found1, found2, existingSum) = stderrSum(found1, found2)
}
if (exists("absoluteRedundancy") && absoluteRedundancy == 1) {
  redundancy(transferred, updated, regen) = transferred - (updated + regen)
  redundancyStderr(transferred, updated, regen) = sqrt(transferred**2 - updated**2 - regen**2)
} else {
  absoluteRedundancy = 0
  redundancy(transferred, updated, regen) = transferred / (updated + regen)
  redundancyStderr(transferred, updated, regen) = "-"
}
if (!exists("systemSize")) {
  systemSize = 4000
}
plot_boxwidth = (0.8 / plotCount)

# OUTPUT
set terminal pdfcairo dashed enhanced font ",15" fontscale 0.5 size 6,4.5
fileEx = "pdf"

system "echo 'PLOT " . files . "'"
system "mkdir -p " .destDir

filename = "file"

# --OPTION
kvvSize0 = 16+4 # key+version size in bytes
kvvSize1 = kvvSize0+10 # key+version+value size in byte

# Helper
stderrSum(x,y) = sqrt(x**2 + y**2)	# sum of std. errors is root of sum of square errors
kB(x) = x / 1024
min(x,y) = (x < y) ? x : y
min3(x,y,z) = min(min(x,y),z)
max(x,y) = (x > y) ? x : y
max3(x,y,z) = max(max(x,y),z)

acc_upd_max=0.5
if (regenAccInPercent == 1) {
  do for [i=1:plotCount] {
    stats "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) u (column(col_missing)+column(col_outdated) - column(col_regen)-column(col_updated)+stderrSum(column(col_sd_regen),column(col_sd_updated))) nooutput
    if (STATS_max > acc_upd_max) {acc_upd_max = STATS_max}
  }
  acc_reg_max=50.5
  acc_reg_min=49.5
  do for [i=1:plotCount] {
    stats "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) u (regenAcc(column(col_regen)+column(col_updated), column(col_missing)+column(col_outdated))+regenAccErr(column(col_sd_regen),column(col_sd_updated),(column(col_missing)+column(col_outdated)))):(regenAcc(column(col_regen)+column(col_updated), column(col_missing)+column(col_outdated))-regenAccErr(column(col_sd_regen),column(col_sd_updated),(column(col_missing)+column(col_outdated)))) nooutput
    if (STATS_min_y < acc_reg_min) {acc_reg_min = STATS_min_y}
    if (STATS_max_x > acc_reg_max) {acc_reg_max = STATS_max_x}
  }
  acc_reg_avg=(acc_reg_max+acc_reg_min)/2.0
  acc_reg_max=max(abs(acc_reg_avg-acc_reg_min), abs(acc_reg_max-acc_reg_avg))
} else {
  do for [i=1:plotCount] {
    stats "<awk '$" . col_ftype . " == \"update\" || $" . col_ftype . " == \"regen\"' " . get_file(i) u (column(col_missing)+column(col_outdated) - column(col_regen)-column(col_updated)+stderrSum(column(col_sd_regen),column(col_sd_updated))) nooutput
    if (STATS_max > acc_upd_max) {acc_upd_max = STATS_max}
  }
  acc_reg_max = acc_upd_max
}
if (acc_upd_max > 0.5) {acc_upd_max=acc_upd_max*1.05}
if (acc_reg_max > 0.5) {acc_reg_max=acc_reg_max*1.05}

red_max=0.5
do for [i=1:plotCount] {
  stats get_file(i) using (redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))+redundancyStderr(column(col_sd_bw_rs_kvv), column(col_sd_updated), column(col_sd_regen))) nooutput
  if (STATS_max > red_max) {red_max = STATS_max}
}
if (red_max > 0.5) {red_max=red_max*1.05}
if (red_max >= 1.5 && red_max < 2) {red_max=2}

bw_max=1
do for [i=1:plotCount] {
  stats get_file(i) using (kB(column(col_bw_rc_size)+column(col_bw_rc2_size)+stderrSum(column(col_sd_bw_rc_size), column(col_sd_bw_rc2_size)))) nooutput
  if (STATS_max > bw_max) {bw_max = STATS_max}
}
# is naive solution more expensive?
stats get_file(1) using (kB(column(col_dbsize)/4*(128+32)/8)) nooutput
if (STATS_max > bw_max) {bw_max = STATS_max}

key_width_fun(i) = min(-0.5, (6-strstrt(get_title(i), "_")) - (strlen(get_title(i)) - strstrt(get_title(i), "_")) * 0.15)
key_width = min(key_width_fun(1),key_width_fun(plotCount))
#print "key_width: ",key_width

# Solid Background
# set object 1 rect from screen 0, 0, 0 to screen 1, 1, 0 behind
# set object 1 rect fc  rgb "white"  fillstyle solid 1.0

# Style
if (plotCount == 1) {
  set style data yerrorlines
} else {
  set style data yerrorbars
}
set logscale x 2
set xrange [((systemSize/1000.0)/2):((systemSize/1000.0)*4**5*2)] # TODO: adapt if number of data points changes!
set grid layerdefault linetype 0 linewidth 1.000,  linetype 0 linewidth 1.000
set pointsize (plotCount >= 4) ? 0.7 : (plotCount == 3) ? 0.8 : 1
arrow_dx=.166666666667 # grid spacing in x
arrow_di=0 # added to each i in loop - arrows drawn at (i+arrow_di)*arrow_dx
arrow_xpoints=6 # TODO: adapt if number of data points changes!

set style line 100 lw 2 lc -1 pt 0 lt 1

#--------------------------------- ALL
set boxwidth plot_boxwidth relative
set style fill solid 1 border -1
systemSizeScaled = systemSize / 1000.0
set xtics scale 0.1 systemSizeScaled,4
set ytics scale 0.8
set grid noxtics nomxtics layerdefault linetype 0 linewidth 1.000,  linetype 0 linewidth 1.000
set for [i=1:arrow_xpoints] arrow from graph (i+arrow_di)*arrow_dx,graph 0 to graph (i+arrow_di)*arrow_dx,graph 1 nohead back linetype 0 linewidth 1.000

set o destDir. "all_" .filename. "." .fileEx
set multiplot

all_width_r = 0.545
all_width_l = all_width_r
bw_height_full = 0.700
bw_height = 0.023 + ((plotCount > 1) ? (bw_height_full - 0.018) : bw_height_full)
red_height = (plotCount > 1) ? 0.170 : 0.174
red_pos_y = (plotCount > 1) ? bw_height_full - 0.033 : bw_height_full - 0.035
acc_height_full = (plotCount > 1) ? 0.200 : 0.204
acc_height = (plotCount > 1) ? (acc_height_full - 0.012) : acc_height_full
acc_pos_y = (plotCount > 1) ? (red_pos_y + red_height - 0.007) : (red_pos_y + red_height - 0.025)

# accuracy

set size all_width_l,acc_height
set origin -0.002,acc_pos_y
unset xlabel
set format x ""
set ylabel "|Δ| missed " font ",16"
set yrange [0:acc_upd_max]
set format y " %4.1f"
if (plotCount > 1) {
  set key at screen 0.512,(acc_pos_y + 0.001) center center vertical Left reverse opaque enhanced autotitles nobox maxrows 1 width (plotCount >= 5 ? (key_width-2.2) : plotCount >= 4 ? (key_width+1) : (key_width+3)) samplen 1.75 font ",14" spacing 1.3
} else {
  set key top left horizontal Left reverse opaque enhanced autotitles box maxcols 1 width key_width samplen 1.5 font ",13"
}

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(column(col_missing)+column(col_outdated) - column(col_regen)-column(col_updated)):(stderrSum(column(col_sd_regen),column(col_sd_updated))) t get_title(i) ls i

set origin 0.49,acc_pos_y
unset key
unset ylabel
unset ytics
set grid y2tics
set size all_width_r,acc_height
if (regenAccInPercent == 1) {
  set y2tics mirror format "%-3.0f_{ }%%" offset 0 scale 0.8
  set y2range [(acc_reg_avg-acc_reg_max):(acc_reg_avg+acc_reg_max)]
} else {
  set y2tics mirror format "%-4.1f " scale 0.8
  set y2range [0:acc_reg_max]
}

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(regenAcc(column(col_regen)+column(col_updated), column(col_missing)+column(col_outdated))):(regenAccErr(column(col_sd_regen),column(col_sd_updated),(column(col_missing)+column(col_outdated)))) axes x1y2 t get_title(i) ls (plotCount > 1 ? i : 2)

set ytics scale 0.8
unset y2tics
set grid noy2tics

# redundancy

set ytics autofreq
set size all_width_l,red_height
set origin -0.002,red_pos_y
if (absoluteRedundancy == 1) {
set ylabel "Red." font ",16" # transferred / updated
} else {
set ylabel "rel. Red." font ",16" # transferred / updated
}
set yrange [0:red_max]
set y2range [0:red_max]
if (red_max > 10) {
  set format y "  %3.0f"
  set format y2 "%-3.0f "
} else {
  set format y " %4.1f"
  set format y2 "%-4.1f "
}
unset key

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))) with boxes t get_title(i) ls i, \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))):(redundancyStderr(column(col_sd_bw_rs_kvv), column(col_sd_updated), column(col_sd_regen))) with yerrorbars notitle ls (plotCount > 1 ? (100+i) : 100)

set size all_width_r,red_height
set origin 0.49,red_pos_y
if (plotCount == 1) {
  set key bottom right horizontal Right noreverse opaque enhanced autotitles box maxcols 1 width key_width samplen 1.5 font ",13"
}
unset ylabel
unset ytics
set grid y2tics
set y2tics mirror scale 0.8

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))) axes x1y2 with boxes t get_title(i) ls (plotCount > 1 ? i : 2), \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(redundancy(column(col_bw_rs_kvv), column(col_updated), column(col_regen))):(redundancyStderr(column(col_sd_bw_rs_kvv), column(col_sd_updated), column(col_sd_regen))) with yerrorbars notitle ls (plotCount > 1 ? (100+i) : 100)

set ytics scale 0.8
unset y2tics
set grid noy2tics

# bandwidth

set size all_width_l,bw_height
set origin -0.002,-0.025
set xlabel "n in 10^3, update" font ",16"
set ylabel "RC costs (phase 1+2) in KiB" font ",16"
set yrange [1:bw_max*1.2]
set y2range [1:bw_max*1.2]
set logscale y 2
set logscale y2 2
set format y "%5.0f"
set format x
if (plotCount > 1) {
  set key at screen 0.512,(red_pos_y + 0.0065) center center vertical Left reverse opaque enhanced autotitles nobox maxrows 1 width (plotCount >= 5 ? (key_width-2.2) : plotCount >= 4 ? (key_width+1) : (key_width+3)) samplen 1.75 font ",14" spacing 1.3
} else {
  set key top left horizontal Left reverse opaque enhanced autotitles box maxcols 1 width key_width samplen 1.5 font ",13"
}

LABELu = "n × (128+32) bits\n_{(≥ naïve approach)}"
set label 10 at systemSizeScaled*1.5,systemSize*66*(128+32)/8/1024 LABELu front left font ",12" textcolor rgb "#777777"

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))) with boxes notitle ls i fs solid 0.4, \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size))) with boxes t get_title(i) ls i, \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))):(kB(stderrSum(column(col_sd_bw_rc_size),column(col_sd_bw_rc2_size)))) with lines notitle ls (plotCount > 1 ? (100+i) : 100), \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"update\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))):(kB(stderrSum(column(col_sd_bw_rc_size),column(col_sd_bw_rc2_size)))) with yerrorbars notitle ls 100, \
     "<awk '$" . col_ftype . " == \"update\"' " . get_file(1) \
 u (plotShift(column(col_dbsize)/4/1000, 1)):(kB(column(col_dbsize)/4*(128+32)/8)) with linespoints notitle ls 6

set size all_width_r,bw_height
set origin 0.49,-0.025
set xlabel "n in 10^3, regen" font ",16"
unset key
unset ylabel
unset ytics
set grid y2tics
set y2tics mirror format "%-5.0f" scale 0.8

unset label 10
LABELr = "n × (1-δ) × (128+32) bits\n_{(≥ naïve approach)}"
set label 10 at systemSizeScaled,128*systemSize*(128+32)/8/1024 LABELr front left font ",12" textcolor rgb "#777777"

plot for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))) axes x1y2 with boxes notitle ls (plotCount > 1 ? i : 2) fs solid 0.4, \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size))) axes x1y2 with boxes t get_title(i) ls (plotCount > 1 ? i : 2), \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))):(kB(stderrSum(column(col_sd_bw_rc_size),column(col_sd_bw_rc2_size)))) axes x1y2 with lines notitle ls (plotCount > 1 ? (100+i) : 100), \
     for [i=1:plotCount] "<awk '$" . col_ftype . " == \"regen\"' " . get_file(i) \
 u (plotShift(column(col_dbsize)/4/1000, i)):(kB(column(col_bw_rc_size)+column(col_bw_rc2_size))):(kB(stderrSum(column(col_sd_bw_rc_size),column(col_sd_bw_rc2_size)))) axes x1y2 with yerrorbars notitle ls 100, \
     "<awk '$" . col_ftype . " == \"update\"' " . get_file(1) \
 u (plotShift(column(col_dbsize)/4/1000, 1)):(kB(column(col_dbsize)*(1-column(col_fprob)/100.0)/4*(128+32)/8)) with linespoints notitle ls 6


format test

format test

#!/usr/bin/gnuplot

set datafile separator ';'

# Title of the plot
set title "Test graph"

# We want a grid
set grid

# Ignore missing values
#set datafile missing "NaN"

# X-axis label
set xlabel "Date/Time"

# set X-axis range to current date only
#set xrange ["$YESTERDAY":"$TODAY"]

# Y-axis ranges from 0 deg C to 100 deg C, same scale as for humidity
set yrange [15:20]

# Y2-axis set from 800 to 1200 kPa, used for barometric pressure
set autoscale y2

# place ticks on second Y2-axis
set y2tics border

# Title for Y-axis
set ylabel "Temperature [degC]"

# Title for Y2-axis
set y2label "Raw values [mV]"

# Define that data on X-axis should be interpreted as time
set xdata time

# Time in log-file is given in Unix format
set timefmt "%s"

# Display notation for time
set format x "%D\n%R"    # Display time in 24 hour notation on the X axis

# generate a legend which is placed underneath the plot
set key outside bottom center box title "--legend--"

# output into png file
set terminal png large
set output "/tmp/bonediagd/plot.png"

# Data columns are:
# 2 is Unix Epoch time
# 3 is TMP36 mV
# 4 is calculated temperature

# read data from file and generate plot
plot "/tmp/sql.csv" using 2:4 title "Temperature [degC]" with lines \
                ,"" using 2:3 title "Raw signal [mV]" with lines axes x1y2 \

#!/usr/bin/gnuplot

set datafile separator ';'

# Title of the plot
set title "Test graph"

# We want a grid
set grid

# Ignore missing values
#set datafile missing "NaN"

# X-axis label
set xlabel "Date/Time"

# set X-axis range to current date only
#set xrange ["$YESTERDAY":"$TODAY"]

# Y-axis ranges from 0 deg C to 100 deg C, same scale as for humidity
set yrange [15:20]

# Y2-axis set from 800 to 1200 kPa, used for barometric pressure
set autoscale y2

# place ticks on second Y2-axis
set y2tics border

# Title for Y-axis
set ylabel "Temperature [degC]"

# Title for Y2-axis
set y2label "Raw values [mV]"

# Define that data on X-axis should be interpreted as time
set xdata time

# Time in log-file is given in Unix format
set timefmt "%s"

# Display notation for time
set format x "%R"    # Display time in 24 hour notation on the X axis

# generate a legend which is placed underneath the plot
set key outside bottom center box title "--legend--"

# output into png file
set terminal png large
set output "/tmp/bonediagd/plot.png"

# Data columns are:
# 2 is Unix Epoch time
# 3 is TMP36 mV
# 4 is calculated temperature

# read data from file and generate plot
plot "/tmp/sql.csv" using 2:4 title "Temperature [degC]" with lines \
                ,"" using 2:3 title "Raw signal [mV]" with lines axes x1y2 \


adjust legend location

adjust legend location

# Tested with gnuplot 4.6 patchlevel 6

# Tablet created/deleted events
FN_IN_CD = system("echo $FN_IN_CD")
# Tablet access counts
FN_IN_AC = system("echo $FN_IN_AC")
FN_OUT = system("echo $FN_OUT")
DESC = system("echo $DESC")
MIN_TABLET_SIZE = system("echo $MIN_TABLET_SIZE")
MAX_NEEDTO_READ_DATAFILE_PER_DAY = system("echo $MAX_NEEDTO_READ_DATAFILE_PER_DAY")

load "../conf/colorscheme.gnuplot"

# Get the plot range
set terminal unknown
set xdata time
set timefmt "%y%m%d-%H%M%S"
plot \
FN_IN_CD u 2:7:2:5:7:($7+$6) w boxxyerrorbars
X_MIN=GPVAL_DATA_X_MIN
X_MAX=GPVAL_DATA_X_MAX
Y_MIN=GPVAL_DATA_Y_MIN
Y_MAX=GPVAL_DATA_Y_MAX

set terminal pdfcairo enhanced rounded size 6, 3in
set output FN_OUT

set border (1) front lc rgb "#808080"
set xtics nomirror scale 0.5,0 tc rgb "#808080" autofreq 0,(365.25*24*3600)
unset ytics

set format x "'%y"

x1p = (X_MAX - X_MIN) / 100
y1p = (Y_MAX - Y_MIN) / 100

# Give some margin on the left and at the bottom
x0=X_MIN-x1p
x1=X_MAX+x1p
y0=Y_MIN-y1p
y1=Y_MAX

set xrange [x0:x1]
set yrange [y0:y1]

set key top left

# Desc
x0 = X_MIN
y0 = Y_MAX - 3*y1p
set label DESC at x0, y0 left tc rgb "black" font ",7"

TRANSP0=0.06

# Legend
x1 = X_MIN + 78*x1p
x2 = x1 + 7*x1p
y2 = Y_MAX - 8*y1p
y1 = y2 - 10*y1p
set object rect from x1, y1 to x2, y2 fc rgb "black" fs transparent solid TRANSP0 noborder
set arrow from x1, y1 to x1, y2 lc rgb "black" nohead

y3 = (y2 + y1) / 2
y4 = y3 + 1.5*y1p
set label "sst\ngen" at x1, y4 right offset -0.5, 0 tc rgb "black" font ",8"

x3 = x1 - 5*x1p
set arrow from x3, y1 to x3, y2 lc rgb "black" nohead

set arrow from x3 - 0.2*x1p, y2 to x3 + 0.2*x1p, y2 lc rgb "black" nohead
set arrow from x3 - 0.2*x1p, y1 to x3 + 0.2*x1p, y1 lc rgb "black" nohead

set label (sprintf("%.1f MB", (y2 - y1)/1024/1024)) at x3, y2 right offset -0.5, 0 tc rgb "black" font ",8"
set label "0"                                     at x3, y1 right offset -0.5, 0 tc rgb "black" font ",8"

x4 = x3 - 7*x1p
set label "Tablet size" at x4, y3 center rotate by 90 tc rgb "black" font ",8"

y4 = y1 - 4*y1p
set arrow from x1, y1 to x1, y4 lt 0 lc rgb "black" nohead
set arrow from x2, y1 to x2, y4 lt 0 lc rgb "black" nohead

y5 = y4 - 2*y1p
set label "created" at x1, y5 center tc rgb "black" font ",8"
set label "deleted" at x2, y5 center tc rgb "black" font ",8"

legendAccesses(x) = (x1 < x) && (x < x2) && (sin(x / (x2 - x1) * pi * 150) > 0) ? \
										y1 + (y2 - y1) * (1 - sin((x - x1) / (x2 - x1) * pi / 2)) + sin(x / (x2 - x1) * pi * 20) * 0.5*y1p \
										: 1 / 0

x5 = x1 + 5.5*x1p
x6 = x2 + 2*x1p
set arrow from x5, y3 to x6, y3 lt 0 lc rgb "black" nohead

x7 = x6 + x1p
y6 = y3 + 2*y1p
set label "# of accesses\nper day" at x7, y6 left tc rgb "black" font ",8"

## Log scale
##   value range
##     x              : [0, max]
##     +1             : [1, max+1]
##     log(above)     : [0(=log(1)), log(max+1)]
##     / log(max+1) : [0, 1]
#AccessCountHeight(x) = x == 0 ? \
#											 1/0 \
#											 : (log(x+1)/log(MAX_NEEDTO_READ_DATAFILE_PER_DAY+1)) * MIN_TABLET_SIZE

AccessCountHeight(x) = x == 0 ? \
											 1/0 \
											 : x / MAX_NEEDTO_READ_DATAFILE_PER_DAY * MIN_TABLET_SIZE

x8 = x7 + 11*x1p
y7 = y3 - AccessCountHeight(MAX_NEEDTO_READ_DATAFILE_PER_DAY) / 2.0
y8 = y3 + AccessCountHeight(MAX_NEEDTO_READ_DATAFILE_PER_DAY) / 2.0
set arrow from x8, y7 to x8, y8 lc rgb "black" nohead
set arrow from x8 - 0.2*x1p, y7 to x8 + 0.2*x1p, y7 lc rgb "black" nohead
set arrow from x8 - 0.2*x1p, y8 to x8 + 0.2*x1p, y8 lc rgb "black" nohead
set label (sprintf("%s", MAX_NEEDTO_READ_DATAFILE_PER_DAY)) at x8, y8 left offset 0.4, 0.1 tc rgb "black" font ",7"
set label "0"                     at x8, y7 left offset 0.4,-0.1 tc rgb "black" font ",7"

set samples 5000

# gnuplot doesn't have a mod function
#   http://www.macs.hw.ac.uk/~ml355/lore/gnuplot.htm
mod(a, b) = a - floor(a/b) * b

color(a) = mod(a, 6)

set style fill transparent solid TRANSP0 noborder

# x  y  xlow  xhigh  ylow  yhigh
plot \
FN_IN_CD u 2:7:2:5:7:($7+$6):(color($1)) w boxxyerrorbars lc variable not, \
FN_IN_AC u 3:($2 + AccessCountHeight($6)):(color($1)) w points pointsize 0.05 lc variable not, \
FN_IN_CD u 2:7:(0):6:(color($1)) w vectors nohead      lt 1 lc variable not, \
FN_IN_CD u 2:($7+$6/2.0):1:(color($1)) w labels right offset -0.5,0 font ",8" tc variable not, \
legendAccesses(x) w lines lc rgb "black" not

# dotted line doesn't work with lc variable
#FN_IN_CD u 4:7:(0):6:(color($1)) w vectors nohead lw 2 lt 0 lc variable not, \

# steps doesn't work with lc variable
#FN_IN_AC u 3:($2 + AccessCountHeight($6)):(color($1)) w steps lc variable not, \
#FN_IN_AC u 3:2:($2 + AccessCountHeight($6)):(color($1)) w filledcurves lc variable not, \

# This doesn't fill the exact same area as the steps, but was the closest thing
# that I can find.
#FN_IN_AC u 3:2:($2 + AccessCountHeight($6)) w filledcurves lc rgb "red" not, \

#FN_IN_AC u 3:($2 + AccessCountHeight($6)) w linespoints pt 7 pointsize 0.1 lc rgb "black" not, \

# no base y option, like y0
#FN_IN_AC u 3:($2 + AccessCountHeight($6)) w fillsteps lc rgb "red" not, \

# Tested with gnuplot 4.6 patchlevel 6

# Tablet created/deleted events
FN_IN_CD = system("echo $FN_IN_CD")
# Tablet access counts
FN_IN_AC = system("echo $FN_IN_AC")
FN_OUT = system("echo $FN_OUT")
DESC = system("echo $DESC")
MIN_TABLET_SIZE = system("echo $MIN_TABLET_SIZE")
MAX_NEEDTO_READ_DATAFILE_PER_DAY = system("echo $MAX_NEEDTO_READ_DATAFILE_PER_DAY")

load "../conf/colorscheme.gnuplot"

# Get the plot range
set terminal unknown
set xdata time
set timefmt "%y%m%d-%H%M%S"
plot \
FN_IN_CD u 2:7:2:5:7:($7+$6) w boxxyerrorbars
X_MIN=GPVAL_DATA_X_MIN
X_MAX=GPVAL_DATA_X_MAX
Y_MIN=GPVAL_DATA_Y_MIN
Y_MAX=GPVAL_DATA_Y_MAX

set terminal pdfcairo enhanced rounded size 6, 3in
set output FN_OUT

set border (1) front lc rgb "#808080"
set xtics nomirror scale 0.5,0 tc rgb "#808080" autofreq 0,(365.25*24*3600)
unset ytics

set format x "'%y"

x1p = (X_MAX - X_MIN) / 100
y1p = (Y_MAX - Y_MIN) / 100

# Give some margin on the left and at the bottom
x0=X_MIN-x1p
x1=X_MAX+x1p
y0=Y_MIN-y1p
y1=Y_MAX

set xrange [x0:x1]
set yrange [y0:y1]

set key top left

# Desc
x0 = X_MIN
y0 = Y_MAX - 3*y1p
set label DESC at x0, y0 left tc rgb "black" font ",7"

TRANSP0=0.06

# Legend
x1 = X_MIN + 11.5*x1p
x2 = x1 + 7*x1p
y2 = y0 - 15*y1p
y1 = y2 - 10*y1p
set object rect from x1, y1 to x2, y2 fc rgb "black" fs transparent solid TRANSP0 noborder
set arrow from x1, y1 to x1, y2 lc rgb "black" nohead

y3 = (y2 + y1) / 2
y4 = y3 + 1.5*y1p
set label "sst\ngen" at x1, y4 right offset -0.5, 0 tc rgb "black" font ",8"

x3 = x1 - 5*x1p
set arrow from x3, y1 to x3, y2 lc rgb "black" nohead

set arrow from x3 - 0.2*x1p, y2 to x3 + 0.2*x1p, y2 lc rgb "black" nohead
set arrow from x3 - 0.2*x1p, y1 to x3 + 0.2*x1p, y1 lc rgb "black" nohead

set label (sprintf("%.1f MB", (y2 - y1)/1024/1024)) at x3, y2 right offset -0.5, 0 tc rgb "black" font ",8"
set label "0"                                     at x3, y1 right offset -0.5, 0 tc rgb "black" font ",8"

x4 = x3 - 7*x1p
set label "Tablet size" at x4, y3 center rotate by 90 tc rgb "black" font ",8"

y4 = y1 - 4*y1p
set arrow from x1, y1 to x1, y4 lt 0 lc rgb "black" nohead
set arrow from x2, y1 to x2, y4 lt 0 lc rgb "black" nohead

y5 = y4 - 2*y1p
set label "created" at x1, y5 center tc rgb "black" font ",8"
set label "deleted" at x2, y5 center tc rgb "black" font ",8"

legendAccesses(x) = (x1 < x) && (x < x2) && (sin(x / (x2 - x1) * pi * 150) > 0) ? \
										y1 + (y2 - y1) * (1 - sin((x - x1) / (x2 - x1) * pi / 2)) + sin(x / (x2 - x1) * pi * 20) * 0.5*y1p \
										: 1 / 0

x5 = x1 + 5.5*x1p
x6 = x2 + 2*x1p
set arrow from x5, y3 to x6, y3 lt 0 lc rgb "black" nohead

x7 = x6 + x1p
y6 = y3 + 2*y1p
set label "# of accesses\nper day" at x7, y6 left tc rgb "black" font ",8"

## Log scale
##   value range
##     x              : [0, max]
##     +1             : [1, max+1]
##     log(above)     : [0(=log(1)), log(max+1)]
##     / log(max+1) : [0, 1]
#AccessCountHeight(x) = x == 0 ? \
#											 1/0 \
#											 : (log(x+1)/log(MAX_NEEDTO_READ_DATAFILE_PER_DAY+1)) * MIN_TABLET_SIZE

AccessCountHeight(x) = x == 0 ? \
											 1/0 \
											 : x / MAX_NEEDTO_READ_DATAFILE_PER_DAY * MIN_TABLET_SIZE

x8 = x7 + 11*x1p
y7 = y3 - AccessCountHeight(MAX_NEEDTO_READ_DATAFILE_PER_DAY) / 2.0
y8 = y3 + AccessCountHeight(MAX_NEEDTO_READ_DATAFILE_PER_DAY) / 2.0
set arrow from x8, y7 to x8, y8 lc rgb "black" nohead
set arrow from x8 - 0.2*x1p, y7 to x8 + 0.2*x1p, y7 lc rgb "black" nohead
set arrow from x8 - 0.2*x1p, y8 to x8 + 0.2*x1p, y8 lc rgb "black" nohead
set label (sprintf("%s", MAX_NEEDTO_READ_DATAFILE_PER_DAY)) at x8, y8 left offset 0.4, 0.1 tc rgb "black" font ",7"
set label "0"                     at x8, y7 left offset 0.4,-0.1 tc rgb "black" font ",7"

set samples 5000

# gnuplot doesn't have a mod function
#   http://www.macs.hw.ac.uk/~ml355/lore/gnuplot.htm
mod(a, b) = a - floor(a/b) * b

color(a) = mod(a, 6)

set style fill transparent solid TRANSP0 noborder

# x  y  xlow  xhigh  ylow  yhigh
plot \
FN_IN_CD u 2:7:2:5:7:($7+$6):(color($1)) w boxxyerrorbars lc variable not, \
FN_IN_AC u 3:($2 + AccessCountHeight($6)):(color($1)) w points pointsize 0.05 lc variable not, \
FN_IN_CD u 2:7:(0):6:(color($1)) w vectors nohead      lt 1 lc variable not, \
FN_IN_CD u 2:($7+$6/2.0):1:(color($1)) w labels right offset -0.5,0 font ",8" tc variable not, \
legendAccesses(x) w lines lc rgb "black" not

# dotted line doesn't work with lc variable
#FN_IN_CD u 4:7:(0):6:(color($1)) w vectors nohead lw 2 lt 0 lc variable not, \

# steps doesn't work with lc variable
#FN_IN_AC u 3:($2 + AccessCountHeight($6)):(color($1)) w steps lc variable not, \
#FN_IN_AC u 3:2:($2 + AccessCountHeight($6)):(color($1)) w filledcurves lc variable not, \

# This doesn't fill the exact same area as the steps, but was the closest thing
# that I can find.
#FN_IN_AC u 3:2:($2 + AccessCountHeight($6)) w filledcurves lc rgb "red" not, \

#FN_IN_AC u 3:($2 + AccessCountHeight($6)) w linespoints pt 7 pointsize 0.1 lc rgb "black" not, \

# no base y option, like y0
#FN_IN_AC u 3:($2 + AccessCountHeight($6)) w fillsteps lc rgb "red" not, \


kdev: kconfig options should be prefixed CONFIG_

Signed-off-by: Erik Hugne <527d9b95423f3946c01de0ba884fdd8bb4a3759d@gmail.com>

#!/bin/bash
#Don't fiddle with users .config if there is one already
if [ -f ./linux/.config ]; then
	echo "Using existing kernel config"
else
	make -C ./linux x86_64_defconfig
	sed -i '/^CONFIG_VIRTIO=/{h;s/=.*/=CONFIG_VIRTIO=m/};${x;/^$/{s//CONFIG_VIRTIO=m/;H};x}' ./linux/.config
	sed -i '/^CONFIG_VIRTIO_NET=/{h;s/=.*/=CONFIG_VIRTIO_NET=m/};${x;/^$/{s//CONFIG_VIRTIO_NET=m/;H};x}' ./linux/.config
	sed -i '/^CONFIG_VIRTIO_PCI=/{h;s/=.*/=CONFIG_VIRTIO_PCI=m/};${x;/^$/{s//CONFIG_VIRTIO_PCI=m/;H};x}' ./linux/.config
fi

#!/bin/bash
#Don't fiddle with users .config if there is one already
if [ -f ./linux/.config ]; then
	echo "Using existing kernel config"
else
	make -C ./linux x86_64_defconfig
	sed -i '/^VIRTIO=/{h;s/=.*/=VIRTIO=y/};${x;/^$/{s//VIRTIO=y/;H};x}' ./linux/.config
	sed -i '/^VIRTIO_NET=/{h;s/=.*/=VIRTIO_NET=y/};${x;/^$/{s//VIRTIO_NET=y/;H};x}' ./linux/.config
	sed -i '/^VIRTIO_PCI=/{h;s/=.*/=VIRTIO_PCI=y/};${x;/^$/{s//VIRTIO_PCI=y/;H};x}' ./linux/.config
fi


Adjust position of name label.

Adjust position of name label.

set terminal png transparent nointerlace \
    font "lucon.ttf,20" \
    size 1920,1080 nocrop \
    noenhanced \
    background '#FFFFFF'

set encoding utf8

set style line 1 pointtype 7 linecolor rgb '#000000' pointsize 4
set style line 100 linetype 1 linewidth 1 linecolor rgbcolor '#aaaaaa'
set style line 101 linetype 1 linewidth 5 linecolor rgbcolor '#000000'
set style line 102 linetype 2 linewidth 4 linecolor rgbcolor '#999999'
set style line 103 linetype 3 linewidth 4 linecolor rgbcolor '#A00000'
set style line 104 linetype 4 linewidth 4 linecolor rgbcolor '#FF0000'
set style line 105 linetype 5 linewidth 4 linecolor rgbcolor '#007000'
set style line 106 linetype 6 linewidth 6 linecolor rgbcolor '#00FF00'
set style line 107 linetype 7 linewidth 4 linecolor rgbcolor '#0000A0'
set style line 108 linetype 8 linewidth 4 linecolor rgbcolor '#1E90FF'
set style line 109 linetype 9 linewidth 4 linecolor rgbcolor '#A020F0'

set key off

# TODO: set origin and size as options or calculate.
set origin 0.02,0
set size 0.98,1
set ytics
set xtics
set border
set colorbox
set grid xtics
set mxtics
set xlabel "x" font "lucon.ttf,30"

set format x ""
set format y ""
set grid ytics
set mytics
set my2tics
set ylabel "f(x)" font "lucon.ttf,30"
set label 1 "eigenholser" at screen 0.99,0.015 right font "times.ttf,12"

set terminal png transparent nointerlace \
    font "lucon.ttf,20" \
    size 1920,1080 nocrop \
    noenhanced \
    background '#FFFFFF'

set encoding utf8

set style line 1 pointtype 7 linecolor rgb '#000000' pointsize 4
set style line 100 linetype 1 linewidth 1 linecolor rgbcolor '#aaaaaa'
set style line 101 linetype 1 linewidth 5 linecolor rgbcolor '#000000'
set style line 102 linetype 2 linewidth 4 linecolor rgbcolor '#999999'
set style line 103 linetype 3 linewidth 4 linecolor rgbcolor '#A00000'
set style line 104 linetype 4 linewidth 4 linecolor rgbcolor '#FF0000'
set style line 105 linetype 5 linewidth 4 linecolor rgbcolor '#007000'
set style line 106 linetype 6 linewidth 6 linecolor rgbcolor '#00FF00'
set style line 107 linetype 7 linewidth 4 linecolor rgbcolor '#0000A0'
set style line 108 linetype 8 linewidth 4 linecolor rgbcolor '#1E90FF'
set style line 109 linetype 9 linewidth 4 linecolor rgbcolor '#A020F0'

set key off

# TODO: set origin and size as options or calculate.
set origin 0.02,0
set size 0.98,1
set ytics
set xtics
set border
set colorbox
set grid xtics
set mxtics
set xlabel "x" font "lucon.ttf,30"

set format x ""
set format y ""
set grid ytics
set mytics
set my2tics
set ylabel "f(x)" font "lucon.ttf,30"
set label 1 "eigenholser" at screen 1.0,0.014 right font "times.ttf,12"


enchanced detial enegy plt

enchanced detial enegy plt

set term pdfcairo
set output 'detail_energy.pdf'
#set pointtype 5
set xlabel "time"
set ylabel "energy"

#plot "energy.dat"  u 1:9 w l,"energy.dat" u 1:10  w l ,"energy.dat" u 1:11  w l
set key outside
plot for [col=1:20] 'energy.dat' using 0:col with lines title columnheader

set term pdfcairo
set output 'detail_energy.pdf'
#set pointtype 5
set xlabel "time"
set ylabel "energy"

plot "energy.dat"  u 1:5 w l,"energy.dat" u 1:6  w l


adding fully functional domain_coloring script for gnuplot

# setting output to file of size 800 x 800
set terminal pngcairo size 1000, 1000
set output 'out.png'

# removes legend
unset key

# projects image onto 2D plane
set view map

# sets aspect ratio of plot to be square
set size square

# setting x and y range
set xrange[-2:2]
set yrange[-2:2]

# scaling the x, y, and colorbar tics to zero so they are not seen in the plot
set xtics border scale 0,0
set ytics border scale 0,0
set cbtics border scale 0,0

# setting tics in color bar at 0 and 2pi
set cbtics ("0" -3.14159, "2pi" 3.14159)
set title "Domain coloring of output"

set cblabel "Phase Angle"
set cbrange [ -3.14159 : 3.14159 ]

# use hsv for colorbar and set palette to use full hsv space
set palette model HSV
set palette defined ( 0 0 1 1, 1 1 1 1 )

# setting isosamples for output grid and samples for input grid
set isosamples 2000, 2000
set samples 2000, 2000

# setting functions necessary for domain coloring
# setting threshold for gridlines. Smaller threashold will make smaller lines
thresh = 0.1
f(z) = z**3-1
Hue(x,y) = (pi + atan2(-y,-x)) / (2*pi)
r(x,y) = sqrt(x*x + y*y)
theta(x,y) = atan2(x,y)
z(x,y) = r(x,y)*exp(theta(x,y)*sqrt(-1))
ip(x,y) = imag(z(x,y))
rp(x,y) = real(z(x,y))
if(z) = imag(f(z))
rf(z) = real(f(z))
val(x,y) = 0.5 + 0.5*(abs(f(z(x,y)))-floor(abs(f(z(x,y)))))
color(x,y) = hsv2rgb(Hue(rf(z(x,y)), if(z(x,y))), abs(f(z(x,y))), val(x,y)*shade(x,y))
#color(x,y) = hsv2rgb(Hue(rp(x,y), ip(x,y)), abs(z(x,y)), val(x,y)*shade(x,y))
#shade(x,y) = (abs(sin(rp(x,y)*pi)**thresh) * abs(sin(ip(x,y)*pi))**thresh)
shade(x,y) = (abs(sin(rf(z(x,y))*pi)**thresh) * abs(sin(if(z(x,y))*pi))**thresh)
save_encoding = "utf8"

## Last datafile plotted: "++"
splot '++' using 1:2:(color($1,$2)) with pm3d lc rgb variable nocontour

# setting output to file of size 800 x 800
set terminal pngcairo size 800, 800
set output 'out.png'

# removes legend
unset key

# projects image onto 2D plane
set view map

# sets aspect ratio of plot to be square
set size square

# scaling the x, y, and colorbar tics to zero so they are not seen in the plot
set xtics border scale 0,0
set ytics border scale 0,0
set cbtics border scale 0,0

# setting tics in color bar at 0 and 2pi
set cbtics ("0" -3.14159, "2pi" 3.14159)
set title "Domain coloring of output"

set cblabel "Phase Angle"
set cbrange [ -3.14159 : 3.14159 ]

# use hsv for colorbar and set palette to use full hsv space
set palette model HSV
set palette defined ( 0 0 1 1, 1 1 1 1 )

# setting functions necessary for domain coloring
# setting threshold for gridlines. Smaller threashold will make smaller lines
thresh = 0.1
Hue(x,y) = (pi + atan2(-y,-x)) / (2*pi)
r(x,y) = sqrt(x*x + y*y)
theta(x,y) = atan2(x,y)
z(x,y) = r(x,y)*exp(theta(x,y)*sqrt(-1))
ip(x,y) = imag(z(x,y))
rp(x,y) = real(z(x,y))
val(x,y) = 0.5 + 0.5*(abs(z(x,y))-floor(abs(z(x,y))))
color(x,y) = hsv2rgb(Hue(rp(x,y), ip(x,y)), abs(z(x,y)), val(x,y)*shade(x,y))
shade(x,y) = (abs(sin(rp(x,y)*pi)**thresh) * abs(sin(ip(x,y)*pi))**thresh)
save_encoding = "utf8"

## Last datafile plotted: "++"
#splot 'out.dat' using 1:2:(color($3,$4)) with pm3d lc rgb variable nocontour
splot 'out.dat' using 1:2:(color($3,$4)) with pm3d lc rgb variable


add tikz output in gnuplot file

add tikz output in gnuplot file

git-svn-id: de9bbed4c30e0eb58fe8e7d66f5c80b71699a07c@3420 bf01a9d7-0df3-0310-8ad4-b1c94d9ae2d5

set autoscale
set term X11
#set term pdf
#extension= ".pdf"
#set term tikz standalone color solid size 5in,3in
set term tikz standalone monochrome  size 5in,3in
extension=".tex"

l=1;
L=1.5;

set xlabel 'time (s)'
#set xrange [0.0001:10]
#set yrange [0.0001:10]
set grid

#scheme =  "MoreauTSFixed"
#scheme  =  "ProjectedMoreauTS"
scheme = "CombinedProjectedMoreauTS"

timestep= "150"

set output scheme."-RockingBlock-q-".timestep.extension

plot 'result.dat'  using 1:2  t '$x$' w lines,\
     'result.dat'  using 1:3  t '$y$' w lines,\
     'result.dat'  using 1:4  t '$\theta$' w lines

set output scheme."-RockingBlock-v-".timestep.extension

plot 'result.dat'  using 1:5  t '$\dot x$' w lines,\
     'result.dat'  using 1:6  t '$\dot y$' w lines,\
     'result.dat'  using 1:7  t '$\dot \theta$' w lines

set output scheme."-RockingBlock-Energy-".timestep.extension
plot 'result.dat'  using 1:8  t 'Kinetic energy' w lines,\
     'result.dat'  using 1:9  t 'Potential energy' w lines,\
     'result.dat'  using ($1):($8+$9)  t 'Total energy' w lines

set output scheme."-RockingBlock-g-".timestep.extension

plot 'result.dat'  using 1:($3-1/2.0*(L*cos($4) -l*sin($4) ))  t 'g1' w lines,\
     'result.dat'  using 1:($3-1/2.0*(L*cos($4) +l*sin($4) ))  t 'g2' w lines

set output scheme."-RockingBlock-viol-".timestep.extension

 plot 'result.dat'  using 1:  ( ($3-1/2.0*(L*cos($4) -l*sin($4) ) < 0 ) ?  ($3-1/2.0*(L*cos($4) -l*sin($4) ) )  : 0.0 )  t 'g1' w lines,\
      'result.dat'  using  1:  ( ($3-1/2.0*(L*cos($4) +l*sin($4) ) < 0 ) ?  ($3-1/2.0*(L*cos($4) +l*sin($4) ) )  : 0.0 ) t 'g2' w lines

set autoscale
set term X11
set term pdf

l=1;
L=1.5;

set xlabel 'time (s)'
#set xrange [0.0001:10]
#set yrange [0.0001:10]
set grid

scheme =  "MoreauTSFixed"
#scheme  =  "ProjectedMoreauTS"
#scheme = "CombinedProjectedMoreauTS"

timestep= "150"

set output scheme."-RockingBlock-q-".timestep.".pdf"

plot 'result.dat'  using 1:2  t 'x' w lines,\
     'result.dat'  using 1:3  t 'y' w lines,\
     'result.dat'  using 1:4  t 'theta' w lines

set output scheme."-RockingBlock-v-".timestep.".pdf"

plot 'result.dat'  using 1:5  t 'dotx' w lines,\
     'result.dat'  using 1:6  t 'doty' w lines,\
     'result.dat'  using 1:7  t 'dottheta' w lines

set output scheme."RockingBlock-Energy-".timestep.".pdf"
plot 'result.dat'  using 1:8  t 'Kinetic' w lines,\
     'result.dat'  using 1:9  t 'Potential' w lines,\
     'result.dat'  using ($1):($8+$9)  t 'Total' w lines

set output scheme."-RockingBlock-g-".timestep.".pdf"

plot 'result.dat'  using 1:($3-1/2.0*(L*cos($4) -l*sin($4) ))  t 'g1' w lines,\
     'result.dat'  using 1:($3-1/2.0*(L*cos($4) +l*sin($4) ))  t 'g2' w lines

set output scheme."-RockingBlock-viol-".timestep.".pdf"

 plot 'result.dat'  using 1:  ( ($3-1/2.0*(L*cos($4) -l*sin($4) ) < 0 ) ?  ($3-1/2.0*(L*cos($4) -l*sin($4) ) )  : 0.0 )  t 'g1' w lines,\
      'result.dat'  using  1:  ( ($3-1/2.0*(L*cos($4) +l*sin($4) ) < 0 ) ?  ($3-1/2.0*(L*cos($4) +l*sin($4) ) )  : 0.0 ) t 'g2' w lines


startcol starts from place 2....

startcol starts from place 2....

but the colors array should start from index 0 (red).

####################################################################################
# Gnuplot 4.6 script for plotting multiple groups of 3 bars in a barchart.
# This part is dynamic and can be altered to influence the look of the graph.
####################################################################################

### plot setup
#set terminal pngcairo transparent enhanced font "inconsolata,10" fontscale 1.0 size 500, 350
set terminal pngcairo size 800,600 enhanced font 'Liberation Mono,10' background "#002b36"
set output 'test.png'
COLORS = "red green gray"
STARTCOL = 2
ENDCOL = 4
set border 3 front linetype -1 linewidth 1.000 linecolor rgb "gold"

### titles and labels
set title "income\_vs\_expenses\n(Extra info here?)" textcolor rgb "gold"
set xlabel "Year"
set xlabel  offset character 0, -2, 0 font "" textcolor rgb "gold" lt -1 norotate
set ylabel "Value (EUR)"

####################################################################################
# Gnuplot 4.6 script for plotting multiple groups of 3 bars in a barchart.
# This part is static and can not be altered.
####################################################################################

### legend
set key bmargin center horizontal Left reverse noenhanced autotitles columnhead nobox

### main code
GAPSIZE = 5
NCOL = ENDCOL-STARTCOL+1
BOXWIDTH = 1./(GAPSIZE+NCOL)

### barchart layout - axis + grid
set style fill solid 1.00 border lt -1
set boxwidth BOXWIDTH absolute
set grid nopolar
set grid noxtics nomxtics ytics nomytics noztics nomztics \
 nox2tics nomx2tics noy2tics nomy2tics nocbtics nomcbtics
set grid layerdefault linetype 0 linewidth 1.000,  linetype 0 linewidth 1.000
set xzeroaxis linetype 0 linewidth 1.000
set yzeroaxis linetype 0 linewidth 1.000
set zzeroaxis linetype 0 linewidth 1.000

### Set tics and histograms
# Note: I can not use GAPSIZE below, for some reason... hardcoded 4 is used instead
set style histogram clustered gap 5 title offset character 2, 0.25, 0
set datafile missing '-'
set style data histograms
set xtics border in scale 0,0 nomirror rotate by -45  offset character 0, 0, 0 autojustify
set xtics  norangelimit font ",8"
set xtics ()
set ytics border in scale 0,0 mirror norotate  offset character 0, 0, 0 autojustify
set ztics border in scale 0,0 nomirror norotate  offset character 0, 0, 0 autojustify
set cbtics border in scale 0,0 mirror norotate  offset character 0, 0, 0 autojustify
set rtics axis in scale 0,0 nomirror norotate  offset character 0, 0, 0 autojustify

#x = 0.0
#i = 23
### plotting
plot for [COL=STARTCOL:ENDCOL] 'test.dat' u COL:xtic(1) w histogram title columnheader(COL) lc rgb word(COLORS, COL-STARTCOL), \
    for [COL=STARTCOL:ENDCOL] 'test.dat' u (column(0)+BOXWIDTH*(COL-STARTCOL+GAPSIZE/2+1)-0.5):COL:COL notitle w labels

####################################################################################
# Gnuplot 4.6 script for plotting multiple groups of 3 bars in a barchart.
# This part is dynamic and can be altered to influence the look of the graph.
####################################################################################

### plot setup
#set terminal pngcairo transparent enhanced font "inconsolata,10" fontscale 1.0 size 500, 350
set terminal pngcairo size 800,600 enhanced font 'Liberation Mono,10' background "#002b36"
set output 'test.png'
COLORS = "red green gray"
STARTCOL = 2
ENDCOL = 4
set border 3 front linetype -1 linewidth 1.000 linecolor rgb "gold"

### titles and labels
set title "income\_vs\_expenses\n(Extra info here?)" textcolor rgb "gold"
set xlabel "Year"
set xlabel  offset character 0, -2, 0 font "" textcolor rgb "gold" lt -1 norotate
set ylabel "Value (EUR)"

####################################################################################
# Gnuplot 4.6 script for plotting multiple groups of 3 bars in a barchart.
# This part is static and can not be altered.
####################################################################################

### legend
set key bmargin center horizontal Left reverse noenhanced autotitles columnhead nobox

### main code
GAPSIZE = 5
NCOL = ENDCOL-STARTCOL+1
BOXWIDTH = 1./(GAPSIZE+NCOL)

### barchart layout - axis + grid
set style fill solid 1.00 border lt -1
set boxwidth BOXWIDTH absolute
set grid nopolar
set grid noxtics nomxtics ytics nomytics noztics nomztics \
 nox2tics nomx2tics noy2tics nomy2tics nocbtics nomcbtics
set grid layerdefault linetype 0 linewidth 1.000,  linetype 0 linewidth 1.000
set xzeroaxis linetype 0 linewidth 1.000
set yzeroaxis linetype 0 linewidth 1.000
set zzeroaxis linetype 0 linewidth 1.000

### Set tics and histograms
# Note: I can not use GAPSIZE below, for some reason... hardcoded 4 is used instead
set style histogram clustered gap 5 title offset character 2, 0.25, 0
set datafile missing '-'
set style data histograms
set xtics border in scale 0,0 nomirror rotate by -45  offset character 0, 0, 0 autojustify
set xtics  norangelimit font ",8"
set xtics ()
set ytics border in scale 0,0 mirror norotate  offset character 0, 0, 0 autojustify
set ztics border in scale 0,0 nomirror norotate  offset character 0, 0, 0 autojustify
set cbtics border in scale 0,0 mirror norotate  offset character 0, 0, 0 autojustify
set rtics axis in scale 0,0 nomirror norotate  offset character 0, 0, 0 autojustify

#x = 0.0
#i = 23
### plotting
plot for [COL=STARTCOL:ENDCOL] 'test.dat' u COL:xtic(1) w histogram title columnheader(COL) lc rgb word(COLORS, COL), \
    for [COL=STARTCOL:ENDCOL] 'test.dat' u (column(0)+BOXWIDTH*(COL-STARTCOL+GAPSIZE/2+1)-0.5):COL:COL notitle w labels


fix tics

fix tics

# Tested with gnuplot 4.6 patchlevel 6

FN_IN = system("echo $FN_IN")
FN_OUT = system("echo $FN_OUT")

# Get min and max values
set terminal unknown
set xdata time
set timefmt "%y%m%d-%H%M%S"
set format x "'%y"

plot FN_IN u 1:($2/1000000) w fsteps, \
FN_IN u 1:($4+$5) w lines axes x1y2

X_MIN=GPVAL_DATA_X_MIN
X_MAX=GPVAL_DATA_X_MAX
Y_MIN=GPVAL_DATA_Y_MIN
Y_MAX=GPVAL_DATA_Y_MAX
Y2_MIN=GPVAL_DATA_Y2_MIN
Y2_MAX=GPVAL_DATA_Y2_MAX

set terminal pdfcairo enhanced size 3in, 2in
set output FN_OUT

#set tmargin at screen 0.975
#set bmargin at screen 0.152
#set lmargin at screen 0.185
#set rmargin at screen 0.940

set xlabel "Time" offset 0,0.3
set ylabel "Storage size (MB)" offset 1.3,0
set y2label "Storage cost ($)"

set border (1 + 2 + 8) back lc rgb "#808080"
set xtics nomirror scale 0.5,0 tc rgb "#808080" #autofreq 0,(365.25*24*3600)

# Not sure if this is what I wanted. Not important.
x1(a)=(10**floor(log10(a)))
x2(a)=floor(a/x1(a))*x1(a)
x3(a)=floor(a/x1(a)/2)*x1(a)*2
startsWith1(a)=(a == x1(a))
yTicsStep(a, b)=(startsWith1(x2(a/b)) ? x2(a/b) : x3(a/b))

set print "-"
print (sprintf("Y_MAX: %f", Y_MAX))
print (sprintf("Y2_MAX: %f", Y2_MAX))
print (sprintf("yTicsStep(Y_MAX, 2)=%f", yTicsStep(Y_MAX, 2)))
print (sprintf("yTicsStep(Y2_MAX, 2)=%f", yTicsStep(Y2_MAX, 2)))
set ytics  nomirror scale 0.5,0 tc rgb "#808080" autofreq 0,yTicsStep(Y_MAX, 2)
set y2tics nomirror scale 0.5,0 tc rgb "#808080" autofreq 0,yTicsStep(Y2_MAX, 2)
set tics front

set xrange [X_MIN:X_MAX]
set yrange [Y_MIN:Y_MAX]
set y2range [Y2_MIN:Y2_MAX]

set key top left

set pointsize 0.1

plot \
FN_IN u 1:($2/1000000) w steps lc rgb "red" t "Hot", \
FN_IN u 1:($3/1000000) w steps lc rgb "blue" t "Cold", \
FN_IN u 1:4 w linespoints axes x1y2 pt 7 lc rgb "red" not, \
FN_IN u 1:5 w linespoints axes x1y2 pt 7 lc rgb "blue" not, \
FN_IN u 1:($4+$5) w linespoints axes x1y2 pt 7 lc rgb "black" not

#FN_IN u 1:($2/1000000) w fillsteps fs solid 0.15 noborder not, \

# Tested with gnuplot 4.6 patchlevel 6

FN_IN = system("echo $FN_IN")
FN_OUT = system("echo $FN_OUT")

# Get min and max values
set terminal unknown
set xdata time
set timefmt "%y%m%d-%H%M%S"
set format x "'%y"

plot FN_IN u 1:($2/1000000) w fsteps, \
FN_IN u 1:($4+$5) w lines axes x1y2

X_MIN=GPVAL_DATA_X_MIN
X_MAX=GPVAL_DATA_X_MAX
Y_MIN=GPVAL_DATA_Y_MIN
Y_MAX=GPVAL_DATA_Y_MAX
Y2_MIN=GPVAL_DATA_Y2_MIN
Y2_MAX=GPVAL_DATA_Y2_MAX

set terminal pdfcairo enhanced size 3in, 2in
set output FN_OUT

#set tmargin at screen 0.975
#set bmargin at screen 0.152
#set lmargin at screen 0.185
#set rmargin at screen 0.940

set xlabel "Time" offset 0,0.3
set ylabel "Storage size (MB)" offset 1.3,0
set y2label "Storage cost ($)"

set border (1 + 2 + 8) back lc rgb "#808080"
set xtics nomirror scale 0.5,0 tc rgb "#808080" #autofreq 0,(365.25*24*3600)

# Not sure if this is what I wanted. Not important.
x1(a)=(10**floor(log10(a)))
x2(a)=floor(a/x1(a))*x1(a)
x3(a)=floor(a/x1(a)/2)*x1(a)*2
yTicsStep(a, b)=(x2(a/b) == 1 ? x2(a/b) : x3(a/b))

set print "-"
print (sprintf("Y_MAX: %f", Y_MAX))
print (sprintf("Y2_MAX: %f", Y2_MAX))
print (sprintf("yTicsStep(Y_MAX, 2)=%f", yTicsStep(Y_MAX, 2)))
print (sprintf("yTicsStep(Y2_MAX, 2)=%f", yTicsStep(Y2_MAX, 2)))
set ytics  nomirror scale 0.5,0 tc rgb "#808080" autofreq 0,yTicsStep(Y_MAX, 2)
set y2tics nomirror scale 0.5,0 tc rgb "#808080" autofreq 0,yTicsStep(Y2_MAX, 2)
set tics front

set xrange [X_MIN:X_MAX]
set yrange [Y_MIN:Y_MAX]
set y2range [Y2_MIN:Y2_MAX]

set key top left

set pointsize 0.1

plot \
FN_IN u 1:($2/1000000) w steps lc rgb "red" t "Hot", \
FN_IN u 1:($3/1000000) w steps lc rgb "blue" t "Cold", \
FN_IN u 1:4 w linespoints axes x1y2 pt 7 lc rgb "red" not, \
FN_IN u 1:5 w linespoints axes x1y2 pt 7 lc rgb "blue" not, \
FN_IN u 1:($4+$5) w linespoints axes x1y2 pt 7 lc rgb "black" not

#FN_IN u 1:($2/1000000) w fillsteps fs solid 0.15 noborder not, \


Hide reload_all_classes messages

Hide reload_all_classes messages

:- begin_tests(vd).

:- use_module(u(v)).
:- use_module(u(vd)).
:- use_module(u(internal/db_i)).
:- use_module(u(util/lambda)).

test(clear_test_db, [fail, setup(db_clear(people))]) :-

	db_recorded(people, _).

test(db_clear, [setup(model_db), List == []]) :-

   current_prolog_flag(verbose, Old_Verbose),
   set_prolog_flag(verbose, silent),
   reload_all_classes,
   set_prolog_flag(verbose, Old_Verbose),

   % clear all DBs with citizen_v
   (  db_name(DB_Key),
      (  named_args_unify(DB_Key, citizen_v, [], [], _)
      -> db_clear(DB_Key)
      ;  true
      ),
      fail ; true
   ),

   findall(X,
           (db_i:current_predicate(citizen_v, X), call(db_i:X)),
           List).

test(db_copy, [setup(model_db), N =:= 3]) :-

   db_copy(people, people2),
   findall('.', db_recorded(people2, _), L),
   length(L, N).

test(db_erase, [setup(model_db)]) :-

   (  named_args_unify(people, _,
                       [weight, surname], [73, _], X),
      db_erase(X),
      fail ; true
   ),

   findall(Y,
           db_recorded(people, Y),
           LY),
   assertion(LY = [man_v(_, _, _, _, 'Eva', woman, _, _)]).

test(db_iterate1, [setup(model_db), N =:= 3]) :-

   findall('.', db_iterate(people, true, _), L),
   length(L, N).

test(db_iterate2, [setup(model_db), N =:= 2]) :-

   findall(O, db_iterate(people, sex(man), O), L),
   length(L, N).

test(db_iterate3, [setup(model_db), fail]) :-

   db_iterate(people, unexisting_name(man_v), _).

test(db_iterate4, [setup(model_db), N =:= 2]) :-

   findall(O, db_iterate(people, functor(man_v), O), L),
   length(L, N).

test(db_iterate4, [setup(model_db), N =:= 3]) :-

   findall(O, db_iterate(people, functor(_), O), L),
   length(L, N).

test(db_to_list, [setup(model_db)]) :-

   db_to_list(people, man_v, L1),
   length(L1, N1),
   assertion(N1 =:= 2),

   db_to_list(people, citizen_v, L2),
   length(L2, N2),
   assertion(N2 =:= 1),

   db_to_list(people, _, L3),
   length(L3, N3),
   assertion(N3 =:= 3).

test(db_put_object1,
     [setup(model_db),
      List == [['Adam'], ['Eva'], ['Moses'], ['Vladimir']]
      ]) :-

   obj_construct(man_v, [name], ['Moses'], Man),
   db_put_object(people, Man),
   db_select_list(people, _, [name], List).

test(db_put_object2, [setup(model_db)]) :-

   obj_construct(man_v, [name], ['Moses'], Man0),
   obj_rebase((object_v -> db_object_v), Man0, Man),
   db_put_object(people, Man).

test(db_put_object3,
     [setup(model_db),
      error(db_obj_replace_protector(people2, _, Man))]) :-

   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man), !,
   db_put_object(people2, Man).

test(db_put_object4, [setup(model_db)]) :-
% replacing

   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man0), !,
   obj_rewrite(Man0, [name], ['Moses'], [_], Man1),
   db_put_object(people2, throw, Man1, Man2, Replaced),
   named_args_unify(Man2,
                    [name, db_key, db_ref],
                    [New_Name, DB_Key, DB_Ref]),
   assertion(New_Name =@= _),
   assertion(Replaced == replaced),
   assertion(nonvar(DB_Ref)),
   assertion(DB_Key == people2),

   db_size(people2, N),
   assertion(N =:= 1).

test(db_put_object5,
     [setup(model_db),
      error(domain_error(unbound_db_ref, DB_Ref))]) :-

   db_construct(people, man_v, [name], ['Moses']),
   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man0), !,
   obj_field(Man0, db_ref, DB_Ref),
   db_put_object(people, throw, Man0, _, _).

test(db_put_object6,
     [setup(model_db),
      error(domain_error(unbound_or_same_db_key, people2))]) :-

   db_construct(people, man_v, [name], ['Moses']),
   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man0), !,
   obj_reset_fields([db_ref], Man0, Man),
   db_put_object(people, throw, Man, _, _).

test(db_put_object7,
     [setup(model_db),
      error(db_obj_replace_protector(people2, replaced, Man1))]) :-

   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man0), !,
   obj_rewrite(Man0, [db_ref, name], [_, 'Moses'], [_, _], Man1),
   db_put_object(people2, throw, Man1, _, replaced).
   % does not replace because of unbound db_ref

test(db_put_object8,
     [setup(model_db),
      error(db_obj_replace_protector(people2, replaced, Man))]) :-

   db_construct(people2, man_v, [name], ['Moses']),
   obj_construct(man_v, [name], ['Simeon'], Man),
   db_put_object(people2, _, Man, _, replaced).
   % does not replace because of not db_object_v descendant

test(db_recorda1,
     [setup(model_db),
      List == [['Moses'], ['Adam'], ['Eva'], ['Vladimir']]
      ]) :-

   obj_construct(man_v, [name], ['Moses'], Man),
   db_recorda(people, Man),
   db_select_list(people, _, [name], List).

test(db_put_objects,
    [setup(db_clear(people)),
     DB_Size =:= 3]
    ) :-

	maplist(obj_construct(man_v, [name]),
		[['Valera'], ['Vika'], ['Yura']],
		Men),

	db_put_objects(people,
		       Men+\El^member(El, Men),
		       fail),

	db_size(people, DB_Size).

test(db_recorded_bug1, [setup(model_db), N =:= 3]) :-

   findall('.', db_recorded(people, _), L),
   length(L, N).

test(db_recorded1,
     [setup(model_db),
      error(domain_error(db_object_v_descendant, X))]) :-

   obj_construct(man_v, [sex], [man], X),
   db_recorded(people, X).

test(db_recorded2, [setup(model_db)]) :-

   findall('.',
           (obj_construct(man_v, [sex], [man], X0),
            obj_rebase((object_v -> db_object_v), X0, X),
            db_recorded(people, X)),
           L2),
   length(L2, N2),
   assertion(N2 =:= 1).

test(db_recorded3, [setup(model_db)]) :-

   findall('.',
           (obj_construct(man_v, [], [], X0),
            obj_rebase((object_v -> db_object_v), X0, X),
            db_recorded(people, X)),
           L2),
   length(L2, N2),
   assertion(N2 =:= 2).

test(db_recorded4, [setup(model_db)]) :-

   findall('.',
           (obj_construct(man_v, [height], [1.76], X0),
            obj_rebase((object_v -> db_object_v), X0, X),
            db_recorded(people, X)),
           L2),
   length(L2, N2),
   assertion(N2 =:= 2).

test(db_recorded5, [setup(db_clear(people))]) :-

   db_construct(people, man_v, [], []),
   db_recorded(people, X), !,
   db_recorded(people, X).

% test(db_rewrite1,
%      [setup(model_db),
%       List =@= [['Adam', 'Kasperski', 66],
%                 ['Eva', 'Kasperski', 66],
%                 ['Vladimir', 'Kasperski', 66]]
%      ]) :-

%    db_rewrite(people, _,
%               [weight, surname], _, [66, 'Kasperski']),
%    db_select_list(people, _, [name, surname, weight], List).

% test(db_rewrite2,
%      [setup(model_db),
%       List =@= [['Adam', 'Kasperski', 66],
%                 ['Eva', 'Kasperski', 66],
%                 ['Vladimir', 'Mayakovsky', _]]
%      ]) :-

%    db_rewrite(people, man_v,
%               [weight, surname], _, [66, 'Kasperski']),
%    db_select_list(people, _, [name, surname, weight], List).

test(db_select1,
     [setup(model_db),
      List =@= [[man_v, man, 'Adam', _, 73, _],
                [man_v, woman, 'Eva', _, 64, _],
                [citizen_v, man, 'Vladimir', 'Mayakovsky', _,
                 ['Soviet Union']]]
      ]) :-

   findall(Row,
           db_select(people,
                     [class, sex, name, surname, weight, country],
                     Row),
           List
          ).

test(db_select2,
     [setup(model_db),
      List =@= [[man_v, man, 'Adam', _, 73, _],
                [man_v, woman, 'Eva', _, 64, _]]
      ]) :-

   findall(Row,
           (   Row = [man_v|_],
               db_select(people,
                         [functor, sex, name, surname, weight,
                          country],
                         Row)
           ), List
          ).

test(db_select_list1,
     [setup(model_db),
      List =@= [[man_v, man, 'Adam', _, 73, _],
                [man_v, woman, 'Eva', _, 64, _],
                [citizen_v, man, 'Vladimir', 'Mayakovsky', _,
                 ['Soviet Union']]]
      ]) :-

   db_select_list(people, _,
                  [class, sex, name, surname, weight, country],
                  List).

test(db_select_list2,
     [setup(model_db),
      List =@= [[man_v, man, 'Adam', _, 73, _],
                [man_v, woman, 'Eva', _, 64, _]]
      ]) :-

   db_select_list(people, man_v, _,
                  [class, sex, name, surname, weight, country],
                  List).

test(db_select_list3,
     [setup(model_db),
      error(no_object_field(_, country))
      ]) :-

   db_select_list(people, man_v, throw,
                  [class, sex, name, surname, weight, country],
                  _).

test(named_args_unify1, [setup(model_db)]) :-

   findall('.',
           named_args_unify(people, _, [sex], [man], _),
           ['.', '.']).

test(named_args_unify2, [setup(model_db)]) :-

   findall('.',
           named_args_unify(people, _, [sex, sex], [man, man], _),
           ['.', '.']).

test(named_args_unify_bug1, [setup(model_db)]) :-

   findall('.',
           named_args_unify(people, citizen_v, [sex], [man], _),
           ['.']).

test(named_args_unify_bug2, [setup(model_db)]) :-

   findall('.',
           named_args_unify(people, _, [], [], _),
           ['.', '.', '.']).

test(store_and_retrieve1,
    [setup(db_clear(people)),
     man(Sex, Name, Surname, Weight, Height) ==
     man(man, 'Adam', 'Adamov', 1, 3)]
    ) :-

	obj_construct(man_v,
		      [sex, name, surname, weight, height],
		      [man, 'Adam', 'Adamov', 1, 3],
		      Man),

	db_put_object(people, Man, Man1),

	assertion(obj_is_descendant(Man1, db_object_v)),
	assertion(\+ obj_is_descendant(Man1, man_v)),
	assertion(\+ obj_is_descendant(Man, db_object_v)),

	obj_field(Man1, sex, Sex),
	obj_field(Man1, name, Name),
	obj_field(Man1, surname, Surname),
	obj_field(Man1, weight, Weight),
	obj_field(Man1, height, Height).

test(key_rule1,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),
   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']).

test(key_rule2,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v, [], []),
   db_construct(people, man_v, [], []).

test(key_rule3,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v, [name], ['Sergei']),
   db_construct(people, man_v, [], []).

test(key_rule4,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v, [], []),
   db_construct(people, man_v, [name], ['Sergei']).

test(key_rule5, [setup(db_clear(people))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Sikorsky']).

test(key_rule6,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name], ['Sergei']),

   db_construct(people, man_v,
                [name], ['Sergei']).

test(key_rule7,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name], ['Sergei']),

   db_construct(people, man_v,
                [surname], ['Lodyagin']).

test(key_rule8, [setup(db_clear(people))]) :-

   db_construct(people, man_v,
                [name], ['Sergei']),

   db_construct(people, man_v,
                [name], ['Artem']).

test(key_rule9,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Sysoev']),

   db_construct(people, man_v,
                [name], ['Sergei']).

test(key_rule10,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name], ['Sergei']),

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Sysoev']).

test(key_rule11,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, citizen_v, [], []).

test(key_rule12, [setup(db_clear(people))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, man_v, [], []).

test(key_rule13, [setup(db_clear(people))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, man_v, [name], ['James']).

test(key_rule14,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, man_v, [], []),
   db_construct(people, citizen_v, [id], [5]).

test(key_rule15, [setup(db_clear(people))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, man_v,
                [name, surname], ['James', 'Crick']),
   db_construct(people, citizen_v,
                [name, surname, id], ['Adam', 'Adamovitch', 5]).

test(key_rule16,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v, [name], ['James']),
   db_construct(people, citizen_v, [id], [4]).

test(db_singleton_v1_overwrite, [setup(db_clear(people))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),
   db_construct(people, db_singleton_v,
                [key_policy], [overwrite]),
   db_construct(people, man_v, [surname], ['Lodyagin']),

   findall([Name, Surname],
           named_args_unify(people, _, [name, surname],
                            [Name, Surname], _),
           List1),
   assertion(List1 =@= [[_, 'Lodyagin']]).

test(db_singleton_v2_throw,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),
   db_construct(people, db_singleton_v,
                [key_policy], [overwrite]),
   db_construct(people, man_v, [surname], ['Lodyagin']),
   db_construct(people, db_singleton_v,
                [key_policy], [throw]),
   db_construct(people, man_v, [name], ['Sergei']).

test(db_singleton_v3_fail_ignore, [setup(db_clear(people))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),
   db_construct(people, db_singleton_v,
                [key_policy], [fail]),
   \+ db_construct(people, man_v, [surname], ['Lodyagin']),

   named_args_unify(people, db_singleton_v, [], _, Singl1), !,
   obj_rewrite(Singl1, [key_policy], [fail], [ignore], Singl2),
   db_put_object(people, _, Singl2, _, replaced),

   db_construct(people, man_v,
                [name, surname, height], ['Sergei', 'Lodyagin',
                1.74]),

   findall([Name, Surname, Height],
           named_args_unify(people, _,
                            [name, surname, height],
                            [Name, Surname, Height], _),
           List1),
   assertion(List1 =@= [['Sergei', 'Lodyagin', _]]).

test(rebase_collision_bug1, [blocked(till_future_version)]) :-

   obj_construct(man_v, [], [], O0),
   obj_rebase((object_v -> tarjan_vertex_v), O0, O),
   db_put_object(people, O).

model_db :-

	db_clear(people),
	db_clear(people2),

        db_construct(people, man_v,
                     [sex, name, weight], [man, 'Adam', 73]),
        db_construct(people, man_v,
                     [sex, name, weight], [woman, 'Eva', 64]),

        db_construct(people, citizen_v,
                      [sex, name, surname, country],
                      [man, 'Vladimir', 'Mayakovsky',
                       ['Soviet Union']]).

:- end_tests(vd).

:- begin_tests(vd).

:- use_module(u(v)).
:- use_module(u(vd)).
:- use_module(u(internal/db_i)).
:- use_module(u(util/lambda)).

test(clear_test_db, [fail, setup(db_clear(people))]) :-

	db_recorded(people, _).

test(db_clear, [setup(model_db), List == []]) :-

   reload_all_classes,

   % clear all DBs with citizen_v
   (  db_name(DB_Key),
      (  named_args_unify(DB_Key, citizen_v, [], [], _)
      -> db_clear(DB_Key)
      ;  true
      ),
      fail ; true
   ),

   findall(X,
           (db_i:current_predicate(citizen_v, X), call(db_i:X)),
           List).

test(db_copy, [setup(model_db), N =:= 3]) :-

   db_copy(people, people2),
   findall('.', db_recorded(people2, _), L),
   length(L, N).

test(db_erase, [setup(model_db)]) :-

   (  named_args_unify(people, _,
                       [weight, surname], [73, _], X),
      db_erase(X),
      fail ; true
   ),

   findall(Y,
           db_recorded(people, Y),
           LY),
   assertion(LY = [man_v(_, _, _, _, 'Eva', woman, _, _)]).

test(db_iterate1, [setup(model_db), N =:= 3]) :-

   findall('.', db_iterate(people, true, _), L),
   length(L, N).

test(db_iterate2, [setup(model_db), N =:= 2]) :-

   findall(O, db_iterate(people, sex(man), O), L),
   length(L, N).

test(db_iterate3, [setup(model_db), fail]) :-

   db_iterate(people, unexisting_name(man_v), _).

test(db_iterate4, [setup(model_db), N =:= 2]) :-

   findall(O, db_iterate(people, functor(man_v), O), L),
   length(L, N).

test(db_iterate4, [setup(model_db), N =:= 3]) :-

   findall(O, db_iterate(people, functor(_), O), L),
   length(L, N).

test(db_to_list, [setup(model_db)]) :-

   db_to_list(people, man_v, L1),
   length(L1, N1),
   assertion(N1 =:= 2),

   db_to_list(people, citizen_v, L2),
   length(L2, N2),
   assertion(N2 =:= 1),

   db_to_list(people, _, L3),
   length(L3, N3),
   assertion(N3 =:= 3).

test(db_put_object1,
     [setup(model_db),
      List == [['Adam'], ['Eva'], ['Moses'], ['Vladimir']]
      ]) :-

   obj_construct(man_v, [name], ['Moses'], Man),
   db_put_object(people, Man),
   db_select_list(people, _, [name], List).

test(db_put_object2, [setup(model_db)]) :-

   obj_construct(man_v, [name], ['Moses'], Man0),
   obj_rebase((object_v -> db_object_v), Man0, Man),
   db_put_object(people, Man).

test(db_put_object3,
     [setup(model_db),
      error(db_obj_replace_protector(people2, _, Man))]) :-

   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man), !,
   db_put_object(people2, Man).

test(db_put_object4, [setup(model_db)]) :-
% replacing

   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man0), !,
   obj_rewrite(Man0, [name], ['Moses'], [_], Man1),
   db_put_object(people2, throw, Man1, Man2, Replaced),
   named_args_unify(Man2,
                    [name, db_key, db_ref],
                    [New_Name, DB_Key, DB_Ref]),
   assertion(New_Name =@= _),
   assertion(Replaced == replaced),
   assertion(nonvar(DB_Ref)),
   assertion(DB_Key == people2),

   db_size(people2, N),
   assertion(N =:= 1).

test(db_put_object5,
     [setup(model_db),
      error(domain_error(unbound_db_ref, DB_Ref))]) :-

   db_construct(people, man_v, [name], ['Moses']),
   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man0), !,
   obj_field(Man0, db_ref, DB_Ref),
   db_put_object(people, throw, Man0, _, _).

test(db_put_object6,
     [setup(model_db),
      error(domain_error(unbound_or_same_db_key, people2))]) :-

   db_construct(people, man_v, [name], ['Moses']),
   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man0), !,
   obj_reset_fields([db_ref], Man0, Man),
   db_put_object(people, throw, Man, _, _).

test(db_put_object7,
     [setup(model_db),
      error(db_obj_replace_protector(people2, replaced, Man1))]) :-

   db_construct(people2, man_v, [name], ['Moses']),
   db_recorded(people2, Man0), !,
   obj_rewrite(Man0, [db_ref, name], [_, 'Moses'], [_, _], Man1),
   db_put_object(people2, throw, Man1, _, replaced).
   % does not replace because of unbound db_ref

test(db_put_object8,
     [setup(model_db),
      error(db_obj_replace_protector(people2, replaced, Man))]) :-

   db_construct(people2, man_v, [name], ['Moses']),
   obj_construct(man_v, [name], ['Simeon'], Man),
   db_put_object(people2, _, Man, _, replaced).
   % does not replace because of not db_object_v descendant

test(db_recorda1,
     [setup(model_db),
      List == [['Moses'], ['Adam'], ['Eva'], ['Vladimir']]
      ]) :-

   obj_construct(man_v, [name], ['Moses'], Man),
   db_recorda(people, Man),
   db_select_list(people, _, [name], List).

test(db_put_objects,
    [setup(db_clear(people)),
     DB_Size =:= 3]
    ) :-

	maplist(obj_construct(man_v, [name]),
		[['Valera'], ['Vika'], ['Yura']],
		Men),

	db_put_objects(people,
		       Men+\El^member(El, Men),
		       fail),

	db_size(people, DB_Size).

test(db_recorded_bug1, [setup(model_db), N =:= 3]) :-

   findall('.', db_recorded(people, _), L),
   length(L, N).

test(db_recorded1,
     [setup(model_db),
      error(domain_error(db_object_v_descendant, X))]) :-

   obj_construct(man_v, [sex], [man], X),
   db_recorded(people, X).

test(db_recorded2, [setup(model_db)]) :-

   findall('.',
           (obj_construct(man_v, [sex], [man], X0),
            obj_rebase((object_v -> db_object_v), X0, X),
            db_recorded(people, X)),
           L2),
   length(L2, N2),
   assertion(N2 =:= 1).

test(db_recorded3, [setup(model_db)]) :-

   findall('.',
           (obj_construct(man_v, [], [], X0),
            obj_rebase((object_v -> db_object_v), X0, X),
            db_recorded(people, X)),
           L2),
   length(L2, N2),
   assertion(N2 =:= 2).

test(db_recorded4, [setup(model_db)]) :-

   findall('.',
           (obj_construct(man_v, [height], [1.76], X0),
            obj_rebase((object_v -> db_object_v), X0, X),
            db_recorded(people, X)),
           L2),
   length(L2, N2),
   assertion(N2 =:= 2).

test(db_recorded5, [setup(db_clear(people))]) :-

   db_construct(people, man_v, [], []),
   db_recorded(people, X), !,
   db_recorded(people, X).

% test(db_rewrite1,
%      [setup(model_db),
%       List =@= [['Adam', 'Kasperski', 66],
%                 ['Eva', 'Kasperski', 66],
%                 ['Vladimir', 'Kasperski', 66]]
%      ]) :-

%    db_rewrite(people, _,
%               [weight, surname], _, [66, 'Kasperski']),
%    db_select_list(people, _, [name, surname, weight], List).

% test(db_rewrite2,
%      [setup(model_db),
%       List =@= [['Adam', 'Kasperski', 66],
%                 ['Eva', 'Kasperski', 66],
%                 ['Vladimir', 'Mayakovsky', _]]
%      ]) :-

%    db_rewrite(people, man_v,
%               [weight, surname], _, [66, 'Kasperski']),
%    db_select_list(people, _, [name, surname, weight], List).

test(db_select1,
     [setup(model_db),
      List =@= [[man_v, man, 'Adam', _, 73, _],
                [man_v, woman, 'Eva', _, 64, _],
                [citizen_v, man, 'Vladimir', 'Mayakovsky', _,
                 ['Soviet Union']]]
      ]) :-

   findall(Row,
           db_select(people,
                     [class, sex, name, surname, weight, country],
                     Row),
           List
          ).

test(db_select2,
     [setup(model_db),
      List =@= [[man_v, man, 'Adam', _, 73, _],
                [man_v, woman, 'Eva', _, 64, _]]
      ]) :-

   findall(Row,
           (   Row = [man_v|_],
               db_select(people,
                         [functor, sex, name, surname, weight,
                          country],
                         Row)
           ), List
          ).

test(db_select_list1,
     [setup(model_db),
      List =@= [[man_v, man, 'Adam', _, 73, _],
                [man_v, woman, 'Eva', _, 64, _],
                [citizen_v, man, 'Vladimir', 'Mayakovsky', _,
                 ['Soviet Union']]]
      ]) :-

   db_select_list(people, _,
                  [class, sex, name, surname, weight, country],
                  List).

test(db_select_list2,
     [setup(model_db),
      List =@= [[man_v, man, 'Adam', _, 73, _],
                [man_v, woman, 'Eva', _, 64, _]]
      ]) :-

   db_select_list(people, man_v, _,
                  [class, sex, name, surname, weight, country],
                  List).

test(db_select_list3,
     [setup(model_db),
      error(no_object_field(_, country))
      ]) :-

   db_select_list(people, man_v, throw,
                  [class, sex, name, surname, weight, country],
                  _).

test(named_args_unify1, [setup(model_db)]) :-

   findall('.',
           named_args_unify(people, _, [sex], [man], _),
           ['.', '.']).

test(named_args_unify2, [setup(model_db)]) :-

   findall('.',
           named_args_unify(people, _, [sex, sex], [man, man], _),
           ['.', '.']).

test(named_args_unify_bug1, [setup(model_db)]) :-

   findall('.',
           named_args_unify(people, citizen_v, [sex], [man], _),
           ['.']).

test(named_args_unify_bug2, [setup(model_db)]) :-

   findall('.',
           named_args_unify(people, _, [], [], _),
           ['.', '.', '.']).

test(store_and_retrieve1,
    [setup(db_clear(people)),
     man(Sex, Name, Surname, Weight, Height) ==
     man(man, 'Adam', 'Adamov', 1, 3)]
    ) :-

	obj_construct(man_v,
		      [sex, name, surname, weight, height],
		      [man, 'Adam', 'Adamov', 1, 3],
		      Man),

	db_put_object(people, Man, Man1),

	assertion(obj_is_descendant(Man1, db_object_v)),
	assertion(\+ obj_is_descendant(Man1, man_v)),
	assertion(\+ obj_is_descendant(Man, db_object_v)),

	obj_field(Man1, sex, Sex),
	obj_field(Man1, name, Name),
	obj_field(Man1, surname, Surname),
	obj_field(Man1, weight, Weight),
	obj_field(Man1, height, Height).

test(key_rule1,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),
   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']).

test(key_rule2,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v, [], []),
   db_construct(people, man_v, [], []).

test(key_rule3,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v, [name], ['Sergei']),
   db_construct(people, man_v, [], []).

test(key_rule4,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v, [], []),
   db_construct(people, man_v, [name], ['Sergei']).

test(key_rule5, [setup(db_clear(people))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Sikorsky']).

test(key_rule6,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name], ['Sergei']),

   db_construct(people, man_v,
                [name], ['Sergei']).

test(key_rule7,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name], ['Sergei']),

   db_construct(people, man_v,
                [surname], ['Lodyagin']).

test(key_rule8, [setup(db_clear(people))]) :-

   db_construct(people, man_v,
                [name], ['Sergei']),

   db_construct(people, man_v,
                [name], ['Artem']).

test(key_rule9,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Sysoev']),

   db_construct(people, man_v,
                [name], ['Sergei']).

test(key_rule10,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name], ['Sergei']),

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Sysoev']).

test(key_rule11,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, citizen_v, [], []).

test(key_rule12, [setup(db_clear(people))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, man_v, [], []).

test(key_rule13, [setup(db_clear(people))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, man_v, [name], ['James']).

test(key_rule14,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, man_v, [], []),
   db_construct(people, citizen_v, [id], [5]).

test(key_rule15, [setup(db_clear(people))]) :-

   db_construct(people, citizen_v, [id], [4]),
   db_construct(people, man_v,
                [name, surname], ['James', 'Crick']),
   db_construct(people, citizen_v,
                [name, surname, id], ['Adam', 'Adamovitch', 5]).

test(key_rule16,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v, [name], ['James']),
   db_construct(people, citizen_v, [id], [4]).

test(db_singleton_v1_overwrite, [setup(db_clear(people))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),
   db_construct(people, db_singleton_v,
                [key_policy], [overwrite]),
   db_construct(people, man_v, [surname], ['Lodyagin']),

   findall([Name, Surname],
           named_args_unify(people, _, [name, surname],
                            [Name, Surname], _),
           List1),
   assertion(List1 =@= [[_, 'Lodyagin']]).

test(db_singleton_v2_throw,
     [setup(db_clear(people)),
      error(db_key_exists(people, _, _))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),
   db_construct(people, db_singleton_v,
                [key_policy], [overwrite]),
   db_construct(people, man_v, [surname], ['Lodyagin']),
   db_construct(people, db_singleton_v,
                [key_policy], [throw]),
   db_construct(people, man_v, [name], ['Sergei']).

test(db_singleton_v3_fail_ignore, [setup(db_clear(people))]) :-

   db_construct(people, man_v,
                [name, surname], ['Sergei', 'Lodyagin']),
   db_construct(people, db_singleton_v,
                [key_policy], [fail]),
   \+ db_construct(people, man_v, [surname], ['Lodyagin']),

   named_args_unify(people, db_singleton_v, [], _, Singl1), !,
   obj_rewrite(Singl1, [key_policy], [fail], [ignore], Singl2),
   db_put_object(people, _, Singl2, _, replaced),

   db_construct(people, man_v,
                [name, surname, height], ['Sergei', 'Lodyagin',
                1.74]),

   findall([Name, Surname, Height],
           named_args_unify(people, _,
                            [name, surname, height],
                            [Name, Surname, Height], _),
           List1),
   assertion(List1 =@= [['Sergei', 'Lodyagin', _]]).

test(rebase_collision_bug1, [blocked(till_future_version)]) :-

   obj_construct(man_v, [], [], O0),
   obj_rebase((object_v -> tarjan_vertex_v), O0, O),
   db_put_object(people, O).

model_db :-

	db_clear(people),
	db_clear(people2),

        db_construct(people, man_v,
                     [sex, name, weight], [man, 'Adam', 73]),
        db_construct(people, man_v,
                     [sex, name, weight], [woman, 'Eva', 64]),

        db_construct(people, citizen_v,
                      [sex, name, surname, country],
                      [man, 'Vladimir', 'Mayakovsky',
                       ['Soviet Union']]).

:- end_tests(vd).