about summary refs log tree commit diff
path: root/nixpkgs/pkgs/applications/science/math
diff options
context:
space:
mode:
Diffstat (limited to 'nixpkgs/pkgs/applications/science/math')
-rw-r--r--nixpkgs/pkgs/applications/science/math/LiE/default.nix47
-rw-r--r--nixpkgs/pkgs/applications/science/math/R/default.nix108
-rw-r--r--nixpkgs/pkgs/applications/science/math/R/no-usr-local-search-paths.patch24
-rw-r--r--nixpkgs/pkgs/applications/science/math/R/setup-hook.sh7
-rw-r--r--nixpkgs/pkgs/applications/science/math/almonds/default.nix26
-rw-r--r--nixpkgs/pkgs/applications/science/math/bcal/default.nix34
-rw-r--r--nixpkgs/pkgs/applications/science/math/bliss/default.nix37
-rw-r--r--nixpkgs/pkgs/applications/science/math/caffe/darwin.patch47
-rw-r--r--nixpkgs/pkgs/applications/science/math/caffe/default.nix126
-rw-r--r--nixpkgs/pkgs/applications/science/math/calc/default.nix49
-rw-r--r--nixpkgs/pkgs/applications/science/math/cbc/default.nix28
-rw-r--r--nixpkgs/pkgs/applications/science/math/clp/default.nix22
-rw-r--r--nixpkgs/pkgs/applications/science/math/cntk/default.nix92
-rw-r--r--nixpkgs/pkgs/applications/science/math/cntk/fix_std_bind.patch11
-rw-r--r--nixpkgs/pkgs/applications/science/math/colpack/default.nix32
-rw-r--r--nixpkgs/pkgs/applications/science/math/cplex/default.nix82
-rw-r--r--nixpkgs/pkgs/applications/science/math/csdp/default.nix29
-rw-r--r--nixpkgs/pkgs/applications/science/math/ecm/default.nix31
-rw-r--r--nixpkgs/pkgs/applications/science/math/eukleides/default.nix37
-rw-r--r--nixpkgs/pkgs/applications/science/math/form/default.nix22
-rw-r--r--nixpkgs/pkgs/applications/science/math/fricas/default.nix27
-rw-r--r--nixpkgs/pkgs/applications/science/math/gap/default.nix103
-rw-r--r--nixpkgs/pkgs/applications/science/math/geogebra/default.nix63
-rw-r--r--nixpkgs/pkgs/applications/science/math/gfan/default.nix28
-rw-r--r--nixpkgs/pkgs/applications/science/math/giac/default.nix112
-rw-r--r--nixpkgs/pkgs/applications/science/math/ginac/default.nix28
-rw-r--r--nixpkgs/pkgs/applications/science/math/glsurf/default.nix31
-rw-r--r--nixpkgs/pkgs/applications/science/math/gmsh/default.nix29
-rw-r--r--nixpkgs/pkgs/applications/science/math/gurobi/default.nix54
-rw-r--r--nixpkgs/pkgs/applications/science/math/hmetis/default.nix42
-rw-r--r--nixpkgs/pkgs/applications/science/math/jags/default.nix19
-rw-r--r--nixpkgs/pkgs/applications/science/math/lp_solve/default.nix49
-rw-r--r--nixpkgs/pkgs/applications/science/math/lp_solve/isnan.patch13
-rw-r--r--nixpkgs/pkgs/applications/science/math/lrcalc/default.nix41
-rw-r--r--nixpkgs/pkgs/applications/science/math/mathematica/10.nix136
-rw-r--r--nixpkgs/pkgs/applications/science/math/mathematica/9.nix122
-rw-r--r--nixpkgs/pkgs/applications/science/math/mathematica/default.nix148
-rw-r--r--nixpkgs/pkgs/applications/science/math/mathematica/l10ns.nix33
-rw-r--r--nixpkgs/pkgs/applications/science/math/maxima/default.nix100
-rw-r--r--nixpkgs/pkgs/applications/science/math/maxima/known-ecl-failures.patch21
-rw-r--r--nixpkgs/pkgs/applications/science/math/msieve/default.nix30
-rw-r--r--nixpkgs/pkgs/applications/science/math/mxnet/default.nix56
-rw-r--r--nixpkgs/pkgs/applications/science/math/nasc/default.nix62
-rw-r--r--nixpkgs/pkgs/applications/science/math/nauty/default.nix31
-rw-r--r--nixpkgs/pkgs/applications/science/math/palp/default.nix86
-rw-r--r--nixpkgs/pkgs/applications/science/math/pari/default.nix77
-rw-r--r--nixpkgs/pkgs/applications/science/math/pari/gp2c.nix28
-rw-r--r--nixpkgs/pkgs/applications/science/math/pcalc/default.nix26
-rw-r--r--nixpkgs/pkgs/applications/science/math/perseus/default.nix40
-rw-r--r--nixpkgs/pkgs/applications/science/math/polymake/default.nix48
-rw-r--r--nixpkgs/pkgs/applications/science/math/pspp/default.nix51
-rw-r--r--nixpkgs/pkgs/applications/science/math/pynac/default.nix48
-rw-r--r--nixpkgs/pkgs/applications/science/math/qalculate-gtk/default.nix30
-rw-r--r--nixpkgs/pkgs/applications/science/math/ratpoints/default.nix37
-rw-r--r--nixpkgs/pkgs/applications/science/math/ries/default.nix21
-rw-r--r--nixpkgs/pkgs/applications/science/math/ripser/default.nix66
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/README.md78
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/default.nix181
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/env-locations.nix48
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/flask-oldsessions.nix36
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/flask-openid.nix28
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/Only-test-py2-py3-optional-tests-when-all-of-sage-is.patch35
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/giac-1.5.0.patch14
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/numpy-1.15.1.patch911
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/pari-stackwarn.patch20
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/python-5755-hotpatch.patch28
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/revert-sphinx-always-fork.patch71
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/pybrial.nix29
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/python-openid.nix42
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage-env.nix170
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage-src.nix144
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage-tests.nix51
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage-with-env.nix128
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage.nix67
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sagedoc.nix81
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sagelib.nix140
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sagenb.nix61
-rw-r--r--nixpkgs/pkgs/applications/science/math/scilab-bin/default.nix106
-rw-r--r--nixpkgs/pkgs/applications/science/math/scilab/default.nix66
-rw-r--r--nixpkgs/pkgs/applications/science/math/scotch/default.nix36
-rw-r--r--nixpkgs/pkgs/applications/science/math/singular/default.nix118
-rw-r--r--nixpkgs/pkgs/applications/science/math/speedcrunch/default.nix37
-rw-r--r--nixpkgs/pkgs/applications/science/math/symmetrica/default.nix62
-rw-r--r--nixpkgs/pkgs/applications/science/math/weka/default.nix31
-rw-r--r--nixpkgs/pkgs/applications/science/math/wxmaxima/default.nix33
-rw-r--r--nixpkgs/pkgs/applications/science/math/yacas/default.nix39
86 files changed, 5718 insertions, 0 deletions
diff --git a/nixpkgs/pkgs/applications/science/math/LiE/default.nix b/nixpkgs/pkgs/applications/science/math/LiE/default.nix
new file mode 100644
index 000000000000..e0b0bc11f05f
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/LiE/default.nix
@@ -0,0 +1,47 @@
+{ stdenv, fetchurl
+, bison, readline }:
+
+stdenv.mkDerivation rec {
+  version = "2.2.2";
+     # The current version of LiE is 2.2.2, which is more or less unchanged
+     # since about the year 2000. Minor bugfixes do get applied now and then.
+  name = "lie-${version}";
+
+  meta = {
+    description = "A Computer algebra package for Lie group computations";
+    homepage = http://wwwmathlabo.univ-poitiers.fr/~maavl/LiE/;
+    license = stdenv.lib.licenses.lgpl3; # see the website
+
+    longDescription = ''
+      LiE is a computer algebra system that is specialised in computations
+      involving (reductive) Lie groups and their representations. It is
+      publically available for free in source code. For a description of its
+      characteristics, we refer to the following sources of information.
+    ''; # take from the website
+
+    platforms = stdenv.lib.platforms.linux;
+    maintainers = [ ]; # this package is probably not going to change anyway
+  };
+
+  src = fetchurl {
+    url = "http://wwwmathlabo.univ-poitiers.fr/~maavl/LiE/conLiE.tar.gz";
+    sha256 = "07lbj75qqr4pq1j1qz8fyfnmrz1gnk92lnsshxycfavxl5zzdmn4";
+  };
+
+  buildInputs = [ bison readline ];
+
+  patchPhase = ''
+    substituteInPlace make_lie \
+      --replace \`/bin/pwd\` $out
+  '';
+
+  installPhase = ''
+    mkdir -vp $out/bin
+
+    cp -v Lie.exe $out
+    cp -v lie $out/bin
+
+    cp -v LEARN* $out
+    cp -v INFO* $out
+  '';
+}
diff --git a/nixpkgs/pkgs/applications/science/math/R/default.nix b/nixpkgs/pkgs/applications/science/math/R/default.nix
new file mode 100644
index 000000000000..4283ebd931a4
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/R/default.nix
@@ -0,0 +1,108 @@
+{ stdenv, fetchurl, bzip2, gfortran, libX11, libXmu, libXt, libjpeg, libpng
+, libtiff, ncurses, pango, pcre, perl, readline, tcl, texLive, tk, xz, zlib
+, less, texinfo, graphviz, icu, pkgconfig, bison, imake, which, jdk, openblas
+, curl, Cocoa, Foundation, libobjc, libcxx, tzdata
+, withRecommendedPackages ? true
+, enableStrictBarrier ? false
+, javaSupport ? (!stdenv.hostPlatform.isAarch32 && !stdenv.hostPlatform.isAarch64)
+}:
+
+stdenv.mkDerivation rec {
+  name = "R-3.5.2";
+
+  src = fetchurl {
+    url = "https://cran.r-project.org/src/base/R-3/${name}.tar.gz";
+    sha256 = "0qjvdic1qd5vndc4f0wjndpm0x18lbvbcc8nkix8saqgy8y8qgg5";
+  };
+
+  dontUseImakeConfigure = true;
+
+  buildInputs = [
+    bzip2 gfortran libX11 libXmu libXt libXt libjpeg libpng libtiff ncurses
+    pango pcre perl readline texLive xz zlib less texinfo graphviz icu
+    pkgconfig bison imake which openblas curl
+  ] ++ stdenv.lib.optionals (!stdenv.isDarwin) [ tcl tk ]
+    ++ stdenv.lib.optionals stdenv.isDarwin [ Cocoa Foundation libobjc libcxx ]
+    ++ stdenv.lib.optional javaSupport jdk;
+
+  patches = [ ./no-usr-local-search-paths.patch ];
+
+  prePatch = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace configure --replace "-install_name libR.dylib" "-install_name $out/lib/R/lib/libR.dylib"
+  '';
+
+  preConfigure = ''
+    configureFlagsArray=(
+      --disable-lto
+      --with${stdenv.lib.optionalString (!withRecommendedPackages) "out"}-recommended-packages
+      --with-blas="-L${openblas}/lib -lopenblas"
+      --with-lapack="-L${openblas}/lib -lopenblas"
+      --with-readline
+      --with-tcltk --with-tcl-config="${tcl}/lib/tclConfig.sh" --with-tk-config="${tk}/lib/tkConfig.sh"
+      --with-cairo
+      --with-libpng
+      --with-jpeglib
+      --with-libtiff
+      --with-ICU
+      ${stdenv.lib.optionalString enableStrictBarrier "--enable-strict-barrier"}
+      --enable-R-shlib
+      AR=$(type -p ar)
+      AWK=$(type -p gawk)
+      CC=$(type -p cc)
+      CXX=$(type -p c++)
+      FC="${gfortran}/bin/gfortran" F77="${gfortran}/bin/gfortran"
+      ${stdenv.lib.optionalString javaSupport "JAVA_HOME=\"${jdk}\""}
+      RANLIB=$(type -p ranlib)
+      R_SHELL="${stdenv.shell}"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+      --without-tcltk
+      --without-aqua
+      --disable-R-framework
+      OBJC="clang"
+      CPPFLAGS="-isystem ${libcxx}/include/c++/v1"
+      LDFLAGS="-L${libcxx}/lib"
+  '' + ''
+    )
+    echo >>etc/Renviron.in "TCLLIBPATH=${tk}/lib"
+    echo >>etc/Renviron.in "TZDIR=${tzdata}/share/zoneinfo"
+  '';
+
+  installTargets = [ "install" "install-info" "install-pdf" ];
+
+  doCheck = true;
+  preCheck = "export TZ=CET; bin/Rscript -e 'sessionInfo()'";
+
+  enableParallelBuilding = true;
+
+  setupHook = ./setup-hook.sh;
+
+  meta = with stdenv.lib; {
+    homepage = http://www.r-project.org/;
+    description = "Free software environment for statistical computing and graphics";
+    license = licenses.gpl2Plus;
+
+    longDescription = ''
+      GNU R is a language and environment for statistical computing and
+      graphics that provides a wide variety of statistical (linear and
+      nonlinear modelling, classical statistical tests, time-series
+      analysis, classification, clustering, ...) and graphical
+      techniques, and is highly extensible. One of R's strengths is the
+      ease with which well-designed publication-quality plots can be
+      produced, including mathematical symbols and formulae where
+      needed. R is an integrated suite of software facilities for data
+      manipulation, calculation and graphical display. It includes an
+      effective data handling and storage facility, a suite of operators
+      for calculations on arrays, in particular matrices, a large,
+      coherent, integrated collection of intermediate tools for data
+      analysis, graphical facilities for data analysis and display
+      either on-screen or on hardcopy, and a well-developed, simple and
+      effective programming language which includes conditionals, loops,
+      user-defined recursive functions and input and output facilities.
+    '';
+
+    platforms = platforms.all;
+    hydraPlatforms = platforms.linux;
+
+    maintainers = [ maintainers.peti ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/R/no-usr-local-search-paths.patch b/nixpkgs/pkgs/applications/science/math/R/no-usr-local-search-paths.patch
new file mode 100644
index 000000000000..6c7f6d4ee02a
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/R/no-usr-local-search-paths.patch
@@ -0,0 +1,24 @@
+diff -ubr R-3.0.1-orig/configure R-3.0.1/configure
+--- R-3.0.1-orig/configure	2013-07-04 10:46:42.336133947 +0200
++++ R-3.0.1/configure	2013-07-04 10:46:17.181919960 +0200
+@@ -3800,13 +3800,13 @@
+ : ${LIBnn=$libnn}
+ ## We provide these defaults so that headers and libraries in
+ ## '/usr/local' are found (by the native tools, mostly).
+-if test -f "/sw/etc/fink.conf"; then
+-  : ${CPPFLAGS="-I/sw/include -I/usr/local/include"}
+-  : ${LDFLAGS="-L/sw/lib -L/usr/local/lib"}
+-else
+-  : ${CPPFLAGS="-I/usr/local/include"}
+-  : ${LDFLAGS="-L/usr/local/${LIBnn}"}
+-fi
++# if test -f "/sw/etc/fink.conf"; then
++#   : ${CPPFLAGS="-I/sw/include -I/usr/local/include"}
++#   : ${LDFLAGS="-L/sw/lib -L/usr/local/lib"}
++# else
++#   : ${CPPFLAGS="-I/usr/local/include"}
++#   : ${LDFLAGS="-L/usr/local/${LIBnn}"}
++# fi
+ 
+ ## take care not to  override the command-line setting
+ if test "${libdir}" = '${exec_prefix}/lib'; then
diff --git a/nixpkgs/pkgs/applications/science/math/R/setup-hook.sh b/nixpkgs/pkgs/applications/science/math/R/setup-hook.sh
new file mode 100644
index 000000000000..6951e2a4b61b
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/R/setup-hook.sh
@@ -0,0 +1,7 @@
+addRLibPath () {
+    if [[ -d "$1/library" ]]; then
+        addToSearchPath R_LIBS_SITE "$1/library"
+    fi
+}
+
+addEnvHooks "$targetOffset" addRLibPath
diff --git a/nixpkgs/pkgs/applications/science/math/almonds/default.nix b/nixpkgs/pkgs/applications/science/math/almonds/default.nix
new file mode 100644
index 000000000000..b5d9632c551d
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/almonds/default.nix
@@ -0,0 +1,26 @@
+{ stdenv, python3, fetchFromGitHub, ncurses }:
+
+with python3.pkgs; buildPythonApplication rec {
+  pname = "almonds";
+  version = "1.25b";
+
+  src = fetchFromGitHub {
+    owner = "Tenchi2xh";
+    repo = "Almonds";
+    rev = version;
+    sha256 = "0j8d8jizivnfx8lpc4w6sbqj5hq35nfz0vdg7ld80sc5cs7jr3ws";
+  };
+
+  nativeBuildInputs = [ pytest ];
+  buildInputs = [ ncurses ];
+  propagatedBuildInputs = [ pillow ];
+
+  checkPhase = "py.test";
+
+  meta = with stdenv.lib; {
+    description = "Terminal Mandelbrot fractal viewer";
+    homepage = https://github.com/Tenchi2xh/Almonds;
+    license = licenses.mit;
+    maintainers = with maintainers; [ infinisil ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/bcal/default.nix b/nixpkgs/pkgs/applications/science/math/bcal/default.nix
new file mode 100644
index 000000000000..61eb1fd3ce4e
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/bcal/default.nix
@@ -0,0 +1,34 @@
+{ stdenv, fetchFromGitHub, python3Packages, readline }:
+
+with stdenv.lib;
+
+stdenv.mkDerivation rec {
+  name = "bcal-${version}";
+  version = "1.9";
+
+  src = fetchFromGitHub {
+    owner = "jarun";
+    repo = "bcal";
+    rev = "v${version}";
+    sha256 = "0h6qi5rvzl6c6fsfdpdb3l4jcgip03l18i0b1x08z1y89i56y8mm";
+  };
+
+  nativeBuildInputs = [ python3Packages.pytest ];
+
+  buildInputs = [ readline ];
+
+  doCheck = true;
+  checkPhase = ''
+    python3 -m pytest test.py
+  '';
+
+  installFlags = [ "DESTDIR=$(out)" "PREFIX=" ];
+
+  meta = {
+    description = "Storage conversion and expression calculator";
+    homepage = https://github.com/jarun/bcal;
+    license = licenses.gpl3;
+    platforms = [ "aarch64-linux" "x86_64-darwin" "x86_64-linux" ];
+    maintainers = with maintainers; [ jfrankenau ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/bliss/default.nix b/nixpkgs/pkgs/applications/science/math/bliss/default.nix
new file mode 100644
index 000000000000..1b7a97360079
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/bliss/default.nix
@@ -0,0 +1,37 @@
+{ stdenv, fetchurl, unzip, doxygen }:
+
+stdenv.mkDerivation rec {
+  name = "bliss-${version}";
+  version = "0.73";
+
+  src = fetchurl {
+    url = "http://www.tcs.hut.fi/Software/bliss/${name}.zip";
+    sha256 = "f57bf32804140cad58b1240b804e0dbd68f7e6bf67eba8e0c0fa3a62fd7f0f84";
+  };
+
+  patches = fetchurl {
+    url = "http://scip.zib.de/download/bugfixes/scip-5.0.1/bliss-0.73.patch";
+    sha256 = "815868d6586bcd49ff3c28e14ccb536d38b2661151088fe08187c13909c5dab0";
+  };
+
+  nativeBuildInputs = [ unzip doxygen ];
+
+  preBuild = ''
+    doxygen Doxyfile
+  '';
+
+  installPhase = ''
+    mkdir -p $out/bin $out/share/doc/bliss $out/lib $out/include/bliss
+    mv bliss $out/bin 
+    mv html/* COPYING* $out/share/doc/bliss
+    mv *.a $out/lib
+    mv *.h *.hh $out/include/bliss
+  '';
+
+  meta = with stdenv.lib; {
+    description = "bliss is an open source tool for computing automorphism groups and canonical forms of graphs. It has both a command line user interface as well as C++ and C programming language APIs.";
+    homepage = http://www.tcs.hut.fi/Software/bliss/;
+    license = licenses.lgpl3;
+    platforms = [ "i686-linux" "x86_64-linux" ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/caffe/darwin.patch b/nixpkgs/pkgs/applications/science/math/caffe/darwin.patch
new file mode 100644
index 000000000000..e8fa6a683f73
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/caffe/darwin.patch
@@ -0,0 +1,47 @@
+diff --git a/Makefile b/Makefile
+index c823f66e..65b90c5e 100644
+--- a/Makefile
++++ b/Makefile
+@@ -32,9 +32,9 @@ SRC_DIRS := $(shell find * -type d -exec bash -c "find {} -maxdepth 1 \
+ LIBRARY_NAME := $(PROJECT)
+ LIB_BUILD_DIR := $(BUILD_DIR)/lib
+ STATIC_NAME := $(LIB_BUILD_DIR)/lib$(LIBRARY_NAME).a
+-DYNAMIC_VERSION_MAJOR 		:= 1
+-DYNAMIC_VERSION_MINOR 		:= 0
+-DYNAMIC_VERSION_REVISION 	:= 0
++DYNAMIC_VERSION_MAJOR		:= 1
++DYNAMIC_VERSION_MINOR		:= 0
++DYNAMIC_VERSION_REVISION	:= 0
+ DYNAMIC_NAME_SHORT := lib$(LIBRARY_NAME).so
+ #DYNAMIC_SONAME_SHORT := $(DYNAMIC_NAME_SHORT).$(DYNAMIC_VERSION_MAJOR)
+ DYNAMIC_VERSIONED_NAME_SHORT := $(DYNAMIC_NAME_SHORT).$(DYNAMIC_VERSION_MAJOR).$(DYNAMIC_VERSION_MINOR).$(DYNAMIC_VERSION_REVISION)
+diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake
+index c48255c8..cf4c580e 100644
+--- a/cmake/Dependencies.cmake
++++ b/cmake/Dependencies.cmake
+@@ -105,7 +105,6 @@ if(USE_OPENCV)
+ endif()
+ 
+ # ---[ BLAS
+-if(NOT APPLE)
+   set(BLAS "Atlas" CACHE STRING "Selected BLAS library")
+   set_property(CACHE BLAS PROPERTY STRINGS "Atlas;Open;MKL")
+ 
+@@ -123,17 +122,6 @@ if(NOT APPLE)
+     list(APPEND Caffe_LINKER_LIBS PUBLIC ${MKL_LIBRARIES})
+     list(APPEND Caffe_DEFINITIONS PUBLIC -DUSE_MKL)
+   endif()
+-elseif(APPLE)
+-  find_package(vecLib REQUIRED)
+-  list(APPEND Caffe_INCLUDE_DIRS PUBLIC ${vecLib_INCLUDE_DIR})
+-  list(APPEND Caffe_LINKER_LIBS PUBLIC ${vecLib_LINKER_LIBS})
+-
+-  if(VECLIB_FOUND)
+-    if(NOT vecLib_INCLUDE_DIR MATCHES "^/System/Library/Frameworks/vecLib.framework.*")
+-      list(APPEND Caffe_DEFINITIONS PUBLIC -DUSE_ACCELERATE)
+-    endif()
+-  endif()
+-endif()
+ 
+ # ---[ Python
+ if(BUILD_python)
diff --git a/nixpkgs/pkgs/applications/science/math/caffe/default.nix b/nixpkgs/pkgs/applications/science/math/caffe/default.nix
new file mode 100644
index 000000000000..e56c63e01bf0
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/caffe/default.nix
@@ -0,0 +1,126 @@
+{ stdenv, lib, runCommand
+, fetchFromGitHub
+, fetchurl
+, cmake
+, boost
+, google-gflags
+, glog
+, hdf5-cpp
+, opencv3
+, protobuf
+, doxygen
+, openblas
+, Accelerate, CoreGraphics, CoreVideo
+, lmdbSupport ? true, lmdb
+, leveldbSupport ? true, leveldb, snappy
+, cudaSupport ? stdenv.isLinux, cudatoolkit
+, cudnnSupport ? false, cudnn ? null
+, ncclSupport ? false, nccl ? null
+, pythonSupport ? false, python ? null, numpy ? null
+}:
+
+assert leveldbSupport -> (leveldb != null && snappy != null);
+assert cudnnSupport -> cudaSupport;
+assert ncclSupport -> cudaSupport;
+assert pythonSupport -> (python != null && numpy != null);
+
+let
+  toggle = bool: if bool then "ON" else "OFF";
+
+  test_model_weights = fetchurl {
+    url = "http://dl.caffe.berkeleyvision.org/bvlc_reference_caffenet.caffemodel";
+    sha256 = "472d4a06035497b180636d8a82667129960371375bd10fcb6df5c6c7631f25e0";
+  };
+
+in
+
+stdenv.mkDerivation rec {
+  name = "caffe-${version}";
+  version = "1.0";
+
+  src = fetchFromGitHub {
+    owner = "BVLC";
+    repo = "caffe";
+    rev = version;
+    sha256 = "104jp3cm823i3cdph7hgsnj6l77ygbwsy35mdmzhmsi4jxprd9j3";
+  };
+
+  enableParallelBuilding = true;
+
+  nativeBuildInputs = [ cmake doxygen ];
+
+  cmakeFlags =
+    [ (if pythonSupport then "-Dpython_version=${python.version}" else "-DBUILD_python=OFF")
+      "-DBLAS=open"
+    ] ++ (if cudaSupport then [
+           "-DCUDA_ARCH_NAME=All"
+           "-DCUDA_HOST_COMPILER=${cudatoolkit.cc}/bin/cc"
+         ] else [ "-DCPU_ONLY=ON" ])
+      ++ ["-DUSE_NCCL=${toggle ncclSupport}"]
+      ++ ["-DUSE_LEVELDB=${toggle leveldbSupport}"]
+      ++ ["-DUSE_LMDB=${toggle lmdbSupport}"];
+
+  buildInputs = [ boost google-gflags glog protobuf hdf5-cpp opencv3 openblas ]
+                ++ lib.optional cudaSupport cudatoolkit
+                ++ lib.optional cudnnSupport cudnn
+                ++ lib.optional lmdbSupport lmdb
+                ++ lib.optional ncclSupport nccl
+                ++ lib.optionals leveldbSupport [ leveldb snappy ]
+                ++ lib.optionals pythonSupport [ python numpy ]
+                ++ lib.optionals stdenv.isDarwin [ Accelerate CoreGraphics CoreVideo ]
+                ;
+
+  propagatedBuildInputs = lib.optional pythonSupport python.pkgs.protobuf;
+
+  outputs = [ "bin" "out"];
+  propagatedBuildOutputs = []; # otherwise propagates out -> bin cycle
+
+  patches = [ ./darwin.patch ];
+
+  preConfigure = lib.optionalString (cudaSupport && lib.versionAtLeast cudatoolkit.version "9.0") ''
+    # CUDA 9.0 doesn't support sm_20
+    sed -i 's,20 21(20) ,,' cmake/Cuda.cmake
+  '' + lib.optionalString (python.isPy3 or false) ''
+    sed -i \
+      -e 's,"python-py''${boost_py_version}",python3,g' \
+      -e 's,''${Boost_PYTHON-PY''${boost_py_version}_FOUND},''${Boost_PYTHON3_FOUND},g' \
+      cmake/Dependencies.cmake
+  '';
+
+  postInstall = ''
+    # Internal static library.
+    rm $out/lib/libproto.a
+
+    # Install models
+    cp -a ../models $out/share/Caffe/models
+
+    moveToOutput "bin" "$bin"
+  '' + lib.optionalString pythonSupport ''
+    mkdir -p $out/${python.sitePackages}
+    mv $out/python/caffe $out/${python.sitePackages}
+    rm -rf $out/python
+  '';
+
+  doInstallCheck = false; # build takes more than 30 min otherwise
+  installCheckPhase = ''
+    model=bvlc_reference_caffenet
+    m_path="$out/share/Caffe/models/$model"
+    $bin/bin/caffe test \
+      -model "$m_path/deploy.prototxt" \
+      -solver "$m_path/solver.prototxt" \
+      -weights "${test_model_weights}"
+  '';
+
+  meta = with stdenv.lib; {
+    description = "Deep learning framework";
+    longDescription = ''
+      Caffe is a deep learning framework made with expression, speed, and
+      modularity in mind. It is developed by the Berkeley Vision and Learning
+      Center (BVLC) and by community contributors.
+    '';
+    homepage = http://caffe.berkeleyvision.org/;
+    maintainers = with maintainers; [ jb55 ];
+    license = licenses.bsd2;
+    platforms = platforms.linux ++ platforms.darwin;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/calc/default.nix b/nixpkgs/pkgs/applications/science/math/calc/default.nix
new file mode 100644
index 000000000000..24cddfb9a1c2
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/calc/default.nix
@@ -0,0 +1,49 @@
+{ stdenv, lib, fetchurl, utillinux, makeWrapper
+, enableReadline ? true, readline, ncurses }:
+
+stdenv.mkDerivation rec {
+  name = "calc-${version}";
+  version = "2.12.7.2";
+
+  src = fetchurl {
+    urls = [
+      "https://github.com/lcn2/calc/releases/download/${version}/${name}.tar.bz2"
+      "http://www.isthe.com/chongo/src/calc/${name}.tar.bz2"
+    ];
+    sha256 = "147wmbajcxv6wp92j6pizq4plrr1sb7jirifr1477bx33hc49bsp";
+  };
+
+  patchPhase = ''
+    substituteInPlace Makefile \
+      --replace 'all: check_include' 'all:' \
+      --replace '-install_name ''${LIBDIR}/libcalc''${LIB_EXT_VERSION}' '-install_name ''${T}''${LIBDIR}/libcalc''${LIB_EXT_VERSION}' \
+      --replace '-install_name ''${LIBDIR}/libcustcalc''${LIB_EXT_VERSION}' '-install_name ''${T}''${LIBDIR}/libcustcalc''${LIB_EXT_VERSION}'
+  '';
+
+  buildInputs = [ utillinux makeWrapper ]
+             ++ lib.optionals enableReadline [ readline ncurses ];
+
+  makeFlags = [
+    "T=$(out)"
+    "INCDIR=${lib.getDev stdenv.cc.libc}/include"
+    "BINDIR=/bin"
+    "LIBDIR=/lib"
+    "CALC_SHAREDIR=/share/calc"
+    "CALC_INCDIR=/include"
+    "MANDIR=/share/man/man1"
+
+    # Handle LDFLAGS defaults in calc
+    "DEFAULT_LIB_INSTALL_PATH=$(out)/lib"
+  ] ++ lib.optionals enableReadline [
+    "READLINE_LIB=-lreadline"
+    "USE_READLINE=-DUSE_READLINE"
+  ];
+
+  meta = with lib; {
+    description = "C-style arbitrary precision calculator";
+    homepage = http://www.isthe.com/chongo/tech/comp/calc/;
+    license = licenses.lgpl21;
+    maintainers = with maintainers; [ matthewbauer ];
+    platforms = platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/cbc/default.nix b/nixpkgs/pkgs/applications/science/math/cbc/default.nix
new file mode 100644
index 000000000000..93aefbca2160
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/cbc/default.nix
@@ -0,0 +1,28 @@
+{ lib, stdenv, fetchurl, zlib, bzip2 }:
+
+stdenv.mkDerivation {
+  name = "cbc-2.9.9";
+
+  src = fetchurl {
+    url = "https://www.coin-or.org/download/source/Cbc/Cbc-2.9.9.tgz";
+    sha256 = "1w8axdzm05xf5y13c31w7rc5z6ywxqxiwafnxcq3p195kgj0915a";
+  };
+
+  configureFlags = [ "-C" ];
+
+  enableParallelBuilding = true;
+
+  hardeningDisable = [ "format" ];
+
+  buildInputs = [ zlib bzip2 ];
+
+  # FIXME: move share/coin/Data to a separate output?
+
+  meta = {
+    homepage = https://projects.coin-or.org/Cbc;
+    license = lib.licenses.epl10;
+    maintainers = [ lib.maintainers.eelco ];
+    platforms = lib.platforms.linux ++ lib.platforms.darwin;
+    description = "A mixed integer programming solver";
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/clp/default.nix b/nixpkgs/pkgs/applications/science/math/clp/default.nix
new file mode 100644
index 000000000000..4899ebe42d77
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/clp/default.nix
@@ -0,0 +1,22 @@
+{ stdenv, fetchurl, zlib }:
+
+stdenv.mkDerivation rec {
+  version = "1.16.11";
+  name = "clp-${version}";
+  src = fetchurl {
+    url = "https://www.coin-or.org/download/source/Clp/Clp-${version}.tgz";
+    sha256 = "0fazlqpp845186nmixa9f1xfxqqkdr1xj4va7q29m8594ca4a9dm";
+  };
+
+  propagatedBuildInputs = [ zlib ];
+
+  doCheck = true;
+
+  meta = {
+    license = stdenv.lib.licenses.epl10;
+    homepage = https://projects.coin-or.org/Clp;
+    description = "An open-source linear programming solver written in C++";
+    platforms = stdenv.lib.platforms.all;
+    maintainers = [ stdenv.lib.maintainers.vbgl ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/cntk/default.nix b/nixpkgs/pkgs/applications/science/math/cntk/default.nix
new file mode 100644
index 000000000000..fe5c77be8b22
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/cntk/default.nix
@@ -0,0 +1,92 @@
+{ lib, stdenv, fetchgit, fetchFromGitHub, cmake
+, openblas, opencv3, libzip, boost, protobuf, openmpi
+, onebitSGDSupport ? false
+, cudaSupport ? false, cudatoolkit, nvidia_x11
+, cudnnSupport ? false, cudnn
+}:
+
+assert cudnnSupport -> cudaSupport;
+
+let
+  # Old specific version required for CNTK.
+  cub = fetchFromGitHub {
+    owner = "NVlabs";
+    repo = "cub";
+    rev = "1.7.4";
+    sha256 = "0ksd5n1lxqhm5l5cd2lps4cszhjkf6gmzahaycs7nxb06qci8c66";
+  };
+
+in stdenv.mkDerivation rec {
+  name = "CNTK-${version}";
+  version = "2.4";
+
+  # Submodules
+  src = fetchgit {
+    url = "https://github.com/Microsoft/CNTK";
+    rev = "v${version}";
+    sha256 = "0m28wb0ljixcpi14g3gcfiraimh487yxqhd9yrglgyvjb69x597y";
+  };
+
+  patches = [ ./fix_std_bind.patch ];
+
+  nativeBuildInputs = [ cmake ];
+
+  buildInputs = [ openblas opencv3 libzip boost protobuf openmpi ]
+             ++ lib.optional cudaSupport cudatoolkit
+             ++ lib.optional cudnnSupport cudnn;
+
+  configureFlags = [
+    "--with-opencv=${opencv3}"
+    "--with-libzip=${libzip.dev}"
+    "--with-openblas=${openblas}"
+    "--with-boost=${boost.dev}"
+    "--with-protobuf=${protobuf}"
+    "--with-mpi=${openmpi}"
+    "--cuda=${if cudaSupport then "yes" else "no"}"
+    # FIXME
+    "--asgd=no"
+  ] ++ lib.optionals cudaSupport [
+    "--with-cuda=${cudatoolkit}"
+    "--with-gdk-include=${cudatoolkit}/include"
+    "--with-gdk-nvml-lib=${nvidia_x11}/lib"
+    "--with-cub=${cub}"
+  ] ++ lib.optional onebitSGDSupport "--1bitsgd=yes";
+
+  configurePhase = ''
+    sed -i \
+      -e 's,^GIT_STATUS=.*,GIT_STATUS=,' \
+      -e 's,^GIT_COMMIT=.*,GIT_COMMIT=v${version},' \
+      -e 's,^GIT_BRANCH=.*,GIT_BRANCH=v${version},' \
+      -e 's,^BUILDER=.*,BUILDER=nixbld,' \
+      -e 's,^BUILDMACHINE=.*,BUILDMACHINE=machine,' \
+      -e 's,^BUILDPATH=.*,BUILDPATH=/homeless-shelter,' \
+      -e '/git does not exist/d' \
+      Tools/generate_build_info
+
+    patchShebangs .
+    mkdir build
+    cd build
+    ${lib.optionalString cudnnSupport ''
+      mkdir cuda
+      ln -s ${cudnn}/include cuda
+      export configureFlags="$configureFlags --with-cudnn=$PWD"
+    ''}
+    ../configure $configureFlags
+  '';
+
+  installPhase = ''
+    mkdir -p $out/bin
+    # Moving to make patchelf remove references later.
+    mv lib $out
+    cp bin/cntk $out/bin
+  '';
+
+  enableParallelBuilding = true;
+
+  meta = with lib; {
+    homepage = https://github.com/Microsoft/CNTK;
+    description = "An open source deep-learning toolkit";
+    license = if onebitSGDSupport then licenses.unfreeRedistributable else licenses.mit;
+    maintainers = with maintainers; [ abbradar ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/cntk/fix_std_bind.patch b/nixpkgs/pkgs/applications/science/math/cntk/fix_std_bind.patch
new file mode 100644
index 000000000000..df97a0c66669
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/cntk/fix_std_bind.patch
@@ -0,0 +1,11 @@
+diff -ru3 CNTK-old/Source/CNTKv2LibraryDll/EvaluatorWrapper.h CNTK-new/Source/CNTKv2LibraryDll/EvaluatorWrapper.h
+--- CNTK-old/Source/CNTKv2LibraryDll/EvaluatorWrapper.h	1970-01-01 03:00:01.000000000 +0300
++++ CNTK-new/Source/CNTKv2LibraryDll/EvaluatorWrapper.h	2018-02-25 18:16:16.330269647 +0300
+@@ -9,6 +9,7 @@
+ #include <boost/noncopyable.hpp>
+ #include <memory>
+ #include <vector>
++#include <functional>
+ 
+ #include "CNTKLibrary.h"
+ #include "CNTKLibraryC.h"
diff --git a/nixpkgs/pkgs/applications/science/math/colpack/default.nix b/nixpkgs/pkgs/applications/science/math/colpack/default.nix
new file mode 100644
index 000000000000..94e0a44226d4
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/colpack/default.nix
@@ -0,0 +1,32 @@
+{ stdenv, fetchFromGitHub, autoconf, automake, libtool, gettext }:
+
+stdenv.mkDerivation rec {
+
+  pname = "ColPack";
+  version = "1.0.10";
+  name = pname + "-" + version;
+
+  src = fetchFromGitHub {
+    owner = "CSCsw";
+    repo = pname;
+    rev = "v" + version;
+    sha256 = "1p05vry940mrjp6236c0z83yizmw9pk6ly2lb7d8rpb7j9h03glr";
+  };
+
+  buildInputs = [ autoconf automake gettext libtool ];
+
+  configurePhase = ''
+    autoreconf -vif
+    ./configure --prefix=$out --enable-openmp
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A package comprising of implementations of algorithms for
+    vertex coloring and derivative computation";
+    homepage = "http://cscapes.cs.purdue.edu/coloringpage/software.htm#functionalities";
+    license = licenses.lgpl3;
+    platforms = platforms.linux;
+    maintainers = with maintainers; [ edwtjo ];
+  };
+
+}
diff --git a/nixpkgs/pkgs/applications/science/math/cplex/default.nix b/nixpkgs/pkgs/applications/science/math/cplex/default.nix
new file mode 100644
index 000000000000..fe3913648f87
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/cplex/default.nix
@@ -0,0 +1,82 @@
+{ stdenv, makeWrapper, openjdk, gtk2, xorg, glibcLocales, releasePath }:
+
+# To use this package, you need to download your own cplex installer from IBM
+# and override the releasePath attribute to point to the location of the file.  
+#
+# Note: cplex creates an individual build for each license which screws
+# somewhat with the use of functions like requireFile as the hash will be
+# different for every user.
+
+stdenv.mkDerivation rec {
+  name = "cplex-${version}";
+  version = "128";
+  
+  src =
+    if builtins.isNull releasePath then
+      throw ''
+        This nix expression requires that the cplex installer is already
+        downloaded to your machine. Get it from IBM: 
+        https://developer.ibm.com/docloud/blog/2017/12/20/cplex-optimization-studio-12-8-now-available/ 
+
+        Set `cplex.releasePath = /path/to/download;` in your
+        ~/.config/nixpkgs/config.nix for `nix-*` commands, or
+        `config.cplex.releasePath = /path/to/download;` in your
+        `configuration.nix` for NixOS.
+      ''
+    else
+      releasePath;
+
+  nativeBuildInputs = [ makeWrapper ];
+  buildInputs = [ openjdk gtk2 xorg.libXtst glibcLocales ];
+
+  unpackPhase = "cp $src $name";
+
+  patchPhase = ''
+    sed -i -e 's|/usr/bin/tr"|tr"         |' $name
+  '';
+
+  buildPhase = ''
+    sh $name -i silent -DLICENSE_ACCEPTED=TRUE -DUSER_INSTALL_DIR=$out
+  '';
+
+  installPhase = ''
+    mkdir -p $out/bin
+    ln -s $out/opl/bin/x86-64_linux/oplrun\
+      $out/opl/bin/x86-64_linux/oplrunjava\
+      $out/opl/oplide/oplide\
+      $out/cplex/bin/x86-64_linux/cplex\
+      $out/cpoptimizer/bin/x86-64_linux/cpoptimizer\
+      $out/bin
+  '';
+
+  fixupPhase = 
+  let 
+    libraryPath = stdenv.lib.makeLibraryPath [ stdenv.cc.cc gtk2 xorg.libXtst ];
+  in ''
+    interpreter=${stdenv.glibc}/lib/ld-linux-x86-64.so.2
+
+    for pgm in $out/opl/bin/x86-64_linux/oplrun $out/opl/bin/x86-64_linux/oplrunjava $out/opl/oplide/oplide;
+    do
+      patchelf --set-interpreter "$interpreter" $pgm;
+      wrapProgram $pgm \
+        --prefix LD_LIBRARY_PATH : $out/opl/bin/x86-64_linux:${libraryPath} \
+        --set LOCALE_ARCHIVE ${glibcLocales}/lib/locale/locale-archive;
+    done
+
+    for pgm in $out/cplex/bin/x86-64_linux/cplex $out/cpoptimizer/bin/x86-64_linux/cpoptimizer $out/opl/oplide/jre/bin/*; 
+    do
+      if grep ELF $pgm > /dev/null;
+      then
+        patchelf --set-interpreter "$interpreter" $pgm;
+      fi
+    done
+  '';
+  
+  meta = with stdenv.lib; {
+    description = "Optimization solver for mathematical programming";
+    homepage = "https://www.ibm.com/be-en/marketplace/ibm-ilog-cplex";
+    license = licenses.unfree;
+    platforms = [ "x86_64-linux" ];
+    maintainers = with maintainers; [ bfortz ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/csdp/default.nix b/nixpkgs/pkgs/applications/science/math/csdp/default.nix
new file mode 100644
index 000000000000..9b402fe0ac94
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/csdp/default.nix
@@ -0,0 +1,29 @@
+{ lib, stdenv, fetchurl, blas, gfortran, liblapack }:
+
+stdenv.mkDerivation {
+  name = "csdp-6.1.1";
+
+  src = fetchurl {
+    url = "https://www.coin-or.org/download/source/Csdp/Csdp-6.1.1.tgz";
+    sha256 = "1f9ql6cjy2gwiyc51ylfan24v1ca9sjajxkbhszlds1lqmma8n05";
+  };
+
+  buildInputs = [ blas gfortran.cc.lib liblapack ];
+
+  postPatch = ''
+    substituteInPlace Makefile --replace /usr/local/bin $out/bin
+  '';
+
+  preInstall = ''
+    rm -f INSTALL
+    mkdir -p $out/bin
+  '';
+
+  meta = {
+    homepage = https://projects.coin-or.org/Csdp;
+    license = lib.licenses.cpl10;
+    maintainers = [ lib.maintainers.roconnor ];
+    description = "A C Library for Semidefinite Programming";
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/ecm/default.nix b/nixpkgs/pkgs/applications/science/math/ecm/default.nix
new file mode 100644
index 000000000000..7b768f7077e7
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/ecm/default.nix
@@ -0,0 +1,31 @@
+{ stdenv, fetchurl, gmp, m4 }:
+
+let
+  pname = "ecm";
+  version = "7.0.4";
+  name = "${pname}-${version}";
+in
+
+stdenv.mkDerivation {
+  inherit name;
+
+  src = fetchurl {
+    url = "http://gforge.inria.fr/frs/download.php/file/36224/ecm-${version}.tar.gz";
+    sha256 = "0hxs24c2m3mh0nq1zz63z3sb7dhy1rilg2s1igwwcb26x3pb7xqc";
+  };
+
+  # See https://trac.sagemath.org/ticket/19233
+  configureFlags = stdenv.lib.optional stdenv.isDarwin "--disable-asm-redc";
+
+  buildInputs = [ m4 gmp ];
+
+  doCheck = true;
+
+  meta = {
+    description = "Elliptic Curve Method for Integer Factorization";
+    license = stdenv.lib.licenses.gpl2Plus;
+    homepage = http://ecm.gforge.inria.fr/;
+    maintainers = [ stdenv.lib.maintainers.roconnor ];
+    platforms = with stdenv.lib.platforms; linux ++ darwin;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/eukleides/default.nix b/nixpkgs/pkgs/applications/science/math/eukleides/default.nix
new file mode 100644
index 000000000000..6d1c778d1e0e
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/eukleides/default.nix
@@ -0,0 +1,37 @@
+{ stdenv, fetchurl, bison, flex, texinfo, readline, texLive }:
+
+let
+  name    = "eukleides";
+  version = "1.5.4";
+in
+stdenv.mkDerivation {
+  name = "${name}-${version}";
+
+  src = fetchurl {
+    url = "http://www.eukleides.org/files/${name}-${version}.tar.bz2";
+    sha256 = "0s8cyh75hdj89v6kpm3z24i48yzpkr8qf0cwxbs9ijxj1i38ki0q";
+  };
+
+  buildInputs = [bison flex texinfo readline texLive];
+
+  preConfigure = "sed -i 's/ginstall-info/install-info/g' doc/Makefile";
+  installPhase = "mkdir -p $out/bin ; make PREFIX=$out install";
+
+  meta = {
+    description = "Geometry Drawing Language";
+    homepage = http://www.eukleides.org/;
+    license = stdenv.lib.licenses.gpl2;
+
+    longDescription = ''
+      Eukleides is a computer language devoted to elementary plane
+      geometry. It aims to be a fairly comprehensive system to create
+      geometric figures, either static or dynamic. Eukleides allows to
+      handle basic types of data: numbers and strings, as well as
+      geometric types of data: points, vectors, sets (of points), lines,
+      circles and conics.
+    '';
+
+    platforms = stdenv.lib.platforms.linux;
+    maintainers = [ stdenv.lib.maintainers.peti ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/form/default.nix b/nixpkgs/pkgs/applications/science/math/form/default.nix
new file mode 100644
index 000000000000..88f2367e3340
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/form/default.nix
@@ -0,0 +1,22 @@
+{ stdenv, fetchurl, gmp, zlib }:
+
+stdenv.mkDerivation rec {
+  version = "4.2.0";
+  name = "form-${version}";
+
+  # This tarball is released by author, it is not downloaded from tag, so can't use fetchFromGitHub
+  src = fetchurl {
+    url = "https://github.com/vermaseren/form/releases/download/v4.2.0/form-4.2.0.tar.gz";
+    sha256 = "19528aphn4hvm151lyyhd7wz0bp2s3rla8jv6s7d8jwfp5ljzysm";
+  };
+
+  buildInputs = [ gmp zlib ];
+
+  meta = with stdenv.lib; {
+    description = "The FORM project for symbolic manipulation of very big expressions";
+    homepage = https://www.nikhef.nl/~form/;
+    license = licenses.gpl3;
+    maintainers = [ maintainers.veprbl ];
+    platforms = platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/fricas/default.nix b/nixpkgs/pkgs/applications/science/math/fricas/default.nix
new file mode 100644
index 000000000000..7d1f738641a6
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/fricas/default.nix
@@ -0,0 +1,27 @@
+{ stdenv, fetchurl, sbcl, libX11, libXpm, libICE, libSM, libXt, libXau, libXdmcp }:
+
+let
+  version = "1.3.4";
+  name = "fricas-" + version;
+in
+stdenv.mkDerivation {
+  inherit name;
+
+  src = fetchurl {
+    url    = "mirror://sourceforge/fricas/files/fricas/${version}/${name}-full.tar.bz2";
+    sha256 = "156k9az1623y5808j845c56z2nvvdrm48dzg1v0ivpplyl7vp57x";
+  };
+
+  buildInputs = [ sbcl libX11 libXpm libICE libSM libXt libXau libXdmcp ];
+
+  dontStrip = true;
+
+  meta = {
+    homepage = http://fricas.sourceforge.net/;
+    description = "An advanced computer algebra system";
+    license = stdenv.lib.licenses.bsd3;
+
+    platforms = stdenv.lib.platforms.linux;
+    maintainers = [ stdenv.lib.maintainers.sprock ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/gap/default.nix b/nixpkgs/pkgs/applications/science/math/gap/default.nix
new file mode 100644
index 000000000000..2927701dbd71
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/gap/default.nix
@@ -0,0 +1,103 @@
+{ stdenv
+, fetchurl
+, fetchpatch
+, m4
+, gmp
+# don't remove any packages -- results in a ~1.3G size increase
+# see https://github.com/NixOS/nixpkgs/pull/38754 for a discussion
+, keepAllPackages ? true
+}:
+
+stdenv.mkDerivation rec {
+  pname = "gap";
+  # https://www.gap-system.org/Releases/
+  # newer versions (4.9.0) are available, but still considered beta (https://github.com/gap-system/gap/wiki/GAP-4.9-release-notes)
+  version = "4r8p10";
+  pkgVer = "2018_01_15-13_02";
+  name = "${pname}-${version}";
+
+  src = let
+    # 4r8p10 -> 48
+    majorminor = stdenv.lib.replaceStrings ["r"] [""] (
+      builtins.head (stdenv.lib.splitString "p" version) # 4r8p10 -> 4r8
+    );
+  in
+    fetchurl {
+    url = "https://www.gap-system.org/pub/gap/gap${majorminor}/tar.bz2/gap${version}_${pkgVer}.tar.bz2";
+    sha256 = "0wzfdjnn6sfiaizbk5c7x44rhbfayis4lf57qbqqg84c7dqlwr6f";
+  };
+
+  # remove all non-essential packages (which take up a lot of space)
+  preConfigure = stdenv.lib.optionalString (!keepAllPackages) ''
+    find pkg -type d -maxdepth 1 -mindepth 1 \
+       -not -name 'GAPDoc-*' \
+       -not -name 'autpgrp*' \
+       -exec echo "Removing package {}" \; \
+       -exec rm -r {} \;
+  '';
+
+  configureFlags = [ "--with-gmp=system" ];
+  buildInputs = [ m4 gmp ];
+
+  patches = [
+    #  fix infinite loop in writeandcheck() when writing an error message fails.
+    (fetchpatch {
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/gap/patches/writeandcheck.patch?id=07d6c37d18811e2b377a9689790a7c5e24da16ba";
+      sha256 = "1r1511x4kc2i2mbdq1b61rb6p3misvkf1v5qy3z6fmn6vqwziaz1";
+    })
+  ];
+
+  doCheck = true;
+  checkTarget = "testinstall";
+  # "teststandard" is a superset of testinstall. It takes ~1h instead of ~1min.
+  # tests are run twice, once with all packages loaded and once without
+  # checkTarget = "teststandard";
+
+  preCheck = ''
+    # gap tests check that the home directory exists
+    export HOME="$TMP/gap-home"
+    mkdir -p "$HOME"
+  '';
+
+  postCheck = ''
+    # The testsuite doesn't exit with a non-zero exit code on failure.
+    # It leaves its logs in dev/log however.
+
+    # grep for error messages
+    if grep ^##### dev/log/*; then
+        exit 1
+    fi
+  '';
+
+  postBuild = ''
+    pushd pkg
+    bash ../bin/BuildPackages.sh
+    popd
+  '';
+
+  installPhase = ''
+    mkdir -p "$out/bin" "$out/share/gap/"
+
+    cp -r . "$out/share/gap/build-dir"
+
+    sed -e "/GAP_DIR=/aGAP_DIR='$out/share/gap/build-dir/'" -i "$out/share/gap/build-dir/bin/gap.sh"
+
+    ln -s "$out/share/gap/build-dir/bin/gap.sh" "$out/bin/gap"
+  '';
+
+  meta = with stdenv.lib; {
+    description = "Computational discrete algebra system";
+    maintainers = with maintainers;
+    [
+      raskin
+      chrisjefferson
+    ];
+    platforms = platforms.all;
+    # keeping all packages increases the package size considerably, wchich
+    # is why a local build is preferable in that situation. The timeframe
+    # is reasonable and that way the binary cache doesn't get overloaded.
+    hydraPlatforms = stdenv.lib.optionals (!keepAllPackages) meta.platforms;
+    license = licenses.gpl2;
+    homepage = http://gap-system.org/;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/geogebra/default.nix b/nixpkgs/pkgs/applications/science/math/geogebra/default.nix
new file mode 100644
index 000000000000..755a60940388
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/geogebra/default.nix
@@ -0,0 +1,63 @@
+{ stdenv, fetchurl, jre, makeDesktopItem, makeWrapper, language ? "en_US" }:
+
+stdenv.mkDerivation rec {
+  name = "geogebra-${version}";
+  version = "5-0-472-0";
+
+  preferLocalBuild = true;
+
+  src = fetchurl {
+    urls = [
+      "https://download.geogebra.org/installers/5.0/GeoGebra-Linux-Portable-${version}.tar.bz2"
+      "http://web.archive.org/https://download.geogebra.org/installers/5.0/GeoGebra-Linux-Portable-${version}.tar.bz2"
+    ];
+    sha256 = "1f56k5r5wf2l27sgp2vjpvx7wl72gizwxs0a6hngk15nzzka87v9";
+  };
+
+  srcIcon = fetchurl {
+    url = "http://static.geogebra.org/images/geogebra-logo.svg";
+    sha256 = "01sy7ggfvck350hwv0cla9ynrvghvssqm3c59x4q5lwsxjsxdpjm";
+  };
+
+  desktopItem = makeDesktopItem {
+    name = "geogebra";
+    exec = "geogebra";
+    icon = "geogebra";
+    desktopName = "Geogebra";
+    genericName = "Geogebra";
+    comment = meta.description;
+    categories = "Education;Science;Math;";
+    mimeType = "application/vnd.geogebra.file;application/vnd.geogebra.tool;";
+  };
+
+  buildInputs = [ makeWrapper ];
+
+  installPhase = ''
+    install -D geogebra/* -t "$out/libexec/geogebra/"
+
+    makeWrapper "$out/libexec/geogebra/geogebra" "$out/bin/geogebra" \
+      --set JAVACMD "${jre}/bin/java" \
+      --set GG_PATH "$out/libexec/geogebra" \
+      --add-flags "--language=${language}"
+
+    install -Dm644 "${desktopItem}/share/applications/"* \
+      -t $out/share/applications/
+
+    install -Dm644 "${srcIcon}" \
+      "$out/share/icons/hicolor/scalable/apps/geogebra.svg"
+  '';
+
+  meta = with stdenv.lib; {
+    description = "Dynamic mathematics software with graphics, algebra and spreadsheets";
+    longDescription = ''
+      Dynamic mathematics software for all levels of education that brings
+      together geometry, algebra, spreadsheets, graphing, statistics and
+      calculus in one easy-to-use package.
+    '';
+    homepage = https://www.geogebra.org/;
+    maintainers = with maintainers; [ ma27 ];
+    license = with licenses; [ gpl3 cc-by-nc-sa-30 geogebra ];
+    platforms = platforms.all;
+    hydraPlatforms = [];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/gfan/default.nix b/nixpkgs/pkgs/applications/science/math/gfan/default.nix
new file mode 100644
index 000000000000..d2d1ddb65846
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/gfan/default.nix
@@ -0,0 +1,28 @@
+{stdenv, fetchurl, gmp, mpir, cddlib}:
+stdenv.mkDerivation rec {
+  name = "${pname}-${version}";
+  pname = "gfan";
+  version = "0.6.2";
+
+  src = fetchurl {
+    url = "http://home.math.au.dk/jensen/software/gfan/gfan${version}.tar.gz";
+    sha256 = "02pihqb1lb76a0xbfwjzs1cd6ay3ldfxsm8dvsbl6qs3vkjxax56";
+  };
+
+  patchPhase = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace Makefile --replace "-fno-guess-branch-probability" ""
+  '';
+
+  buildFlags = [ "CC=cc" "CXX=c++" "cddnoprefix=1" ];
+  installFlags = [ ''PREFIX=$(out)'' ];
+  buildInputs = [ gmp mpir cddlib ];
+
+  meta = {
+    inherit version;
+    description = ''A software package for computing Gröbner fans and tropical varieties'';
+    license = stdenv.lib.licenses.gpl2 ;
+    maintainers = [stdenv.lib.maintainers.raskin];
+    platforms = stdenv.lib.platforms.unix;
+    homepage = http://home.math.au.dk/jensen/software/gfan/gfan.html;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/giac/default.nix b/nixpkgs/pkgs/applications/science/math/giac/default.nix
new file mode 100644
index 000000000000..ad82d7572e34
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/giac/default.nix
@@ -0,0 +1,112 @@
+{ stdenv, fetchurl, fetchpatch, texlive, bison, flex, liblapack
+, gmp, mpfr, pari, ntl, gsl, blas, mpfi, ecm, glpk, nauty
+, readline, gettext, libpng, libao, gfortran, perl
+, enableGUI ? false, libGLU_combined ? null, xorg ? null, fltk ? null
+}:
+
+assert enableGUI -> libGLU_combined != null && xorg != null && fltk != null;
+
+stdenv.mkDerivation rec {
+  name = "${attr}-${version}";
+  attr = if enableGUI then "giac-with-xcas" else "giac";
+  version = "1.5.0-21"; # TODO try to remove preCheck phase on upgrade
+
+  src = fetchurl {
+    url = "https://www-fourier.ujf-grenoble.fr/~parisse/debian/dists/stable/main/source/giac_${version}.tar.gz";
+    sha256 = "1b9khiv0mk2xzw1rblm2jy6qsf8y6f9k7qy15sxpb21d72hzzbl2";
+  };
+
+  patches = stdenv.lib.optionals (!enableGUI) [
+    # when enableGui is false, giac is compiled without fltk. That means some
+    # outputs differ in the make check. Patch around this:
+    (fetchpatch {
+      url    = "https://git.sagemath.org/sage.git/plain/build/pkgs/giac/patches/nofltk-check.patch?id=7553a3c8dfa7bcec07241a07e6a4e7dcf5bb4f26";
+      sha256 = "0xkmfc028vg5w6va04gp2x2iv31n8v4shd6vbyvk4blzgfmpj2cw";
+    })
+  ];
+
+  postPatch = ''
+    for i in doc/*/Makefile*; do
+      substituteInPlace "$i" --replace "/bin/cp" "cp";
+    done;
+  '';
+
+  nativeBuildInputs = [
+    texlive.combined.scheme-small bison flex
+  ];
+
+  # perl is only needed for patchShebangs fixup.
+  buildInputs = [
+    gmp mpfr pari ntl gsl blas mpfi glpk nauty
+    readline gettext libpng libao perl ecm
+    # gfortran.cc default output contains static libraries compiled without -fPIC
+    # we want libgfortran.so.3 instead
+    (stdenv.lib.getLib gfortran.cc)
+    liblapack
+  ] ++ stdenv.lib.optionals enableGUI [
+    libGLU_combined fltk xorg.libX11
+  ];
+
+  /* fixes:
+  configure:16211: checking for main in -lntl
+  configure:16230: g++ -o conftest -g -O2   conftest.cpp -lntl  -llapack -lblas -lgfortran -ldl -lpng16 -lm -lmpfi -lmpfr -lgmp  >&5
+  /nix/store/y9c1v4x7y39j2rfbg17agjwqdzxpsn18-ntl-11.3.2/lib/libntl.so: undefined reference to `pthread_key_create'
+  */
+  NIX_CFLAGS_LINK="-lpthread";
+
+  # xcas Phys and Turtle menus are broken with split outputs
+  # and interactive use is likely to need docs
+  outputs = [ "out" ] ++ stdenv.lib.optional (!enableGUI) "doc";
+
+  doCheck = true;
+  preCheck = ''
+    # One test in this file fails. That test just tests a part of the pari
+    # interface that isn't actually used in giac. Of course it would be better
+    # to only remove that one test, but that would require a patch.
+    # Removing the whole test set should be good enough for now.
+    # Upstream report: https://xcas.univ-grenoble-alpes.fr/forum/viewtopic.php?f=4&t=2102#p10326
+    echo > check/chk_fhan11
+  '';
+
+  enableParallelBuilding = true;
+
+  configureFlags = [
+    "--enable-gc" "--enable-png" "--enable-gsl" "--enable-lapack"
+    "--enable-pari" "--enable-ntl" "--enable-gmpxx" # "--enable-cocoa"
+    "--enable-ao" "--enable-ecm" "--enable-glpk"
+  ] ++ stdenv.lib.optionals enableGUI [
+    "--enable-gui" "--with-x"
+  ];
+
+  postInstall = ''
+    # example Makefiles contain the full path to some commands
+    # notably texlive, and we don't want texlive to become a runtime
+    # dependency
+    for file in $(find $out -name Makefile) ; do
+      sed -i "s@/nix/store/[^/]*/bin/@@" "$file" ;
+    done;
+
+    # reference cycle
+    rm "$out/share/giac/doc/el/"{casinter,tutoriel}/Makefile
+
+    if [ -n "$doc" ]; then
+      mkdir -p "$doc/share/giac"
+      mv "$out/share/giac/doc" "$doc/share/giac"
+      mv "$out/share/giac/examples" "$doc/share/giac"
+    fi
+  '' + stdenv.lib.optionalString (!enableGUI) ''
+    for i in pixmaps application-registry applications icons; do
+      rm -r "$out/share/$i";
+    done;
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A free computer algebra system (CAS)";
+    homepage = "https://www-fourier.ujf-grenoble.fr/~parisse/giac.html";
+    license = licenses.gpl3Plus;
+    ## xcas is buildable on darwin but there are specific instructions I could
+    ## not test
+    platforms = platforms.linux;
+    maintainers = [ maintainers.symphorien ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/ginac/default.nix b/nixpkgs/pkgs/applications/science/math/ginac/default.nix
new file mode 100644
index 000000000000..18a5281bebb0
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/ginac/default.nix
@@ -0,0 +1,28 @@
+{ stdenv, fetchurl, cln, pkgconfig, readline, gmp, python }:
+
+stdenv.mkDerivation rec {
+  name = "ginac-1.7.4";
+
+  src = fetchurl {
+    url    = "${meta.homepage}/${name}.tar.bz2";
+    sha256 = "1vvqv73yk9klbq0mz239zzw77rlp72qcvzci4j1v6rafvji1616n";
+  };
+
+  propagatedBuildInputs = [ cln ];
+
+  buildInputs = [ readline ] ++ stdenv.lib.optional stdenv.isDarwin gmp;
+
+  nativeBuildInputs = [ pkgconfig python ];
+
+  preConfigure = "patchShebangs ginsh";
+
+  configureFlags = [ "--disable-rpath" ];
+
+  meta = with stdenv.lib; {
+    description = "GiNaC is Not a CAS";
+    homepage    = http://www.ginac.de/;
+    maintainers = with maintainers; [ lovek323 ];
+    license = licenses.gpl2;
+    platforms   = platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/glsurf/default.nix b/nixpkgs/pkgs/applications/science/math/glsurf/default.nix
new file mode 100644
index 000000000000..4de683cdce90
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/glsurf/default.nix
@@ -0,0 +1,31 @@
+{ stdenv, fetchurl, ocamlPackages, libGLU_combined, freeglut
+, mysql, mpfr, gmp, libtiff, libjpeg, libpng, giflib
+}:
+
+stdenv.mkDerivation {
+  name = "glsurf-3.3.1";
+
+  src = fetchurl {
+    url = "https://lama.univ-savoie.fr/~raffalli/glsurf/glsurf-3.3.1.tar.gz";
+    sha256 = "0w8xxfnw2snflz8wdr2ca9f5g91w5vbyp1hwlx1v7vg83d4bwqs7";
+  };
+
+  buildInputs = [ freeglut libGLU_combined mysql.connector-c mpfr gmp
+    libtiff libjpeg libpng giflib ]
+  ++ (with ocamlPackages; [
+    ocaml findlib ocaml_mysql lablgl camlimages_4_0 mlgmpidl
+  ]);
+
+  installPhase = ''
+    mkdir -p $out/bin $out/share/doc/glsurf
+    cp ./src/glsurf.opt $out/bin/glsurf
+    cp ./doc/doc.pdf $out/share/doc/glsurf
+    cp -r ./examples $out/share/doc/glsurf
+  '';
+
+  meta = {
+    homepage = http://www.lama.univ-savoie.fr/~raffalli/glsurf;
+    description = "A program to draw implicit surfaces and curves";
+    license = stdenv.lib.licenses.lgpl21;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/gmsh/default.nix b/nixpkgs/pkgs/applications/science/math/gmsh/default.nix
new file mode 100644
index 000000000000..c689ae98b7ad
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/gmsh/default.nix
@@ -0,0 +1,29 @@
+{ stdenv, fetchurl, cmake, openblasCompat, gfortran, gmm, fltk, libjpeg
+, zlib, libGLU_combined, libGLU, xorg }:
+
+let version = "4.0.7"; in
+
+stdenv.mkDerivation {
+  name = "gmsh-${version}";
+
+  src = fetchurl {
+    url = "http://gmsh.info/src/gmsh-${version}-source.tgz";
+    sha256 = "c6572320d0ffdf7d2488e113861bc4bd9c38a29f7fc5b67957f6fbcb63fbdbd5";
+  };
+
+  buildInputs = [ cmake openblasCompat gmm fltk libjpeg zlib libGLU_combined
+    libGLU xorg.libXrender xorg.libXcursor xorg.libXfixes xorg.libXext
+    xorg.libXft xorg.libXinerama xorg.libX11 xorg.libSM xorg.libICE
+  ];
+
+  nativeBuildInputs = [ gfortran ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "A three-dimensional finite element mesh generator";
+    homepage = http://gmsh.info/;
+    platforms = [ "x86_64-linux" ];
+    license = stdenv.lib.licenses.gpl2Plus;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/gurobi/default.nix b/nixpkgs/pkgs/applications/science/math/gurobi/default.nix
new file mode 100644
index 000000000000..d4a4133d06e8
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/gurobi/default.nix
@@ -0,0 +1,54 @@
+{ stdenv, fetchurl, autoPatchelfHook, python }:
+
+stdenv.mkDerivation rec {
+  name = "gurobi-${version}";
+  version = "8.0.1";
+
+  src = with stdenv.lib; fetchurl {
+    url = "http://packages.gurobi.com/${versions.majorMinor version}/gurobi${version}_linux64.tar.gz";
+    sha256 = "0y3lb0mngnyn7ql4s2n8qxnr1d2xcjdpdhpdjdxc4sc8f2w2ih18";
+  };
+
+  sourceRoot = "gurobi${builtins.replaceStrings ["."] [""] version}/linux64";
+
+  nativeBuildInputs = [ autoPatchelfHook ];
+  buildInputs = [ (python.withPackages (ps: [ ps.gurobipy ])) ];
+
+  buildPhase = ''
+    cd src/build
+    make
+    cd ../..
+  '';
+
+  installPhase = ''
+    mkdir -p $out/bin
+    cp bin/* $out/bin/
+    rm $out/bin/gurobi.env
+    rm $out/bin/gurobi.sh
+    rm $out/bin/python2.7
+
+    cp lib/gurobi.py $out/bin/gurobi.sh
+
+    mkdir -p $out/include
+    cp include/gurobi*.h $out/include/
+
+    mkdir -p $out/lib
+    cp lib/*.jar $out/lib/
+    cp lib/libGurobiJni*.so $out/lib/
+    cp lib/libgurobi*.so* $out/lib/
+    cp lib/libgurobi*.a $out/lib/
+    cp src/build/*.a $out/lib/
+
+    mkdir -p $out/share/java
+    ln -s $out/lib/gurobi.jar $out/share/java/
+    ln -s $out/lib/gurobi-javadoc.jar $out/share/java/
+  '';
+
+  meta = with stdenv.lib; {
+    description = "Optimization solver for mathematical programming";
+    homepage = https://www.gurobi.com;
+    license = licenses.unfree;
+    platforms = [ "x86_64-linux" ];
+    maintainers = with maintainers; [ jfrankenau ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/hmetis/default.nix b/nixpkgs/pkgs/applications/science/math/hmetis/default.nix
new file mode 100644
index 000000000000..9eab9ca39992
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/hmetis/default.nix
@@ -0,0 +1,42 @@
+{ stdenv, fetchurl, ghostscript }:
+
+stdenv.mkDerivation rec {
+  name = "hmetis-${version}";
+  version = "1.5";
+
+  src = fetchurl {
+    url = "http://glaros.dtc.umn.edu/gkhome/fetch/sw/hmetis/hmetis-${version}-linux.tar.gz";
+    sha256 = "e835a098c046e9c26cecb8addfea4d18ff25214e49585ffd87038e72819be7e1";
+  };
+
+  nativeBuildInputs = [ ghostscript ];
+
+  binaryFiles = "hmetis khmetis shmetis";
+
+  patchPhase = ''
+    for binaryfile in $binaryFiles; do
+      patchelf \
+        --set-interpreter ${stdenv.glibc}/lib/ld-linux.so.2 \
+        --set-rpath ${stdenv.glibc}/lib \
+        $binaryfile
+    done
+  '';
+
+  buildPhase = ''
+    gs -sOutputFile=manual.pdf -sDEVICE=pdfwrite -SNOPAUSE -dBATCH manual.ps
+  '';
+
+  installPhase = ''
+    mkdir -p $out/bin $out/share/doc/hmetis $out/lib
+    mv $binaryFiles $out/bin
+    mv manual.pdf $out/share/doc/hmetis
+    mv libhmetis.a $out/lib
+  '';
+
+  meta = with stdenv.lib; {
+    description = "hMETIS is a set of programs for partitioning hypergraphs";
+    homepage = http://glaros.dtc.umn.edu/gkhome/metis/hmetis/overview;
+    license = licenses.unfree;
+    platforms = [ "i686-linux" "x86_64-linux" ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/jags/default.nix b/nixpkgs/pkgs/applications/science/math/jags/default.nix
new file mode 100644
index 000000000000..1d1fb96a4739
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/jags/default.nix
@@ -0,0 +1,19 @@
+{stdenv, fetchurl, gfortran, openblas}:
+
+stdenv.mkDerivation rec {
+  name = "JAGS-4.3.0";
+  src = fetchurl {
+    url = "mirror://sourceforge/mcmc-jags/${name}.tar.gz";
+    sha256 = "1z3icccg2ic56vmhyrpinlsvpq7kcaflk1731rgpvz9bk1bxvica";
+  };
+  buildInputs = [gfortran openblas];
+  configureFlags = [ "--with-blas=-lopenblas" "--with-lapack=-lopenblas" ];
+
+  meta = with stdenv.lib; {
+    description = "Just Another Gibbs Sampler";
+    license     = licenses.gpl2;
+    homepage    = http://mcmc-jags.sourceforge.net;
+    maintainers = [ maintainers.andres ];
+    platforms = platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/lp_solve/default.nix b/nixpkgs/pkgs/applications/science/math/lp_solve/default.nix
new file mode 100644
index 000000000000..0cf834c8cdea
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/lp_solve/default.nix
@@ -0,0 +1,49 @@
+{ stdenv, fetchurl }:
+
+stdenv.mkDerivation rec {
+
+  name = "lp_solve-${version}";
+  version = "5.5.2.5";
+
+  src = fetchurl {
+    url = "mirror://sourceforge/project/lpsolve/lpsolve/${version}/lp_solve_${version}_source.tar.gz";
+    sha256 = "12pj1idjz31r7c2mb5w03vy1cmvycvbkx9z29s40qdmkp1i7q6i0";
+  };
+
+  patches = [ ./isnan.patch ];
+
+  buildCommand = ''
+    . $stdenv/setup
+    tar xvfz $src
+    (
+    cd lp_solve*
+    eval patchPhase
+    )
+    (
+    cd lp_solve*/lpsolve55
+    bash ccc
+    mkdir -pv $out/lib
+    cp -v bin/*/* $out/lib
+    )
+    (
+    cd lp_solve*/lp_solve
+    bash ccc
+    mkdir -pv $out/bin
+    cp -v bin/*/* $out/bin
+    )
+    (
+    mkdir -pv $out/include
+    cp -v lp_solve*/*.h $out/include
+    )
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A Mixed Integer Linear Programming (MILP) solver";
+    homepage    = "http://lpsolve.sourceforge.net";
+    license     = licenses.gpl2Plus;
+    maintainers = with maintainers; [ smironov ];
+    platforms   = platforms.unix;
+  };
+
+}
+
diff --git a/nixpkgs/pkgs/applications/science/math/lp_solve/isnan.patch b/nixpkgs/pkgs/applications/science/math/lp_solve/isnan.patch
new file mode 100644
index 000000000000..bc1983d4423d
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/lp_solve/isnan.patch
@@ -0,0 +1,13 @@
+diff -u a/lp_lib.h b/lp_lib.h
+--- a/lp_lib.h	2016-05-04 19:45:15.753143720 +0900
++++ b/lp_lib.h	2016-05-04 19:53:59.536920722 +0900
+@@ -59,9 +59,6 @@
+ # if defined _WIN32 && !defined __GNUC__
+ #  define isnan _isnan
+ # endif
+-#if defined NOISNAN
+-# define isnan(x) FALSE
+-#endif
+ 
+ #define SETMASK(variable, mask)     variable |= mask
+ #define CLEARMASK(variable, mask)   variable &= ~(mask)
diff --git a/nixpkgs/pkgs/applications/science/math/lrcalc/default.nix b/nixpkgs/pkgs/applications/science/math/lrcalc/default.nix
new file mode 100644
index 000000000000..9e02b08c8ad0
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/lrcalc/default.nix
@@ -0,0 +1,41 @@
+{ stdenv
+, fetchFromBitbucket
+, fetchpatch
+, autoreconfHook
+}:
+
+stdenv.mkDerivation rec {
+  version = "1.2";
+  pname = "lrcalc";
+  name = "${pname}-${version}";
+
+  src = fetchFromBitbucket {
+    owner = "asbuch";
+    repo = "lrcalc";
+    rev = "lrcalc-${version}";
+    sha256 = "1c12d04jdyxkkav4ak8d1aqrv594gzihwhpxvc6p9js0ry1fahss";
+  };
+
+  doCheck = true;
+
+  nativeBuildInputs = [
+    autoreconfHook
+  ];
+
+  patches = [
+    # Fix include syntax:
+    # For private includes, use `#include "..."` instead of `#include <...>`
+    (fetchpatch {
+      url = "https://bitbucket.org/asbuch/lrcalc/commits/226981a0/raw/";
+      sha256 = "02kaqx5s3l642rhh28kn2wg9wr098vzpknxyl4pv627lqa3lv9vm";
+    })
+  ];
+
+  meta = with stdenv.lib; {
+    description = "Littlewood-Richardson calculator";
+    homepage = http://math.rutgers.edu/~asbuch/lrcalc/;
+    license = licenses.gpl2Plus;
+    maintainers = with maintainers; [ timokau ];
+    platforms = platforms.linux;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/mathematica/10.nix b/nixpkgs/pkgs/applications/science/math/mathematica/10.nix
new file mode 100644
index 000000000000..c6802c3719e9
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mathematica/10.nix
@@ -0,0 +1,136 @@
+{ stdenv
+, coreutils
+, patchelf
+, requireFile
+, alsaLib
+, fontconfig
+, freetype
+, gcc
+, glib
+, ncurses
+, opencv
+, openssl
+, unixODBC
+, xorg
+, libxml2
+, libuuid
+}:
+
+let
+  platform =
+    if stdenv.hostPlatform.system == "i686-linux" || stdenv.hostPlatform.system == "x86_64-linux" then
+      "Linux"
+    else
+      throw "Mathematica requires i686-linux or x86_64 linux";
+in
+stdenv.mkDerivation rec {
+  version = "10.0.2";
+
+  name = "mathematica-${version}";
+
+  src = requireFile rec {
+    name = "Mathematica_${version}_LINUX.sh";
+    message = '' 
+      This nix expression requires that ${name} is
+      already part of the store. Find the file on your Mathematica CD
+      and add it to the nix store with nix-store --add-fixed sha256 <FILE>.
+    '';
+    sha256 = "1d2yaiaikzcacjamlw64g3xkk81m3pb4vz4an12cv8nb7kb20x9l";
+  };
+
+  buildInputs = [
+    coreutils
+    patchelf
+    alsaLib
+    coreutils
+    fontconfig
+    freetype
+    gcc.cc
+    gcc.libc
+    glib
+    ncurses
+    opencv
+    openssl
+    unixODBC
+    libxml2
+    libuuid
+  ] ++ (with xorg; [
+    libX11
+    libXext
+    libXtst
+    libXi
+    libXmu
+    libXrender
+    libxcb
+    libXcursor
+    libXfixes
+    libXrandr
+    libICE
+    libSM
+  ]);
+
+  ldpath = stdenv.lib.makeLibraryPath buildInputs
+    + stdenv.lib.optionalString (stdenv.hostPlatform.system == "x86_64-linux")
+      (":" + stdenv.lib.makeSearchPathOutput "lib" "lib64" buildInputs);
+
+  phases = "unpackPhase installPhase fixupPhase";
+
+  unpackPhase = ''
+    echo "=== Extracting makeself archive ==="
+    # find offset from file
+    offset=$(${stdenv.shell} -c "$(grep -axm1 -e 'offset=.*' $src); echo \$offset" $src)
+    dd if="$src" ibs=$offset skip=1 | tar -xf -
+    cd Unix
+  '';
+
+  installPhase = ''
+    cd Installer
+    # don't restrict PATH, that has already been done
+    sed -i -e 's/^PATH=/# PATH=/' MathInstaller
+
+    echo "=== Running MathInstaller ==="
+    ./MathInstaller -auto -createdir=y -execdir=$out/bin -targetdir=$out/libexec/Mathematica -platforms=${platform} -silent
+  '';
+
+  preFixup = ''
+    echo "=== PatchElfing away ==="
+    # This code should be a bit forgiving of errors, unfortunately
+    set +e
+    find $out/libexec/Mathematica/SystemFiles -type f -perm -0100 | while read f; do
+      type=$(readelf -h "$f" 2>/dev/null | grep 'Type:' | sed -e 's/ *Type: *\([A-Z]*\) (.*/\1/')
+      if [ -z "$type" ]; then
+        :
+      elif [ "$type" == "EXEC" ]; then
+        echo "patching $f executable <<"
+        patchelf --shrink-rpath "$f"
+        patchelf \
+	  --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" \
+          --set-rpath "$(patchelf --print-rpath "$f"):${ldpath}" \
+          "$f" \
+          && patchelf --shrink-rpath "$f" \
+          || echo unable to patch ... ignoring 1>&2
+      elif [ "$type" == "DYN" ]; then
+        echo "patching $f library <<"
+        patchelf \
+          --set-rpath "$(patchelf --print-rpath "$f"):${ldpath}" \
+          "$f" \
+          && patchelf --shrink-rpath "$f" \
+          || echo unable to patch ... ignoring 1>&2
+      else
+        echo "not patching $f <<: unknown elf type"
+      fi
+    done
+  '';
+
+  # all binaries are already stripped
+  dontStrip = true;
+
+  # we did this in prefixup already
+  dontPatchELF = true;
+
+  meta = {
+    description = "Wolfram Mathematica computational software system";
+    homepage = http://www.wolfram.com/mathematica/;
+    license = stdenv.lib.licenses.unfree;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/mathematica/9.nix b/nixpkgs/pkgs/applications/science/math/mathematica/9.nix
new file mode 100644
index 000000000000..1023e7ca3d5c
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mathematica/9.nix
@@ -0,0 +1,122 @@
+{ stdenv
+, coreutils
+, patchelf
+, requireFile
+, alsaLib
+, fontconfig
+, freetype
+, gcc
+, glib
+, ncurses
+, opencv
+, openssl
+, unixODBC
+, xorg
+}:
+
+let
+  platform =
+    if stdenv.hostPlatform.system == "i686-linux" || stdenv.hostPlatform.system == "x86_64-linux" then
+      "Linux"
+    else
+      throw "Mathematica requires i686-linux or x86_64 linux";
+in
+stdenv.mkDerivation rec {
+
+  name = "mathematica-9.0.0";
+
+  src = requireFile rec {
+    name = "Mathematica_9.0.0_LINUX.sh";
+    message = '' 
+      This nix expression requires that Mathematica_9.0.0_LINUX.sh is
+      already part of the store. Find the file on your Mathematica CD
+      and add it to the nix store with nix-store --add-fixed sha256 <FILE>.
+    '';
+    sha256 = "106zfaplhwcfdl9rdgs25x83xra9zcny94gb22wncbfxvrsk3a4q";
+  };
+
+  buildInputs = [
+    coreutils
+    patchelf
+    alsaLib
+    coreutils
+    fontconfig
+    freetype
+    gcc.cc
+    gcc.libc
+    glib
+    ncurses
+    opencv
+    openssl
+    unixODBC
+  ] ++ (with xorg; [
+    libX11
+    libXext
+    libXtst
+    libXi
+    libXmu
+    libXrender
+    libxcb
+  ]);
+
+  ldpath = stdenv.lib.makeLibraryPath buildInputs
+    + stdenv.lib.optionalString (stdenv.hostPlatform.system == "x86_64-linux")
+      (":" + stdenv.lib.makeSearchPathOutput "lib" "lib64" buildInputs);
+
+  phases = "unpackPhase installPhase fixupPhase";
+
+  unpackPhase = ''
+    echo "=== Extracting makeself archive ==="
+    # find offset from file
+    offset=$(${stdenv.shell} -c "$(grep -axm1 -e 'offset=.*' $src); echo \$offset" $src)
+    dd if="$src" ibs=$offset skip=1 | tar -xf -
+    cd Unix
+  '';
+
+  installPhase = ''
+    cd Installer
+    # don't restrict PATH, that has already been done
+    sed -i -e 's/^PATH=/# PATH=/' MathInstaller
+
+    echo "=== Running MathInstaller ==="
+    ./MathInstaller -auto -createdir=y -execdir=$out/bin -targetdir=$out/libexec/Mathematica -platforms=${platform} -silent
+  '';
+
+  preFixup = ''
+    echo "=== PatchElfing away ==="
+    find $out/libexec/Mathematica/SystemFiles -type f -perm -0100 | while read f; do
+      type=$(readelf -h "$f" 2>/dev/null | grep 'Type:' | sed -e 's/ *Type: *\([A-Z]*\) (.*/\1/')
+      if [ -z "$type" ]; then
+        :
+      elif [ "$type" == "EXEC" ]; then
+        echo "patching $f executable <<"
+        patchelf \
+            --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" \
+            --set-rpath "${ldpath}" \
+            "$f"
+        patchelf --shrink-rpath "$f"
+      elif [ "$type" == "DYN" ]; then
+        echo "patching $f library <<"
+        patchelf \
+          --set-rpath "$(patchelf --print-rpath "$f"):${ldpath}" \
+          "$f" \
+          && patchelf --shrink-rpath "$f" \
+          || echo unable to patch ... ignoring 1>&2
+      else
+        echo "not patching $f <<: unknown elf type"
+      fi
+    done
+  '';
+
+  # all binaries are already stripped
+  dontStrip = true;
+
+  # we did this in prefixup already
+  dontPatchELF = true;
+
+  meta = {
+    description = "Wolfram Mathematica computational software system";
+    homepage = http://www.wolfram.com/mathematica/;
+    license = stdenv.lib.licenses.unfree;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/mathematica/default.nix b/nixpkgs/pkgs/applications/science/math/mathematica/default.nix
new file mode 100644
index 000000000000..165a56605579
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mathematica/default.nix
@@ -0,0 +1,148 @@
+{ stdenv
+, coreutils
+, patchelf
+, callPackage
+, alsaLib
+, dbus
+, fontconfig
+, freetype
+, gcc
+, glib
+, ncurses
+, opencv
+, openssl
+, unixODBC
+, xkeyboard_config
+, xorg
+, zlib
+, libxml2
+, libuuid
+, lang ? "en"
+, libGL
+, libGLU
+}:
+
+let
+  l10n =
+    with stdenv.lib;
+    with callPackage ./l10ns.nix {};
+    flip (findFirst (l: l.lang == lang)) l10ns
+      (throw "Language '${lang}' not supported");
+in
+stdenv.mkDerivation rec {
+  inherit (l10n) version name src;
+
+  buildInputs = [
+    coreutils
+    patchelf
+    alsaLib
+    coreutils
+    dbus
+    fontconfig
+    freetype
+    gcc.cc
+    gcc.libc
+    glib
+    ncurses
+    opencv
+    openssl
+    unixODBC
+    xkeyboard_config
+    libxml2
+    libuuid
+    zlib
+    libGL
+    libGLU
+  ] ++ (with xorg; [
+    libX11
+    libXext
+    libXtst
+    libXi
+    libXmu
+    libXrender
+    libxcb
+    libXcursor
+    libXfixes
+    libXrandr
+    libICE
+    libSM
+  ]);
+
+  ldpath = stdenv.lib.makeLibraryPath buildInputs
+    + stdenv.lib.optionalString (stdenv.hostPlatform.system == "x86_64-linux")
+      (":" + stdenv.lib.makeSearchPathOutput "lib" "lib64" buildInputs);
+
+  phases = "unpackPhase installPhase fixupPhase";
+
+  unpackPhase = ''
+    echo "=== Extracting makeself archive ==="
+    # find offset from file
+    offset=$(${stdenv.shell} -c "$(grep -axm1 -e 'offset=.*' $src); echo \$offset" $src)
+    dd if="$src" ibs=$offset skip=1 | tar -xf -
+    cd Unix
+  '';
+
+  installPhase = ''
+    cd Installer
+    # don't restrict PATH, that has already been done
+    sed -i -e 's/^PATH=/# PATH=/' MathInstaller
+    sed -i -e 's/\/bin\/bash/\/bin\/sh/' MathInstaller
+
+    echo "=== Running MathInstaller ==="
+    ./MathInstaller -auto -createdir=y -execdir=$out/bin -targetdir=$out/libexec/Mathematica -silent
+
+    # Fix library paths
+    cd $out/libexec/Mathematica/Executables
+    for path in mathematica MathKernel Mathematica WolframKernel wolfram math; do
+      sed -i -e 's#export LD_LIBRARY_PATH$#export LD_LIBRARY_PATH=${zlib}/lib:\''${LD_LIBRARY_PATH}#' $path
+    done
+
+    # Fix xkeyboard config path for Qt
+    for path in mathematica Mathematica; do
+      line=$(grep -n QT_PLUGIN_PATH $path | sed 's/:.*//')
+      sed -i -e "$line iexport QT_XKB_CONFIG_ROOT=\"${xkeyboard_config}/share/X11/xkb\"" $path
+    done
+  '';
+
+  preFixup = ''
+    echo "=== PatchElfing away ==="
+    # This code should be a bit forgiving of errors, unfortunately
+    set +e
+    find $out/libexec/Mathematica/SystemFiles -type f -perm -0100 | while read f; do
+      type=$(readelf -h "$f" 2>/dev/null | grep 'Type:' | sed -e 's/ *Type: *\([A-Z]*\) (.*/\1/')
+      if [ -z "$type" ]; then
+        :
+      elif [ "$type" == "EXEC" ]; then
+        echo "patching $f executable <<"
+        patchelf --shrink-rpath "$f"
+        patchelf \
+	  --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" \
+          --set-rpath "$(patchelf --print-rpath "$f"):${ldpath}" \
+          "$f" \
+          && patchelf --shrink-rpath "$f" \
+          || echo unable to patch ... ignoring 1>&2
+      elif [ "$type" == "DYN" ]; then
+        echo "patching $f library <<"
+        patchelf \
+          --set-rpath "$(patchelf --print-rpath "$f"):${ldpath}" \
+          "$f" \
+          && patchelf --shrink-rpath "$f" \
+          || echo unable to patch ... ignoring 1>&2
+      else
+        echo "not patching $f <<: unknown elf type"
+      fi
+    done
+  '';
+
+  # all binaries are already stripped
+  dontStrip = true;
+
+  # we did this in prefixup already
+  dontPatchELF = true;
+
+  meta = {
+    description = "Wolfram Mathematica computational software system";
+    homepage = http://www.wolfram.com/mathematica/;
+    license = stdenv.lib.licenses.unfree;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/mathematica/l10ns.nix b/nixpkgs/pkgs/applications/science/math/mathematica/l10ns.nix
new file mode 100644
index 000000000000..2158021c7548
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mathematica/l10ns.nix
@@ -0,0 +1,33 @@
+{ lib, requireFile }:
+
+with lib;
+{
+  l10ns = flip map
+  [
+    {
+      version = "11.2.0";
+      lang = "en";
+      language = "English";
+      sha256 = "4a1293cc1c404303aa1cab1bd273c7be151d37ac5ed928fbbb18e9c5ab2d8df9";
+    }
+    {
+      version = "11.2.0";
+      lang = "ja";
+      language = "Japanese";
+      sha256 = "916392edd32bed8622238df435dd8e86426bb043038a3336f30df10d819b49b1";
+    }
+  ]
+  ({ version, lang, language, sha256 }: {
+    inherit version lang;
+    name = "mathematica-${version}" + optionalString (lang != "en") "-${lang}";
+    src = requireFile rec {
+      name = "Mathematica_${version}" + optionalString (lang != "en") "_${language}" + "_LINUX.sh";
+      message = ''
+        This nix expression requires that ${name} is
+        already part of the store. Find the file on your Mathematica CD
+        and add it to the nix store with nix-store --add-fixed sha256 <FILE>.
+      '';
+      inherit sha256;
+    };
+  });
+}
diff --git a/nixpkgs/pkgs/applications/science/math/maxima/default.nix b/nixpkgs/pkgs/applications/science/math/maxima/default.nix
new file mode 100644
index 000000000000..9f6e281849d6
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/maxima/default.nix
@@ -0,0 +1,100 @@
+{ stdenv, fetchurl, fetchpatch, sbcl, texinfo, perl, python, makeWrapper, rlwrap ? null
+, tk ? null, gnuplot ? null, ecl ? null, ecl-fasl ? false
+}:
+
+let
+  name    = "maxima";
+  version = "5.41.0";
+
+  searchPath =
+    stdenv.lib.makeBinPath
+      (stdenv.lib.filter (x: x != null) [ sbcl ecl rlwrap tk gnuplot ]);
+in
+stdenv.mkDerivation ({
+  inherit version;
+  name = "${name}-${version}";
+
+  src = fetchurl {
+    url = "mirror://sourceforge/${name}/${name}-${version}.tar.gz";
+    sha256 = "0x0n81z0s4pl8nwpf7ivlsbvsdphm9w42250g7qdkizl0132by6s";
+  };
+
+  buildInputs = stdenv.lib.filter (x: x != null) [
+    sbcl ecl texinfo perl python makeWrapper
+  ];
+
+  postInstall = ''
+    # Make sure that maxima can find its runtime dependencies.
+    for prog in "$out/bin/"*; do
+      wrapProgram "$prog" --prefix PATH ":" "$out/bin:${searchPath}"
+    done
+    # Move emacs modules and documentation into the right place.
+    mkdir -p $out/share/emacs $out/share/doc
+    ln -s ../maxima/${version}/emacs $out/share/emacs/site-lisp
+    ln -s ../maxima/${version}/doc $out/share/doc/maxima
+  ''
+   + (stdenv.lib.optionalString ecl-fasl ''
+     cp src/binary-ecl/maxima.fas* "$out/lib/maxima/${version}/binary-ecl/"
+   '')
+  ;
+
+  patches = [
+    # fix path to info dir (see https://trac.sagemath.org/ticket/11348)
+    (fetchpatch {
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/maxima/patches/infodir.patch?id=07d6c37d18811e2b377a9689790a7c5e24da16ba";
+      sha256 = "09v64n60f7i6frzryrj0zd056lvdpms3ajky4f9p6kankhbiv21x";
+    })
+
+    # fix https://sourceforge.net/p/maxima/bugs/2596/
+    (fetchpatch {
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/maxima/patches/matrixexp.patch?id=07d6c37d18811e2b377a9689790a7c5e24da16ba";
+      sha256 = "06961hn66rhjijfvyym21h39wk98sfxhp051da6gz0n9byhwc6zg";
+    })
+
+    # undo https://sourceforge.net/p/maxima/code/ci/f5e9b0f7eb122c4e48ea9df144dd57221e5ea0ca, see see https://trac.sagemath.org/ticket/13364#comment:93
+    (fetchpatch {
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/maxima/patches/undoing_true_false_printing_patch.patch?id=07d6c37d18811e2b377a9689790a7c5e24da16ba";
+      sha256 = "0fvi3rcjv6743sqsbgdzazy9jb6r1p1yq63zyj9fx42wd1hgf7yx";
+    })
+
+    # upstream bug https://sourceforge.net/p/maxima/bugs/2520/ (not fixed)
+    # introduced in https://trac.sagemath.org/ticket/13364
+    (fetchpatch {
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/maxima/patches/0001-taylor2-Avoid-blowing-the-stack-when-diff-expand-isn.patch?id=07d6c37d18811e2b377a9689790a7c5e24da16ba";
+      sha256 = "0xa0b6cr458zp7lc7qi0flv5ar0r3ivsqhjl0c3clv86di2y522d";
+    })
+  ] ++ stdenv.lib.optionals ecl-fasl [
+    # build fasl, needed for ECL support
+    (fetchpatch {
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/maxima/patches/maxima.system.patch?id=07d6c37d18811e2b377a9689790a7c5e24da16ba";
+      sha256 = "18zafig8vflhkr80jq2ivk46k92dkszqlyq8cfmj0b2vcfjwwbar";
+    })
+    # There are some transient test failures. I hope this disables all those tests.
+    # If those test failures ever happen in the non-ecl version, that should be
+    # reportetd upstream.
+    ./known-ecl-failures.patch
+  ];
+
+  # Failures in the regression test suite won't abort the build process. We run
+  # the suite only so that potential errors show up in the build log. See also:
+  # https://sourceforge.net/tracker/?func=detail&aid=3365831&group_id=4933&atid=104933.
+  doCheck = true;
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "Computer algebra system";
+    homepage = http://maxima.sourceforge.net;
+    license = stdenv.lib.licenses.gpl2;
+
+    longDescription = ''
+      Maxima is a fairly complete computer algebra system written in
+      lisp with an emphasis on symbolic computation. It is based on
+      DOE-MACSYMA and licensed under the GPL. Its abilities include
+      symbolic integration, 3D plotting, and an ODE solver.
+    '';
+
+    platforms = stdenv.lib.platforms.unix;
+    maintainers = [ stdenv.lib.maintainers.peti ];
+  };
+})
diff --git a/nixpkgs/pkgs/applications/science/math/maxima/known-ecl-failures.patch b/nixpkgs/pkgs/applications/science/math/maxima/known-ecl-failures.patch
new file mode 100644
index 000000000000..f1d612d993e6
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/maxima/known-ecl-failures.patch
@@ -0,0 +1,21 @@
+diff --git a/tests/testsuite.lisp b/tests/testsuite.lisp
+index 45a81f4..36c35b8 100644
+--- a/tests/testsuite.lisp
++++ b/tests/testsuite.lisp
+@@ -25,13 +25,14 @@
+         ((mlist simp) "rtest10" 24 25)
+         ((mlist) "rtest11" #+(or gcl cmucl ccl64) 158 #+(or gcl cmucl ccl64) 174 #+gcl 175)
+         "rtest13" "rtest13s"
+-        "rtest14"
++        ;; "rtest14" ;; some tests sometimes fail with ecl, hard to reproduce. Observed failing: 250, 267, 297, 307, 310, 312, 315, 319
+         "rtest15"
+ 	;; ccl versions 1.11 and earlier fail test 50.  Mark it as a
+ 	;; known failure.  Presumably 1.12 will have this fixed.
+         ((mlist simp) "rtest16" #+ccl 50)
+         "rtestode" "rtestode_zp"
+-        "rtest3" "rtest8"
++        "rtest3"
++        ((mlist simp) "rtest8" 104) ;; fails with ecl
+         ((mlist simp) "rtest12" 76 78)
+         "rexamples"
+         ((mlist simp) "rtesthyp" 105 112 113 123 124 128)
diff --git a/nixpkgs/pkgs/applications/science/math/msieve/default.nix b/nixpkgs/pkgs/applications/science/math/msieve/default.nix
new file mode 100644
index 000000000000..6e1926810df0
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/msieve/default.nix
@@ -0,0 +1,30 @@
+{stdenv, fetchurl, zlib, gmp, ecm }:
+
+stdenv.mkDerivation {
+  name = "msieve-1.53";
+
+  src = fetchurl {
+    url = mirror://sourceforge/msieve/msieve/Msieve%20v1.53/msieve153_src.tar.gz;
+    sha256 = "1d1vv7j4rh3nnxsmvafi73qy7lw7n3akjlm5pjl3m936yapvmz65";
+  };
+
+  buildInputs = [ zlib gmp ecm ];
+
+  ECM = if ecm == null then "0" else "1";
+
+  # Doesn't hurt Linux but lets clang-based platforms like Darwin work fine too
+  makeFlags = "CC=cc all";
+
+  installPhase = ''
+    mkdir -p $out/bin/
+    cp msieve $out/bin/
+  '';
+
+  meta = {
+    description = "A C library implementing a suite of algorithms to factor large integers";
+    license = stdenv.lib.licenses.publicDomain;
+    homepage = http://msieve.sourceforge.net/;
+    maintainers = [ stdenv.lib.maintainers.roconnor ];
+    platforms = [ "x86_64-linux" ] ++ stdenv.lib.platforms.darwin;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/mxnet/default.nix b/nixpkgs/pkgs/applications/science/math/mxnet/default.nix
new file mode 100644
index 000000000000..990d3f1a5d59
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mxnet/default.nix
@@ -0,0 +1,56 @@
+{ stdenv, lib, fetchurl, bash, cmake
+, opencv, gtest, openblas, liblapack, perl
+, cudaSupport ? false, cudatoolkit, nvidia_x11
+, cudnnSupport ? false, cudnn
+}:
+
+assert cudnnSupport -> cudaSupport;
+
+stdenv.mkDerivation rec {
+  name = "mxnet-${version}";
+  version = "1.2.1";
+
+  # Fetching from git does not work at the time (1.2.1) due to an
+  # incorrect hash in one of the submodules. The provided tarballs
+  # contain all necessary sources.
+  src = fetchurl {
+    url = "https://github.com/apache/incubator-mxnet/releases/download/${version}/apache-mxnet-src-${version}-incubating.tar.gz";
+    sha256 = "053zbdgs4j8l79ipdz461zc7wyfbfcflmi5bw7lj2q08zm1glnb2";
+  };
+
+  nativeBuildInputs = [ cmake perl ];
+
+  buildInputs = [ opencv gtest openblas liblapack ]
+              ++ lib.optionals cudaSupport [ cudatoolkit nvidia_x11 ]
+              ++ lib.optional cudnnSupport cudnn;
+
+  cmakeFlags =
+    (if cudaSupport then [
+      "-DCUDA_ARCH_NAME=All"
+      "-DCUDA_HOST_COMPILER=${cudatoolkit.cc}/bin/cc"
+    ] else [ "-DUSE_CUDA=OFF" ])
+    ++ lib.optional (!cudnnSupport) "-DUSE_CUDNN=OFF";
+
+  postPatch = ''
+    substituteInPlace 3rdparty/mkldnn/tests/CMakeLists.txt \
+      --replace "/bin/bash" "${bash}/bin/bash"
+
+    # Build against the system version of OpenMP. 
+    # https://github.com/apache/incubator-mxnet/pull/12160
+    rm -rf 3rdparty/openmp
+  '';
+
+  postInstall = ''
+    rm "$out"/lib/*.a
+  '';
+
+  enableParallelBuilding = true;
+
+  meta = with stdenv.lib; {
+    description = "Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler";
+    homepage = https://mxnet.incubator.apache.org/;
+    maintainers = with maintainers; [ abbradar ];
+    license = licenses.asl20;
+    platforms = platforms.linux;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/nasc/default.nix b/nixpkgs/pkgs/applications/science/math/nasc/default.nix
new file mode 100644
index 000000000000..4afaa5194db8
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/nasc/default.nix
@@ -0,0 +1,62 @@
+{ stdenv
+, fetchFromGitHub
+, fetchpatch
+, pkgconfig
+, gtk3
+, granite
+, gnome3
+, cmake
+, vala_0_40
+, libqalculate
+, gobject-introspection
+, wrapGAppsHook }:
+
+stdenv.mkDerivation rec {
+  name = "nasc-${version}";
+  version = "0.5.1";
+
+  src = fetchFromGitHub {
+    owner = "parnold-x";
+    repo = "nasc";
+    rev = version;
+    sha256 = "13y5fnm7g3xgdxmdydlgly73nigh8maqbf9d6c9bpyzxkxq1csy5";
+  };
+
+  postPatch = ''
+    # libqalculatenasc.so is not installed, and nasc fails to start
+    substituteInPlace libqalculatenasc/CMakeLists.txt --replace SHARED STATIC
+  '';
+
+  nativeBuildInputs = [
+    pkgconfig
+    wrapGAppsHook
+    vala_0_40 # should be `elementary.vala` when elementary attribute set is merged
+    cmake
+    gobject-introspection # for setup-hook
+  ];
+
+  buildInputs = [
+    gnome3.defaultIconTheme # should be `elementary.defaultIconTheme`when elementary attribute set is merged
+    gnome3.gtksourceview
+    gnome3.libgee
+    gnome3.libsoup
+    granite
+    gtk3
+    libqalculate
+  ];
+
+  meta = with stdenv.lib; {
+    description = "Do maths like a normal person";
+    longDescription = ''
+      It’s an app where you do maths like a normal person. It lets you
+      type whatever you want and smartly figures out what is math and
+      spits out an answer on the right pane. Then you can plug those
+      answers in to future equations and if that answer changes, so does
+      the equations it’s used in.
+    '';
+    homepage = https://github.com/parnold-x/nasc;
+    maintainers = with maintainers; [ samdroid-apps ];
+    platforms = platforms.linux;
+    license = licenses.gpl3Plus;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/nauty/default.nix b/nixpkgs/pkgs/applications/science/math/nauty/default.nix
new file mode 100644
index 000000000000..5b431f419261
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/nauty/default.nix
@@ -0,0 +1,31 @@
+{stdenv, fetchurl}:
+stdenv.mkDerivation rec {
+  name = "nauty-${version}";
+  version = "26r11";
+  src = fetchurl {
+    url = "http://pallini.di.uniroma1.it/nauty${version}.tar.gz";
+    sha256 = "05z6mk7c31j70md83396cdjmvzzip1hqb88pfszzc6k4gy8h3m2y";
+  };
+  outputs = [ "out" "dev" ];
+  buildInputs = [];
+  installPhase = ''
+    mkdir -p "$out"/{bin,share/doc/nauty} "$dev"/{lib,include/nauty}
+
+    find . -type f -perm -111 \! -name '*.*' \! -name configure -exec cp '{}' "$out/bin" \;
+    cp [Rr][Ee][Aa][Dd]* COPYRIGHT This* [Cc]hange* "$out/share/doc/nauty"
+
+    cp *.h $dev/include/nauty
+    for i in *.a; do
+      cp "$i" "$dev/lib/lib$i";
+    done
+  '';
+  checkTarget = "checks";
+  meta = {
+    inherit version;
+    description = ''Programs for computing automorphism groups of graphs and digraphs'';
+    license = stdenv.lib.licenses.asl20;
+    maintainers = [stdenv.lib.maintainers.raskin];
+    platforms = stdenv.lib.platforms.linux;
+    homepage = http://pallini.di.uniroma1.it/;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/palp/default.nix b/nixpkgs/pkgs/applications/science/math/palp/default.nix
new file mode 100644
index 000000000000..e9fd21b46d8a
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/palp/default.nix
@@ -0,0 +1,86 @@
+{ stdenv
+, fetchurl
+, dimensions ? 6 # works for <= dimensions dimensions, but is only optimized for that exact value
+, doSymlink ? true # symlink the executables to the default location (without dimension postfix)
+}:
+
+stdenv.mkDerivation rec {
+  version = "2.1";
+  dim = toString dimensions;
+  name = "palp-${dim}d-${version}";
+
+  src = fetchurl {
+    url = "http://hep.itp.tuwien.ac.at/~kreuzer/CY/palp/palp-${version}.tar.gz";
+    sha256 = "1s7s2lc5f0ig1yy7ygsh3sddm3sbq4mxwybqsj8lp9wjdxs7qfrs";
+  };
+
+  hardeningDisable = [
+    "format"
+    "strictoverflow" # causes runtime failure (tested in checkPhase)
+  ];
+
+  patchPhase = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace GNUmakefile --replace gcc cc
+  '';
+
+  preBuild = ''
+      echo Building PALP optimized for ${dim} dimensions
+      sed -i "s/^#define[^a-zA-Z]*POLY_Dmax.*/#define POLY_Dmax ${dim}/" Global.h
+  '';
+
+  # palp has no tests of its own. This test is an adapted sage test that failed
+  # when #28029 was merged.
+  doCheck = true;
+  checkPhase = ''
+    ./nef.x -f -N << EOF | grep -q 'np='
+      3 6
+      1  0  0 -1  0  0
+      0  1  0  0 -1  0
+      0  0  1  0  0 -1
+    EOF
+  '';
+
+  installPhase = ''
+    mkdir -p "$out/bin"
+    for file in poly class cws nef mori; do
+        cp -p $file.x "$out/bin/$file-${dim}d.x"
+    done
+  '' + stdenv.lib.optionalString doSymlink ''
+    cd "$out/bin"
+    for file in poly class cws nef mori; do
+        ln -sf $file-6d.x $file.x
+    done
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A Package for Analyzing Lattice Polytopes";
+    longDescription = ''
+      A Package for Analyzing Lattice Polytopes (PALP) is a set of C
+      programs for calculations with lattice polytopes and applications to
+      toric geometry.
+
+      It contains routines for vertex and facet enumeration, computation of
+      incidences and symmetries, as well as completion of the set of lattice
+      points in the convex hull of a given set of points. In addition, there
+      are procedures specialised to reflexive polytopes such as the
+      enumeration of reflexive subpolytopes, and applications to toric
+      geometry and string theory, like the computation of Hodge data and
+      fibration structures for toric Calabi-Yau varieties.  The package is
+      well tested and optimised in speed as it was used for time consuming
+      tasks such as the classification of reflexive polyhedra in 4
+      dimensions and the creation and manipulation of very large lists of
+      5-dimensional polyhedra.
+
+      While originally intended for low-dimensional applications, the
+      algorithms work in any dimension and our key routine for vertex and
+      facet enumeration compares well with existing packages.
+    '';
+    homepage = http://hep.itp.tuwien.ac.at/~kreuzer/CY/CYpalp.html;
+    # Just a link on the website pointing to gpl -- now gplv3. When the last
+    # version was released that pointed to gplv2 however, so thats probably
+    # the right license.
+    license = licenses.gpl2;
+    maintainers = with maintainers; [ timokau ];
+    platforms = platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/pari/default.nix b/nixpkgs/pkgs/applications/science/math/pari/default.nix
new file mode 100644
index 000000000000..32e4d81acec0
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/pari/default.nix
@@ -0,0 +1,77 @@
+{ stdenv, fetchurl
+, gmp, readline, libX11, tex, perl
+, withThread ? true, libpthreadstubs
+}:
+
+assert withThread -> libpthreadstubs != null;
+
+stdenv.mkDerivation rec {
+
+  name = "pari-${version}";
+  version = "2.11.1";
+
+  src = fetchurl {
+    url = "https://pari.math.u-bordeaux.fr/pub/pari/unix/${name}.tar.gz";
+    sha256 = "1jfax92jpydjd02fwl30r6b8kfzqqd6sm4yx94gidyz9lqjb7a94";
+  };
+
+  buildInputs = [
+    gmp
+    readline
+    libX11
+    tex
+    perl
+  ] ++ stdenv.lib.optionals withThread [
+    libpthreadstubs
+  ];
+
+  configureScript = "./Configure";
+  configureFlags = [
+    "--with-gmp=${gmp.dev}"
+    "--with-readline=${readline.dev}"
+  ] ++ stdenv.lib.optional stdenv.isDarwin "--host=x86_64-darwin"
+  ++ stdenv.lib.optional withThread "--mt=pthread";
+
+  preConfigure = ''
+    export LD=$CC
+  '';
+
+  postConfigure = stdenv.lib.optionalString stdenv.isDarwin ''
+    echo 'echo x86_64-darwin' > config/arch-osname
+  '';
+
+  makeFlags = [ "all" ];
+
+  meta = with stdenv.lib; {
+    description = "Computer algebra system for high-performance number theory computations";
+    longDescription = ''
+       PARI/GP is a widely used computer algebra system designed for fast
+       computations in number theory (factorizations, algebraic number theory,
+       elliptic curves...), but also contains a large number of other useful
+       functions to compute with mathematical entities such as matrices,
+       polynomials, power series, algebraic numbers etc., and a lot of
+       transcendental functions. PARI is also available as a C library to allow
+       for faster computations.
+
+       Originally developed by Henri Cohen and his co-workers (Université
+       Bordeaux I, France), PARI is now under the GPL and maintained by Karim
+       Belabas with the help of many volunteer contributors.
+
+       - PARI is a C library, allowing fast computations.
+       - gp is an easy-to-use interactive shell giving access to the
+          PARI functions.
+       - GP is the name of gp's scripting language.
+       - gp2c, the GP-to-C compiler, combines the best of both worlds
+          by compiling GP scripts to the C language and transparently loading
+          the resulting functions into gp. (gp2c-compiled scripts will typically
+          run 3 or 4 times faster.) gp2c currently only understands a subset
+           of the GP language.
+    '';
+    homepage    = http://pari.math.u-bordeaux.fr;
+    downloadPage = http://pari.math.u-bordeaux.fr/download.html;
+    license     = licenses.gpl2Plus;
+    maintainers = with maintainers; [ ertes raskin AndersonTorres ];
+    platforms   = platforms.linux ++ platforms.darwin;
+    updateWalker = true;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/pari/gp2c.nix b/nixpkgs/pkgs/applications/science/math/pari/gp2c.nix
new file mode 100644
index 000000000000..4915e42025b5
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/pari/gp2c.nix
@@ -0,0 +1,28 @@
+{ stdenv, fetchurl
+, pari, perl }:
+
+stdenv.mkDerivation rec {
+
+  name = "gp2c-${version}";
+  version = "0.0.11pl1";
+
+  src = fetchurl {
+    url = "https://pari.math.u-bordeaux.fr/pub/pari/GP2C/${name}.tar.gz";
+    sha256 = "1c6f6vmncw032kfzrfyr8bynw6yd3faxpy2285r009fmr0zxfs5s";
+  };
+
+  buildInputs = [ pari perl ];
+
+  configureFlags = [
+    "--with-paricfg=${pari}/lib/pari/pari.cfg"
+    "--with-perl=${perl}/bin/perl" ];
+
+  meta = with stdenv.lib; {
+    description =  "A compiler to translate GP scripts to PARI programs";
+    homepage    = "http://pari.math.u-bordeaux.fr/";
+    downloadPage = "http://pari.math.u-bordeaux.fr/download.html";
+    license     = licenses.gpl2Plus;
+    maintainers = with maintainers; [ AndersonTorres ];
+  };
+}
+# TODO: add it as "source file" for default package
diff --git a/nixpkgs/pkgs/applications/science/math/pcalc/default.nix b/nixpkgs/pkgs/applications/science/math/pcalc/default.nix
new file mode 100644
index 000000000000..3e7d9898a656
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/pcalc/default.nix
@@ -0,0 +1,26 @@
+{ stdenv, fetchgit, bison2, flex }:
+
+with stdenv.lib;
+
+stdenv.mkDerivation rec {
+  name = "pcalc-${version}";
+  version = "20141224";
+
+  src = fetchgit {
+    url = git://git.code.sf.net/p/pcalc/code;
+    rev = "181d60d3c880da4344fef7138065943eb3b9255f";
+    sha256 = "1hd5bh20j5xzvv6qa0fmzmv0h8sf38r7zgi7y0b6nk17pjq33v90";
+  };
+
+  makeFlags = [ "DESTDIR= BINDIR=$(out)/bin" ];
+  buildInputs = [ bison2 flex ];
+
+  meta = {
+    homepage = http://pcalc.sourceforge.net/;
+    description = "Programmer's calculator";
+    license = licenses.gpl2;
+    maintainers = with stdenv.lib.maintainers; [ ftrvxmtrx ];
+    platforms = stdenv.lib.platforms.linux;
+    inherit version;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/perseus/default.nix b/nixpkgs/pkgs/applications/science/math/perseus/default.nix
new file mode 100644
index 000000000000..2d150d0c30e9
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/perseus/default.nix
@@ -0,0 +1,40 @@
+{ stdenv, fetchurl, unzip }:
+
+stdenv.mkDerivation {
+  name = "perseus-4-beta";
+  version = "4-beta";
+  buildInputs = [ unzip ];
+
+  hardeningDisable = [ "stackprotector" ];
+
+  src = fetchurl {
+    url = "http://www.sas.upenn.edu/~vnanda/source/perseus_4_beta.zip";
+    sha256 = "09brijnqabhgfjlj5wny0bqm5dwqcfkp1x5wif6yzdmqh080jybj";
+  };
+
+  sourceRoot = ".";
+
+  buildPhase = ''
+    g++ Pers.cpp -O3 -fpermissive -o perseus
+  '';
+
+  installPhase = ''
+    mkdir -p $out/bin
+    cp perseus $out/bin
+  '';
+
+  meta = {
+    description = "The Persistent Homology Software";
+    longDescription = ''
+      Persistent homology - or simply, persistence - is an algebraic
+      topological invariant of a filtered cell complex. Perseus
+      computes this invariant for a wide class of filtrations built
+      around datasets arising from point samples, images, distance
+      matrices and so forth.
+    '';
+    homepage = http://www.sas.upenn.edu/~vnanda/perseus/index.html;
+    license = stdenv.lib.licenses.gpl3;
+    maintainers = with stdenv.lib.maintainers; [erikryb];
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/polymake/default.nix b/nixpkgs/pkgs/applications/science/math/polymake/default.nix
new file mode 100644
index 000000000000..4fba231f094d
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/polymake/default.nix
@@ -0,0 +1,48 @@
+{ stdenv, fetchurl
+, ninja, libxml2, libxslt, readline, perl, gmp, mpfr, boost
+, bliss, ppl, singular, cddlib, lrs, nauty
+, ant, openjdk
+, perlPackages
+, makeWrapper
+}:
+
+stdenv.mkDerivation rec {
+  name = "${pname}-${version}";
+  pname = "polymake";
+  version = "3.2.rc4";
+
+  src = fetchurl {
+    url = "https://polymake.org/lib/exe/fetch.php/download/polymake-3.2r4.tar.bz2";
+    sha256 = "02jpkvy1cc6kc23vkn7nkndzr40fq1gkb3v257bwyi1h5d37fyqy";
+  };
+
+  buildInputs = [
+    libxml2 libxslt readline perl gmp mpfr boost
+    bliss ppl singular cddlib lrs nauty
+    openjdk
+  ] ++
+  (with perlPackages; [
+    XMLLibXML XMLLibXSLT XMLWriter TermReadLineGnu TermReadKey
+  ]);
+
+  nativeBuildInputs = [
+    makeWrapper ninja ant perl
+  ];
+
+  ninjaFlags = "-C build/Opt";
+
+  postInstall = ''
+    for i in "$out"/bin/*; do
+      wrapProgram "$i" --prefix PERL5LIB : "$PERL5LIB"
+    done
+  '';
+
+  meta = {
+    inherit version;
+    description = "Software for research in polyhedral geometry";
+    license = stdenv.lib.licenses.gpl2 ;
+    maintainers = [stdenv.lib.maintainers.raskin];
+    platforms = stdenv.lib.platforms.linux;
+    homepage = "https://www.polymake.org/doku.php";
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/pspp/default.nix b/nixpkgs/pkgs/applications/science/math/pspp/default.nix
new file mode 100644
index 000000000000..c53e87caa9ad
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/pspp/default.nix
@@ -0,0 +1,51 @@
+{ stdenv, fetchurl, libxml2, readline, zlib, perl, cairo, gtk3, gsl
+, pkgconfig, gtksourceview, pango, gettext
+, makeWrapper, gsettings-desktop-schemas, hicolor-icon-theme
+, gnome3
+}:
+
+stdenv.mkDerivation rec {
+  name = "pspp-1.0.1";
+
+  src = fetchurl {
+    url = "mirror://gnu/pspp/${name}.tar.gz";
+    sha256 = "1r8smr5057993h90nx0mdnff8nxw9x546zzh6qpy4h3xblp1la5s";
+  };
+
+  nativeBuildInputs = [ pkgconfig ];
+  buildInputs = [ libxml2 readline zlib perl cairo gtk3 gsl
+    gtksourceview pango gettext
+    makeWrapper gsettings-desktop-schemas hicolor-icon-theme ];
+
+  doCheck = false;
+
+  enableParallelBuilding = true;
+
+  preFixup = ''
+    wrapProgram "$out/bin/psppire" \
+     --prefix XDG_DATA_DIRS : "$out/share" \
+     --prefix XDG_DATA_DIRS : "$XDG_ICON_DIRS" \
+     --prefix XDG_DATA_DIRS : "$GSETTINGS_SCHEMAS_PATH" \
+     --prefix GIO_EXTRA_MODULES : "${stdenv.lib.getLib gnome3.dconf}/lib/gio/modules"
+  '';
+
+  meta = {
+    homepage = https://www.gnu.org/software/pspp/;
+    description = "A free replacement for SPSS, a program for statistical analysis of sampled data";
+    license = stdenv.lib.licenses.gpl3Plus;
+
+    longDescription = ''
+      PSPP is a program for statistical analysis of sampled data. It is
+      a Free replacement for the proprietary program SPSS.
+
+      PSPP can perform descriptive statistics, T-tests, anova, linear
+      and logistic regression, cluster analysis, factor analysis,
+      non-parametric tests and more. Its backend is designed to perform
+      its analyses as fast as possible, regardless of the size of the
+      input data. You can use PSPP with its graphical interface or the
+      more traditional syntax commands.
+    '';
+
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/pynac/default.nix b/nixpkgs/pkgs/applications/science/math/pynac/default.nix
new file mode 100644
index 000000000000..9bbb695a331b
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/pynac/default.nix
@@ -0,0 +1,48 @@
+{ stdenv
+, fetchFromGitHub
+, autoreconfHook
+, pkgconfig
+, flint
+, gmp
+, python2
+, singular
+}:
+
+stdenv.mkDerivation rec {
+  version = "0.7.22";
+  name = "pynac-${version}";
+
+  src = fetchFromGitHub {
+    owner = "pynac";
+    repo = "pynac";
+    rev = "pynac-${version}";
+    sha256 = "1ribm5vpbgsja4hbca1ckw4ln9kjkv608aaqsvxxvbs4z76ys6yi";
+  };
+
+  buildInputs = [
+    flint
+    gmp
+    singular
+    singular
+    python2
+  ];
+
+  nativeBuildInputs = [
+    autoreconfHook
+    pkgconfig
+  ];
+
+  meta = with stdenv.lib; {
+    description = "Python is Not a CAS -- modified version of Ginac";
+    longDescription = ''
+      Pynac -- "Python is Not a CAS" is a modified version of Ginac that
+      replaces the depency of GiNaC on CLN by a dependency instead of Python.
+      It is a lite version of GiNaC as well, not implementing all the features
+      of the full GiNaC, and it is *only* meant to be used as a Python library.
+    '';
+    homepage    = http://pynac.org;
+    license = licenses.gpl3;
+    maintainers = with maintainers; [ timokau ];
+    platforms   = platforms.linux;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/qalculate-gtk/default.nix b/nixpkgs/pkgs/applications/science/math/qalculate-gtk/default.nix
new file mode 100644
index 000000000000..42dc28534092
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/qalculate-gtk/default.nix
@@ -0,0 +1,30 @@
+{ stdenv, fetchFromGitHub, intltool, autoreconfHook, pkgconfig, libqalculate, gtk3, wrapGAppsHook }:
+
+stdenv.mkDerivation rec {
+  name = "qalculate-gtk-${version}";
+  version = "2.8.2";
+
+  src = fetchFromGitHub {
+    owner = "qalculate";
+    repo = "qalculate-gtk";
+    rev = "v${version}";
+    sha256 = "0vdrpnarbwhappwgp38jjndnq30h1lh8hbk75i9rhkb7x4kblqfi";
+  };
+
+  patchPhase = ''
+    substituteInPlace src/main.cc --replace 'getPackageDataDir().c_str()' \"$out/share\"
+  '';
+
+  hardeningDisable = [ "format" ];
+
+  nativeBuildInputs = [ intltool pkgconfig autoreconfHook wrapGAppsHook ];
+  buildInputs = [ libqalculate gtk3 ];
+  enableParallelBuilding = true;
+
+  meta = with stdenv.lib; {
+    description = "The ultimate desktop calculator";
+    homepage = http://qalculate.github.io;
+    maintainers = with maintainers; [ gebner ];
+    platforms = platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/ratpoints/default.nix b/nixpkgs/pkgs/applications/science/math/ratpoints/default.nix
new file mode 100644
index 000000000000..2dd4778234df
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/ratpoints/default.nix
@@ -0,0 +1,37 @@
+{ stdenv, fetchurl, fetchpatch, gmp }:
+stdenv.mkDerivation rec {
+  name = "ratpoints-${version}";
+  version = "2.1.3.p4";
+
+  src = fetchurl {
+    url = "http://www.mathe2.uni-bayreuth.de/stoll/programs/ratpoints-${version}.tar.gz";
+    sha256 = "0zhad84sfds7izyksbqjmwpfw4rvyqk63yzdjd3ysd32zss5bgf4";
+  };
+
+  enableParallelBuilding = true;
+
+  patches = [
+    (fetchpatch {
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/ratpoints/patches/sturm_and_rp_private.patch?id=1615f58890e8f9881c4228c78a6b39b9aab1303a";
+      sha256 = "0q3wajncyfr3gahd8gwk9x7g56zw54lpywrl63lqk7drkf60mrcl";
+    })
+  ];
+
+  buildInputs = [ gmp ];
+
+  makeFlags = [ "CC=cc" ];
+  buildFlags = stdenv.lib.optional stdenv.isDarwin ["CCFLAGS2=-lgmp -lc -lm" "CCFLAGS=-UUSE_SSE"];
+  installFlags = [ "INSTALL_DIR=$(out)" ];
+
+  preInstall = ''mkdir -p "$out"/{bin,share,lib,include}'';
+
+  meta = {
+    inherit version;
+    description = ''A program to find rational points on hyperelliptic curves'';
+    license = stdenv.lib.licenses.gpl2Plus;
+    maintainers = [stdenv.lib.maintainers.raskin];
+    platforms = stdenv.lib.platforms.unix;
+    homepage = http://www.mathe2.uni-bayreuth.de/stoll/programs/;
+    updateWalker = true;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/ries/default.nix b/nixpkgs/pkgs/applications/science/math/ries/default.nix
new file mode 100644
index 000000000000..4b237a01a3e5
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/ries/default.nix
@@ -0,0 +1,21 @@
+{ stdenv, fetchzip }:
+stdenv.mkDerivation {
+  name = "ries-2018-04-11";
+
+  # upstream does not provide a stable link
+  src = fetchzip {
+    url = "https://salsa.debian.org/debian/ries/-/archive/debian/2018.04.11-1/ries-debian-2018.04.11-1.zip";
+    sha256 = "1h2wvd4k7f0l0i1vm9niz453xdbcs3nxccmri50qyrzzzc1b0842";
+  };
+
+  makeFlags = "PREFIX=$(out)";
+
+  meta = with stdenv.lib; {
+    homepage = https://mrob.com/pub/ries/;
+    description = "Tool to produce a list of equations that approximately solve to a given number";
+    platforms = platforms.all;
+    maintainers = with maintainers; [ symphorien ];
+    license = licenses.gpl3Plus;
+  };
+}
+
diff --git a/nixpkgs/pkgs/applications/science/math/ripser/default.nix b/nixpkgs/pkgs/applications/science/math/ripser/default.nix
new file mode 100644
index 000000000000..5e0b7fc300ba
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/ripser/default.nix
@@ -0,0 +1,66 @@
+{ stdenv, fetchurl, fetchFromGitHub
+, assembleReductionMatrix ? false
+, useCoefficients ? false
+, indicateProgress ? false
+, useGoogleHashmap ? false, sparsehash ? null
+, fileFormat ? "lowerTriangularCsv"
+}:
+
+with stdenv.lib;
+
+assert assertOneOf "fileFormat" fileFormat
+  ["lowerTriangularCsv" "upperTriangularCsv" "dipha"];
+assert useGoogleHashmap -> sparsehash != null;
+
+let
+  inherit (stdenv.lib) optional;
+  version = "1.0";
+in
+stdenv.mkDerivation {
+  name = "ripser-${version}";
+
+  src = fetchFromGitHub {
+    owner = "Ripser";
+    repo = "ripser";
+    rev = "f69c6af6ca6883dd518c48faf41cf8901c379598";
+    sha256 = "1mw2898s7l29hgajsaf75bs9bjn2sn4g2mvmh41a602jpwp9r0rz";
+  };
+
+  #Patch from dev branch to make compilation work.
+  #Will be removed when it gets merged into master.
+  patches = [(fetchurl {
+    url = https://github.com/Ripser/ripser/commit/dc78d8ce73ee35f3828f0aad67a4e53620277ebf.patch;
+    sha256 = "1y93aqpqz8fm1cxxrf90dhh67im3ndkr8dnxgbw5y96296n4r924";
+  })];
+
+  buildInputs = optional useGoogleHashmap sparsehash;
+
+  buildFlags = [
+    "-std=c++11"
+    "-Ofast"
+    "-D NDEBUG"
+  ]
+  ++ optional assembleReductionMatrix "-D ASSEMBLE_REDUCTION_MATRIX"
+  ++ optional useCoefficients "-D USE_COEFFICIENTS"
+  ++ optional indicateProgress "-D INDICATE_PROGRESS"
+  ++ optional useGoogleHashmap "-D USE_GOOGLE_HASHMAP"
+  ++ optional (fileFormat == "lowerTriangularCsv") "-D FILE_FORMAT_LOWER_TRIANGULAR_CSV"
+  ++ optional (fileFormat == "upperTriangularCsv") "-D FILE_FORMAT_UPPER_TRIANGULAR_CSV"
+  ++ optional (fileFormat == "dipha") "-D FILE_FORMAT_DIPHA"
+  ;
+
+  buildPhase = "c++ ripser.cpp -o ripser $buildFlags";
+
+  installPhase = ''
+    mkdir -p $out/bin
+    cp ripser $out/bin
+  '';
+
+  meta = {
+    description = "A lean C++ code for the computation of Vietoris–Rips persistence barcodes";
+    homepage = https://github.com/Ripser/ripser;
+    license = stdenv.lib.licenses.lgpl3;
+    maintainers = with stdenv.lib.maintainers; [erikryb];
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/README.md b/nixpkgs/pkgs/applications/science/math/sage/README.md
new file mode 100644
index 000000000000..26e91fc63133
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/README.md
@@ -0,0 +1,78 @@
+# Sage on nixos
+
+Sage is a pretty complex package that depends on many other complex packages and patches some of those. As a result, the sage nix package is also quite complex.
+
+Don't feel discouraged to fix, simplify or improve things though. The individual files have comments explaining their purpose. The most importent ones are `default.nix` linking everything together, `sage-src.nix` adding patches and `sagelib.nix` building the actual sage package.
+
+## The sage build is broken
+
+First you should find out which change to nixpkgs is at fault (if you don't already know). You can use `git-bisect` for that (see the manpage).
+
+If the build broke as a result of a package update, try those solutions in order:
+
+- search the [sage trac](https://trac.sagemath.org/) for keywords like "Upgrade <package>". Maybe somebody has already proposed a patch that fixes the issue. You can then add a `fetchpatch` to `sage-src.nix`.
+
+- check if [gentoo](https://github.com/cschwan/sage-on-gentoo/tree/master/sci-mathematics/sage), [debian](https://salsa.debian.org/science-team/sagemath/tree/master/debian) or [arch linux](https://git.archlinux.org/svntogit/community.git/tree/trunk?h=packages/sagemath) already solved the problem. You can then again add a `fetchpatch` to `sage-src.nix`. If applicable you should also [propose the patch upstream](#proposing-a-sage-patch).
+
+- fix the problem yourself. First clone the sagemath source and then check out the sage version you want to patch:
+
+```
+[user@localhost ~]$ git clone git://github.com/sagemath/sage.git
+[user@localhost ~]$ cd sage
+[user@localhost sage]$ git checkout 8.2 # substitute the relevant version here
+```
+
+Then make the needed changes and generate a patch with `git diff`:
+
+```
+[user@localhost ~]$ <make changes>
+[user@localhost ~]$ git diff -u > /path/to/nixpkgs/pkgs/applications/science/math/sage/patches/name-of-patch.patch
+```
+
+Now just add the patch to `sage-src.nix` and test your changes. If they fix the problem, [propose them upstream](#proposing-a-sage-patch) and add a link to the trac ticket.
+
+- pin the package version in `default.nix` and add a note that explains why that is necessary.
+
+
+## Proposing a sage patch
+
+You can [login the sage trac using GitHub](https://trac.sagemath.org/login). Your username will then be `gh-<your-github-name>`. The only other way is to request a trac account via email. After that refer to [git the hard way](http://doc.sagemath.org/html/en/developer/manual_git.html#chapter-manual-git) in the sage documentation. The "easy way" requires a non-GitHub account (requested via email) and a special tool. The "hard way" is really not all that hard if you're a bit familiar with git.
+
+Here's the gist, assuming you want to use ssh key authentication. First, [add your public ssh key](https://trac.sagemath.org/prefs/sshkeys). Then:
+
+```
+[user@localhost ~]$ git clone git://github.com/sagemath/sage.git
+[user@localhost ~]$ cd sage
+[user@localhost sage]$ git remote add trac git@trac.sagemath.org:sage.git -t master
+[user@localhost sage]$ git checkout -b u/gh-<your-github-username>/<your-branch-name> develop
+[user@localhost sage]$ <make changes>
+[user@localhost sage]$ git add .
+[user@localhost sage]$ git commit
+[user@localhost sage]$ git show # review your changes
+[user@localhost sage]$ git push --set-upstream trac u/gh-<your-github-username>/<your-branch-name>
+```
+
+You now created a branch on the trac server (you *must* follow the naming scheme as you only have push access to branches with the `u/gh-<your-github-username>/` prefix).
+Now you can [create a new trac ticket](https://trac.sagemath.org/newticket).
+- Write a description of the change
+- set the type and component as appropriate
+- write your real name in the "Authors" field
+- write `u/gh-<your-github-username>/<your-branch-name>` in the "Branch" field
+- click "Create ticket"
+- click "Modify" on the top right of your ticket (for some reason you can only change the ticket status after you have created it)
+- set the ticket status from `new` to `needs_review`
+- click "Save changes"
+
+Refer to sages [Developer's Guide](http://doc.sagemath.org/html/en/developer/index.html) for further details.
+
+## I want to update sage
+
+You'll need to change the `version` field in `sage-src.nix`. Afterwards just try to build and let nix tell you which patches no longer apply (hopefully because they were adopted upstream). Remove those.
+
+Hopefully the build will succeed now. If it doesn't and the problem is obvious, fix it as described in [The sage build is broken](#the-sage-build-is-broken).
+If the problem is not obvious, you can try to first update sage to an intermediate version (remember that you can also set the `version` field to any git revision of sage) and locate the sage commit that introduced the issue. You can even use `git-bisect` for that (it will only be a bit tricky to keep track of which patches to apply). Hopefully after that the issue will be obvious.
+
+## Well, that didn't help!
+
+If you couldn't fix the problem, create a GitHub issue on the nixpkgs repo and ping @timokau (or whoever is listed in the `maintainers` list of the sage package).
+Describe what you did and why it didn't work. Afterwards it would be great if you help the next guy out and improve this documentation!
diff --git a/nixpkgs/pkgs/applications/science/math/sage/default.nix b/nixpkgs/pkgs/applications/science/math/sage/default.nix
new file mode 100644
index 000000000000..46e60a2b81e4
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/default.nix
@@ -0,0 +1,181 @@
+{ pkgs
+, withDoc ? false
+}:
+
+# Here sage and its dependencies are put together. Some dependencies may be pinned
+# as a last resort. Patching sage for compatibility with newer dependency versions
+# is always preferred, see `sage-src.nix` for that.
+
+let
+  inherit (pkgs) fetchurl symlinkJoin callPackage nodePackages;
+
+  # https://trac.sagemath.org/ticket/15980 for tracking of python3 support
+  python = pkgs.python2.override {
+    packageOverrides = self: super: {
+      # python packages that appear unmaintained and were not accepted into the nixpkgs
+      # tree because of that. These packages are only dependencies of the more-or-less
+      # deprecated sagenb. However sagenb is still a default dependency and the doctests
+      # depend on it.
+      # See https://github.com/NixOS/nixpkgs/pull/38787 for a discussion.
+      # The dependency on the sage notebook (and therefore these packages) will be
+      # removed in the future:
+      # https://trac.sagemath.org/ticket/25837
+      flask-oldsessions = self.callPackage ./flask-oldsessions.nix {};
+      flask-openid = self.callPackage ./flask-openid.nix {};
+      python-openid = self.callPackage ./python-openid.nix {};
+      sagenb = self.callPackage ./sagenb.nix {
+        mathjax = nodePackages.mathjax;
+      };
+
+      # Package with a cyclic dependency with sage
+      pybrial = self.callPackage ./pybrial.nix {};
+
+      # `sagelib`, i.e. all of sage except some wrappers and runtime dependencies
+      sagelib = self.callPackage ./sagelib.nix {
+        inherit flint ecl arb;
+        inherit sage-src pynac singular;
+        linbox = pkgs.linbox.override { withSage = true; };
+      };
+    };
+  };
+
+  jupyter-kernel-definition = {
+    displayName = "SageMath ${sage-src.version}";
+    argv = [
+      "${sage-with-env}/bin/sage" # FIXME which sage
+      "--python"
+      "-m"
+      "sage.repl.ipython_kernel"
+      "-f"
+      "{connection_file}"
+    ];
+    language = "sagemath";
+    # just one 16x16 logo is available
+    logo32 = "${sage-src}/doc/common/themes/sage/static/sageicon.png";
+    logo64 = "${sage-src}/doc/common/themes/sage/static/sageicon.png";
+  };
+
+  # A bash script setting various environment variables to tell sage where
+  # the files its looking fore are located. Also see `sage-env`.
+  env-locations = callPackage ./env-locations.nix {
+    inherit pari_data ecl;
+    inherit singular;
+    cysignals = python.pkgs.cysignals;
+    three = nodePackages.three;
+    mathjax = nodePackages.mathjax;
+  };
+
+  # The shell file that gets sourced on every sage start. Will also source
+  # the env-locations file.
+  sage-env = callPackage ./sage-env.nix {
+    sagelib = python.pkgs.sagelib;
+    inherit env-locations;
+    inherit python rWrapper ecl singular palp flint pynac pythonEnv;
+    pkg-config = pkgs.pkgconfig; # not to confuse with pythonPackages.pkgconfig
+  };
+
+  # The documentation for sage, building it takes a lot of ram.
+  sagedoc = callPackage ./sagedoc.nix {
+    inherit sage-with-env;
+    inherit python;
+  };
+
+  # sagelib with added wrappers and a dependency on sage-tests to make sure thet tests were run.
+  sage-with-env = callPackage ./sage-with-env.nix {
+    inherit pythonEnv;
+    inherit sage-env;
+    inherit pynac singular;
+    pkg-config = pkgs.pkgconfig; # not to confuse with pythonPackages.pkgconfig
+    three = nodePackages.three;
+  };
+
+  # Doesn't actually build anything, just runs sages testsuite. This is a
+  # separate derivation to make it possible to re-run the tests without
+  # rebuilding sagelib (which takes ~30 minutes).
+  # Running the tests should take something in the order of 1h.
+  sage-tests = callPackage ./sage-tests.nix {
+    inherit sage-with-env;
+  };
+
+  sage-src = callPackage ./sage-src.nix {};
+
+  pythonRuntimeDeps = with python.pkgs; [
+    sagelib
+    pybrial
+    sagenb
+    cvxopt
+    networkx
+    service-identity
+    psutil
+    sympy
+    fpylll
+    matplotlib
+    tkinter # optional, as a matplotlib backend (use with `%matplotlib tk`)
+    scipy
+    ipywidgets
+    rpy2
+    sphinx
+    typing
+    pillow
+  ];
+
+  pythonEnv = python.buildEnv.override {
+    extraLibs = pythonRuntimeDeps;
+    ignoreCollisions = true;
+  } // { extraLibs = pythonRuntimeDeps; }; # make the libs accessible
+
+  # needs to be rWrapper, standard "R" doesn't include default packages
+  rWrapper = pkgs.rWrapper.override {
+    # https://trac.sagemath.org/ticket/25674
+    R = pkgs.R.overrideAttrs (attrs: rec {
+      name = "R-3.4.4";
+      doCheck = false;
+      src = fetchurl {
+        url = "http://cran.r-project.org/src/base/R-3/${name}.tar.gz";
+        sha256 = "0dq3jsnwsb5j3fhl0wi3p5ycv8avf8s5j1y4ap3d2mkjmcppvsdk";
+      };
+    });
+  };
+
+  arb = pkgs.arb.override { inherit flint; };
+
+  singular = pkgs.singular.override { inherit flint; };
+
+  # *not* to confuse with the python package "pynac"
+  pynac = pkgs.pynac.override { inherit singular flint; };
+
+  # With openblas (64 bit), the tests fail the same way as when sage is build with
+  # openblas instead of openblasCompat. Apparently other packages somehow use flints
+  # blas when it is available. Alternative would be to override flint to use
+  # openblasCompat.
+  flint = pkgs.flint.override { withBlas = false; };
+
+  # Multiple palp dimensions need to be available and sage expects them all to be
+  # in the same folder.
+  palp = symlinkJoin {
+    name = "palp-${pkgs.palp.version}";
+    paths = [
+      (pkgs.palp.override { dimensions = 4; doSymlink = false; })
+      (pkgs.palp.override { dimensions = 5; doSymlink = false; })
+      (pkgs.palp.override { dimensions = 6; doSymlink = true; })
+      (pkgs.palp.override { dimensions = 11; doSymlink = false; })
+    ];
+  };
+
+  # Sage expects those in the same directory.
+  pari_data = symlinkJoin {
+    name = "pari_data";
+    paths = with pkgs; [
+      pari-galdata
+      pari-seadata-small
+    ];
+  };
+
+  # https://trac.sagemath.org/ticket/22191
+  ecl = pkgs.ecl_16_1_2;
+in
+# A wrapper around sage that makes sure sage finds its docs (if they were build).
+callPackage ./sage.nix {
+  inherit sage-tests sage-with-env sagedoc jupyter-kernel-definition;
+  inherit withDoc;
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/env-locations.nix b/nixpkgs/pkgs/applications/science/math/sage/env-locations.nix
new file mode 100644
index 000000000000..9ec8d5cd83e5
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/env-locations.nix
@@ -0,0 +1,48 @@
+{ writeTextFile
+, pari_data
+, pari
+, singular
+, maxima-ecl
+, conway_polynomials
+, graphs
+, elliptic_curves
+, polytopes_db
+, gap-libgap-compatible
+, ecl
+, combinatorial_designs
+, jmol
+, mathjax
+, three
+, cysignals
+}:
+
+# A bash script setting various environment variables to tell sage where
+# the files its looking fore are located. Also see `sage-env`.
+writeTextFile rec {
+  name = "sage-env-locations";
+  destination = "/${name}";
+  text = ''
+    export GP_DATA_DIR="${pari_data}/share/pari"
+    export PARI_DATA_DIR="${pari_data}"
+    export GPHELP="${pari}/bin/gphelp"
+    export GPDOCDIR="${pari}/share/pari/doc"
+    export SINGULARPATH='${singular}/share/singular'
+    export SINGULAR_SO='${singular}/lib/libSingular.so'
+    export SINGULAR_EXECUTABLE='${singular}/bin/Singular'
+    export MAXIMA_FAS='${maxima-ecl}/lib/maxima/${maxima-ecl.version}/binary-ecl/maxima.fas'
+    export MAXIMA_PREFIX="${maxima-ecl}"
+    export CONWAY_POLYNOMIALS_DATA_DIR='${conway_polynomials}/share/conway_polynomials'
+    export GRAPHS_DATA_DIR='${graphs}/share/graphs'
+    export ELLCURVE_DATA_DIR='${elliptic_curves}/share/ellcurves'
+    export POLYTOPE_DATA_DIR='${polytopes_db}/share/reflexive_polytopes'
+    export GAP_ROOT_DIR='${gap-libgap-compatible}/share/gap/build-dir'
+    export ECLDIR='${ecl}/lib/ecl-${ecl.version}/'
+    export COMBINATORIAL_DESIGN_DATA_DIR="${combinatorial_designs}/share/combinatorial_designs"
+    export CREMONA_MINI_DATA_DIR="${elliptic_curves}/share/cremona"
+    export JMOL_DIR="${jmol}/share/jmol" # point to the directory that contains JmolData.jar
+    export JSMOL_DIR="${jmol}/share/jsmol"
+    export MATHJAX_DIR="${mathjax}/lib/node_modules/mathjax"
+    export THREEJS_DIR="${three}/lib/node_modules/three"
+    export SAGE_INCLUDE_DIRECTORIES="${cysignals}/lib/python2.7/site-packages"
+  '';
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/flask-oldsessions.nix b/nixpkgs/pkgs/applications/science/math/sage/flask-oldsessions.nix
new file mode 100644
index 000000000000..85e35736d030
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/flask-oldsessions.nix
@@ -0,0 +1,36 @@
+{ stdenv
+, buildPythonPackage
+, fetchFromGitHub
+, python
+, flask
+}:
+
+buildPythonPackage rec {
+  pname = "Flask-OldSessions";
+  version = "0.10";
+
+  # no artifact on pypi: https://github.com/mitsuhiko/flask-oldsessions/issues/1
+  src = fetchFromGitHub {
+    owner = "mitsuhiko";
+    repo = "flask-oldsessions";
+    rev = "${version}";
+    sha256 = "04b5m8njjiwld9a0zw55iqwvyjgwcpdbhz1cic8nyhgcmypbicqn";
+  };
+
+  propagatedBuildInputs = [
+    flask
+  ];
+
+  # missing module flask.testsuite, probably assumes an old version of flask
+  doCheck = false;
+  checkPhase = ''
+    ${python.interpreter} run-tests.py
+  '';
+
+  meta = with stdenv.lib; {
+    description = "Provides a session class that works like the one in Flask before 0.10.";
+    license = licenses.bsd2;
+    maintainers = with maintainers; [ timokau ];
+    homepage = https://github.com/mitsuhiko/flask-oldsessions;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/flask-openid.nix b/nixpkgs/pkgs/applications/science/math/sage/flask-openid.nix
new file mode 100644
index 000000000000..9043fabd9b4a
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/flask-openid.nix
@@ -0,0 +1,28 @@
+{ stdenv
+, buildPythonPackage
+, fetchPypi
+, flask
+, python-openid
+}:
+
+buildPythonPackage rec {
+  pname = "Flask-OpenID";
+  version = "1.2.5";
+
+  src = fetchPypi {
+    inherit pname version;
+    sha256 = "1aycwmwi7ilcaa5ab8hm0bp6323zl8z25q9ha0gwrl8aihfgx3ss";
+  };
+
+  propagatedBuildInputs = [
+    flask
+    python-openid
+  ];
+
+  meta = with stdenv.lib; {
+    description = "Adds openid support to flask applications";
+    license = licenses.bsd2;
+    maintainers = with maintainers; [ timokau ];
+    homepage = https://pythonhosted.org/Flask-OpenID/;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/Only-test-py2-py3-optional-tests-when-all-of-sage-is.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/Only-test-py2-py3-optional-tests-when-all-of-sage-is.patch
new file mode 100644
index 000000000000..8cd80281d0e4
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/Only-test-py2-py3-optional-tests-when-all-of-sage-is.patch
@@ -0,0 +1,35 @@
+From 8218bd4fdeb4c92de8af0d3aabec55980fc4fb3d Mon Sep 17 00:00:00 2001
+From: Timo Kaufmann <timokau@zoho.com>
+Date: Sun, 21 Oct 2018 17:52:40 +0200
+Subject: [PATCH] Only test py2/py3 optional tests when all of sage is tested
+
+---
+ src/sage/doctest/control.py | 5 +++--
+ 1 file changed, 3 insertions(+), 2 deletions(-)
+
+diff --git a/src/sage/doctest/control.py b/src/sage/doctest/control.py
+index bf18df8b2b..935c67abf7 100644
+--- a/src/sage/doctest/control.py
++++ b/src/sage/doctest/control.py
+@@ -362,7 +362,8 @@ class DocTestController(SageObject):
+                     if not optionaltag_regex.search(o):
+                         raise ValueError('invalid optional tag {!r}'.format(o))
+ 
+-                options.optional |= auto_optional_tags
++                if "sage" in options.optional:
++                    options.optional |= auto_optional_tags
+ 
+         self.options = options
+ 
+@@ -765,7 +766,7 @@ class DocTestController(SageObject):
+             sage: DC = DocTestController(DD, [dirname])
+             sage: DC.expand_files_into_sources()
+             sage: sorted(DC.sources[0].options.optional)  # abs tol 1
+-            ['guava', 'magma', 'py2']
++            ['guava', 'magma']
+ 
+         We check that files are skipped appropriately::
+ 
+-- 
+2.18.1
+
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/giac-1.5.0.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/giac-1.5.0.patch
new file mode 100644
index 000000000000..58090b241d2d
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/giac-1.5.0.patch
@@ -0,0 +1,14 @@
+--- a/src/sage/interfaces/giac.py	2018-12-08 22:11:56.285500644 +0100
++++ b/src/sage/interfaces/giac.py	2018-12-08 22:11:56.285500644 +0100
+@@ -617,10 +617,7 @@
+             '4\n3'
+             sage: s='g(x):={\nx+1;\nx+2;\n}'
+             sage: giac(s)
+-            (x)->{
+-            x+1;
+-            x+2;
+-            }
++            (x)->[x+1,x+2]
+             sage: giac.g(5)
+             7
+         """
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/numpy-1.15.1.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/numpy-1.15.1.patch
new file mode 100644
index 000000000000..9e855ba4ad94
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/numpy-1.15.1.patch
@@ -0,0 +1,911 @@
+diff --git a/src/doc/en/faq/faq-usage.rst b/src/doc/en/faq/faq-usage.rst
+index 2347a1190d..f5b0fe71a4 100644
+--- a/src/doc/en/faq/faq-usage.rst
++++ b/src/doc/en/faq/faq-usage.rst
+@@ -338,7 +338,7 @@ ints. For example::
+     sage: RealNumber = float; Integer = int
+     sage: from scipy import stats
+     sage: stats.ttest_ind(list([1,2,3,4,5]),list([2,3,4,5,.6]))
+-    Ttest_indResult(statistic=0.076752955645333687, pvalue=0.94070490247380478)
++    Ttest_indResult(statistic=0.0767529..., pvalue=0.940704...)
+     sage: stats.uniform(0,15).ppf([0.5,0.7])
+     array([  7.5,  10.5])
+ 
+diff --git a/src/doc/en/thematic_tutorials/numerical_sage/cvxopt.rst b/src/doc/en/thematic_tutorials/numerical_sage/cvxopt.rst
+index 314811c42b..e5f54ec4c2 100644
+--- a/src/doc/en/thematic_tutorials/numerical_sage/cvxopt.rst
++++ b/src/doc/en/thematic_tutorials/numerical_sage/cvxopt.rst
+@@ -48,11 +48,13 @@ we could do the following.
+     sage: B = numpy.array([1.0]*5)
+     sage: B.shape=(5,1)
+     sage: print(B)
+-    [[ 1.]
+-     [ 1.]
+-     [ 1.]
+-     [ 1.]
+-     [ 1.]]
++    [[1.]
++     [1.]
++     [1.]
++     [1.]
++     [1.]]
++
++
+     sage: print(A)
+     [ 2.00e+00  3.00e+00     0         0         0    ]
+     [ 3.00e+00     0      4.00e+00     0      6.00e+00]
+diff --git a/src/doc/en/thematic_tutorials/numerical_sage/numpy.rst b/src/doc/en/thematic_tutorials/numerical_sage/numpy.rst
+index 5b89cd75ee..e50b2ea5d4 100644
+--- a/src/doc/en/thematic_tutorials/numerical_sage/numpy.rst
++++ b/src/doc/en/thematic_tutorials/numerical_sage/numpy.rst
+@@ -84,7 +84,7 @@ well as take slices
+     sage: l[3]
+     3.0
+     sage: l[3:6]
+-    array([ 3.,  4.,  5.])
++    array([3., 4., 5.])
+ 
+ You can do basic arithmetic operations
+ 
+@@ -147,11 +147,11 @@ also do matrix vector multiplication, and matrix addition
+     sage: n = numpy.matrix([[1,2],[3,4]],dtype=float)
+     sage: v = numpy.array([[1],[2]],dtype=float)
+     sage: n*v
+-    matrix([[  5.],
+-            [ 11.]])
++    matrix([[ 5.],
++            [11.]])
+     sage: n+n
+-    matrix([[ 2.,  4.],
+-            [ 6.,  8.]])
++    matrix([[2., 4.],
++            [6., 8.]])
+ 
+ If ``n`` was created with :meth:`numpy.array`, then to do matrix vector
+ multiplication, you would use ``numpy.dot(n,v)``.
+@@ -170,11 +170,11 @@ to manipulate
+             22.,  23.,  24.])
+     sage: n.shape=(5,5)
+     sage: n
+-    array([[  0.,   1.,   2.,   3.,   4.],
+-           [  5.,   6.,   7.,   8.,   9.],
+-           [ 10.,  11.,  12.,  13.,  14.],
+-           [ 15.,  16.,  17.,  18.,  19.],
+-           [ 20.,  21.,  22.,  23.,  24.]])
++    array([[ 0.,  1.,  2.,  3.,  4.],
++           [ 5.,  6.,  7.,  8.,  9.],
++           [10., 11., 12., 13., 14.],
++           [15., 16., 17., 18., 19.],
++           [20., 21., 22., 23., 24.]])
+ 
+ This changes the one-dimensional array into a `5\times 5` array.
+ 
+@@ -187,8 +187,8 @@ NumPy arrays can be sliced as well
+     sage: n=numpy.array(range(25),dtype=float)
+     sage: n.shape=(5,5)
+     sage: n[2:4,1:3]
+-    array([[ 11.,  12.],
+-           [ 16.,  17.]])
++    array([[11., 12.],
++           [16., 17.]])
+ 
+ It is important to note that the sliced matrices are references to
+ the original
+@@ -224,8 +224,8 @@ Some particularly useful commands are
+ 
+     sage: x=numpy.arange(0,2,.1,dtype=float)
+     sage: x
+-    array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ,
+-            1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9])
++    array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2,
++           1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9])
+ 
+ You can see that :meth:`numpy.arange` creates an array of floats increasing by 0.1
+ from 0 to 2. There is a useful command :meth:`numpy.r_` that is best explained by example
+@@ -240,10 +240,11 @@ from 0 to 2. There is a useful command :meth:`numpy.r_` that is best explained b
+     sage: Integer=int
+     sage: n=r_[0.0:5.0]
+     sage: n
+-    array([ 0.,  1.,  2.,  3.,  4.])
++    array([0., 1., 2., 3., 4.])
+     sage: n=r_[0.0:5.0, [0.0]*5]
+     sage: n
+-    array([ 0.,  1.,  2.,  3.,  4.,  0.,  0.,  0.,  0.,  0.])
++    array([0., 1., 2., 3., 4., 0., 0., 0., 0., 0.])
++
+ 
+ :meth:`numpy.r_` provides a shorthand for constructing NumPy arrays efficiently.
+ Note in the above ``0.0:5.0`` was shorthand for ``0.0, 1.0, 2.0, 3.0, 4.0``.
+@@ -255,7 +256,7 @@ intervals. We can do this as follows
+ ::
+ 
+     sage: r_[0.0:5.0:11*j]
+-    array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ])
++    array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])
+ 
+ The notation ``0.0:5.0:11*j`` expands to a list of 11 equally space
+ points between 0 and 5 including both endpoints. Note that ``j`` is the
+@@ -287,23 +288,23 @@ an equally spaced grid with `\Delta x = \Delta y = .25` for
+     sage: y=numpy.r_[0.0:1.0:5*j]
+     sage: xx,yy= meshgrid(x,y)
+     sage: xx
+-    array([[ 0.  ,  0.25,  0.5 ,  0.75,  1.  ],
+-           [ 0.  ,  0.25,  0.5 ,  0.75,  1.  ],
+-           [ 0.  ,  0.25,  0.5 ,  0.75,  1.  ],
+-           [ 0.  ,  0.25,  0.5 ,  0.75,  1.  ],
+-           [ 0.  ,  0.25,  0.5 ,  0.75,  1.  ]])
++    array([[0.  , 0.25, 0.5 , 0.75, 1.  ],
++           [0.  , 0.25, 0.5 , 0.75, 1.  ],
++           [0.  , 0.25, 0.5 , 0.75, 1.  ],
++           [0.  , 0.25, 0.5 , 0.75, 1.  ],
++           [0.  , 0.25, 0.5 , 0.75, 1.  ]])
+     sage: yy
+-    array([[ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
+-           [ 0.25,  0.25,  0.25,  0.25,  0.25],
+-           [ 0.5 ,  0.5 ,  0.5 ,  0.5 ,  0.5 ],
+-           [ 0.75,  0.75,  0.75,  0.75,  0.75],
+-           [ 1.  ,  1.  ,  1.  ,  1.  ,  1.  ]])
++    array([[0.  , 0.  , 0.  , 0.  , 0.  ],
++           [0.25, 0.25, 0.25, 0.25, 0.25],
++           [0.5 , 0.5 , 0.5 , 0.5 , 0.5 ],
++           [0.75, 0.75, 0.75, 0.75, 0.75],
++           [1.  , 1.  , 1.  , 1.  , 1.  ]])
+     sage: f(xx,yy)
+-    array([[ 0.    ,  0.0625,  0.25  ,  0.5625,  1.    ],
+-           [ 0.0625,  0.125 ,  0.3125,  0.625 ,  1.0625],
+-           [ 0.25  ,  0.3125,  0.5   ,  0.8125,  1.25  ],
+-           [ 0.5625,  0.625 ,  0.8125,  1.125 ,  1.5625],
+-           [ 1.    ,  1.0625,  1.25  ,  1.5625,  2.    ]])
++    array([[0.    , 0.0625, 0.25  , 0.5625, 1.    ],
++           [0.0625, 0.125 , 0.3125, 0.625 , 1.0625],
++           [0.25  , 0.3125, 0.5   , 0.8125, 1.25  ],
++           [0.5625, 0.625 , 0.8125, 1.125 , 1.5625],
++           [1.    , 1.0625, 1.25  , 1.5625, 2.    ]])
+ 
+ You can see that :meth:`numpy.meshgrid` produces a pair of matrices, here denoted
+ `xx` and `yy`, such that `(xx[i,j],yy[i,j])` has coordinates
+@@ -324,7 +325,7 @@ equation `Ax=b` do
+     sage: b=numpy.array(range(1,6))
+     sage: x=linalg.solve(A,b)
+     sage: numpy.dot(A,x)
+-    array([ 1.,  2.,  3.,  4., 5.])
++    array([1., 2., 3., 4., 5.])
+ 
+ This creates a random 5x5 matrix ``A``, and solves `Ax=b` where
+ ``b=[0.0,1.0,2.0,3.0,4.0]``. There are many other routines in the :mod:`numpy.linalg`
+diff --git a/src/sage/calculus/riemann.pyx b/src/sage/calculus/riemann.pyx
+index 60f37f7557..4ac3dedf1d 100644
+--- a/src/sage/calculus/riemann.pyx
++++ b/src/sage/calculus/riemann.pyx
+@@ -1191,30 +1191,30 @@ cpdef complex_to_spiderweb(np.ndarray[COMPLEX_T, ndim = 2] z_values,
+         sage: zval = numpy.array([[0, 1, 1000],[.2+.3j,1,-.3j],[0,0,0]],dtype = numpy.complex128)
+         sage: deriv = numpy.array([[.1]],dtype = numpy.float64)
+         sage: complex_to_spiderweb(zval, deriv,deriv, 4,4,[0,0,0],1,False,0.001)
+-        array([[[ 1.,  1.,  1.],
+-                [ 1.,  1.,  1.],
+-                [ 1.,  1.,  1.]],
++        array([[[1., 1., 1.],
++                [1., 1., 1.],
++                [1., 1., 1.]],
+         <BLANKLINE>
+-               [[ 1.,  1.,  1.],
+-                [ 0.,  0.,  0.],
+-                [ 1.,  1.,  1.]],
++               [[1., 1., 1.],
++                [0., 0., 0.],
++                [1., 1., 1.]],
+         <BLANKLINE>
+-               [[ 1.,  1.,  1.],
+-                [ 1.,  1.,  1.],
+-                [ 1.,  1.,  1.]]])
++               [[1., 1., 1.],
++                [1., 1., 1.],
++                [1., 1., 1.]]])
+ 
+         sage: complex_to_spiderweb(zval, deriv,deriv, 4,4,[0,0,0],1,True,0.001)
+-        array([[[ 1.        ,  1.        ,  1.        ],
+-                [ 1.        ,  0.05558355,  0.05558355],
+-                [ 0.17301243,  0.        ,  0.        ]],
++        array([[[1.        , 1.        , 1.        ],
++                [1.        , 0.05558355, 0.05558355],
++                [0.17301243, 0.        , 0.        ]],
+         <BLANKLINE>
+-               [[ 1.        ,  0.96804683,  0.48044583],
+-                [ 0.        ,  0.        ,  0.        ],
+-                [ 0.77351965,  0.5470393 ,  1.        ]],
++               [[1.        , 0.96804683, 0.48044583],
++                [0.        , 0.        , 0.        ],
++                [0.77351965, 0.5470393 , 1.        ]],
+         <BLANKLINE>
+-               [[ 1.        ,  1.        ,  1.        ],
+-                [ 1.        ,  1.        ,  1.        ],
+-                [ 1.        ,  1.        ,  1.        ]]])
++               [[1.        , 1.        , 1.        ],
++                [1.        , 1.        , 1.        ],
++                [1.        , 1.        , 1.        ]]])
+      """
+     cdef Py_ssize_t i, j, imax, jmax
+     cdef FLOAT_T x, y, mag, arg, width, target, precision, dmag, darg
+@@ -1279,14 +1279,14 @@ cpdef complex_to_rgb(np.ndarray[COMPLEX_T, ndim = 2] z_values):
+         sage: from sage.calculus.riemann import complex_to_rgb
+         sage: import numpy
+         sage: complex_to_rgb(numpy.array([[0, 1, 1000]], dtype = numpy.complex128))
+-        array([[[ 1.        ,  1.        ,  1.        ],
+-                [ 1.        ,  0.05558355,  0.05558355],
+-                [ 0.17301243,  0.        ,  0.        ]]])
++        array([[[1.        , 1.        , 1.        ],
++                [1.        , 0.05558355, 0.05558355],
++                [0.17301243, 0.        , 0.        ]]])
+ 
+         sage: complex_to_rgb(numpy.array([[0, 1j, 1000j]], dtype = numpy.complex128))
+-        array([[[ 1.        ,  1.        ,  1.        ],
+-                [ 0.52779177,  1.        ,  0.05558355],
+-                [ 0.08650622,  0.17301243,  0.        ]]])
++        array([[[1.        , 1.        , 1.        ],
++                [0.52779177, 1.        , 0.05558355],
++                [0.08650622, 0.17301243, 0.        ]]])
+ 
+ 
+     TESTS::
+diff --git a/src/sage/combinat/fully_packed_loop.py b/src/sage/combinat/fully_packed_loop.py
+index 0a9bd61267..d2193cc2d6 100644
+--- a/src/sage/combinat/fully_packed_loop.py
++++ b/src/sage/combinat/fully_packed_loop.py
+@@ -72,11 +72,11 @@ def _make_color_list(n, colors=None,  color_map=None, randomize=False):
+         sage: _make_color_list(5, ['blue', 'red'])
+         ['blue', 'red', 'blue', 'red', 'blue']
+         sage: _make_color_list(5, color_map='summer')
+-        [(0.0, 0.5, 0.40000000000000002),
+-         (0.25098039215686274, 0.62549019607843137, 0.40000000000000002),
+-         (0.50196078431372548, 0.75098039215686274, 0.40000000000000002),
+-         (0.75294117647058822, 0.87647058823529411, 0.40000000000000002),
+-         (1.0, 1.0, 0.40000000000000002)]
++        [(0.0, 0.5, 0.4),
++         (0.25098039215686274, 0.6254901960784314, 0.4),
++         (0.5019607843137255, 0.7509803921568627, 0.4),
++         (0.7529411764705882, 0.8764705882352941, 0.4),
++         (1.0, 1.0, 0.4)]
+         sage: _make_color_list(8, ['blue', 'red'], randomize=True)
+         ['blue', 'blue', 'red', 'blue', 'red', 'red', 'red', 'blue']
+     """
+diff --git a/src/sage/finance/time_series.pyx b/src/sage/finance/time_series.pyx
+index 28779365df..3ab0282861 100644
+--- a/src/sage/finance/time_series.pyx
++++ b/src/sage/finance/time_series.pyx
+@@ -111,8 +111,8 @@ cdef class TimeSeries:
+ 
+             sage: import numpy
+             sage: v = numpy.array([[1,2], [3,4]], dtype=float); v
+-            array([[ 1.,  2.],
+-                   [ 3.,  4.]])
++            array([[1., 2.],
++                   [3., 4.]])
+             sage: finance.TimeSeries(v)
+             [1.0000, 2.0000, 3.0000, 4.0000]
+             sage: finance.TimeSeries(v[:,0])
+@@ -2100,14 +2100,14 @@ cdef class TimeSeries:
+ 
+             sage: w[0] = 20
+             sage: w
+-            array([ 20. ,  -3. ,   4.5,  -2. ])
++            array([20. , -3. ,  4.5, -2. ])
+             sage: v
+             [20.0000, -3.0000, 4.5000, -2.0000]
+ 
+         If you want a separate copy do not give the ``copy=False`` option. ::
+ 
+             sage: z = v.numpy(); z
+-            array([ 20. ,  -3. ,   4.5,  -2. ])
++            array([20. , -3. ,  4.5, -2. ])
+             sage: z[0] = -10
+             sage: v
+             [20.0000, -3.0000, 4.5000, -2.0000]
+diff --git a/src/sage/functions/hyperbolic.py b/src/sage/functions/hyperbolic.py
+index aff552f450..7a6df931e7 100644
+--- a/src/sage/functions/hyperbolic.py
++++ b/src/sage/functions/hyperbolic.py
+@@ -214,7 +214,7 @@ class Function_coth(GinacFunction):
+             sage: import numpy
+             sage: a = numpy.arange(2, 5)
+             sage: coth(a)
+-            array([ 1.03731472,  1.00496982,  1.00067115])
++            array([1.03731472, 1.00496982, 1.00067115])
+         """
+         return 1.0 / tanh(x)
+ 
+@@ -267,7 +267,7 @@ class Function_sech(GinacFunction):
+             sage: import numpy
+             sage: a = numpy.arange(2, 5)
+             sage: sech(a)
+-            array([ 0.26580223,  0.09932793,  0.03661899])
++            array([0.26580223, 0.09932793, 0.03661899])
+         """
+         return 1.0 / cosh(x)
+ 
+@@ -318,7 +318,7 @@ class Function_csch(GinacFunction):
+             sage: import numpy
+             sage: a = numpy.arange(2, 5)
+             sage: csch(a)
+-            array([ 0.27572056,  0.09982157,  0.03664357])
++            array([0.27572056, 0.09982157, 0.03664357])
+         """
+         return 1.0 / sinh(x)
+ 
+@@ -586,7 +586,7 @@ class Function_arccoth(GinacFunction):
+             sage: import numpy
+             sage: a = numpy.arange(2,5)
+             sage: acoth(a)
+-            array([ 0.54930614,  0.34657359,  0.25541281])
++            array([0.54930614, 0.34657359, 0.25541281])
+         """
+         return arctanh(1.0 / x)
+ 
+diff --git a/src/sage/functions/orthogonal_polys.py b/src/sage/functions/orthogonal_polys.py
+index ed6365bef4..99b8b04dad 100644
+--- a/src/sage/functions/orthogonal_polys.py
++++ b/src/sage/functions/orthogonal_polys.py
+@@ -810,12 +810,12 @@ class Func_chebyshev_T(ChebyshevFunction):
+             sage: z2 = numpy.array([[1,2],[1,2]])
+             sage: z3 = numpy.array([1,2,3.])
+             sage: chebyshev_T(1,z)
+-            array([ 1.,  2.])
++            array([1., 2.])
+             sage: chebyshev_T(1,z2)
+-            array([[ 1.,  2.],
+-                   [ 1.,  2.]])
++            array([[1., 2.],
++                   [1., 2.]])
+             sage: chebyshev_T(1,z3)
+-            array([ 1.,  2.,  3.])
++            array([1., 2., 3.])
+             sage: chebyshev_T(z,0.1)
+             array([ 0.1 , -0.98])
+         """
+@@ -1095,12 +1095,12 @@ class Func_chebyshev_U(ChebyshevFunction):
+             sage: z2 = numpy.array([[1,2],[1,2]])
+             sage: z3 = numpy.array([1,2,3.])
+             sage: chebyshev_U(1,z)
+-            array([ 2.,  4.])
++            array([2., 4.])
+             sage: chebyshev_U(1,z2)
+-            array([[ 2.,  4.],
+-                   [ 2.,  4.]])
++            array([[2., 4.],
++                   [2., 4.]])
+             sage: chebyshev_U(1,z3)
+-            array([ 2.,  4.,  6.])
++            array([2., 4., 6.])
+             sage: chebyshev_U(z,0.1)
+             array([ 0.2 , -0.96])
+         """
+diff --git a/src/sage/functions/other.py b/src/sage/functions/other.py
+index 1883daa3e6..9885222817 100644
+--- a/src/sage/functions/other.py
++++ b/src/sage/functions/other.py
+@@ -389,7 +389,7 @@ class Function_ceil(BuiltinFunction):
+             sage: import numpy
+             sage: a = numpy.linspace(0,2,6)
+             sage: ceil(a)
+-            array([ 0.,  1.,  1.,  2.,  2.,  2.])
++            array([0., 1., 1., 2., 2., 2.])
+ 
+         Test pickling::
+ 
+@@ -553,7 +553,7 @@ class Function_floor(BuiltinFunction):
+             sage: import numpy
+             sage: a = numpy.linspace(0,2,6)
+             sage: floor(a)
+-            array([ 0.,  0.,  0.,  1.,  1.,  2.])
++            array([0., 0., 0., 1., 1., 2.])
+             sage: floor(x)._sympy_()
+             floor(x)
+ 
+@@ -869,7 +869,7 @@ def sqrt(x, *args, **kwds):
+             sage: import numpy
+             sage: a = numpy.arange(2,5)
+             sage: sqrt(a)
+-            array([ 1.41421356,  1.73205081,  2.        ])
++            array([1.41421356, 1.73205081, 2.        ])
+         """
+         if isinstance(x, float):
+             return math.sqrt(x)
+diff --git a/src/sage/functions/spike_function.py b/src/sage/functions/spike_function.py
+index 1e021de3fe..56635ca98f 100644
+--- a/src/sage/functions/spike_function.py
++++ b/src/sage/functions/spike_function.py
+@@ -157,7 +157,7 @@ class SpikeFunction:
+             sage: S = spike_function([(-3,4),(-1,1),(2,3)]); S
+             A spike function with spikes at [-3.0, -1.0, 2.0]
+             sage: P = S.plot_fft_abs(8)
+-            sage: p = P[0]; p.ydata
++            sage: p = P[0]; p.ydata  # abs tol 1e-8
+             [5.0, 5.0, 3.367958691924177, 3.367958691924177, 4.123105625617661, 4.123105625617661, 4.759921664218055, 4.759921664218055]
+         """
+         w = self.vector(samples = samples, xmin=xmin, xmax=xmax)
+@@ -176,8 +176,8 @@ class SpikeFunction:
+             sage: S = spike_function([(-3,4),(-1,1),(2,3)]); S
+             A spike function with spikes at [-3.0, -1.0, 2.0]
+             sage: P = S.plot_fft_arg(8)
+-            sage: p = P[0]; p.ydata
+-            [0.0, 0.0, -0.211524990023434..., -0.211524990023434..., 0.244978663126864..., 0.244978663126864..., -0.149106180027477..., -0.149106180027477...]
++            sage: p = P[0]; p.ydata  # abs tol 1e-8
++            [0.0, 0.0, -0.211524990023434, -0.211524990023434, 0.244978663126864, 0.244978663126864, -0.149106180027477, -0.149106180027477]
+         """
+         w = self.vector(samples = samples, xmin=xmin, xmax=xmax)
+         xmin, xmax = self._ranges(xmin, xmax)
+diff --git a/src/sage/functions/trig.py b/src/sage/functions/trig.py
+index 501e7ff6b6..5f760912f0 100644
+--- a/src/sage/functions/trig.py
++++ b/src/sage/functions/trig.py
+@@ -724,7 +724,7 @@ class Function_arccot(GinacFunction):
+             sage: import numpy
+             sage: a = numpy.arange(2, 5)
+             sage: arccot(a)
+-            array([ 0.46364761,  0.32175055,  0.24497866])
++            array([0.46364761, 0.32175055, 0.24497866])
+         """
+         return math.pi/2 - arctan(x)
+ 
+@@ -780,7 +780,7 @@ class Function_arccsc(GinacFunction):
+             sage: import numpy
+             sage: a = numpy.arange(2, 5)
+             sage: arccsc(a)
+-            array([ 0.52359878,  0.33983691,  0.25268026])
++            array([0.52359878, 0.33983691, 0.25268026])
+         """
+         return arcsin(1.0/x)
+ 
+@@ -838,7 +838,7 @@ class Function_arcsec(GinacFunction):
+             sage: import numpy
+             sage: a = numpy.arange(2, 5)
+             sage: arcsec(a)
+-            array([ 1.04719755,  1.23095942,  1.31811607])
++            array([1.04719755, 1.23095942, 1.31811607])
+         """
+         return arccos(1.0/x)
+ 
+@@ -913,13 +913,13 @@ class Function_arctan2(GinacFunction):
+             sage: a = numpy.linspace(1, 3, 3)
+             sage: b = numpy.linspace(3, 6, 3)
+             sage: atan2(a, b)
+-            array([ 0.32175055,  0.41822433,  0.46364761])
++            array([0.32175055, 0.41822433, 0.46364761])
+ 
+             sage: atan2(1,a)
+-            array([ 0.78539816,  0.46364761,  0.32175055])
++            array([0.78539816, 0.46364761, 0.32175055])
+ 
+             sage: atan2(a, 1)
+-            array([ 0.78539816,  1.10714872,  1.24904577])
++            array([0.78539816, 1.10714872, 1.24904577])
+ 
+         TESTS::
+ 
+diff --git a/src/sage/matrix/constructor.pyx b/src/sage/matrix/constructor.pyx
+index 12136f1773..491bf22e62 100644
+--- a/src/sage/matrix/constructor.pyx
++++ b/src/sage/matrix/constructor.pyx
+@@ -503,8 +503,8 @@ def matrix(*args, **kwds):
+         [7 8 9]
+         Full MatrixSpace of 3 by 3 dense matrices over Integer Ring
+         sage: n = matrix(QQ, 2, 2, [1, 1/2, 1/3, 1/4]).numpy(); n
+-        array([[ 1.        ,  0.5       ],
+-               [ 0.33333333,  0.25      ]])
++        array([[1.        , 0.5       ],
++               [0.33333333, 0.25      ]])
+         sage: matrix(QQ, n)
+         [  1 1/2]
+         [1/3 1/4]
+diff --git a/src/sage/matrix/matrix_double_dense.pyx b/src/sage/matrix/matrix_double_dense.pyx
+index 66e54a79a4..0498334f4b 100644
+--- a/src/sage/matrix/matrix_double_dense.pyx
++++ b/src/sage/matrix/matrix_double_dense.pyx
+@@ -606,6 +606,9 @@ cdef class Matrix_double_dense(Matrix_dense):
+             [ 3.0 + 9.0*I 4.0 + 16.0*I 5.0 + 25.0*I]
+             [6.0 + 36.0*I 7.0 + 49.0*I 8.0 + 64.0*I]
+             sage: B.condition()
++            doctest:warning
++            ...
++            ComplexWarning: Casting complex values to real discards the imaginary part
+             203.851798...
+             sage: B.condition(p='frob')
+             203.851798...
+@@ -654,9 +657,7 @@ cdef class Matrix_double_dense(Matrix_dense):
+             True
+             sage: B = A.change_ring(CDF)
+             sage: B.condition()
+-            Traceback (most recent call last):
+-            ...
+-            LinAlgError: Singular matrix
++            +Infinity
+ 
+         Improper values of ``p`` are caught.  ::
+ 
+@@ -2519,7 +2520,7 @@ cdef class Matrix_double_dense(Matrix_dense):
+             sage: P.is_unitary(algorithm='orthonormal')
+             Traceback (most recent call last):
+             ...
+-            ValueError: failed to create intent(cache|hide)|optional array-- must have defined dimensions but got (0,)
++            error: ((lwork==-1)||(lwork >= MAX(1,2*n))) failed for 3rd keyword lwork: zgees:lwork=0
+ 
+         TESTS::
+ 
+@@ -3635,8 +3636,8 @@ cdef class Matrix_double_dense(Matrix_dense):
+             [0.0 1.0 2.0]
+             [3.0 4.0 5.0]
+             sage: m.numpy()
+-            array([[ 0.,  1.,  2.],
+-                   [ 3.,  4.,  5.]])
++            array([[0., 1., 2.],
++                   [3., 4., 5.]])
+ 
+         Alternatively, numpy automatically calls this function (via
+         the magic :meth:`__array__` method) to convert Sage matrices
+@@ -3647,16 +3648,16 @@ cdef class Matrix_double_dense(Matrix_dense):
+             [0.0 1.0 2.0]
+             [3.0 4.0 5.0]
+             sage: numpy.array(m)
+-            array([[ 0.,  1.,  2.],
+-                   [ 3.,  4.,  5.]])
++            array([[0., 1., 2.],
++                   [3., 4., 5.]])
+             sage: numpy.array(m).dtype
+             dtype('float64')
+             sage: m = matrix(CDF, 2, range(6)); m
+             [0.0 1.0 2.0]
+             [3.0 4.0 5.0]
+             sage: numpy.array(m)
+-            array([[ 0.+0.j,  1.+0.j,  2.+0.j],
+-                   [ 3.+0.j,  4.+0.j,  5.+0.j]])
++            array([[0.+0.j, 1.+0.j, 2.+0.j],
++                   [3.+0.j, 4.+0.j, 5.+0.j]])
+             sage: numpy.array(m).dtype
+             dtype('complex128')
+ 
+diff --git a/src/sage/matrix/special.py b/src/sage/matrix/special.py
+index ccbd208810..c3f9a65093 100644
+--- a/src/sage/matrix/special.py
++++ b/src/sage/matrix/special.py
+@@ -706,7 +706,7 @@ def diagonal_matrix(arg0=None, arg1=None, arg2=None, sparse=True):
+ 
+         sage: import numpy
+         sage: entries = numpy.array([1.2, 5.6]); entries
+-        array([ 1.2,  5.6])
++        array([1.2, 5.6])
+         sage: A = diagonal_matrix(3, entries); A
+         [1.2 0.0 0.0]
+         [0.0 5.6 0.0]
+@@ -716,7 +716,7 @@ def diagonal_matrix(arg0=None, arg1=None, arg2=None, sparse=True):
+ 
+         sage: j = numpy.complex(0,1)
+         sage: entries = numpy.array([2.0+j, 8.1, 3.4+2.6*j]); entries
+-        array([ 2.0+1.j ,  8.1+0.j ,  3.4+2.6j])
++        array([2. +1.j , 8.1+0.j , 3.4+2.6j])
+         sage: A = diagonal_matrix(entries); A
+         [2.0 + 1.0*I         0.0         0.0]
+         [        0.0         8.1         0.0]
+diff --git a/src/sage/modules/free_module_element.pyx b/src/sage/modules/free_module_element.pyx
+index 37d92c1282..955d083b34 100644
+--- a/src/sage/modules/free_module_element.pyx
++++ b/src/sage/modules/free_module_element.pyx
+@@ -988,7 +988,7 @@ cdef class FreeModuleElement(Vector):   # abstract base class
+             sage: v.numpy()
+             array([1, 2, 5/6], dtype=object)
+             sage: v.numpy(dtype=float)
+-            array([ 1.        ,  2.        ,  0.83333333])
++            array([1.        , 2.        , 0.83333333])
+             sage: v.numpy(dtype=int)
+             array([1, 2, 0])
+             sage: import numpy
+@@ -999,7 +999,7 @@ cdef class FreeModuleElement(Vector):   # abstract base class
+         be more efficient but may have unintended consequences::
+ 
+             sage: v.numpy(dtype=None)
+-            array([ 1.        ,  2.        ,  0.83333333])
++            array([1.        , 2.        , 0.83333333])
+ 
+             sage: w = vector(ZZ, [0, 1, 2^63 -1]); w
+             (0, 1, 9223372036854775807)
+diff --git a/src/sage/modules/vector_double_dense.pyx b/src/sage/modules/vector_double_dense.pyx
+index 39fc2970de..2badf98284 100644
+--- a/src/sage/modules/vector_double_dense.pyx
++++ b/src/sage/modules/vector_double_dense.pyx
+@@ -807,13 +807,13 @@ cdef class Vector_double_dense(FreeModuleElement):
+ 
+             sage: v = vector(CDF,4,range(4))
+             sage: v.numpy()
+-            array([ 0.+0.j,  1.+0.j,  2.+0.j,  3.+0.j])
++            array([0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j])
+             sage: v = vector(CDF,0)
+             sage: v.numpy()
+             array([], dtype=complex128)
+             sage: v = vector(RDF,4,range(4))
+             sage: v.numpy()
+-            array([ 0.,  1.,  2.,  3.])
++            array([0., 1., 2., 3.])
+             sage: v = vector(RDF,0)
+             sage: v.numpy()
+             array([], dtype=float64)
+@@ -823,11 +823,11 @@ cdef class Vector_double_dense(FreeModuleElement):
+             sage: import numpy
+             sage: v = vector(CDF, 3, range(3))
+             sage: v.numpy()
+-            array([ 0.+0.j,  1.+0.j,  2.+0.j])
++            array([0.+0.j, 1.+0.j, 2.+0.j])
+             sage: v.numpy(dtype=numpy.float64)
+-            array([ 0.,  1.,  2.])
++            array([0., 1., 2.])
+             sage: v.numpy(dtype=numpy.float32)
+-            array([ 0.,  1.,  2.], dtype=float32)
++            array([0., 1., 2.], dtype=float32)
+         """
+         if dtype is None or dtype is self._vector_numpy.dtype:
+             from copy import copy
+diff --git a/src/sage/plot/complex_plot.pyx b/src/sage/plot/complex_plot.pyx
+index ad9693da62..758fb709b7 100644
+--- a/src/sage/plot/complex_plot.pyx
++++ b/src/sage/plot/complex_plot.pyx
+@@ -61,9 +61,9 @@ cdef inline double mag_to_lightness(double r):
+ 
+         sage: from sage.plot.complex_plot import complex_to_rgb
+         sage: complex_to_rgb([[0, 1, 10]])
+-        array([[[ 0.        ,  0.        ,  0.        ],
+-                [ 0.77172568,  0.        ,  0.        ],
+-                [ 1.        ,  0.22134776,  0.22134776]]])
++        array([[[0.        , 0.        , 0.        ],
++                [0.77172568, 0.        , 0.        ],
++                [1.        , 0.22134776, 0.22134776]]])
+     """
+     return atan(log(sqrt(r)+1)) * (4/PI) - 1
+ 
+@@ -82,13 +82,13 @@ def complex_to_rgb(z_values):
+ 
+         sage: from sage.plot.complex_plot import complex_to_rgb
+         sage: complex_to_rgb([[0, 1, 1000]])
+-        array([[[ 0.        ,  0.        ,  0.        ],
+-                [ 0.77172568,  0.        ,  0.        ],
+-                [ 1.        ,  0.64421177,  0.64421177]]])
++        array([[[0.        , 0.        , 0.        ],
++                [0.77172568, 0.        , 0.        ],
++                [1.        , 0.64421177, 0.64421177]]])
+         sage: complex_to_rgb([[0, 1j, 1000j]])
+-        array([[[ 0.        ,  0.        ,  0.        ],
+-                [ 0.38586284,  0.77172568,  0.        ],
+-                [ 0.82210588,  1.        ,  0.64421177]]])
++        array([[[0.        , 0.        , 0.        ],
++                [0.38586284, 0.77172568, 0.        ],
++                [0.82210588, 1.        , 0.64421177]]])
+     """
+     import numpy
+     cdef unsigned int i, j, imax, jmax
+diff --git a/src/sage/plot/histogram.py b/src/sage/plot/histogram.py
+index 5d28473731..fc4b2046c0 100644
+--- a/src/sage/plot/histogram.py
++++ b/src/sage/plot/histogram.py
+@@ -53,10 +53,17 @@ class Histogram(GraphicPrimitive):
+         """
+         import numpy as np
+         self.datalist=np.asarray(datalist,dtype=float)
++        if 'normed' in options:
++            from sage.misc.superseded import deprecation
++            deprecation(25260, "the 'normed' option is deprecated. Use 'density' instead.")
+         if 'linestyle' in options:
+             from sage.plot.misc import get_matplotlib_linestyle
+             options['linestyle'] = get_matplotlib_linestyle(
+                     options['linestyle'], return_type='long')
++        if options.get('range', None):
++            # numpy.histogram performs type checks on "range" so this must be
++            # actual floats
++            options['range'] = [float(x) for x in options['range']]
+         GraphicPrimitive.__init__(self, options)
+ 
+     def get_minmax_data(self):
+@@ -80,10 +87,14 @@ class Histogram(GraphicPrimitive):
+             {'xmax': 4.0, 'xmin': 0, 'ymax': 2, 'ymin': 0}
+ 
+         TESTS::
+-
+             sage: h = histogram([10,3,5], normed=True)[0]
+-            sage: h.get_minmax_data()  # rel tol 1e-15
+-            {'xmax': 10.0, 'xmin': 3.0, 'ymax': 0.4761904761904765, 'ymin': 0}
++            doctest:warning...:
++            DeprecationWarning: the 'normed' option is deprecated. Use 'density' instead.
++            See https://trac.sagemath.org/25260 for details.
++            sage: h.get_minmax_data()
++            doctest:warning ...:
++            VisibleDeprecationWarning: Passing `normed=True` on non-uniform bins has always been broken, and computes neither the probability density function nor the probability mass function. The result is only correct if the bins are uniform, when density=True will produce the same result anyway. The argument will be removed in a future version of numpy.
++            {'xmax': 10.0, 'xmin': 3.0, 'ymax': 0.476190476190..., 'ymin': 0}
+         """
+         import numpy
+ 
+@@ -152,7 +163,7 @@ class Histogram(GraphicPrimitive):
+                 'rwidth': 'The relative width of the bars as a fraction of the bin width',
+                 'cumulative': '(True or False) If True, then a histogram is computed in which each bin gives the counts in that bin plus all bins for smaller values.  Negative values give a reversed direction of accumulation.',
+                 'range': 'A list [min, max] which define the range of the histogram. Values outside of this range are treated as outliers and omitted from counts.',
+-                'normed': 'Deprecated alias for density',
++                'normed': 'Deprecated. Use density instead.',
+                 'density': '(True or False) If True, the counts are normalized to form a probability density. (n/(len(x)*dbin)',
+                 'weights': 'A sequence of weights the same length as the data list. If supplied, then each value contributes its associated weight to the bin count.',
+                 'stacked': '(True or False) If True, multiple data are stacked on top of each other.',
+@@ -199,7 +210,7 @@ class Histogram(GraphicPrimitive):
+             subplot.hist(self.datalist.transpose(), **options)
+ 
+ 
+-@options(aspect_ratio='automatic',align='mid', weights=None, range=None, bins=10, edgecolor='black')
++@options(aspect_ratio='automatic', align='mid', weights=None, range=None, bins=10, edgecolor='black')
+ def histogram(datalist, **options):
+     """
+     Computes and draws the histogram for list(s) of numerical data.
+@@ -231,8 +242,9 @@ def histogram(datalist, **options):
+     - ``linewidth`` -- (float) width of the lines defining the bars
+     - ``linestyle`` -- (default: 'solid') Style of the line. One of 'solid'
+       or '-', 'dashed' or '--', 'dotted' or ':', 'dashdot' or '-.'
+-    - ``density`` -- (boolean - default: False) If True, the counts are
+-      normalized to form a probability density.
++    - ``density`` -- (boolean - default: False) If True, the result is the
++      value of the probability density function at the bin, normalized such
++      that the integral over the range is 1.
+     - ``range`` -- A list [min, max] which define the range of the
+       histogram. Values outside of this range are treated as outliers and
+       omitted from counts
+diff --git a/src/sage/plot/line.py b/src/sage/plot/line.py
+index 23f5e61446..3b1b51d7cf 100644
+--- a/src/sage/plot/line.py
++++ b/src/sage/plot/line.py
+@@ -502,14 +502,12 @@ def line2d(points, **options):
+     from sage.plot.all import Graphics
+     from sage.plot.plot import xydata_from_point_list
+     from sage.rings.all import CC, CDF
++    points = list(points) # make sure points is a python list
+     if points in CC or points in CDF:
+         pass
+     else:
+-        try:
+-            if not points:
+-                return Graphics()
+-        except ValueError: # numpy raises a ValueError if not empty
+-            pass
++        if len(points) == 0:
++            return Graphics()
+     xdata, ydata = xydata_from_point_list(points)
+     g = Graphics()
+     g._set_extra_kwds(Graphics._extract_kwds_for_show(options))
+diff --git a/src/sage/plot/plot_field.py b/src/sage/plot/plot_field.py
+index 0025098a8d..23c80902f3 100644
+--- a/src/sage/plot/plot_field.py
++++ b/src/sage/plot/plot_field.py
+@@ -49,9 +49,10 @@ class PlotField(GraphicPrimitive):
+             sage: r.xpos_array
+             [0.0, 0.0, 1.0, 1.0]
+             sage: r.yvec_array
+-            masked_array(data = [0.0 0.70710678118... 0.70710678118... 0.89442719...],
+-                         mask = [False False False False],
+-                   fill_value = 1e+20)
++            masked_array(data=[0.0, 0.70710678118..., 0.70710678118...,
++                               0.89442719...],
++                         mask=[False, False, False, False],
++                   fill_value=1e+20)
+ 
+         TESTS:
+ 
+diff --git a/src/sage/plot/streamline_plot.py b/src/sage/plot/streamline_plot.py
+index f3da57c370..3806f4b32f 100644
+--- a/src/sage/plot/streamline_plot.py
++++ b/src/sage/plot/streamline_plot.py
+@@ -38,16 +38,14 @@ class StreamlinePlot(GraphicPrimitive):
+             sage: r.options()['plot_points']
+             2
+             sage: r.xpos_array
+-            array([ 0.,  1.])
++            array([0., 1.])
+             sage: r.yvec_array
+-            masked_array(data =
+-             [[1.0 1.0]
+-             [0.5403023058681398 0.5403023058681398]],
+-                         mask =
+-             [[False False]
+-             [False False]],
+-                   fill_value = 1e+20)
+-            <BLANKLINE>
++            masked_array(
++              data=[[1.0, 1.0],
++                    [0.5403023058681398, 0.5403023058681398]],
++              mask=[[False, False],
++                    [False, False]],
++              fill_value=1e+20)
+ 
+         TESTS:
+ 
+diff --git a/src/sage/probability/probability_distribution.pyx b/src/sage/probability/probability_distribution.pyx
+index 1b119e323f..3290b00695 100644
+--- a/src/sage/probability/probability_distribution.pyx
++++ b/src/sage/probability/probability_distribution.pyx
+@@ -130,7 +130,17 @@ cdef class ProbabilityDistribution:
+              0.0,
+              1.4650000000000003]
+             sage: b
+-            [0.0, 0.20000000000000001, 0.40000000000000002, 0.60000000000000009, 0.80000000000000004, 1.0, 1.2000000000000002, 1.4000000000000001, 1.6000000000000001, 1.8, 2.0]
++            [0.0,
++             0.2,
++             0.4,
++             0.6000000000000001,
++             0.8,
++             1.0,
++             1.2000000000000002,
++             1.4000000000000001,
++             1.6,
++             1.8,
++             2.0]
+         """
+         import pylab
+         l = [float(self.get_random_element()) for _ in range(num_samples)]
+diff --git a/src/sage/rings/rational.pyx b/src/sage/rings/rational.pyx
+index 12ca1b222b..9bad7dae0c 100644
+--- a/src/sage/rings/rational.pyx
++++ b/src/sage/rings/rational.pyx
+@@ -1041,7 +1041,7 @@ cdef class Rational(sage.structure.element.FieldElement):
+             dtype('O')
+ 
+             sage: numpy.array([1, 1/2, 3/4])
+-            array([ 1.  ,  0.5 ,  0.75])
++            array([1.  , 0.5 , 0.75])
+         """
+         if mpz_cmp_ui(mpq_denref(self.value), 1) == 0:
+             if mpz_fits_slong_p(mpq_numref(self.value)):
+diff --git a/src/sage/rings/real_mpfr.pyx b/src/sage/rings/real_mpfr.pyx
+index 9b90c8833e..1ce05b937d 100644
+--- a/src/sage/rings/real_mpfr.pyx
++++ b/src/sage/rings/real_mpfr.pyx
+@@ -1439,7 +1439,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+             sage: import numpy
+             sage: numpy.arange(10.0)
+-            array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])
++            array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
+             sage: numpy.array([1.0, 1.1, 1.2]).dtype
+             dtype('float64')
+             sage: numpy.array([1.000000000000000000000000000000000000]).dtype
+diff --git a/src/sage/schemes/elliptic_curves/height.py b/src/sage/schemes/elliptic_curves/height.py
+index de31fe9883..7a33ea6f5b 100644
+--- a/src/sage/schemes/elliptic_curves/height.py
++++ b/src/sage/schemes/elliptic_curves/height.py
+@@ -1627,18 +1627,18 @@ class EllipticCurveCanonicalHeight:
+         even::
+ 
+             sage: H.wp_on_grid(v,4)
+-            array([[ 25.43920182,   5.28760943,   5.28760943,  25.43920182],
+-            [  6.05099485,   1.83757786,   1.83757786,   6.05099485],
+-            [  6.05099485,   1.83757786,   1.83757786,   6.05099485],
+-            [ 25.43920182,   5.28760943,   5.28760943,  25.43920182]])
++            array([[25.43920182,  5.28760943,  5.28760943, 25.43920182],
++                   [ 6.05099485,  1.83757786,  1.83757786,  6.05099485],
++                   [ 6.05099485,  1.83757786,  1.83757786,  6.05099485],
++                   [25.43920182,  5.28760943,  5.28760943, 25.43920182]])
+ 
+         The array of values on the half-grid::
+ 
+             sage: H.wp_on_grid(v,4,True)
+-            array([[ 25.43920182,   5.28760943],
+-            [  6.05099485,   1.83757786],
+-            [  6.05099485,   1.83757786],
+-            [ 25.43920182,   5.28760943]])
++            array([[25.43920182,  5.28760943],
++                   [ 6.05099485,  1.83757786],
++                   [ 6.05099485,  1.83757786],
++                   [25.43920182,  5.28760943]])
+         """
+         tau = self.tau(v)
+         fk, err = self.fk_intervals(v, 15, CDF)
+diff --git a/src/sage/symbolic/ring.pyx b/src/sage/symbolic/ring.pyx
+index 9da38002e8..d61e74bf82 100644
+--- a/src/sage/symbolic/ring.pyx
++++ b/src/sage/symbolic/ring.pyx
+@@ -1136,7 +1136,7 @@ cdef class NumpyToSRMorphism(Morphism):
+         sage: cos(numpy.int('2'))
+         cos(2)
+         sage: numpy.cos(numpy.int('2'))
+-        -0.41614683654714241
++        -0.4161468365471424
+     """
+     cdef _intermediate_ring
+ 
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/pari-stackwarn.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/pari-stackwarn.patch
new file mode 100644
index 000000000000..49cdfd189b92
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/pari-stackwarn.patch
@@ -0,0 +1,20 @@
+diff --git a/src/sage/doctest/parsing.py b/src/sage/doctest/parsing.py
+index 6bdc9a0..31fc780 100644
+--- a/src/sage/doctest/parsing.py
++++ b/src/sage/doctest/parsing.py
+@@ -40,6 +40,7 @@ from .external import available_software
+ 
+ float_regex = re.compile('\s*([+-]?\s*((\d*\.?\d+)|(\d+\.?))([eE][+-]?\d+)?)')
+ optional_regex = re.compile(r'(py2|py3|long time|not implemented|not tested|known bug)|([^ a-z]\s*optional\s*[:-]*((\s|\w)*))')
++pari_stack_warning_regex = re.compile(r'\s*\*\*\*.*(Warning: increasing stack size to )\d+\.')
+ find_sage_prompt = re.compile(r"^(\s*)sage: ", re.M)
+ find_sage_continuation = re.compile(r"^(\s*)\.\.\.\.:", re.M)
+ random_marker = re.compile('.*random', re.I)
+@@ -935,6 +936,7 @@ class SageOutputChecker(doctest.OutputChecker):
+             <type 'float'>
+         """
+         got = self.human_readable_escape_sequences(got)
++        got = pari_stack_warning_regex.sub('', got)
+         if isinstance(want, MarkedOutput):
+             if want.random:
+                 return True
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/python-5755-hotpatch.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/python-5755-hotpatch.patch
new file mode 100644
index 000000000000..1b64f39fe60f
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/python-5755-hotpatch.patch
@@ -0,0 +1,28 @@
+diff --git a/src/sage/all.py b/src/sage/all.py
+index ca309ef..be3186b 100644
+--- a/src/sage/all.py
++++ b/src/sage/all.py
+@@ -298,6 +298,23 @@ warnings.filterwarnings('ignore', module='matplotlib[.]font_manager')
+ warnings.filterwarnings('default',
+     '[\s\S]*See http://trac.sagemath.org/[0-9]* for details.')
+ 
++# Hotpatch around https://bugs.python.org/issue5755 which won't be fixed for
++# python 2.7. Idea by https://stackoverflow.com/a/36293331.
++from distutils.command.build_ext import build_ext
++from distutils.sysconfig import customize_compiler
++
++_build_extensions = build_ext.build_extensions
++
++def build_extensions_patched(self):
++    customize_compiler(self.compiler)
++    try:
++        self.compiler.compiler_so.remove("-Wstrict-prototypes")
++    except (AttributeError, ValueError):
++        pass
++    _build_extensions(self)
++
++build_ext.build_extensions = build_extensions_patched
++
+ 
+ # Set a new random number seed as the very last thing
+ # (so that printing initial_seed() and using that seed
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/revert-sphinx-always-fork.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/revert-sphinx-always-fork.patch
new file mode 100644
index 000000000000..64dd6fd93777
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/revert-sphinx-always-fork.patch
@@ -0,0 +1,71 @@
+commit f1c59929c3c180ac283334c2b3c901ac8c82f6b1
+Author: Timo Kaufmann <timokau@zoho.com>
+Date:   Sat Oct 20 20:07:41 2018 +0200
+
+    Revert "Something related to the sphinxbuild seems to be leaking memory"
+    
+    This reverts commit 7d85dc796c58c3de57401bc22d3587b94e205091.
+
+diff --git a/src/sage_setup/docbuild/__init__.py b/src/sage_setup/docbuild/__init__.py
+index 0b24b1a60b..084c3f89d7 100644
+--- a/src/sage_setup/docbuild/__init__.py
++++ b/src/sage_setup/docbuild/__init__.py
+@@ -265,29 +265,35 @@ class DocBuilder(object):
+     # import the customized builder for object.inv files
+     inventory = builder_helper('inventory')
+ 
+-def build_many(target, args):
+-    # Pool() uses an actual fork() to run each new instance. This is important
+-    # for performance reasons, i.e., don't use a forkserver when it becomes
+-    # available with Python 3: Here, sage is already initialized which is quite
+-    # costly, with a forkserver we would have to reinitialize it for every
+-    # document we build. At the same time, don't serialize this by taking the
+-    # pool (and thus the call to fork()) out completely: The call to Sphinx
+-    # leaks memory, so we need to build each document in its own process to
+-    # control the RAM usage.
+-    from multiprocessing import Pool
+-    pool = Pool(NUM_THREADS, maxtasksperchild=1)
+-    # map_async handles KeyboardInterrupt correctly. Plain map and
+-    # apply_async does not, so don't use it.
+-    x = pool.map_async(target, args, 1)
+-    try:
+-        ret = x.get(99999)
+-        pool.close()
+-        pool.join()
+-    except Exception:
+-        pool.terminate()
+-        if ABORT_ON_ERROR:
+-            raise
+-    return ret
++if NUM_THREADS > 1:
++    def build_many(target, args):
++        from multiprocessing import Pool
++        pool = Pool(NUM_THREADS, maxtasksperchild=1)
++        # map_async handles KeyboardInterrupt correctly. Plain map and
++        # apply_async does not, so don't use it.
++        x = pool.map_async(target, args, 1)
++        try:
++            ret = x.get(99999)
++            pool.close()
++            pool.join()
++        except Exception:
++            pool.terminate()
++            if ABORT_ON_ERROR:
++                raise
++        return ret
++else:
++    def build_many(target, args):
++        results = []
++
++        for arg in args:
++            try:
++                results.append(target(arg))
++            except Exception:
++                if ABORT_ON_ERROR:
++                    raise
++
++        return results
++
+ 
+ ##########################################
+ #      Parallel Building Ref Manual      #
diff --git a/nixpkgs/pkgs/applications/science/math/sage/pybrial.nix b/nixpkgs/pkgs/applications/science/math/sage/pybrial.nix
new file mode 100644
index 000000000000..f5cb39603c32
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/pybrial.nix
@@ -0,0 +1,29 @@
+{ stdenv
+, fetchFromGitHub
+, buildPythonPackage
+}:
+# This has a cyclic dependency with sage. I don't include sage in the
+# buildInputs and let python figure it out at runtime. Because of this,
+# I don't include the package in the main nipxkgs tree. It wouldn't be useful
+# outside of sage anyways (as you could just directly depend on sage and use
+# it).
+buildPythonPackage rec {
+    pname = "pyBRiAl";
+    version = "1.2.3";
+
+    # included with BRiAl source
+    src = fetchFromGitHub {
+      owner = "BRiAl";
+      repo = "BRiAl";
+      rev = "${version}";
+      sha256 = "0qy4cwy7qrk4zg151cmws5cglaa866z461cnj9wdnalabs7v7qbg";
+    };
+
+    sourceRoot = "source/sage-brial";
+
+    meta = with stdenv.lib; {
+      description = "python implementation of BRiAl";
+      license = licenses.gpl2;
+      maintainers = with maintainers; [ timokau ];
+    };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/python-openid.nix b/nixpkgs/pkgs/applications/science/math/sage/python-openid.nix
new file mode 100644
index 000000000000..184eaf29bdd3
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/python-openid.nix
@@ -0,0 +1,42 @@
+{ stdenv
+, buildPythonPackage
+, fetchPypi
+, isPy3k
+, django
+, nose
+, twill
+, pycrypto
+}:
+
+buildPythonPackage rec {
+  pname = "python-openid";
+  version = "2.2.5";
+
+  disabled = isPy3k;
+
+  src = fetchPypi {
+    inherit pname version;
+    sha256 = "1vvhxlghjan01snfdc4k7ykd80vkyjgizwgg9bncnin8rqz1ricj";
+  };
+
+  propagatedBuildInputs = [
+    django
+    twill
+    pycrypto
+  ];
+
+  # Cannot access the djopenid example module.
+  # I don't know how to fix that (adding the examples dir to PYTHONPATH doesn't work)
+  doCheck = false;
+  checkInputs = [ nose ];
+  checkPhase = ''
+    nosetests
+  '';
+
+  meta = with stdenv.lib; {
+    description = "OpenID library for Python";
+    license = licenses.asl20;
+    maintainers = with maintainers; [ timokau ];
+    homepage = https://github.com/openid/python-openid/;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/sage-env.nix b/nixpkgs/pkgs/applications/science/math/sage/sage-env.nix
new file mode 100644
index 000000000000..c071f8945506
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage-env.nix
@@ -0,0 +1,170 @@
+{ stdenv
+, lib
+, writeTextFile
+, python
+, sagelib
+, env-locations
+, gfortran
+, bash
+, coreutils
+, gnused
+, gnugrep
+, binutils
+, pythonEnv
+, python3
+, pkg-config
+, pari
+, gap-libgap-compatible
+, libgap
+, ecl
+, maxima-ecl
+, singular
+, giac
+, palp
+, rWrapper
+, gfan
+, cddlib
+, jmol
+, tachyon
+, glpk
+, eclib
+, sympow
+, nauty
+, sqlite
+, ppl
+, ecm
+, lcalc
+, rubiks
+, flintqs
+, openblasCompat
+, flint
+, gmp
+, mpfr
+, pynac
+, zlib
+, gsl
+, ntl
+, jdk
+}:
+
+# This generates a `sage-env` shell file that will be sourced by sage on startup.
+# It sets up various environment variables, telling sage where to find its
+# dependencies.
+
+let
+  runtimepath = (lib.makeBinPath ([
+    "@sage-local@"
+    "@sage-local@/build"
+    pythonEnv
+    # empty python env to add python wrapper that clears PYTHONHOME (see
+    # wrapper.nix). This is necessary because sage will call the python3 binary
+    # (from python2 code). The python2 PYTHONHOME (again set in wrapper.nix)
+    # will then confuse python3, if it is not overwritten.
+    python3.buildEnv
+    gfortran # for inline fortran
+    stdenv.cc # for cython
+    bash
+    coreutils
+    gnused
+    gnugrep
+    binutils.bintools
+    pkg-config
+    pari
+    gap-libgap-compatible
+    libgap
+    ecl
+    maxima-ecl
+    singular
+    giac
+    palp
+    rWrapper
+    gfan
+    cddlib
+    jmol
+    tachyon
+    glpk
+    eclib
+    sympow
+    nauty
+    sqlite
+    ppl
+    ecm
+    lcalc
+    rubiks
+    flintqs
+    jdk # only needed for `jmol` which may be replaced in the future
+  ]
+  ));
+in
+writeTextFile rec {
+  name = "sage-env";
+  destination = "/${name}";
+  text = ''
+    export PKG_CONFIG_PATH='${lib.concatStringsSep ":" (map (pkg: "${pkg}/lib/pkgconfig") [
+        # This is only needed in the src/sage/misc/cython.py test and I'm not
+        # sure if there's really a usecase for it outside of the tests. However
+        # since singular and openblas are runtime dependencies anyways, it doesn't
+        # really hurt to include.
+        singular
+        openblasCompat
+      ])
+    }'
+    export SAGE_ROOT='${sagelib.src}'
+    export SAGE_LOCAL='@sage-local@'
+    export SAGE_SHARE='${sagelib}/share'
+    orig_path="$PATH"
+    export PATH='${runtimepath}'
+
+    # set dependent vars, like JUPYTER_CONFIG_DIR
+    source "${sagelib.src}/src/bin/sage-env"
+    export PATH="${runtimepath}:$orig_path" # sage-env messes with PATH
+
+    export SAGE_LOGS="$TMPDIR/sage-logs"
+    export SAGE_DOC="''${SAGE_DOC_OVERRIDE:-doc-placeholder}"
+    export SAGE_DOC_SRC="''${SAGE_DOC_SRC_OVERRIDE:-${sagelib.src}/src/doc}"
+
+    # set locations of dependencies
+    . ${env-locations}/sage-env-locations
+
+    # needed for cython
+    export CC='${stdenv.cc}/bin/${stdenv.cc.targetPrefix}cc'
+    # cython needs to find these libraries, otherwise will fail with `ld: cannot find -lflint` or similar
+    export LDFLAGS='${
+      lib.concatStringsSep " " (map (pkg: "-L${pkg}/lib") [
+        flint
+        libgap
+        glpk
+        gmp
+        mpfr
+        pari
+        pynac
+        zlib
+        eclib
+        gsl
+        ntl
+        jmol
+        sympow
+      ])
+    }'
+    export CFLAGS='${
+      lib.concatStringsSep " " (map (pkg: "-isystem ${pkg}/include") [
+        singular
+        gmp.dev
+        glpk
+        flint
+        libgap
+        pynac
+        mpfr.dev
+      ])
+    }'
+
+    export SAGE_LIB='${sagelib}/${python.sitePackages}'
+
+    export SAGE_EXTCODE='${sagelib.src}/src/ext'
+
+  # for find_library
+    export DYLD_LIBRARY_PATH="${lib.makeLibraryPath [stdenv.cc.libc singular]}:$DYLD_LIBRARY_PATH"
+  '';
+} // {
+  lib = sagelib; # equivalent of `passthru`, which `writeTextFile` doesn't support
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/sage-src.nix b/nixpkgs/pkgs/applications/science/math/sage/sage-src.nix
new file mode 100644
index 000000000000..5dc73e26a596
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage-src.nix
@@ -0,0 +1,144 @@
+{ stdenv
+, fetchFromGitHub
+, fetchpatch
+}:
+
+# This file is responsible for fetching the sage source and adding necessary patches.
+# It does not actually build anything, it just copies the patched sources to $out.
+# This is done because multiple derivations rely on these sources and they should
+# all get the same sources with the same patches applied.
+
+stdenv.mkDerivation rec {
+  version = "8.4";
+  name = "sage-src-${version}";
+
+  src = fetchFromGitHub {
+    owner = "sagemath";
+    repo = "sage";
+    rev = version;
+    sha256 = "0gips1hagiz9m7s21bg5as8hrrm2x5k47h1bsq0pc46iplfwmv2d";
+  };
+
+  # Patches needed because of particularities of nix or the way this is packaged.
+  # The goal is to upstream all of them and get rid of this list.
+  nixPatches = [
+    # https://trac.sagemath.org/ticket/25358
+    (fetchpatch {
+      name = "safe-directory-test-without-patch.patch";
+      url = "https://git.sagemath.org/sage.git/patch?id2=8bdc326ba57d1bb9664f63cf165a9e9920cc1afc&id=dc673c17555efca611f68398d5013b66e9825463";
+      sha256 = "1hhannz7xzprijakn2w2d0rhd5zv2zikik9p51i87bas3nc658f7";
+    })
+
+    # Unfortunately inclusion in upstream sage was rejected. Instead the bug was
+    # fixed in python, but of course not backported to 2.7. So we'll probably
+    # have to keep this around until 2.7 is deprecated.
+    # https://trac.sagemath.org/ticket/25316
+    # https://github.com/python/cpython/pull/7476
+    ./patches/python-5755-hotpatch.patch
+
+    # Revert the commit that made the sphinx build fork even in the single thread
+    # case. For some yet unknown reason, that breaks the docbuild on nix and archlinux.
+    # See https://groups.google.com/forum/#!msg/sage-packaging/VU4h8IWGFLA/mrmCMocYBwAJ.
+    # https://trac.sagemath.org/ticket/26608
+    ./patches/revert-sphinx-always-fork.patch
+
+    # Make sure py2/py3 tests are only run when their expected context (all "sage"
+    # tests) are also run. That is necessary to test dochtml individually. See
+    # https://trac.sagemath.org/ticket/26110 for an upstream discussion.
+    ./patches/Only-test-py2-py3-optional-tests-when-all-of-sage-is.patch
+  ];
+
+  # Patches needed because of package updates. We could just pin the versions of
+  # dependencies, but that would lead to rebuilds, confusion and the burdons of
+  # maintaining multiple versions of dependencies. Instead we try to make sage
+  # compatible with never dependency versions when possible. All these changes
+  # should come from or be proposed to upstream. This list will probably never
+  # be empty since dependencies update all the time.
+  packageUpgradePatches = let
+    # Fetch a diff between `base` and `rev` on sage's git server.
+    # Used to fetch trac tickets by setting the `base` to the last release and the
+    # `rev` to the last commit of the ticket.
+    fetchSageDiff = { base, rev, ...}@args: (
+      fetchpatch ({
+        url = "https://git.sagemath.org/sage.git/patch?id2=${base}&id=${rev}";
+        # We don't care about sage's own build system (which builds all its dependencies).
+        # Exclude build system changes to avoid conflicts.
+        excludes = [ "build/*" ];
+      } // builtins.removeAttrs args [ "rev" "base" ])
+    );
+  in [
+    # New glpk version has new warnings, filter those out until upstream sage has found a solution
+    # https://trac.sagemath.org/ticket/24824
+    ./patches/pari-stackwarn.patch # not actually necessary since the pari upgrade, but necessary for the glpk patch to apply
+    (fetchpatch {
+      url = "https://salsa.debian.org/science-team/sagemath/raw/58bbba93a807ca2933ca317501d093a1bb4b84db/debian/patches/dt-version-glpk-4.65-ignore-warnings.patch";
+      sha256 = "0b9293v73wb4x13wv5zwyjgclc01zn16msccfzzi6znswklgvddp";
+      stripLen = 1;
+    })
+
+    # https://trac.sagemath.org/ticket/25260
+    ./patches/numpy-1.15.1.patch
+
+    # https://trac.sagemath.org/ticket/26315
+    ./patches/giac-1.5.0.patch
+
+    # needed for ntl update
+    # https://trac.sagemath.org/ticket/25532
+    (fetchpatch {
+      name = "lcalc-c++11.patch";
+      url = "https://git.archlinux.org/svntogit/community.git/plain/trunk/sagemath-lcalc-c++11.patch?h=packages/sagemath&id=0e31ae526ab7c6b5c0bfacb3f8b1c4fd490035aa";
+      sha256 = "0p5wnvbx65i7cp0bjyaqgp4rly8xgnk12pqwaq3dqby0j2bk6ijb";
+    })
+
+    (fetchpatch {
+      name = "cython-0.29.patch";
+      url = "https://git.sagemath.org/sage.git/patch/?h=f77de1d0e7f90ee12761140500cb8cbbb789ab20";
+      sha256 = "14wrpy8jgbnpza1j8a2nx8y2r946y82pll1fv3cn6gpfmm6640l3";
+    })
+    # https://trac.sagemath.org/ticket/26360
+    (fetchpatch {
+      name = "arb-2.15.1.patch";
+      url = "https://git.sagemath.org/sage.git/patch/?id=30cc778d46579bd0c7537ed33e8d7a4f40fd5c31";
+      sha256 = "13vc2q799dh745sm59xjjabllfj0sfjzcacf8k59kwj04x755d30";
+    })
+
+    # https://trac.sagemath.org/ticket/26326
+    # needs to be split because there is a merge commit in between
+    (fetchSageDiff {
+      name = "networkx-2.2-1.patch";
+      base = "8.4";
+      rev = "68f5ad068184745b38ba6716bf967c8c956c52c5";
+      sha256 = "112b5ywdqgyzgvql2jj5ss8la9i8rgnrzs8vigsfzg4shrcgh9p6";
+    })
+    (fetchSageDiff {
+      name = "networkx-2.2-2.patch";
+      base = "626485bbe5f33bf143d6dfba4de9c242f757f59b~1";
+      rev = "db10d327ade93711da735a599a67580524e6f7b4";
+      sha256 = "09v87id25fa5r9snfn4mv79syhc77jxfawj5aizmdpwdmpgxjk1f";
+    })
+  ];
+
+  patches = nixPatches ++ packageUpgradePatches;
+
+  postPatch = ''
+    # make sure shebangs etc are fixed, but sage-python23 still works
+    find . -type f -exec sed \
+      -e 's/sage-python23/python/g' \
+      -i {} \;
+
+    echo '#!${stdenv.shell}
+    python "$@"' > build/bin/sage-python23
+
+    # Do not use sage-env-config (generated by ./configure).
+    # Instead variables are set manually.
+    echo '# do nothing' >  src/bin/sage-env-config
+  '';
+
+  configurePhase = "# do nothing";
+
+  buildPhase = "# do nothing";
+
+  installPhase = ''
+    cp -r . "$out"
+  '';
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/sage-tests.nix b/nixpkgs/pkgs/applications/science/math/sage/sage-tests.nix
new file mode 100644
index 000000000000..1f400db18fcb
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage-tests.nix
@@ -0,0 +1,51 @@
+{ stdenv
+, lib
+, sage-with-env
+, makeWrapper
+, files ? null # "null" means run all tests
+, longTests ? true # run tests marked as "long time"
+}:
+
+# for a quick test of some source files:
+# nix-build -E 'with (import ./. {}); sage.tests.override { files = [ "src/sage/misc/cython.py" ];}'
+
+let
+  src = sage-with-env.env.lib.src;
+  runAllTests = files == null;
+  testArgs = if runAllTests then "--all" else testFileList;
+  patienceSpecifier = if longTests then "--long" else "";
+  relpathToArg = relpath: lib.escapeShellArg "${src}/${relpath}"; # paths need to be absolute
+  testFileList = lib.concatStringsSep " " (map relpathToArg files);
+in
+stdenv.mkDerivation rec {
+  version = src.version;
+  name = "sage-tests-${version}";
+  inherit src;
+
+  buildInputs = [
+    makeWrapper
+    sage-with-env
+  ];
+
+  unpackPhase = "#do nothing";
+  configurePhase = "#do nothing";
+  buildPhase = "#do nothing";
+
+  installPhase = ''
+    # This output is not actually needed for anything, the package just
+    # exists to decouple the sage build from its t ests.
+
+    mkdir -p "$out/bin"
+    # Like a symlink, but make sure that $0 points to the original.
+    makeWrapper "${sage-with-env}/bin/sage" "$out/bin/sage"
+  '';
+
+  doInstallCheck = true;
+  installCheckPhase = ''
+    export HOME="$TMPDIR/sage-home"
+    mkdir -p "$HOME"
+
+    # "--long" tests are in the order of 1h, without "--long" its 1/2h
+    "sage" -t --timeout=0 --nthreads "$NIX_BUILD_CORES" --optional=sage ${patienceSpecifier} ${testArgs}
+  '';
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/sage-with-env.nix b/nixpkgs/pkgs/applications/science/math/sage/sage-with-env.nix
new file mode 100644
index 000000000000..c5db392f1036
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage-with-env.nix
@@ -0,0 +1,128 @@
+{ stdenv
+, lib
+, makeWrapper
+, sage-env
+, openblasCompat
+, pkg-config
+, three
+, singular
+, libgap
+, gap-libgap-compatible
+, giac
+, maxima-ecl
+, pari
+, gmp
+, gfan
+, python2
+, flintqs
+, eclib
+, ntl
+, ecm
+, pynac
+, pythonEnv
+}:
+
+# Wrapper that combined `sagelib` with `sage-env` to produce an actually
+# executable sage. No tests are run yet and no documentation is built.
+
+let
+  buildInputs = [
+    pythonEnv # for patchShebangs
+    makeWrapper
+    pkg-config
+    openblasCompat # lots of segfaults with regular (64 bit) openblas
+    singular
+    three
+    pynac
+    giac
+    libgap
+    gap-libgap-compatible
+    pari
+    gmp
+    gfan
+    maxima-ecl
+    eclib
+    flintqs
+    ntl
+    ecm
+  ];
+
+  # remove python prefix, replace "-" in the name by "_", apply patch_names
+  # python2.7-some-pkg-1.0 -> some_pkg-1.0
+  pkg_to_spkg_name = pkg: patch_names: let
+    parts = lib.splitString "-" pkg.name;
+    # remove python2.7-
+    stripped_parts = if (builtins.head parts) == python2.libPrefix then builtins.tail parts else parts;
+    version = lib.last stripped_parts;
+    orig_pkgname = lib.init stripped_parts;
+    pkgname = patch_names (lib.concatStringsSep "_" orig_pkgname);
+  in pkgname + "-" + version;
+
+
+  # return the names of all dependencies in the transitive closure
+  transitiveClosure = dep:
+  if isNull dep then
+    # propagatedBuildInputs might contain null
+    # (although that might be considered a programming error in the derivation)
+    []
+  else
+    [ dep ] ++ (
+      if builtins.hasAttr "propagatedBuildInputs" dep then
+        lib.unique (builtins.concatLists (map transitiveClosure dep.propagatedBuildInputs))
+      else
+      []
+    );
+
+  allInputs = lib.remove null (buildInputs ++ pythonEnv.extraLibs);
+  transitiveDeps = lib.unique (builtins.concatLists (map transitiveClosure allInputs ));
+  # fix differences between spkg and sage names
+  # (could patch sage instead, but this is more lightweight and also works for packages depending on sage)
+  patch_names = builtins.replaceStrings [
+    "zope.interface"
+    "node_three"
+  ] [
+    "zope_interface"
+    "threejs"
+  ];
+  # spkg names (this_is_a_package-version) of all transitive deps
+  input_names = map (dep: pkg_to_spkg_name dep patch_names) transitiveDeps;
+in
+stdenv.mkDerivation rec {
+  version = src.version;
+  name = "sage-with-env-${version}";
+  src = sage-env.lib.src;
+
+  inherit buildInputs;
+
+  configurePhase = "#do nothing";
+
+  buildPhase = ''
+    mkdir installed
+    for pkg in ${lib.concatStringsSep " " input_names}; do
+      touch "installed/$pkg"
+    done
+  '';
+
+  installPhase = ''
+    mkdir -p "$out/var/lib/sage"
+    cp -r installed "$out/var/lib/sage"
+
+    mkdir -p "$out/etc"
+    # sage tests will try to create this file if it doesn't exist
+    touch "$out/etc/sage-started.txt"
+
+    mkdir -p "$out/build"
+
+    # the scripts in src/bin will find the actual sage source files using environment variables set in `sage-env`
+    cp -r src/bin "$out/bin"
+    cp -r build/bin "$out/build/bin"
+
+    cp -f '${sage-env}/sage-env' "$out/bin/sage-env"
+    substituteInPlace "$out/bin/sage-env" \
+      --subst-var-by sage-local "$out"
+  '';
+
+  passthru = {
+    env = sage-env;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/sage.nix b/nixpkgs/pkgs/applications/science/math/sage/sage.nix
new file mode 100644
index 000000000000..ac255643a348
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage.nix
@@ -0,0 +1,67 @@
+{ stdenv
+, makeWrapper
+, sage-tests
+, sage-with-env
+, jupyter-kernel-definition
+, jupyter-kernel
+, sagedoc
+, withDoc
+}:
+
+# A wrapper that makes sure sage finds its docs (if they were build) and the
+# jupyter kernel spec.
+
+let 
+  # generate kernel spec + default kernels
+  kernel-specs = jupyter-kernel.create {
+    definitions = jupyter-kernel.default // {
+      sagemath = jupyter-kernel-definition;
+    };
+  };
+in
+stdenv.mkDerivation rec {
+  version = src.version;
+  name = "sage-${version}";
+  src = sage-with-env.env.lib.src;
+
+  buildInputs = [
+    makeWrapper
+
+    # This is a hack to make sure sage-tests is evaluated. It doesn't acutally
+    # produce anything of value, it just decouples the tests from the build.
+    sage-tests
+  ];
+
+  unpackPhase = "#do nothing";
+  configurePhase = "#do nothing";
+  buildPhase = "#do nothing";
+
+  installPhase = ''
+    mkdir -p "$out/bin"
+    makeWrapper "${sage-with-env}/bin/sage" "$out/bin/sage" \
+      --set SAGE_DOC_SRC_OVERRIDE "${src}/src/doc" ${
+        stdenv.lib.optionalString withDoc "--set SAGE_DOC_OVERRIDE ${sagedoc}/share/doc/sage"
+      } \
+      --prefix JUPYTER_PATH : "${kernel-specs}"
+  '';
+
+  doInstallCheck = withDoc;
+  installCheckPhase = ''
+    export HOME="$TMPDIR/sage-home"
+    mkdir -p "$HOME"
+    "$out/bin/sage" -c 'browse_sage_doc._open("reference", testing=True)'
+  '';
+
+  passthru = {
+    tests = sage-tests;
+    doc = sagedoc;
+    lib = sage-with-env.env.lib;
+    kernelspec = jupyter-kernel-definition;
+  };
+
+  meta = with stdenv.lib; {
+    description = "Open Source Mathematics Software, free alternative to Magma, Maple, Mathematica, and Matlab";
+    license = licenses.gpl2;
+    maintainers = with maintainers; [ timokau ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/sagedoc.nix b/nixpkgs/pkgs/applications/science/math/sage/sagedoc.nix
new file mode 100644
index 000000000000..cc1a4fc61e0c
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sagedoc.nix
@@ -0,0 +1,81 @@
+{ stdenv
+, sage-with-env
+, python
+, maxima-ecl
+, tachyon
+, jmol
+, cddlib
+}:
+
+stdenv.mkDerivation rec {
+  version = src.version;
+  name = "sagedoc-${version}";
+  src = sage-with-env.env.lib.src;
+
+
+  # Building the documentation has many dependencies, because all documented
+  # modules are imported and because matplotlib is used to produce plots.
+  buildInputs = [
+    sage-with-env.env.lib
+    python
+    maxima-ecl
+    tachyon
+    jmol
+    cddlib
+  ] ++ (with python.pkgs; [
+    psutil
+    future
+    sphinx
+    sagenb
+    scipy
+    sympy
+    matplotlib
+    pillow
+    networkx
+    ipykernel
+    ipywidgets
+    jupyter_client
+    typing
+    pybrial
+  ]);
+
+  unpackPhase = ''
+    export SAGE_DOC_OVERRIDE="$PWD/share/doc/sage"
+    export SAGE_DOC_SRC_OVERRIDE="$PWD/docsrc"
+
+    cp -r "${src}/src/doc" "$SAGE_DOC_SRC_OVERRIDE"
+    chmod -R 755 "$SAGE_DOC_SRC_OVERRIDE"
+  '';
+
+  buildPhase = ''
+    export SAGE_NUM_THREADS="$NIX_BUILD_CORES"
+    export HOME="$TMPDIR/sage_home"
+    mkdir -p "$HOME"
+
+    ${sage-with-env}/bin/sage -python -m sage_setup.docbuild \
+      --mathjax \
+      --no-pdf-links \
+      all html
+  '';
+
+  installPhase = ''
+    cd "$SAGE_DOC_OVERRIDE"
+
+    mkdir -p "$out/share/doc/sage"
+    cp -r html "$out"/share/doc/sage
+
+    # Replace duplicated files by symlinks (Gentoo)
+    cd "$out"/share/doc/sage
+    mv html/en/_static{,.tmp}
+    for _dir in `find -name _static` ; do
+          rm -r $_dir
+          ln -s /share/doc/sage/html/en/_static $_dir
+    done
+    mv html/en/_static{.tmp,}
+  '';
+
+  doCheck = true;
+  checkPhase = ''
+    ${sage-with-env}/bin/sage -t --optional=dochtml --all
+  '';
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/sagelib.nix b/nixpkgs/pkgs/applications/science/math/sage/sagelib.nix
new file mode 100644
index 000000000000..03b1ecd2c0b7
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sagelib.nix
@@ -0,0 +1,140 @@
+{ sage-src
+, perl
+, buildPythonPackage
+, arb
+, openblasCompat
+, brial
+, cliquer
+, cypari2
+, cysignals
+, cython
+, ecl
+, eclib
+, ecm
+, flint
+, gd
+, givaro
+, glpk
+, gsl
+, iml
+, jinja2
+, lcalc
+, lrcalc
+, libgap
+, linbox
+, m4ri
+, m4rie
+, libmpc
+, mpfi
+, ntl
+, numpy
+, pari
+, pkgconfig
+, planarity
+, ppl
+, pynac
+, python
+, ratpoints
+, readline
+, rankwidth
+, symmetrica
+, zn_poly
+, fflas-ffpack
+, boost
+, singular
+, pip
+, jupyter_core
+, libhomfly
+, libbraiding
+}:
+
+# This is the core sage python package. Everything else is just wrappers gluing
+# stuff together. It is not very useful on its own though, since it will not
+# find many of its dependencies without `sage-env`, will not be tested without
+# `sage-tests` and will not have html docs without `sagedoc`.
+
+buildPythonPackage rec {
+  format = "other";
+  version = src.version;
+  name = "sagelib-${version}";
+  src = sage-src;
+
+  nativeBuildInputs = [
+    iml
+    perl
+    jupyter_core
+  ];
+
+  buildInputs = [
+    gd
+    readline
+  ];
+
+  propagatedBuildInputs = [
+    cypari2
+    jinja2
+    numpy
+    pkgconfig
+    boost
+    arb
+    brial
+    cliquer
+    ecl
+    eclib
+    ecm
+    fflas-ffpack
+    flint
+    givaro
+    glpk
+    gsl
+    lcalc
+    libgap
+    libmpc
+    linbox
+    lrcalc
+    m4ri
+    m4rie
+    mpfi
+    ntl
+    openblasCompat
+    pari
+    planarity
+    ppl
+    pynac
+    rankwidth
+    ratpoints
+    singular
+    symmetrica
+    zn_poly
+    pip
+    cython
+    cysignals
+    libhomfly
+    libbraiding
+  ];
+
+  buildPhase = ''
+    export SAGE_ROOT="$PWD"
+    export SAGE_LOCAL="$SAGE_ROOT"
+    export SAGE_SHARE="$SAGE_LOCAL/share"
+    export JUPYTER_PATH="$SAGE_LOCAL/jupyter"
+
+    export PATH="$SAGE_ROOT/build/bin:$SAGE_ROOT/src/bin:$PATH"
+
+    export SAGE_NUM_THREADS="$NIX_BUILD_CORES"
+
+    mkdir -p "$SAGE_SHARE/sage/ext/notebook-ipython"
+    mkdir -p "var/lib/sage/installed"
+
+    cd src
+    source bin/sage-dist-helpers
+
+    ${python.interpreter} -u setup.py --no-user-cfg build
+  '';
+
+  installPhase = ''
+    ${python.interpreter} -u setup.py --no-user-cfg install --prefix=$out
+
+    rm -r "$out/${python.sitePackages}/sage/cython_debug"
+  '';
+}
diff --git a/nixpkgs/pkgs/applications/science/math/sage/sagenb.nix b/nixpkgs/pkgs/applications/science/math/sage/sagenb.nix
new file mode 100644
index 000000000000..bbd403177f32
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sagenb.nix
@@ -0,0 +1,61 @@
+{ stdenv
+, fetchpatch
+, python
+, buildPythonPackage
+, fetchFromGitHub
+, mathjax
+, twisted
+, flask
+, flask-oldsessions
+, flask-openid
+, flask-autoindex
+, flask-babel
+}:
+
+# Has a cyclic dependency with sage (not expressed here) and is not useful outside of sage.
+# Deprecated, hopefully soon to be removed. See
+# https://trac.sagemath.org/ticket/25837
+
+buildPythonPackage rec {
+  pname = "sagenb";
+  version = "2018-06-26"; # not 1.0.1 because of new flask syntax
+
+  src = fetchFromGitHub {
+    owner = "sagemath";
+    repo = "sagenb";
+    rev = "b360a0172e15501fb0163d02dce713a561fee2af";
+    sha256 = "12anydw0v9w23rbc0a94bqmjhjdir9h820c5zdhipw9ccdcc2jlf";
+  };
+
+  propagatedBuildInputs = [
+    twisted
+    flask
+    flask-oldsessions
+    flask-openid
+    flask-autoindex
+    flask-babel
+  ];
+
+  # tests depend on sage
+  doCheck = false;
+
+  patches = [
+    # work with latest flask-babel
+    (fetchpatch {
+      url = "https://github.com/sagemath/sagenb/commit/ba065eca63dd34a383e4c7ba7561430a90fcd087.patch";
+      sha256 = "1lamzsrgymdd618imrasjp6ivhw2aynh83gkybsd7pm1rzjcq4x8";
+    })
+  ];
+
+  meta = with stdenv.lib; {
+    description = "Sage Notebook";
+    license = licenses.gpl3Plus;
+    maintainers = with maintainers; [ timokau ];
+  };
+
+  # let sagenb use mathjax
+  postInstall = ''
+    mkdir -p "$out/${python.sitePackages}/sagenb/data"
+    ln -s ${mathjax}/lib/node_modules/mathjax "$out/${python.sitePackages}/sagenb/data/mathjax"
+  '';
+}
diff --git a/nixpkgs/pkgs/applications/science/math/scilab-bin/default.nix b/nixpkgs/pkgs/applications/science/math/scilab-bin/default.nix
new file mode 100644
index 000000000000..c3a74d14bc0a
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/scilab-bin/default.nix
@@ -0,0 +1,106 @@
+{ stdenv, fetchurl, lib, xorg }:
+
+let
+  name = "scilab-bin-${ver}";
+
+  ver = "6.0.1";
+
+  majorVer = builtins.elemAt (lib.splitString "." ver) 0;
+
+  badArch = throw "${name} requires i686-linux or x86_64-linux";
+
+  architecture =
+    if stdenv.hostPlatform.system == "i686-linux" then
+      "i686"
+    else if stdenv.hostPlatform.system == "x86_64-linux" then
+      "x86_64"
+    else
+      badArch;
+in
+stdenv.mkDerivation rec {
+  inherit name;
+
+  src = fetchurl {
+    url = "https://www.scilab.org/download/${ver}/scilab-${ver}.bin.linux-${architecture}.tar.gz";
+    sha256 =
+      if stdenv.hostPlatform.system == "i686-linux" then
+        "0fgjc2ak3b2qi6yin3fy50qwk2bcj0zbz1h4lyyic9n1n1qcliib"
+      else if stdenv.hostPlatform.system == "x86_64-linux" then
+        "1scswlznc14vyzg0gqa1q9gcpwx05kz1sbn563463mzkdp7nd35d"
+      else
+        badArch;
+  };
+
+  libPath = lib.makeLibraryPath [
+    stdenv.cc.cc
+    xorg.libX11
+    xorg.libXext
+    xorg.libXi
+    xorg.libXrender
+    xorg.libXtst
+    xorg.libXxf86vm
+  ];
+
+  phases = [ "unpackPhase" "fixupPhase" "installPhase" ];
+
+  fixupPhase = ''
+    sed -i 's|\$(/bin/|$(|g' bin/scilab
+    sed -i 's|/usr/bin/||g' bin/scilab
+
+    sci="$out/opt/scilab-${ver}"
+    fullLibPath="$sci/lib/scilab:$sci/lib/thirdparty:$libPath"
+    fullLibPath="$fullLibPath:$sci/lib/thirdparty/redist"
+
+    patchelf --set-interpreter $(cat $NIX_CC/nix-support/dynamic-linker) \
+             --set-rpath "$fullLibPath" bin/scilab-bin
+    find . -name '*.so' -type f | while read file; do
+      patchelf --set-rpath "$fullLibPath" "$file" 2>/dev/null
+    done
+  '';
+
+  installPhase = ''
+    mkdir -p "$out/opt/scilab-${ver}"
+    cp -r . "$out/opt/scilab-${ver}/"
+
+    # Create bin/ dir
+    mkdir "$out/bin"
+
+    # Creating executable symlinks
+    ln -s "$out/opt/scilab-${ver}/bin/scilab" "$out/bin/scilab"
+    ln -s "$out/opt/scilab-${ver}/bin/scilab-cli" "$out/bin/scilab-cli"
+    ln -s "$out/opt/scilab-${ver}/bin/scilab-adv-cli" "$out/bin/scilab-adv-cli"
+
+    # Creating desktop config dir
+    mkdir -p "$out/share/applications"
+
+    # Moving desktop config files
+    mv $out/opt/scilab-${ver}/share/applications/*.desktop $out/share/applications
+
+    # Fixing Exec paths and launching each app with a terminal
+    sed -i -e "s|Exec=|Exec=$out/opt/scilab-${ver}/bin/|g" \
+           -e "s|Terminal=.*$|Terminal=true|g" $out/share/applications/*.desktop
+
+    # Moving icons to the appropriate locations
+    for path in $out/opt/scilab-${ver}/share/icons/hicolor/*/*/*
+    do
+      newpath=$(echo $path | sed 's|/opt/scilab-${ver}||g')
+      filename=$(echo $path | sed 's|.*/||g')
+      dir=$(echo $newpath | sed "s|$filename||g")
+      mkdir -p $dir
+      mv $path $newpath
+    done
+
+    # Removing emptied folders
+    rm -rf $out/opt/scilab-${ver}/share/{applications,icons}
+
+    # Moving other share/ folders
+    mv $out/opt/scilab-${ver}/share/{appdata,locale,mime} $out/share
+  '';
+
+  meta = {
+    homepage = http://www.scilab.org/;
+    description = "Scientific software package for numerical computations (Matlab lookalike)";
+    # see http://www.scilab.org/legal_notice
+    license = "Scilab";
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/scilab/default.nix b/nixpkgs/pkgs/applications/science/math/scilab/default.nix
new file mode 100644
index 000000000000..96b7dec19c21
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/scilab/default.nix
@@ -0,0 +1,66 @@
+{stdenv, fetchurl, lib, gfortran
+, ncurses
+, withXaw3d ? false
+#, withPVMlib ? false
+, tcl, tk, withTk ? false
+, gtk2, withGtk ? false # working ?
+#, withF2c ? false
+, ocaml, withOCaml ? false
+#, withJava ? false
+#, atlasMath, withAtlas ? false
+, xlibsWrapper, withX ? false
+}:
+
+stdenv.mkDerivation rec {
+  version = "4.1.2";
+  name = "scilab-${version}";
+  src = fetchurl {
+    url = "https://www.scilab.org/download/${version}/${name}-src.tar.gz";
+    sha256 = "1adk6jqlj7i3gjklvlf1j3il1nb22axnp4rvwl314an62siih0sc";
+  };
+
+  buildInputs = [gfortran ncurses]
+  ++ lib.optionals withGtk [gtk2]
+  ++ lib.optionals withOCaml [ocaml]
+  ++ lib.optional withX xlibsWrapper
+  ;
+
+
+/*
+  --with-atlas-library=DIR  Atlas library files are in DIR and we use Atlas
+*/
+  configureFlags = [
+    # use gcc C compiler and gnu Fortran compiler (g77 or gfortran)
+    "--with-gcc" "--with-g77"
+    # do not compile with PVM library
+    "--without-pvm"
+    # compile with GTK
+    (stdenv.lib.enableFeature withGtk "gtk")
+    (stdenv.lib.enableFeature withGtk "gtk2")
+    # compile with ocaml
+    (stdenv.lib.withFeature withOCaml "ocaml")
+    # do not compile Java interface
+    "--without-java"
+    # use the X Window System
+    (stdenv.lib.withFeature withX "x")
+    # compile with TCL/TK
+  ] ++ lib.optionals withTk [
+    "--with-tk"
+    "--with-tcl-library=${tcl}/lib"
+    "--with-tcl-include=${tcl}/include"
+    "--with-tk-library=${tk}/lib"
+    "--with-tk-include=${tk}/include"
+  ]    # use Xaw3d widgets given with Scilab
+    ++ lib.optional (!withXaw3d) "--with-local-xaw"
+  ;
+
+  makeFlags = "all";
+
+  meta = {
+    homepage = http://www.scilab.org/;
+    description = "Scientific software package for numerical computations (Matlab lookalike)";
+    # see http://www.scilab.org/legal
+    license = "SciLab";
+    broken = true;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/scotch/default.nix b/nixpkgs/pkgs/applications/science/math/scotch/default.nix
new file mode 100644
index 000000000000..8fa020ba07c9
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/scotch/default.nix
@@ -0,0 +1,36 @@
+{ stdenv, fetchurl, bison, openmpi, flex, zlib}:
+
+stdenv.mkDerivation rec {
+  version = "6.0.4";
+  name = "scotch-${version}";
+  src_name = "scotch_${version}";
+
+  buildInputs = [ bison openmpi flex zlib ];
+
+  src = fetchurl {
+    url = "https://gforge.inria.fr/frs/download.php/file/34618/${src_name}.tar.gz";
+    sha256 = "f53f4d71a8345ba15e2dd4e102a35fd83915abf50ea73e1bf6efe1bc2b4220c7";
+  };
+
+  sourceRoot = "${src_name}/src";
+
+  preConfigure = ''
+    ln -s Make.inc/Makefile.inc.x86-64_pc_linux2 Makefile.inc
+  '';
+
+  buildFlags = [ "scotch ptscotch" ];
+  installFlags = [ "prefix=\${out}" ];
+
+  meta = {
+    description = "Graph and mesh/hypergraph partitioning, graph clustering, and sparse matrix ordering";
+    longDescription = ''
+      Scotch is a software package for graph and mesh/hypergraph partitioning, graph clustering, 
+      and sparse matrix ordering.
+    '';
+    homepage = http://www.labri.fr/perso/pelegrin/scotch;
+    license = stdenv.lib.licenses.cecill-c;
+    maintainers = [ stdenv.lib.maintainers.bzizou ];
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
+
diff --git a/nixpkgs/pkgs/applications/science/math/singular/default.nix b/nixpkgs/pkgs/applications/science/math/singular/default.nix
new file mode 100644
index 000000000000..24063216db04
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/singular/default.nix
@@ -0,0 +1,118 @@
+{ stdenv, fetchurl, gmp, bison, perl, ncurses, readline, coreutils, pkgconfig
+, lib
+, fetchpatch
+, autoreconfHook
+, file
+, flint
+, ntl
+, cddlib
+, enableFactory ? true
+, enableGfanlib ? true
+}:
+
+stdenv.mkDerivation rec {
+  name = "singular-${version}";
+  version = "4.1.1p2";
+
+  src = let
+    # singular sorts its tarballs in directories by base release (without patch version)
+    # for example 4.1.1p1 will be in the directory 4-1-1
+    baseVersion = builtins.head (lib.splitString "p" version);
+    urlVersion = builtins.replaceStrings [ "." ] [ "-" ] baseVersion;
+  in
+  fetchurl {
+    url = "http://www.mathematik.uni-kl.de/ftp/pub/Math/Singular/SOURCES/${urlVersion}/singular-${version}.tar.gz";
+    sha256 = "07x9kri8vl4galik7lr6pscq3c51n8570pyw64i7gbj0m706f7wf";
+  };
+
+  configureFlags = [
+    "--with-ntl=${ntl}"
+  ] ++ lib.optionals enableFactory [
+    "--enable-factory"
+  ] ++ lib.optionals enableGfanlib [
+    "--enable-gfanlib"
+  ];
+
+  postUnpack = ''
+    patchShebangs .
+  '';
+
+  patches = [
+    # NTL error handler was introduced in the library part, preventing users of
+    # the library from implementing their own error handling
+    # https://www.singular.uni-kl.de/forum/viewtopic.php?t=2769
+    (fetchpatch {
+      name = "move_error_handler_out_of_libsingular.patch";
+      # rebased version of https://github.com/Singular/Sources/commit/502cf86d0bb2a96715be6764774b64a69c1ca34c.patch
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/singular/patches/singular-ntl-error-handler.patch?h=50b9ae2fd233c30860e1cbb3e63a26f2cc10560a";
+      sha256 = "0vgh4m9zn1kjl0br68n04j4nmn5i1igfn28cph0chnwf7dvr9194";
+    })
+  ];
+
+  # For reference (last checked on commit 75f460d):
+  # https://github.com/Singular/Sources/blob/spielwiese/doc/Building-Singular-from-source.md
+  # https://github.com/Singular/Sources/blob/spielwiese/doc/external-packages-dynamic-modules.md
+  buildInputs = [
+    # necessary
+    gmp
+    # by upstream recommended but optional
+    ncurses
+    readline
+    ntl
+    flint
+  ] ++ lib.optionals enableGfanlib [
+    cddlib
+  ];
+  nativeBuildInputs = [
+    bison
+    perl
+    pkgconfig
+    autoreconfHook
+  ];
+
+  preAutoreconf = ''
+    find . -type f -readable -writable -exec sed \
+      -e 's@/bin/rm@${coreutils}&@g' \
+      -e 's@/bin/uname@${coreutils}&@g' \
+      -e 's@/usr/bin/file@${file}/bin/file@g' \
+      -i '{}' ';'
+  '';
+
+  hardeningDisable = lib.optional stdenv.isi686 "stackprotector";
+
+  # The Makefile actually defaults to `make install` anyway
+  buildPhase = ''
+    # do nothing
+  '';
+
+  installPhase = ''
+    mkdir -p "$out"
+    cp -r Singular/LIB "$out/lib"
+    make install
+
+    # Make sure patchelf picks up the right libraries
+    rm -rf libpolys factory resources omalloc Singular
+  '';
+
+  # simple test to make sure singular starts and finds its libraries
+  doInstallCheck = true;
+  installCheckPhase = ''
+    "$out/bin/Singular" -c 'LIB "freegb.lib"; exit;'
+    if [ $? -ne 0 ]; then
+        echo >&2 "Error loading the freegb library in Singular."
+        exit 1
+    fi
+  '';
+
+  enableParallelBuilding = true;
+
+  meta = with lib; {
+    description = "A CAS for polynomial computations";
+    maintainers = with maintainers; [ raskin timokau ];
+    # 32 bit x86 fails with some link error: `undefined reference to `__divmoddi4@GCC_7.0.0'`
+    platforms = subtractLists platforms.i686 platforms.linux;
+    license = licenses.gpl3; # Or GPLv2 at your option - but not GPLv4
+    homepage = http://www.singular.uni-kl.de;
+    downloadPage = "http://www.mathematik.uni-kl.de/ftp/pub/Math/Singular/SOURCES/";
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/speedcrunch/default.nix b/nixpkgs/pkgs/applications/science/math/speedcrunch/default.nix
new file mode 100644
index 000000000000..d36b135531c2
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/speedcrunch/default.nix
@@ -0,0 +1,37 @@
+{ mkDerivation, lib, fetchgit, cmake, qtbase, qttools }:
+
+mkDerivation rec {
+  name = "speedcrunch-${version}";
+  version = "0.12.0";
+
+  src = fetchgit {
+    # the tagging is not standard, so you probably need to check this when updating
+    rev = "refs/tags/release-${version}";
+    url = "https://bitbucket.org/heldercorreia/speedcrunch";
+    sha256 = "0vh7cd1915bjqzkdp3sk25ngy8cq624mkh8c53c5bnzk357kb0fk";
+  };
+
+  buildInputs = [ qtbase qttools ];
+
+  nativeBuildInputs = [ cmake ];
+
+  preConfigure = ''
+    cd src
+  '';
+
+  meta = with lib; {
+    homepage    = http://speedcrunch.org;
+    license     = licenses.gpl2Plus;
+    description = "A fast power user calculator";
+    longDescription = ''
+      SpeedCrunch is a fast, high precision and powerful desktop calculator.
+      Among its distinctive features are a scrollable display, up to 50 decimal
+      precisions, unlimited variable storage, intelligent automatic completion
+      full keyboard-friendly and more than 15 built-in math function.
+    '';
+    maintainers = with maintainers; [ gebner ];
+    inherit (qtbase.meta) platforms;
+    # works with qt 5.6 and qt 5.8
+    broken = builtins.compareVersions qtbase.version "5.7.0" == 0;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/symmetrica/default.nix b/nixpkgs/pkgs/applications/science/math/symmetrica/default.nix
new file mode 100644
index 000000000000..bc971606cd08
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/symmetrica/default.nix
@@ -0,0 +1,62 @@
+{ stdenv
+, fetchurl
+, fetchpatch
+}:
+stdenv.mkDerivation rec {
+  name = "symmetrica-${version}";
+  version = "2.0";
+
+  src = fetchurl {
+    url = "http://www.algorithm.uni-bayreuth.de/en/research/SYMMETRICA/SYM2_0_tar.gz";
+    sha256 = "1qhfrbd5ybb0sinl9pad64rscr08qvlfzrzmi4p4hk61xn6phlmz";
+    name = "symmetrica-2.0.tar.gz";
+  };
+
+  sourceRoot = ".";
+
+  patches = [
+      # don't show banner ("SYMMETRICA VERSION X - STARTING)
+      # it doesn't contain very much helpful information and a banner is not ideal for a library
+      (fetchpatch {
+        url = "https://git.sagemath.org/sage.git/plain/build/pkgs/symmetrica/patches/de.patch?id=07d6c37d18811e2b377a9689790a7c5e24da16ba";
+        sha256 = "0df0vqixcfpzny6dkhyj87h8aznz3xn3zfwwlj8pd10bpb90k6gb";
+      })
+
+      # use int32_t and uint32_t for type INT
+      # see https://trac.sagemath.org/ticket/13413
+      (fetchpatch {
+        name = "fix_64bit_integer_overflow.patch";
+        url = "https://git.sagemath.org/sage.git/plain/build/pkgs/symmetrica/patches/int32.patch?id=07d6c37d18811e2b377a9689790a7c5e24da16ba";
+        sha256 = "0p33c85ck4kd453z687ni4bdcqr1pqx2756j7aq11bf63vjz4cyz";
+      })
+
+      (fetchpatch {
+        url = "https://git.sagemath.org/sage.git/plain/build/pkgs/symmetrica/patches/return_values.patch?id=1615f58890e8f9881c4228c78a6b39b9aab1303a";
+        sha256 = "0dmczkicwl50sivc07w3wm3jpfk78wm576dr25999jdj2ipsb7nk";
+      })
+  ];
+
+  postPatch = ''
+    substituteInPlace makefile --replace gcc cc
+  '';
+
+  enableParallelBuilding = true;
+
+  installPhase = ''
+    mkdir -p "$out"/{lib,share/doc/symmetrica,include/symmetrica}
+    ar crs libsymmetrica.a *.o
+    ranlib libsymmetrica.a
+    cp libsymmetrica.a "$out/lib"
+    cp *.h "$out/include/symmetrica"
+    cp README *.doc "$out/share/doc/symmetrica"
+  '';
+
+  meta = {
+    inherit version;
+    description = ''A collection of routines for representation theory and combinatorics'';
+    license = stdenv.lib.licenses.publicDomain;
+    maintainers = [stdenv.lib.maintainers.raskin];
+    platforms = stdenv.lib.platforms.unix;
+    homepage = http://www.algorithm.uni-bayreuth.de/en/research/SYMMETRICA/index.html;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/weka/default.nix b/nixpkgs/pkgs/applications/science/math/weka/default.nix
new file mode 100644
index 000000000000..3bfb22dad936
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/weka/default.nix
@@ -0,0 +1,31 @@
+{ stdenv, fetchurl, jre, unzip, makeWrapper }:
+
+stdenv.mkDerivation rec {
+  name = "weka-${version}";
+  version = "3.9.2";
+
+  src = fetchurl {
+    url = "mirror://sourceforge/weka/${stdenv.lib.replaceChars ["."]["-"] name}.zip";
+    sha256 = "0zwmhspmqb0a7cm6k6i0s6q3w19ws1g9dx3cp2v3g3vsif6cdh31";
+  };
+
+  buildInputs = [ unzip makeWrapper ];
+
+  # The -Xmx1000M comes suggested from their download page:
+  # http://www.cs.waikato.ac.nz/ml/weka/downloading.html
+  installPhase = ''
+    mkdir -pv $out/share/weka
+    cp -Rv * $out/share/weka
+
+    makeWrapper ${jre}/bin/java $out/bin/weka \
+      --add-flags "-Xmx1000M -jar $out/share/weka/weka.jar"
+  '';
+
+  meta = {
+    homepage = http://www.cs.waikato.ac.nz/ml/weka/;
+    description = "Collection of machine learning algorithms for data mining tasks";
+    license = stdenv.lib.licenses.gpl2Plus;
+    maintainers = [ stdenv.lib.maintainers.mimadrid ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/wxmaxima/default.nix b/nixpkgs/pkgs/applications/science/math/wxmaxima/default.nix
new file mode 100644
index 000000000000..67cdaa4055ac
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/wxmaxima/default.nix
@@ -0,0 +1,33 @@
+{ stdenv, fetchFromGitHub
+, wrapGAppsHook, cmake, gettext
+, maxima, wxGTK, gnome3 }:
+
+stdenv.mkDerivation rec {
+  name = "wxmaxima-${version}";
+  version = "18.02.0";
+
+  src = fetchFromGitHub {
+    owner = "andrejv";
+    repo = "wxmaxima";
+    rev = "Version-${version}";
+    sha256 = "0s7bdykc77slqix28cyaa6x8wvxrn8461mkdgxflvi2apwsl56aa";
+  };
+
+  buildInputs = [ wxGTK maxima gnome3.defaultIconTheme ];
+
+  nativeBuildInputs = [ wrapGAppsHook cmake gettext ];
+
+  preConfigure = ''
+    gappsWrapperArgs+=(--prefix PATH ":" ${maxima}/bin)
+  '';
+
+  enableParallelBuilding = true;
+
+  meta = with stdenv.lib; {
+    description = "Cross platform GUI for the computer algebra system Maxima";
+    license = licenses.gpl2;
+    homepage = http://wxmaxima.sourceforge.net;
+    platforms = platforms.linux;
+    maintainers = [ maintainers.peti ];
+  };
+}
diff --git a/nixpkgs/pkgs/applications/science/math/yacas/default.nix b/nixpkgs/pkgs/applications/science/math/yacas/default.nix
new file mode 100644
index 000000000000..c02ef73df119
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/yacas/default.nix
@@ -0,0 +1,39 @@
+{ stdenv, fetchFromGitHub, cmake, perl
+, enableGui ? false, qt5
+, enableJupyter ? false, boost, jsoncpp, openssl, zmqpp
+}:
+
+stdenv.mkDerivation rec {
+  name = "yacas-${version}";
+  version = "1.6.1";
+
+  src = fetchFromGitHub {
+    owner = "grzegorzmazur";
+    repo = "yacas";
+    rev = "v${version}";
+    sha256 = "0awvlvf607r4hwl1vkhs6jq2s6ig46c66pmr4vspj2cdnypx99cc";
+  };
+
+  hardeningDisable = [ "format" ];
+
+  cmakeFlags = [
+    "-DENABLE_CYACAS_GUI=${if enableGui then "ON" else "OFF"}"
+    "-DENABLE_CYACAS_KERNEL=${if enableJupyter then "ON" else "OFF"}"
+  ];
+
+  # Perl is only for the documentation
+  nativeBuildInputs = [ cmake perl ];
+  buildInputs = [
+  ] ++ stdenv.lib.optionals enableGui (with qt5; [ qtbase qtwebkit ])
+    ++ stdenv.lib.optionals enableJupyter [ boost jsoncpp openssl zmqpp ]
+    ;
+
+  meta = {
+    description = "Easy to use, general purpose Computer Algebra System";
+    homepage = http://www.yacas.org/;
+    license = stdenv.lib.licenses.gpl2Plus;
+    maintainers = with stdenv.lib.maintainers; [viric];
+    platforms = with stdenv.lib.platforms; linux;
+    broken = enableGui || enableJupyter;
+  };
+}