Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr//gitroot/simgrid/simgrid
authorPierre Veyre <pierre.veyre@cc.in2p3.fr>
Thu, 20 Mar 2014 10:44:24 +0000 (11:44 +0100)
committerPierre Veyre <pierre.veyre@cc.in2p3.fr>
Thu, 20 Mar 2014 10:44:24 +0000 (11:44 +0100)
25 files changed:
buildtools/Cmake/AddTests.cmake
buildtools/Cmake/CompleteInFiles.cmake
buildtools/Cmake/DefinePackages.cmake
buildtools/Cmake/Distrib.cmake
buildtools/Cmake/MakeExe.cmake
buildtools/Cmake/MakeJava.cmake
buildtools/Cmake/Scripts/java_bundle.sh
contrib/benchmarking_code_block/Rdhist.R [new file with mode: 0644]
contrib/benchmarking_code_block/Rhist.R
contrib/benchmarking_code_block/Rplot_hist.R [new file with mode: 0644]
contrib/benchmarking_code_block/inject.h
examples/java/surfPlugin/CMakeLists.txt [new file with mode: 0644]
examples/java/surfPlugin/Receiver.java [new file with mode: 0644]
examples/java/surfPlugin/Sender.java [new file with mode: 0644]
examples/java/surfPlugin/TestPlugin.java [new file with mode: 0644]
examples/java/surfPlugin/TracePlugin.java [new file with mode: 0644]
examples/java/surfPlugin/surfPluginDeployment.xml [new file with mode: 0644]
examples/java/surfPlugin/surfPluginPlatform.xml [new file with mode: 0644]
examples/java/surfPlugin/surf_plugin.tesh [new file with mode: 0644]
src/bindings/java/org/simgrid/NativeLib.java [new file with mode: 0644]
src/bindings/java/org/simgrid/msg/Msg.java
src/bindings/java/surf.i [new file with mode: 0644]
src/bindings/java/surf_swig.cpp [new file with mode: 0644]
src/bindings/java/surf_swig.hpp [new file with mode: 0644]
src/surf/surf_interface.hpp

index 33ecd81..0accf2c 100644 (file)
@@ -625,6 +625,7 @@ if(NOT enable_memcheck)
     ADD_TEST(java-pingPong                      ${TESH_COMMAND} ${TESH_OPTION} --setenv srcdir=${CMAKE_HOME_DIRECTORY}/examples/java --setenv classpath=${TESH_CLASSPATH} --cd ${CMAKE_BINARY_DIR}/examples/java ${CMAKE_HOME_DIRECTORY}/examples/java/pingPong/pingpong.tesh)
     ADD_TEST(java-priority                      ${TESH_COMMAND} ${TESH_OPTION} --setenv srcdir=${CMAKE_HOME_DIRECTORY}/examples/java --setenv classpath=${TESH_CLASSPATH} --cd ${CMAKE_BINARY_DIR}/examples/java ${CMAKE_HOME_DIRECTORY}/examples/java/priority/priority.tesh)
     ADD_TEST(java-startKillTime                 ${TESH_COMMAND} ${TESH_OPTION} --setenv srcdir=${CMAKE_HOME_DIRECTORY}/examples/java --setenv classpath=${TESH_CLASSPATH} --cd ${CMAKE_BINARY_DIR}/examples/java ${CMAKE_HOME_DIRECTORY}/examples/java/startKillTime/startKillTime.tesh)
+    ADD_TEST(java-surf-plugin                   ${TESH_COMMAND} ${TESH_OPTION} --setenv srcdir=${CMAKE_HOME_DIRECTORY}/examples/java --setenv classpath=${TESH_CLASSPATH} --cd ${CMAKE_BINARY_DIR}/examples/java ${CMAKE_HOME_DIRECTORY}/examples/java/surfPlugin/surf_plugin.tesh)
     ADD_TEST(java-suspend                       ${TESH_COMMAND} ${TESH_OPTION} --setenv srcdir=${CMAKE_HOME_DIRECTORY}/examples/java --setenv classpath=${TESH_CLASSPATH} --cd ${CMAKE_BINARY_DIR}/examples/java ${CMAKE_HOME_DIRECTORY}/examples/java/suspend/suspend.tesh)
     if(HAVE_TRACING)
       ADD_TEST(java-tracing                     ${TESH_COMMAND} ${TESH_OPTION} --setenv srcdir=${CMAKE_HOME_DIRECTORY}/examples/java --setenv classpath=${TESH_CLASSPATH} --cd ${CMAKE_BINARY_DIR}/examples/java ${CMAKE_HOME_DIRECTORY}/examples/java/tracing/tracingPingPong.tesh)
index 1085ffd..5db8766 100644 (file)
@@ -84,6 +84,9 @@ if(enable_java)
   find_package(JNI REQUIRED)
   message("-- [Java] JNI found: ${JNI_FOUND}")
   message("-- [Java] JNI include dirs: ${JNI_INCLUDE_DIRS}")
+  find_package(SWIG REQUIRED)
+  include(UseSWIG)
+  message("-- [Java] Swig found: ${SWIG_FOUND}")
   set(HAVE_Java 1)
 endif()
 if(enable_scala)
index 3cda367..a414011 100644 (file)
@@ -460,6 +460,9 @@ set(JMSG_C_SRC
 )
 
 set(JMSG_JAVA_SRC
+  src/bindings/java/org/simgrid/NativeLib.java
+  #src/bindings/java/org/simgrid/NativeException.java
+
   src/bindings/java/org/simgrid/msg/As.java    
   src/bindings/java/org/simgrid/msg/Comm.java
   src/bindings/java/org/simgrid/msg/File.java
@@ -470,8 +473,7 @@ set(JMSG_JAVA_SRC
   src/bindings/java/org/simgrid/msg/Msg.java
   src/bindings/java/org/simgrid/msg/MsgException.java
   src/bindings/java/org/simgrid/msg/Mutex.java
-  src/bindings/java/org/simgrid/msg/NativeException.java
-  src/bindings/java/org/simgrid/msg/NativeLib.java
+  src/bindings/java/org/simgrid/msg/NativeException.java    
   src/bindings/java/org/simgrid/msg/Process.java
   src/bindings/java/org/simgrid/msg/ProcessKilledError.java
   src/bindings/java/org/simgrid/msg/ProcessNotFoundException.java
@@ -484,6 +486,30 @@ set(JMSG_JAVA_SRC
   src/bindings/java/org/simgrid/msg/VM.java
 )
 
+set(JSURF_SWIG_SRC
+  src/bindings/java/surf.i
+)
+set(JSURF_JAVA_C_SRC
+  src/bindings/java/surf_swig.cpp
+  src/bindings/java/surf_swig.hpp
+)
+
+set(JSURF_JAVA_GENERATED_SRC
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/Surf.java
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/SurfJNI.java
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/Plugin.java
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/Model.java
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/Resource.java
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/Action.java  
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/Cpu.java
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/CpuAction.java  
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/NetworkLink.java  
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/NetworkAction.java  
+
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/LmmConstraint.java  
+  ${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf/XbtDict.java
+) 
+
 set(JTRACE_C_SRC
   src/bindings/java/jtrace.c
   src/bindings/java/jtrace.h
@@ -875,6 +901,7 @@ set(EXAMPLES_CMAKEFILES_TXT
   examples/java/cloud/CMakeLists.txt
   examples/java/cloud/migration/CMakeLists.txt
   examples/java/commTime/CMakeLists.txt
+  examples/java/surfPlugin/CMakeLists.txt
   examples/java/io/CMakeLists.txt
   examples/java/kademlia/CMakeLists.txt
   examples/java/master_slave_bypass/CMakeLists.txt
index 74b539b..2bb482a 100644 (file)
@@ -189,6 +189,8 @@ set(source_to_pack
   ${JEDULE_SRC}
   ${JMSG_C_SRC}
   ${JMSG_JAVA_SRC}
+  ${JSURF_SWIG_SRC}
+  ${JSURF_JAVA_C_SRC}
   ${LUA_SRC}
   ${MC_SRC}
   ${MSG_SRC}
index 72ec2fc..1742b95 100644 (file)
@@ -19,6 +19,7 @@ add_subdirectory(${CMAKE_HOME_DIRECTORY}/examples/java/mutualExclusion)
 add_subdirectory(${CMAKE_HOME_DIRECTORY}/examples/java/pingPong)
 add_subdirectory(${CMAKE_HOME_DIRECTORY}/examples/java/priority)
 add_subdirectory(${CMAKE_HOME_DIRECTORY}/examples/java/startKillTime)
+add_subdirectory(${CMAKE_HOME_DIRECTORY}/examples/java/surfPlugin)
 add_subdirectory(${CMAKE_HOME_DIRECTORY}/examples/java/suspend)
 add_subdirectory(${CMAKE_HOME_DIRECTORY}/examples/java/tracing)
 
index f1c43de..8091c98 100644 (file)
@@ -29,8 +29,6 @@ message("-- [Java] simgrid-java includes: ${CHECK_INCLUDES}")
 target_link_libraries(simgrid-java simgrid)
 
 
-
-
 if(WIN32)
   exec_program("java -d32 -version"
                 OUTPUT_VARIABLE IS_32_BITS_JVM)
@@ -65,6 +63,8 @@ set(LIBSIMGRID_SO
   libsimgrid${CMAKE_SHARED_LIBRARY_SUFFIX})
 set(LIBSIMGRID_JAVA_SO
   ${CMAKE_SHARED_LIBRARY_PREFIX}simgrid-java${CMAKE_SHARED_LIBRARY_SUFFIX})
+set(LIBSURF_JAVA_SO
+  ${CMAKE_SHARED_LIBRARY_PREFIX}surf-java${CMAKE_SHARED_LIBRARY_SUFFIX})
 
 ## Don't strip libraries if not in release mode
 ##
@@ -78,15 +78,16 @@ endif()
 ##
 if(CMAKE_VERSION VERSION_LESS "2.8.12")
   set(CMAKE_JAVA_TARGET_OUTPUT_NAME simgrid)
-  add_jar(simgrid-java_pre_jar ${JMSG_JAVA_SRC})
+  add_jar(simgrid-java_pre_jar ${JMSG_JAVA_SRC} ${JSURF_JAVA_GENERATED_SRC})
 else()
-  add_jar(simgrid-java_pre_jar ${JMSG_JAVA_SRC} OUTPUT_NAME simgrid)
+  add_jar(simgrid-java_pre_jar ${JMSG_JAVA_SRC} ${JSURF_JAVA_GENERATED_SRC} OUTPUT_NAME simgrid)
 endif()
 
 set(JAVA_BUNDLE "${CMAKE_HOME_DIRECTORY}/buildtools/Cmake/Scripts/java_bundle.sh")
 set(JAVA_BUNDLE_SO_FILES
   ${CMAKE_BINARY_DIR}/lib/${LIBSIMGRID_SO}
   ${CMAKE_BINARY_DIR}/lib/${LIBSIMGRID_JAVA_SO}
+  ${CMAKE_BINARY_DIR}/lib/${LIBSURF_JAVA_SO}
   )
 set(JAVA_BUNDLE_TXT_FILES
   ${CMAKE_HOME_DIRECTORY}/COPYING
@@ -111,3 +112,15 @@ add_custom_command(
   COMMAND ${CMAKE_COMMAND} -E touch ${SIMGRID_JAR}_finalized
   )
 add_custom_target(simgrid-java_jar ALL DEPENDS ${SIMGRID_JAR}_finalized)
+
+set(CMAKE_SWIG_FLAGS "-package" "org.simgrid.surf")
+set(CMAKE_SWIG_OUTDIR "${CMAKE_HOME_DIRECTORY}/src/bindings/java/org/simgrid/surf")
+set(CMAKE_SWIG_OUTDIR "${CMAKE_BINARY_DIR}/src/bindings/java/org/simgrid/surf")
+
+set_source_files_properties(${JSURF_SWIG_SRC} PROPERTIES CPLUSPLUS 1)
+#set_source_files_properties(${SURF_SWIG_FILE} PROPERTIES SWIG_FLAGS "-includeall")
+include_directories(${JNI_INCLUDE_DIRS})
+swig_add_module(surf-java java ${JSURF_SWIG_SRC} ${JSURF_JAVA_C_SRC})
+swig_link_libraries(surf-java simgrid)
+
+add_dependencies(simgrid-java surf-java)
index 1c232b8..c0d51ce 100755 (executable)
@@ -20,7 +20,7 @@ JAVA=$2
 STRIP=$3
 shift 3
 
-JSG_BUNDLE=$("$JAVA" -classpath "$SIMGRID_JAR" org.simgrid.msg.NativeLib)
+JSG_BUNDLE=$("$JAVA" -classpath "$SIMGRID_JAR" org.simgrid.NativeLib)
 
 # sanity check
 case "$JSG_BUNDLE" in
diff --git a/contrib/benchmarking_code_block/Rdhist.R b/contrib/benchmarking_code_block/Rdhist.R
new file mode 100644 (file)
index 0000000..76ff210
--- /dev/null
@@ -0,0 +1,313 @@
+#-------------------------------------------------------------------------------
+# Copyright (c) 2012 University of Illinois, NCSA.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the
+# University of Illinois/NCSA Open Source License
+# which accompanies this distribution, and is available at
+# http://opensource.ncsa.illinois.edu/license.html
+#-------------------------------------------------------------------------------
+##--------------------------------------------------------------------------------------------------#
+##' Variable-width (dagonally cut) histogram
+##'
+##'
+##' When constructing a histogram, it is common to make all bars the same width.
+##' One could also choose to make them all have the same area.
+##' These two options have complementary strengths and weaknesses; the equal-width histogram oversmooths in regions of high density, and is poor at identifying sharp peaks; the equal-area histogram oversmooths in regions of low density, and so does not identify outliers.
+##' We describe a compromise approach which avoids both of these defects. We regard the histogram as an exploratory device, rather than as an estimate of a density.
+##' @name dhist
+##' @title Diagonally Cut Histogram
+##' @param x is a numeric vector (the data)
+##' @param a is the scaling factor, default is 5 * IQR
+##' @param nbins is the number of bins, default is assigned by the Stuges method
+##' @param rx is the range used for the left of the left-most bin to the right of the right-most bin
+##' @param eps used to set artificial bound on min width / max height of bins as described in Denby and Mallows (2009) on page 24.
+##' @param xlab is label for the x axis
+##' @param plot = TRUE produces the plot, FALSE returns the heights, breaks and counts
+##' @param lab.spikes = TRUE labels the \% of data in the spikes
+##' @return list with two elements, heights of length n and breaks of length n+1 indicating the heights and break points of the histogram bars.
+##' @author Lorraine Denby, Colin Mallows
+##' @references Lorraine Denby, Colin Mallows. Journal of Computational and Graphical Statistics. March 1, 2009, 18(1): 21-31. doi:10.1198/jcgs.2009.0002.
+dhist <- function(x, a=5*iqr(x),
+                nbins=nclass.Sturges(x), rx = range(x,na.rm = TRUE),
+                eps=.15, xlab = "x", plot = TRUE,lab.spikes = TRUE)
+{
+
+  if(is.character(nbins))
+    nbins <- switch(casefold(nbins),
+                    sturges = nclass.Sturges(x),
+                    fd = nclass.FD(x),
+                    scott = nclass.scott(x),
+                    stop("Nclass method not recognized"))
+  else if(is.function(nbins))
+    nbins <- nbins(x)
+
+  x <- sort(x[!is.na(x)])
+  if(a == 0)
+    a <- diff(range(x))/100000000
+  if(a != 0 & a != Inf) {
+    n <- length(x)
+    h <- (rx[2] + a - rx[1])/nbins
+    ybr <- rx[1] + h * (0:nbins)
+    yupper <- x + (a * (1:n))/n
+                                        # upper and lower corners in the ecdf
+    ylower <- yupper - a/n
+                                        #
+    cmtx <- cbind(cut(yupper, breaks = ybr), cut(yupper, breaks =
+                                ybr, left.include = TRUE), cut(ylower, breaks = ybr),
+                  cut(ylower, breaks = ybr, left.include = TRUE))
+    cmtx[1, 3] <- cmtx[1, 4] <- 1
+                                        # to replace NAs when default r is used
+    cmtx[n, 1] <- cmtx[n, 2] <- nbins
+                                        #
+                                        #checksum <- apply(cmtx, 1, sum) %% 4
+    checksum <- (cmtx[, 1] + cmtx[, 2] + cmtx[, 3] + cmtx[, 4]) %%
+    4
+                                        # will be 2 for obs. that straddle two bins
+    straddlers <- (1:n)[checksum == 2]
+                                        # to allow for zero counts
+    if(length(straddlers) > 0) {
+      counts <- table(c(1:nbins, cmtx[ - straddlers, 1]))
+    } else {
+      counts <- table(c(1:nbins, cmtx[, 1]))
+    }
+    counts <- counts - 1
+                                        #
+    if(length(straddlers) > 0) {
+      for(i in straddlers) {
+        binno <- cmtx[i, 1]
+        theta <- ((yupper[i] - ybr[binno]) * n)/a
+        counts[binno - 1] <- counts[binno - 1] + (
+                                                  1 - theta)
+        counts[binno] <- counts[binno] + theta
+      }
+    }
+    xbr <- ybr
+    xbr[-1] <- ybr[-1] - (a * cumsum(counts))/n
+    spike<-eps*diff(rx)/nbins
+    flag.vec<-c(diff(xbr)<spike,F)
+    if ( sum(abs(diff(xbr))<=spike) >1) {
+      xbr.new<-xbr
+      counts.new<-counts
+      diff.xbr<-abs(diff(xbr))
+      amt.spike<-diff.xbr[length(diff.xbr)]
+      for (i in rev(2:length(diff.xbr))) {
+        if (diff.xbr[i-1] <= spike&diff.xbr[i] <= spike &
+            !is.na(diff.xbr[i])) {
+          amt.spike <- amt.spike+diff.xbr[i-1]
+          counts.new[i-1] <- counts.new[i-1]+counts.new[i]
+          xbr.new[i] <- NA
+          counts.new[i] <- NA
+          flag.vec[i-1] <- T
+        }
+        else amt.spike<-diff.xbr[i-1]
+      }
+      flag.vec<-flag.vec[!is.na(xbr.new)]
+      flag.vec<-flag.vec[-length(flag.vec)]
+      counts<-counts.new[!is.na(counts.new)]
+      xbr<-xbr.new[!is.na(xbr.new)]
+
+    }
+    else flag.vec<-flag.vec[-length(flag.vec)]
+    widths <- abs(diff(xbr))
+    ## N.B. argument "widths" in barplot must be xbr
+    heights <- counts/widths
+  }
+  bin.size <- length(x)/nbins
+  cut.pt <- unique(c(min(x) - abs(min(x))/1000,
+                     approx(seq(length(x)), x, (1:(nbins - 1)) * bin.size, rule = 2)$y, max(x)))
+  aa <- hist(x, breaks = cut.pt, plot = FALSE, probability = TRUE)
+  if(a == Inf) {
+    heights <- aa$counts
+    xbr <- aa$breaks
+  }
+  amt.height<-3
+  q75<-quantile(heights,.75)
+  if (sum(flag.vec)!=0) {
+    amt<-max(heights[!flag.vec])
+    ylim.height<-amt*amt.height
+    ind.h<-flag.vec&heights> ylim.height
+    flag.vec[heights<ylim.height*(amt.height-1)/amt.height]<-F
+    heights[ind.h] <- ylim.height
+  }
+  amt.txt<-0
+  end.y<-(-10000)
+  if(plot) {
+    barplot(heights, abs(diff(xbr)), space = 0, density = -1, xlab =
+            xlab, plot = TRUE, xaxt = "n",yaxt='n')
+    at <- pretty(xbr)
+    axis(1, at = at - xbr[1], labels = as.character(at))
+    if (lab.spikes) {
+      if (sum(flag.vec)>=1) {
+        usr<-par('usr')
+        for ( i in seq(length(xbr)-1)) {
+          if (!flag.vec[i]) {
+            amt.txt<-0
+            if (xbr[i]-xbr[1]<end.y) amt.txt<-1
+          }
+          else {
+            amt.txt<-amt.txt+1
+            end.y<-xbr[i]-xbr[1]+3*par('cxy')[1]
+          }
+          if (flag.vec[i]) {
+            txt<-paste(' ',format(round(counts[i]/
+                                        sum(counts)*100)),'%',sep='')
+            par(xpd = TRUE)
+            text(xbr[i+1]-xbr[1],ylim.height-par('cxy')[2]*(amt.txt-1),txt, adj=0)
+          }}
+      }
+      else print('no spikes or more than one spike')
+    }
+    invisible(list(heights = heights, xbr = xbr))
+  }
+  else {
+    return(list(heights = heights, xbr = xbr,counts=counts))
+  }
+}
+#==================================================================================================#
+
+
+#--------------------------------------------------------------------------------------------------#
+##' Calculate interquartile range
+##'
+##' Calculates the 25th and 75th quantiles given a vector x; used in function \link{dhist}.
+##' @name iqr
+##' @title Interquartile range
+##' @param x vector
+##' @return numeric vector of length 2, with the 25th and 75th quantiles of input vector x.
+iqr <- function(x){
+  return(diff(quantile(x, c(0.25, 0.75), na.rm = TRUE)))
+}
+##==================================================================================================#
+
+##--------------------------------------------------------------------------------------------------#
+##' Creates empty ggplot object
+##'
+##' An empty base plot to which layers created by other functions
+##' (\code{\link{plot.data}}, \code{\link{plot.prior.density}},
+##' \code{\link{plot.posterior.density}}) can be added.
+##' @name create.base.plot
+##' @title Create Base Plot
+##' @return empty ggplot object
+##' @export
+##' @author David LeBauer
+create.base.plot <- function() {
+  base.plot <- ggplot()
+  return(base.plot)
+}
+#==================================================================================================#
+
+
+
+
+##--------------------------------------------------------------------------------------------------#
+##' Add data to an existing plot or create a new one from \code{\link{create.base.plot}}
+##'
+##' Used to add raw data or summary statistics to the plot of a distribution.
+##' The height of Y is arbitrary, and can be set to optimize visualization.
+##' If SE estimates are available, tehse wil be plotted
+##' @name plot.data
+##' @title Add data to plot
+##' @param trait.data data to be plotted
+##' @param base.plot a ggplot object (grob),
+##' created by \code{\link{create.base.plot}} if none provided
+##' @param ymax maximum height of y
+##' @seealso \code{\link{create.base.plot}}
+##' @return updated plot object
+##' @author David LeBauer
+##' @export
+##' @examples
+##' \dontrun{plot.data(data.frame(Y = c(1, 2), se = c(1,2)), base.plot = NULL, ymax = 10)}
+plot.data <- function(trait.data, base.plot = NULL, ymax, color = 'black') {
+  if(is.null(base.plot)) base.plot <- create.base.plot()
+  n.pts <- nrow(trait.data)
+  if(n.pts == 1){
+    ymax <- ymax/8
+  } else if (n.pts < 5) {
+    ymax <- ymax / 4
+  } else {
+    ymax <- ymax / 2
+  }
+  y.pts <- seq(0, ymax, length.out = 1 + n.pts)[-1]
+  plot.data <- data.frame(x = trait.data$Y,
+                          y = y.pts,
+                          se = trait.data$se,
+                          control = !trait.data$trt == 1 & trait.data$ghs == 1)
+  new.plot <- base.plot +
+    geom_point(data = plot.data,
+               aes(x = x, y = y,
+               color = control)) +
+                 geom_segment(data = plot.data,
+                              aes(x = x - se, y = y, xend = x + se, yend = y,
+                                  color = control)) +
+                                    scale_color_manual(values = c('black', 'grey')) +
+                                      opts(legend_position = "none")
+  return(new.plot)
+}
+##==================================================================================================#
+
+
+#--------------------------------------------------------------------------------------------------#
+##' Add borders to .. content for \description{} (no empty lines) ..
+##'
+##' Has ggplot2 display only specified borders, e.g. ("L"-shaped) borders, rather than a rectangle or no border. Note that the order can be significant; for example, if you specify the L border option and then a theme, the theme settings will override the border option, so you need to specify the theme (if any) before the border option, as above.
+##' @name theme_border
+##' @title Theme border for plot
+##' @param type
+##' @param colour
+##' @param size
+##' @param linetype
+##' @return adds borders to ggplot as a side effect
+##' @author Rudolf Cardinal
+##' @author \url{ggplot2 google group}{https://groups.google.com/forum/?fromgroups#!topic/ggplot2/-ZjRE2OL8lE}
+##' @examples
+##' \dontrun{
+##' df = data.frame( x=c(1,2,3), y=c(4,5,6) )
+##' ggplot(data=df, aes(x=x, y=y)) + geom_point() + theme_bw() +
+##' opts(panel.border = theme_border(c("bottom","left")) )
+##' ggplot(data=df, aes(x=x, y=y)) + geom_point() + theme_bw() +
+##' opts(panel.border = theme_border(c("b","l")) )
+##' }
+theme_border <- function(type = c("left", "right", "bottom", "top",
+                           "none"), colour = "black", size = 1, linetype = 1) {
+  type <- match.arg(type, several.ok=TRUE)
+  structure(
+            function(x = 0, y = 0, width = 1, height = 1, ...) {
+              xlist <- c()
+              ylist <- c()
+              idlist <- c()
+              if ("bottom" %in% type) { # bottom
+                xlist <- append(xlist, c(x, x+width))
+                ylist <- append(ylist, c(y, y))
+                idlist <- append(idlist, c(1,1))
+              }
+              if ("top" %in% type) { # top
+                xlist <- append(xlist, c(x, x+width))
+                ylist <- append(ylist, c(y+height, y+height))
+                idlist <- append(idlist, c(2,2))
+              }
+              if ("left" %in% type) { # left
+                xlist <- append(xlist, c(x, x))
+                ylist <- append(ylist, c(y, y+height))
+                idlist <- append(idlist, c(3,3))
+              }
+              if ("right" %in% type) { # right
+                xlist <- append(xlist, c(x+width, x+width))
+                ylist <- append(ylist, c(y, y+height))
+                idlist <- append(idlist, c(4,4))
+              }
+              polylineGrob(
+                           x=xlist, y=ylist, id=idlist, ..., default.units = "npc",
+                           gp=gpar(lwd=size, col=colour, lty=linetype),
+                           )
+            },
+            class = "theme",
+            type = "box",
+            call = match.call()
+            )
+}
+#==================================================================================================#
+
+
+####################################################################################################
+### EOF. End of R script file.                         
+####################################################################################################
index 92fe61b..991060e 100644 (file)
@@ -3,15 +3,55 @@
 # Can be called from the bash script with the following code:
 # export R_INPUT=$inputfile
 # export R_OUTPUT=$outputfile
+# export R_TYPE=$hist_type
+
 # R CMD BATCH $this_script.R
+#or
+# Rscript $this_script.R
 
 # Use functions from bench.h to benchmark execution time of the desired block,
 # then Rhist.R script to read all timings and produce histograms
 # and finally inject.h to inject values instead of executing block
 
+# This is a small function to help merging empty nbins for dhist histograms
+merge_empty_bins <- function (h)
+{
+  i<-1
+  j<-1
+  counts2<--1
+  breaks2<-h$breaks[1]
+
+  if (length(h$counts)>1)
+    for(i in 1:(length(h$counts)-1))
+      {
+        if(h$counts[i]!=0 || h$counts[i+1]!=0)
+          {
+            counts2[j]<-h$counts[i]
+            breaks2[j+1]<-h$breaks[i+1];
+            j<-j+1
+          }
+      }
   
+  counts2[j]<-h$counts[length(h$counts)]
+  breaks2[j+1]<-h$breaks[length(h$breaks)]
+
+  h$counts<-counts2
+  h$breaks<-breaks2
+
+  return (h)
+}
+
+# Main
+source("analysis/hist_script/Rdhist.R")
+
 inputfile<-Sys.getenv("R_INPUT")
 outputfile<-Sys.getenv("R_OUTPUT")
+type<-Sys.getenv("R_TYPE")
+
+if (!(type %in% c("mean","default","sturges","scott")))
+  {
+    stop("Wrong histogram type")
+  }
 
 df<-read.table(inputfile,header=F)
 df<-df[,c(1,4)]
@@ -21,17 +61,49 @@ attach(df)
 for(i in unique(NAME))
 {
   vector1<-df[NAME==i,2]
-  h<-hist(vector1)
-  
+
+  if (length(vector1)==1)
+    {
+      #If there is only one element
+      h<-hist(vector1) # Just for R compatibility reasons
+      h$breaks<-c(vector1,vector1)
+      h$counts<-1
+    }
+  else
+    {
+      if (type=="mean")
+        {
+          #Mean value only
+          h<-hist(vector1) # Just for R compatibility reasons
+          h$breaks<-c(mean(vector1),mean(vector1))
+          h$counts<-length(vector1)
+        }
+      else
+        if (type=="default")
+          #Standard HISTOGRAM:
+          h<-hist(vector1)
+        else
+          {
+            #Dhist:
+            h<-dhist(vector1,nbins=type, plot = FALSE, lab.spikes = FALSE, a=5*iqr(vector1), eps=0.15)
+            h$breaks<-h$xbr
+            h$count<-as.vector(h$counts)
+            h$counts<-h$count
+            h<-merge_empty_bins(h)
+          }
+    }
+    
   cat(i, file = outputfile, sep = "\t", append = TRUE)
-  cat("  ", file = outputfile, sep = "\t", append = TRUE)
-  cat(sprintf("%.8f", mean(vector1)), file =outputfile, sep = "\t ", append = TRUE)
+  cat("\t", file = outputfile,  append = TRUE)
+  cat(sum(h$counts), file =outputfile, sep = "\t", append = TRUE)
+  cat("\t", file = outputfile,  append = TRUE)
+  cat(sprintf("%.8f", mean(vector1)), file =outputfile, sep = "\t", append = TRUE)
   cat("\t", file = outputfile,  append = TRUE)
   cat(length(h$breaks), file = outputfile, append = TRUE)
   cat("\t", file = outputfile,  append = TRUE)
-  cat(sprintf("%.8f", h$breaks), file = outputfile, sep = " \t", append = TRUE)
+  cat(sprintf("%.8f", h$breaks), file = outputfile, sep = "\t", append = TRUE)
   cat("\t", file = outputfile,  append = TRUE)
   h$density = h$counts/sum(h$counts)
-  cat(sprintf("%.14f", h$density), file = outputfile, sep = " \t", append = TRUE)
+  cat(sprintf("%.8f", h$density), file = outputfile, sep = "\t", append = TRUE)
   cat("\n", file = outputfile,  append = TRUE)
 }
diff --git a/contrib/benchmarking_code_block/Rplot_hist.R b/contrib/benchmarking_code_block/Rplot_hist.R
new file mode 100644 (file)
index 0000000..1f7487a
--- /dev/null
@@ -0,0 +1,72 @@
+# R script showing .pdf file with plots of all injection histograms for a certain file
+
+# Can be called from the command line with:
+# Rscript $this_script.R inputfile
+
+# Necessary libraries
+library(plyr)
+library(ggplot2)
+library(data.table)
+library(grid)
+
+# Functions for arranging multiple plots
+vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
+arrange_ggplot2 <- function(list, nrow=NULL, ncol=NULL, as.table=FALSE) {
+n <- length(list)
+if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
+if(is.null(nrow)) { nrow = ceiling(n/ncol)}
+if(is.null(ncol)) { ncol = ceiling(n/nrow)}
+## NOTE see n2mfrow in grDevices for possible alternative
+grid.newpage()
+pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
+ii.p <- 1
+for(ii.row in seq(1, nrow)){
+ii.table.row <- ii.row
+if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
+for(ii.col in seq(1, ncol)){
+ii.table <- ii.p
+if(ii.p > n) break
+print(list[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
+ii.p <- ii.p + 1
+}
+}
+}
+
+### Main
+
+# Reading command line argument with the input file path
+args <- commandArgs(trailingOnly = TRUE)
+fp  <- file(args[1], open = "r")
+
+plots<-list()
+i<-1
+
+# Reading histograms one by one, line by line
+while (length(oneLine <- readLines(fp, n = 1, warn = FALSE)) > 0)
+{ myVector <- (strsplit(oneLine, "\t")) 
+  
+  dfl <- ldply (myVector, data.frame)
+
+  name<-as.character(dfl[1,])
+  nbins<-as.numeric(as.character(dfl[4,]))
+  allbreaks<-as.numeric(as.character(dfl[5:(5+nbins-1),]))
+  
+  dh<-data.frame(Name=as.character(dfl[1,]), Total=as.numeric(as.character(dfl[2,])), Mean=as.numeric(as.character(dfl[3,])), Nbins=as.numeric(as.character(dfl[4,])))
+  dh<-cbind(dh,Bstart=allbreaks[-length(allbreaks)])
+  dh<-cbind(dh,Bend=allbreaks[-1])
+  dh<-cbind(dh,Density=as.numeric(as.character(dfl[(5+nbins):(5+nbins*2-2),])))
+
+  # Plotting single histogram, if it only has one value then use geom_bar
+  if (nbins > 2)
+    plots[[i]]<-ggplot(data=data.frame(dh), aes(xmin=Bstart, xmax=Bend, ymin=0, ymax=Density)) + geom_rect(aes(fill=Density)) + theme_bw() + scale_x_continuous("Time [s]", allbreaks) + labs(title=name, y=element_text("Density %"))
+  else
+    plots[[i]]<-ggplot(data=data.frame(dh), aes(factor(Bstart))) + geom_bar(aes(fill=Density)) + theme_bw() + labs(title=name, y=element_text("Density %"), x=element_text("Time [s]"))
+
+  i<-i+1
+}
+
+# Printing all plots together in a table
+arrange_ggplot2(plots, as.table=TRUE)
+
+# End
+write("Done producing a histogram plot. Open Rplots.pdf located in this folder to see the results", stdout())
index f4d9fa2..57e2c82 100644 (file)
 #include "xbt/dict.h"
 #include "xbt/sysdep.h"
 
-#define MAX_LINE_INJ 1000
+#define MAX_LINE_INJ 10000
 
 /*
  * Histogram entry for each measured block
  * Each entry is guarded inside xbt dictionary which is read from the file */
 typedef struct xbt_hist {
        int n;
+       int counts;
        double mean;
        double *breaks;
        double *percentage;
@@ -68,7 +69,7 @@ static inline void xbt_inject_init(char *inputfile)
                printf("Error input file is empty!");//Skipping first row
        while (fgets(line, 200, fpInput) != NULL)
        {
-               key = strtok(line, " \t");
+               key = strtok(line, "\t");
 
                data = xbt_dict_get_or_null(mydict, key);
                if (data)
@@ -77,15 +78,16 @@ static inline void xbt_inject_init(char *inputfile)
                data = (xbt_hist_t *) xbt_new(xbt_hist_t, 1);
 
                data->block_id = key;
-               data->mean = atof(strtok(NULL, " \t"));
-               data->n = atoi(strtok(NULL, " \t"));
+               data->counts = atoi(strtok(NULL, "\t"));
+               data->mean = atof(strtok(NULL, "\t"));
+               data->n = atoi(strtok(NULL, "\t"));
 
                data->breaks = (double*) malloc(sizeof(double) * data->n);
                data->percentage = (double*) malloc(sizeof(double) * (data->n - 1));
                for (i = 0; i < data->n; i++)
-                       data->breaks[i] = atof(strtok(NULL, " \t"));
+                       data->breaks[i] = atof(strtok(NULL, "\t"));
                for (i = 0; i < (data->n - 1); i++)
-                       data->percentage[i] = atof(strtok(NULL, " \t"));
+                       data->percentage[i] = atof(strtok(NULL, "\t"));
 
                xbt_dict_set(mydict, key, data, NULL);
        }
@@ -103,7 +105,10 @@ static inline void inject_init_starpu(char *inputfile, xbt_dict_t *dict, RngStre
        mydict = *dict;
        FILE* fpInput = fopen(inputfile, "r");
        if (fpInput == NULL)
+       {
                printf("Error while opening the inputfile");
+               return;
+       }
 
        fseek(fpInput, 0, 0);
 
@@ -113,12 +118,15 @@ static inline void inject_init_starpu(char *inputfile, xbt_dict_t *dict, RngStre
        xbt_hist_t* data;
 
        if (fgets(line, MAX_LINE_INJ, fpInput) == NULL)
+       {
                printf("Error input file is empty!");//Skipping first row
+               return;
+       }
 
 
        while (fgets(line, MAX_LINE_INJ, fpInput) != NULL)
        {
-               key = strtok(line, " \t");
+               key = strtok(line, "\t");
 
                data = xbt_dict_get_or_null(mydict, key);
                if (data)
@@ -126,16 +134,17 @@ static inline void inject_init_starpu(char *inputfile, xbt_dict_t *dict, RngStre
 
                data = (xbt_hist_t *) xbt_new(xbt_hist_t, 1);
                data->block_id = key;
-               data->mean = atof(strtok(NULL, " \t"));
-               data->n = atoi(strtok(NULL, " \t"));
+               data->counts = atoi(strtok(NULL, "\t"));
+               data->mean = atof(strtok(NULL, "\t"));
+               data->n = atoi(strtok(NULL, "\t"));
                data->breaks = (double*) malloc(sizeof(double) * data->n);
                data->percentage = (double*) malloc(sizeof(double) * (data->n - 1));
 
                for (i = 0; i < data->n; i++)
-                       data->breaks[i] = atof(strtok(NULL, " \t"));
+                       data->breaks[i] = atof(strtok(NULL, "\t"));
                        for (i = 0; i < (data->n - 1); i++)
                        {
-                               data->percentage[i] = atof(strtok(NULL, " \t"));
+                               data->percentage[i] = atof(strtok(NULL, "\t"));
                        }
 
                xbt_dict_set(mydict, key, data, NULL);
diff --git a/examples/java/surfPlugin/CMakeLists.txt b/examples/java/surfPlugin/CMakeLists.txt
new file mode 100644 (file)
index 0000000..2773890
--- /dev/null
@@ -0,0 +1,47 @@
+cmake_minimum_required(VERSION 2.6)
+
+set(example java_surf_plugin)
+set(sources
+   ${CMAKE_CURRENT_SOURCE_DIR}/TestPlugin.java
+   ${CMAKE_CURRENT_SOURCE_DIR}/TracePlugin.java
+   ${CMAKE_CURRENT_SOURCE_DIR}/Sender.java
+   ${CMAKE_CURRENT_SOURCE_DIR}/Receiver.java
+  )
+
+if(enable_java)
+  add_custom_command(
+    COMMENT "Building ${example}..."
+    OUTPUT ${example}_compiled
+    DEPENDS ${sources} simgrid-java_jar ${SIMGRID_JAR}
+    COMMAND ${JAVA_COMPILE} -classpath ${SIMGRID_JAR}
+                             -d ${CMAKE_CURRENT_BINARY_DIR}/.. ${sources}
+    COMMAND ${CMAKE_COMMAND} -E remove ${example}_compiled
+    COMMAND ${CMAKE_COMMAND} -E touch ${example}_compiled
+  )
+  add_custom_target(${example} ALL DEPENDS ${example}_compiled)
+endif()
+
+set(tesh_files
+  ${tesh_files}
+  ${CMAKE_CURRENT_SOURCE_DIR}/surf_plugin.tesh
+  PARENT_SCOPE
+  )
+set(xml_files
+  ${xml_files}
+  ${CMAKE_CURRENT_SOURCE_DIR}/surfPluginPlatform.xml
+  ${CMAKE_CURRENT_SOURCE_DIR}/surfPluginDeployment.xml  
+  PARENT_SCOPE
+  )
+set(examples_src
+  ${examples_src}
+  ${sources}
+  PARENT_SCOPE
+  )
+set(bin_files
+  ${bin_files}
+  PARENT_SCOPE
+  )
+set(txt_files
+  ${txt_files}
+  PARENT_SCOPE
+  )
diff --git a/examples/java/surfPlugin/Receiver.java b/examples/java/surfPlugin/Receiver.java
new file mode 100644 (file)
index 0000000..8d8158f
--- /dev/null
@@ -0,0 +1,36 @@
+/* Copyright (c) 2006-2014. The SimGrid Team.
+ * All rights reserved.                                                     */
+
+/* This program is free software; you can redistribute it and/or modify it
+ * under the terms of the license (GNU LGPL) which comes with this package. */
+
+package surfPlugin;
+import org.simgrid.msg.Host;
+import org.simgrid.msg.Msg;
+import org.simgrid.msg.MsgException;
+import org.simgrid.msg.Task;
+import org.simgrid.msg.Process;
+
+public class Receiver extends Process {
+   public Receiver(Host host, String name, String[]args) {
+               super(host,name,args);
+   } 
+   final double commSizeLat = 1;
+   final double commSizeBw = 100000000;
+    
+   public void main(String[] args) throws MsgException {
+        
+      Msg.info("helloo!");
+      double communicationTime=0;
+
+      Msg.info("try to get a task");
+        
+      Task task = Task.receive(getHost().getName());
+      double timeGot = Msg.getClock();
+            
+      Msg.info("Got at time "+ timeGot);
+      task.execute();
+       
+      Msg.info("goodbye!");
+    }
+}
diff --git a/examples/java/surfPlugin/Sender.java b/examples/java/surfPlugin/Sender.java
new file mode 100644 (file)
index 0000000..2f4a382
--- /dev/null
@@ -0,0 +1,55 @@
+/* Copyright (c) 2006-2014. The SimGrid Team.
+ * All rights reserved.                                                     */
+
+/* This program is free software; you can redistribute it and/or modify it
+ * under the terms of the license (GNU LGPL) which comes with this package. */
+
+package surfPlugin;
+import org.simgrid.msg.Host;
+import org.simgrid.msg.HostNotFoundException;
+import org.simgrid.msg.Msg;
+import org.simgrid.msg.MsgException;
+import org.simgrid.msg.Process;
+import org.simgrid.msg.Task;
+
+public class Sender extends Process {
+       public Sender(Host host, String name, String[] args) {
+               super(host,name,args);
+       }
+    private final double commSizeLat = 1;
+    final double commSizeBw = 100000000;
+   
+    public void main(String[] args) throws MsgException {
+       
+       Msg.info("helloo!");
+        
+       int hostCount = args.length;
+        
+       Msg.info("host count: " + hostCount);
+       String mailboxes[] = new String[hostCount]; 
+       double time;
+       double computeDuration = 10000;
+       Task task;
+        
+       for(int pos = 0; pos < args.length ; pos++) {
+         try {
+            mailboxes[pos] = Host.getByName(args[pos]).getName();
+         } catch (HostNotFoundException e) {
+            Msg.info("Invalid deployment file: " + e.toString());           
+            System.exit(1);
+         }
+        }
+        
+        for (int pos = 0; pos < hostCount; pos++) { 
+          time = Msg.getClock(); 
+            
+          Msg.info("sender time: " + time);
+          
+          task = new Task("no name",computeDuration,commSizeLat);
+            
+          task.send(mailboxes[pos]);
+        } 
+        
+        Msg.info("goodbye!");
+    }
+}
diff --git a/examples/java/surfPlugin/TestPlugin.java b/examples/java/surfPlugin/TestPlugin.java
new file mode 100644 (file)
index 0000000..cf0752b
--- /dev/null
@@ -0,0 +1,37 @@
+/* Copyright (c) 2006-2014. The SimGrid Team.
+ * All rights reserved.                                                     */
+
+/* This program is free software; you can redistribute it and/or modify it
+ * under the terms of the license (GNU LGPL) which comes with this package. */
+
+package surfPlugin;
+import org.simgrid.msg.Msg;
+import org.simgrid.msg.NativeException;
+import org.simgrid.surf.Surf;
+import org.simgrid.surf.Cpu;
+
+public class TestPlugin {
+
+  /* This only contains the launcher. If you do nothing more than than you can run 
+  *   java simgrid.msg.Msg
+  * which also contains such a launcher
+  */
+  //static TracePlugin tp = new TracePlugin();
+  
+  public static void main(String[] args) throws NativeException {      
+    /* initialize the MSG simulation. Must be done before anything else (even logging). */
+    Msg.init(args);
+    if(args.length < 2) {
+      Msg.info("Usage   : TestPlugin platform_file deployment_file");
+      Msg.info("example : TestPlugin ping_pong_platform.xml ping_pong_deployment.xml");
+      System.exit(1);
+    }
+    TracePlugin tp = new TracePlugin();
+         
+    /* construct the platform and deploy the application */
+    Msg.createEnvironment(args[0]);
+    Msg.deployApplication(args[1]);
+    /*  execute the simulation. */
+    Msg.run();
+  }
+}
diff --git a/examples/java/surfPlugin/TracePlugin.java b/examples/java/surfPlugin/TracePlugin.java
new file mode 100644 (file)
index 0000000..e121274
--- /dev/null
@@ -0,0 +1,45 @@
+package surfPlugin;
+
+import org.simgrid.surf.*;
+import org.simgrid.msg.Msg;
+import java.util.HashMap;
+
+public class TracePlugin extends Plugin {
+
+  public TracePlugin() {
+    activateCpuCreatedCallback(); 
+    //activateCpuDestructedCallback();
+    activateCpuStateChangedCallback();                
+    activateCpuActionStateChangedCallback();
+
+    activateNetworkLinkCreatedCallback(); 
+    //activateCpuDestructedCallback();
+    activateNetworkLinkStateChangedCallback();                
+    activateNetworkActionStateChangedCallback();
+  }
+  public void cpuCreatedCallback(Cpu cpu) {
+    Msg.info("Trace: Cpu created "+cpu.getName());
+  }
+
+  public void cpuStateChangedCallback(Cpu cpu){
+    Msg.info("Trace: Cpu state changed "+cpu.getName());
+  }
+
+  public void cpuActionStateChangedCallback(CpuAction action){
+    Msg.info("Trace: CpuAction state changed "+action.getModel().getName());
+  }
+
+  public void networkLinkCreatedCallback(NetworkLink link) {
+    Msg.info("Trace: NetworkLink created "+link.getName());
+  }
+
+  public void networkLinkStateChangedCallback(NetworkLink link){
+    Msg.info("Trace: NetworkLink state changed "+link.getName());
+  }
+
+  public void networkActionStateChangedCallback(NetworkAction action){
+    Msg.info("Trace: NetworkAction state changed "+action.getModel().getName());
+  }
+
+}
diff --git a/examples/java/surfPlugin/surfPluginDeployment.xml b/examples/java/surfPlugin/surfPluginDeployment.xml
new file mode 100644 (file)
index 0000000..9101480
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version='1.0'?>
+<!DOCTYPE platform SYSTEM "http://simgrid.gforge.inria.fr/simgrid.dtd">
+<platform version="3">
+  <process host="Jacquelin" function="surfPlugin.Sender">
+      <argument value="Boivin"/>
+  </process>
+<process host="Boivin" function="surfPlugin.Receiver"/>
+</platform>
diff --git a/examples/java/surfPlugin/surfPluginPlatform.xml b/examples/java/surfPlugin/surfPluginPlatform.xml
new file mode 100644 (file)
index 0000000..be9a6e1
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version='1.0'?>
+ <!DOCTYPE platform SYSTEM "http://simgrid.gforge.inria.fr/simgrid.dtd">
+ <platform version="3">
+ <AS  id="AS0"  routing="Full">
+   <host id="Jacquelin" power="137.333Mf"/>
+   <host id="Boivin" power="98.095Mf"/>
+   <link id="link" bandwidth="1MBps" latency="100ms"/>
+   <route src="Jacquelin" dst="Boivin">
+     <link_ctn id="link"/>
+   </route>
+ </AS>
+ </platform>
diff --git a/examples/java/surfPlugin/surf_plugin.tesh b/examples/java/surfPlugin/surf_plugin.tesh
new file mode 100644 (file)
index 0000000..c209537
--- /dev/null
@@ -0,0 +1,23 @@
+#! tesh
+
+$ java -classpath ${classpath:=.} surfPlugin/TestPlugin ${srcdir:=.}/surfPlugin/surfPluginPlatform.xml ${srcdir:=.}/surfPlugin/surfPluginDeployment.xml
+> [0.000000] [jmsg/INFO] Using regular java threads. Coroutines could speed your simulation up.
+> [0.000000] [jmsg/INFO] Trace: NetworkLink created __loopback__
+> [0.000000] [jmsg/INFO] Trace: NetworkLink state changed __loopback__
+> [0.000000] [jmsg/INFO] Trace: Cpu created Jacquelin
+> [0.000000] [jmsg/INFO] Trace: Cpu state changed Jacquelin
+> [0.000000] [jmsg/INFO] Trace: Cpu created Boivin
+> [0.000000] [jmsg/INFO] Trace: Cpu state changed Boivin
+> [0.000000] [jmsg/INFO] Trace: NetworkLink created link
+> [0.000000] [jmsg/INFO] Trace: NetworkLink state changed link
+> [Jacquelin:surfPlugin.Sender:(1) 0.000000] [jmsg/INFO] helloo!
+> [Jacquelin:surfPlugin.Sender:(1) 0.000000] [jmsg/INFO] host count: 1
+> [Jacquelin:surfPlugin.Sender:(1) 0.000000] [jmsg/INFO] sender time: 0.0
+> [Boivin:surfPlugin.Receiver:(2) 0.000000] [jmsg/INFO] helloo!
+> [Boivin:surfPlugin.Receiver:(2) 0.000000] [jmsg/INFO] try to get a task
+> [1.301001] [jmsg/INFO] Trace: NetworkAction state changed network
+> [Boivin:surfPlugin.Receiver:(2) 1.301001] [jmsg/INFO] Got at time 1.3010010824742269
+> [Jacquelin:surfPlugin.Sender:(1) 1.301001] [jmsg/INFO] goodbye!
+> [1.301103] [jmsg/INFO] Trace: CpuAction state changed cpu
+> [Boivin:surfPlugin.Receiver:(2) 1.301103] [jmsg/INFO] goodbye!
+> [1.301103] [jmsg/INFO] MSG_main finished; Cleaning up the simulation...
diff --git a/src/bindings/java/org/simgrid/NativeLib.java b/src/bindings/java/org/simgrid/NativeLib.java
new file mode 100644 (file)
index 0000000..130c904
--- /dev/null
@@ -0,0 +1,112 @@
+package org.simgrid;
+
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.File;
+
+public final class NativeLib {
+
+    public static String getPath() {
+        String prefix = "NATIVE";
+        String os = System.getProperty("os.name");
+        String arch = System.getProperty("os.arch");
+
+        if (os.toLowerCase().startsWith("^win"))
+            os = "Windows";
+        else if (os.contains("OS X"))
+            os = "Darwin";
+
+        if (arch.matches("^i[3-6]86$"))
+            arch = "x86";
+        else if (arch.equalsIgnoreCase("amd64"))
+            arch = "x86_64";
+
+        os = os.replace(' ', '_');
+        arch = arch.replace(' ', '_');
+
+        return prefix + "/" + os + "/" + arch + "/";
+    }
+    public static void nativeInit(String name) {
+        try {
+            /* prefer the version on disk, if existing */
+            System.loadLibrary(name);
+        } catch (UnsatisfiedLinkError e) {
+            /* If not found, unpack the one bundled into the jar file and use it */
+            loadLib(name);
+        }
+    }
+
+    private static void loadLib (String name) {
+        String Path = NativeLib.getPath();
+
+        String filename=name;
+        InputStream in = NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
+               
+        if (in == null) {
+           filename = "lib"+name+".so";
+            in = NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
+        } 
+       if (in == null) {
+           filename = name+".dll";
+           in =  NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
+       }  
+       if (in == null) {
+           filename = "lib"+name+".dll";
+           in =  NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
+       }  
+       if (in == null) {
+           filename = "lib"+name+".dylib";
+           in =  NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
+       }  
+       if (in == null) {
+           throw new RuntimeException("Cannot find library "+name+" in path "+Path+". Sorry, but this jar does not seem to be usable on your machine.");
+       }
+       try {
+           // We must write the lib onto the disk before loading it -- stupid operating systems
+           File fileOut = new File(filename);
+           fileOut = File.createTempFile(name+"-", ".tmp");
+           // don't leak the file on disk, but remove it on JVM shutdown
+           Runtime.getRuntime().addShutdownHook(new Thread(new FileCleaner(fileOut.getAbsolutePath())));
+           OutputStream out = new FileOutputStream(fileOut);
+                       
+           /* copy the library in position */  
+           byte[] buffer = new byte[4096]; 
+           int bytes_read; 
+           while ((bytes_read = in.read(buffer)) != -1)     // Read until EOF
+                   out.write(buffer, 0, bytes_read); 
+                     
+           /* close all file descriptors, and load that shit */
+           in.close();
+           out.close();
+           System.load(fileOut.getAbsolutePath());
+
+       } catch (Exception e) {
+           System.err.println("Cannot load the bindings to the "+name+" library: ");
+           e.printStackTrace();
+           System.err.println("This jar file does not seem to fit your system, sorry");
+           System.exit(1);
+       }
+    }
+    
+       /* A hackish mechanism used to remove the file containing our library when the JVM shuts down */
+       private static class FileCleaner implements Runnable {
+               private String target;
+               public FileCleaner(String name) {
+                       target = name;
+               }
+        public void run() {
+            try {
+                new File(target).delete();
+            } catch(Exception e) {
+                System.out.println("Unable to clean temporary file "+target+" during shutdown.");
+                e.printStackTrace();
+            }
+        }    
+       }
+
+
+    public static void main(String[] args) {
+        System.out.println(getPath());
+    }
+}
index 108c7b5..ec212a7 100644 (file)
@@ -7,6 +7,7 @@
  * under the terms of the license (GNU LGPL) which comes with this package. */
 
 package org.simgrid.msg;
+import org.simgrid.NativeLib;
 
 import java.io.FileOutputStream;
 import java.io.InputStream;
@@ -17,98 +18,19 @@ import java.io.File;
 public final class Msg {
        /* Statically load the library which contains all native functions used in here */
        static private boolean isNativeInited = false;
-       public static void nativeInit() {
-               if (isNativeInited)
-                       return;
-               try {
-                       /* prefer the version on disk, if existing */
-                       System.loadLibrary("simgrid-java");
-               } catch (UnsatisfiedLinkError e) {
-                       /* If not found, unpack the one bundled into the jar file and use it */
-                       loadLib("simgrid");
-                       loadLib("simgrid-java");
-               }
+        public static void nativeInit() {
+                if (isNativeInited)
+                      return;
+                NativeLib.nativeInit("simgrid");
+                NativeLib.nativeInit("simgrid-java");      
                isNativeInited = true;
+
        }
+
        static {
-               nativeInit();
+                nativeInit();
        }
-       private static void loadLib (String name) {
-               String Path = NativeLib.getPath();
-
-               String filename=name;
-               InputStream in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
-               
-               if (in == null) {
-                       filename = "lib"+name+".so";
-                       in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
-               } 
-               if (in == null) {
-                       filename = name+".dll";
-                       in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
-               }  
-               if (in == null) {
-                       filename = "lib"+name+".dll";
-                       in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
-               }  
-               if (in == null) {
-                       filename = "lib"+name+".dylib";
-                       in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
-               }  
-               if (in == null) {
-                       throw new RuntimeException("Cannot find library "+name+" in path "+Path+". Sorry, but this jar does not seem to be usable on your machine.");
-               }
-// Caching the file on disk: desactivated because it could fool the users              
-//             if (new File(filename).isFile()) {
-//                     // file was already unpacked -- use it directly
-//                     System.load(new File(".").getAbsolutePath()+File.separator+filename);
-//                     return;
-//             }
-               try {
-                       // We must write the lib onto the disk before loading it -- stupid operating systems
-                       File fileOut = new File(filename);
-//                     if (!new File(".").canWrite()) {
-//                             System.out.println("Cannot write in ."+File.separator+filename+"; unpacking the library into a temporary file instead");
-                               fileOut = File.createTempFile("simgrid-", ".tmp");
-                               // don't leak the file on disk, but remove it on JVM shutdown
-                               Runtime.getRuntime().addShutdownHook(new Thread(new FileCleaner(fileOut.getAbsolutePath())));
-//                     }
-//                     System.out.println("Unpacking SimGrid native library to " + fileOut.getAbsolutePath());
-                       OutputStream out = new FileOutputStream(fileOut);
-                       
-                       /* copy the library in position */  
-                       byte[] buffer = new byte[4096]; 
-                       int bytes_read; 
-                       while ((bytes_read = in.read(buffer)) != -1)     // Read until EOF
-                               out.write(buffer, 0, bytes_read); 
-                     
-                       /* close all file descriptors, and load that shit */
-                       in.close();
-                       out.close();
-                       System.load(fileOut.getAbsolutePath());
-               } catch (Exception e) {
-                       System.err.println("Cannot load the bindings to the simgrid library: ");
-                       e.printStackTrace();
-                       System.err.println("This jar file does not seem to fit your system, sorry");
-                       System.exit(1);
-               }
-       }               
-       /* A hackish mechanism used to remove the file containing our library when the JVM shuts down */
-       private static class FileCleaner implements Runnable {
-               private String target;
-               public FileCleaner(String name) {
-                       target = name;
-               }
-        public void run() {
-            try {
-                new File(target).delete();
-            } catch(Exception e) {
-                System.out.println("Unable to clean temporary file "+target+" during shutdown.");
-                e.printStackTrace();
-            }
-        }    
-       }
-
+        
     /** Retrieve the simulation time
      * @return The simulation time.
      */
diff --git a/src/bindings/java/surf.i b/src/bindings/java/surf.i
new file mode 100644 (file)
index 0000000..4d69190
--- /dev/null
@@ -0,0 +1,88 @@
+/* File : example.i */
+%module(directors="1") Surf
+
+%pragma(java) jniclassimports=%{
+import org.simgrid.NativeLib;
+
+%}
+%pragma(java) jniclasscode=%{
+  static {
+    NativeLib.nativeInit("surf-java");
+  }
+%}
+
+%{
+#include "src/surf/cpu_interface.hpp"
+#include "src/surf/network_interface.hpp"
+#include "src/bindings/java/surf_swig.hpp"
+#include "src/xbt/dict_private.h"
+typedef struct lmm_constraint *lmm_constraint_t;
+%}
+
+%feature("director") Plugin;
+
+%include "src/bindings/java/surf_swig.hpp"
+
+%nodefaultctor Model;
+class Model {
+public:
+  const char *getName();
+};
+
+class Resource {
+public:
+  Resource();
+  const char *getName();
+  virtual bool isUsed()=0;
+  lmm_constraint *getConstraint();
+  s_xbt_dict *getProperties();
+};
+
+class Cpu : public Resource {
+public:
+  Cpu();
+  ~Cpu();
+  double getCurrentPowerPeak();
+};
+
+class NetworkLink : public Resource {
+public:
+  NetworkLink();
+  ~NetworkLink();
+};
+
+class Action {
+public:
+  Model *getModel();
+};
+
+class CpuAction : public Action {
+public:
+%extend {
+  Cpu *getCpu() {return getActionCpu($self);}
+}
+};
+
+%nodefaultctor NetworkAction;
+class NetworkAction : public Action {
+public:
+%extend {
+  double getLatency() {return $self->m_latency;}
+}
+};
+
+
+%rename lmm_constraint LmmConstraint;
+struct lmm_constraint {
+%extend {
+  double getUsage() {return lmm_constraint_get_usage($self);}
+}
+};
+
+%rename s_xbt_dict XbtDict;
+struct s_xbt_dict {
+%extend {
+  char *getValue(char *key) {return (char*)xbt_dict_get_or_null($self, key);}
+}
+};
+
diff --git a/src/bindings/java/surf_swig.cpp b/src/bindings/java/surf_swig.cpp
new file mode 100644 (file)
index 0000000..6da728c
--- /dev/null
@@ -0,0 +1,42 @@
+#include <boost/lambda/bind.hpp>
+#include "src/surf/surf_interface.hpp"
+#include "surf_swig.hpp"
+
+double getClock() {
+  surf_get_clock();
+}
+
+void Plugin::activateCpuCreatedCallback(){
+  surf_callback_connect(cpuCreatedCallbacks, boost::bind(&Plugin::cpuCreatedCallback, this, _1));
+}
+
+void Plugin::activateCpuDestructedCallback(){
+  surf_callback_connect(cpuDestructedCallbacks, boost::bind(&Plugin::cpuDestructedCallback, this, _1));
+}
+
+void Plugin::activateCpuStateChangedCallback(){
+  surf_callback_connect(cpuStateChangedCallbacks, boost::bind(&Plugin::cpuStateChangedCallback, this, _1));
+}
+
+void Plugin::activateCpuActionStateChangedCallback(){
+  surf_callback_connect(cpuActionStateChangedCallbacks, boost::bind(&Plugin::cpuActionStateChangedCallback, this, _1));
+}
+
+
+void Plugin::activateNetworkLinkCreatedCallback(){
+  surf_callback_connect(networkLinkCreatedCallbacks, boost::bind(&Plugin::networkLinkCreatedCallback, this, _1));
+}
+
+void Plugin::activateNetworkLinkDestructedCallback(){
+  surf_callback_connect(networkLinkDestructedCallbacks, boost::bind(&Plugin::networkLinkDestructedCallback, this, _1));
+}
+
+void Plugin::activateNetworkLinkStateChangedCallback(){
+  surf_callback_connect(networkLinkStateChangedCallbacks, boost::bind(&Plugin::networkLinkStateChangedCallback, this, _1));
+}
+
+void Plugin::activateNetworkActionStateChangedCallback(){
+  surf_callback_connect(networkActionStateChangedCallbacks, boost::bind(&Plugin::networkActionStateChangedCallback, this, _1));
+}
+
+
diff --git a/src/bindings/java/surf_swig.hpp b/src/bindings/java/surf_swig.hpp
new file mode 100644 (file)
index 0000000..6066116
--- /dev/null
@@ -0,0 +1,46 @@
+#include <cstdio>
+#include <iostream>
+#include "src/surf/cpu_interface.hpp"
+#include "src/surf/network_interface.hpp"
+#include "src/surf/maxmin_private.hpp"
+
+double getClock();
+
+class Plugin {
+public:
+ virtual ~Plugin() { 
+   std::cout << "Plugin::~Plugin()" << std:: endl;
+ }
+
+ void exit() {
+   surf_exit();
+ }
+
+ void activateCpuCreatedCallback(); 
+ virtual void cpuCreatedCallback(Cpu *cpu) {}
+
+ void activateCpuDestructedCallback();
+ virtual void cpuDestructedCallback(Cpu *cpu) {}
+ void activateCpuStateChangedCallback();
+ virtual void cpuStateChangedCallback(Cpu *cpu) {}
+
+ void activateCpuActionStateChangedCallback();
+ virtual void cpuActionStateChangedCallback(CpuAction *action) {}
+
+
+ void activateNetworkLinkCreatedCallback();
+ virtual void networkLinkCreatedCallback(NetworkLink *link) {}
+
+ void activateNetworkLinkDestructedCallback();
+ virtual void networkLinkDestructedCallback(NetworkLink *link) {}
+
+ void activateNetworkLinkStateChangedCallback();
+ virtual void networkLinkStateChangedCallback(NetworkLink *link) {}
+
+ void activateNetworkActionStateChangedCallback();
+ virtual void networkActionStateChangedCallback(NetworkAction *action) {}
+
+};
+
+
index 6be1e2c..a56495f 100644 (file)
@@ -631,6 +631,8 @@ public:
 
   s_xbt_swag_hookup_t p_stateHookup;
 
+  ModelPtr getModel() {return p_model;}
+
 protected:
   ActionListPtr p_stateSet;
   double m_priority; /**< priority (1.0 by default) */
@@ -639,8 +641,6 @@ protected:
   double m_maxDuration; /*< max_duration (may fluctuate until the task is completed) */
   double m_finish; /**< finish time : this is modified during the run and fluctuates until the task is completed */
 
-  ModelPtr getModel() {return p_model;}
-
 private:
   int resourceUsed(void *resource_id);