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.nix115
-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.nix142
-rw-r--r--nixpkgs/pkgs/applications/science/math/caffe/python.patch70
-rw-r--r--nixpkgs/pkgs/applications/science/math/calc/default.nix49
-rw-r--r--nixpkgs/pkgs/applications/science/math/cbc/default.nix30
-rw-r--r--nixpkgs/pkgs/applications/science/math/clp/default.nix22
-rw-r--r--nixpkgs/pkgs/applications/science/math/cntk/default.nix91
-rw-r--r--nixpkgs/pkgs/applications/science/math/colpack/default.nix32
-rw-r--r--nixpkgs/pkgs/applications/science/math/cplex/default.nix87
-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.nix180
-rw-r--r--nixpkgs/pkgs/applications/science/math/geogebra/default.nix63
-rw-r--r--nixpkgs/pkgs/applications/science/math/getdp/default.nix25
-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.nix58
-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/11.nix150
-rw-r--r--nixpkgs/pkgs/applications/science/math/mathematica/9.nix122
-rw-r--r--nixpkgs/pkgs/applications/science/math/mathematica/default.nix150
-rw-r--r--nixpkgs/pkgs/applications/science/math/mathematica/l10ns.nix54
-rw-r--r--nixpkgs/pkgs/applications/science/math/maxima/5.41.nix102
-rw-r--r--nixpkgs/pkgs/applications/science/math/maxima/default.nix104
-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.nix55
-rw-r--r--nixpkgs/pkgs/applications/science/math/nasc/default.nix60
-rw-r--r--nixpkgs/pkgs/applications/science/math/nauty/default.nix43
-rw-r--r--nixpkgs/pkgs/applications/science/math/palp/default.nix86
-rw-r--r--nixpkgs/pkgs/applications/science/math/pari/default.nix94
-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.nix172
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/env-locations.nix49
-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/do-not-test-find-library.patch95
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/fix-ecl-race.patch19
-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/sphinx-docbuild-subprocesses.patch57
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/sympow-cache.patch21
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/patches/threejs-offline.patch64
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/pybrial.nix29
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/python-openid.nix40
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage-env.nix169
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage-src.nix139
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage-tests.nix57
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage-with-env.nix133
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sage.nix68
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sagedoc.nix84
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sagelib.nix152
-rw-r--r--nixpkgs/pkgs/applications/science/math/sage/sagenb.nix52
-rw-r--r--nixpkgs/pkgs/applications/science/math/scilab-bin/default.nix104
-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
91 files changed, 5477 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..a791f9a57727
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/R/default.nix
@@ -0,0 +1,115 @@
+{ 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, fetchpatch
+, withRecommendedPackages ? true
+, enableStrictBarrier ? false
+, javaSupport ? (!stdenv.hostPlatform.isAarch32 && !stdenv.hostPlatform.isAarch64)
+}:
+
+stdenv.mkDerivation rec {
+  name = "R-3.6.1";
+
+  src = fetchurl {
+    url = "https://cran.r-project.org/src/base/R-3/${name}.tar.gz";
+    sha256 = "128kifbq0w25y8aq77w289ddax5i5w2djcfsqgffrb3i7syrxajv";
+  };
+
+  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" ];
+
+  # The store path to "which" is baked into src/library/base/R/unix/system.unix.R,
+  # but Nix cannot detect it as a run-time dependency because the installed file
+  # is compiled and compressed, which hides the store path.
+  postFixup = "echo ${which} > $out/nix-support/undetected-runtime-dependencies";
+
+  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 = with maintainers; [ peti timokau ];
+  };
+}
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..e8171bcb256a
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/caffe/default.nix
@@ -0,0 +1,142 @@
+{ config, stdenv, lib
+, fetchFromGitHub
+, fetchurl
+, cmake
+, boost
+, gflags
+, glog
+, hdf5-cpp
+, opencv3
+, protobuf
+, doxygen
+, openblas
+, Accelerate, CoreGraphics, CoreVideo
+, lmdbSupport ? true, lmdb
+, leveldbSupport ? true, leveldb, snappy
+, cudaSupport ? config.cudaSupport or false, cudatoolkit
+, cudnnSupport ? cudaSupport, cudnn ? null
+, ncclSupport ? false, nccl ? null
+, pythonSupport ? false, python ? null, numpy ? null
+, substituteAll
+}:
+
+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 =
+    # It's important that caffe is passed the major and minor version only because that's what
+    # boost_python expects
+    [ (if pythonSupport then "-Dpython_version=${python.pythonVersion}" 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 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.optionals pythonSupport (
+    # requirements.txt
+    let pp = python.pkgs; in ([
+      pp.numpy pp.scipy pp.scikitimage pp.h5py
+      pp.matplotlib pp.ipython pp.networkx pp.nose
+      pp.pandas pp.dateutil pp.protobuf pp.gflags
+      pp.pyyaml pp.pillow pp.six
+    ] ++ lib.optional leveldbSupport pp.leveldb)
+  );
+
+  outputs = [ "bin" "out" ];
+  propagatedBuildOutputs = []; # otherwise propagates out -> bin cycle
+
+  patches = [
+    ./darwin.patch
+  ] ++ lib.optional pythonSupport (substituteAll {
+    src = ./python.patch;
+    inherit (python.sourceVersion) major minor;  # Should be changed in case of PyPy
+  });
+
+  postPatch = 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
+  '';
+
+  preConfigure = lib.optionalString pythonSupport ''
+    # We need this when building with Python bindings
+    export BOOST_LIBRARYDIR="${boost.out}/lib";
+  '';
+
+  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/caffe/python.patch b/nixpkgs/pkgs/applications/science/math/caffe/python.patch
new file mode 100644
index 000000000000..dac5071aa08c
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/caffe/python.patch
@@ -0,0 +1,70 @@
+commit b14ca23651d390fcae4a929dedc7c33a83453a66
+Author: Frederik Rietdijk <fridh@fridh.nl>
+Date:   Sun Feb 17 08:41:27 2019 +0100
+
+    Find boost_pythonXX
+
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 08f56a33..0a04592a 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -99,10 +99,10 @@ add_subdirectory(docs)
+ add_custom_target(lint COMMAND ${CMAKE_COMMAND} -P ${PROJECT_SOURCE_DIR}/cmake/lint.cmake)
+ 
+ # ---[ pytest target
+-if(BUILD_python)
+-  add_custom_target(pytest COMMAND python${python_version} -m unittest discover -s caffe/test WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/python )
+-  add_dependencies(pytest pycaffe)
+-endif()
++# if(BUILD_python)
++#   add_custom_target(pytest COMMAND python${python_version} -m unittest discover -s caffe/test WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/python )
++#   add_dependencies(pytest pycaffe)
++# endif()
+ 
+ # ---[ uninstall target
+ configure_file(
+diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake
+index 4a5bac47..be026d43 100644
+--- a/cmake/Dependencies.cmake
++++ b/cmake/Dependencies.cmake
+@@ -141,37 +141,14 @@ if(BUILD_python)
+     # use python3
+     find_package(PythonInterp 3.0)
+     find_package(PythonLibs 3.0)
+-    find_package(NumPy 1.7.1)
+-    # Find the matching boost python implementation
+-    set(version ${PYTHONLIBS_VERSION_STRING})
+-
+-    STRING( REGEX REPLACE "[^0-9]" "" boost_py_version ${version} )
+-    find_package(Boost 1.46 COMPONENTS "python-py${boost_py_version}")
+-    set(Boost_PYTHON_FOUND ${Boost_PYTHON-PY${boost_py_version}_FOUND})
+-
+-    while(NOT "${version}" STREQUAL "" AND NOT Boost_PYTHON_FOUND)
+-      STRING( REGEX REPLACE "([0-9.]+).[0-9]+" "\\1" version ${version} )
+-
+-      STRING( REGEX REPLACE "[^0-9]" "" boost_py_version ${version} )
+-      find_package(Boost 1.46 COMPONENTS "python-py${boost_py_version}")
+-      set(Boost_PYTHON_FOUND ${Boost_PYTHON-PY${boost_py_version}_FOUND})
+-
+-      STRING( REGEX MATCHALL "([0-9.]+).[0-9]+" has_more_version ${version} )
+-      if("${has_more_version}" STREQUAL "")
+-        break()
+-      endif()
+-    endwhile()
+-    if(NOT Boost_PYTHON_FOUND)
+-      find_package(Boost 1.46 COMPONENTS python)
+-    endif()
+   else()
+     # disable Python 3 search
+     find_package(PythonInterp 2.7)
+     find_package(PythonLibs 2.7)
+-    find_package(NumPy 1.7.1)
+-    find_package(Boost 1.46 COMPONENTS python)
+   endif()
+-  if(PYTHONLIBS_FOUND AND NUMPY_FOUND AND Boost_PYTHON_FOUND)
++  find_package(NumPy 1.7.1)
++  find_package(Boost 1.46 REQUIRED COMPONENTS python@major@@minor@)
++  if(PYTHONLIBS_FOUND AND NUMPY_FOUND AND Boost_PYTHON@major@@minor@_FOUND)
+     set(HAVE_PYTHON TRUE)
+     if(BUILD_python_layer)
+       list(APPEND Caffe_DEFINITIONS PRIVATE -DWITH_PYTHON_LAYER)
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..d0857e2a517c
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/cbc/default.nix
@@ -0,0 +1,30 @@
+{ lib, stdenv, fetchurl, zlib, bzip2 }:
+
+stdenv.mkDerivation rec {
+  pname = "cbc";
+  version = "2.10.2";
+
+  src = fetchurl {
+    url = "https://www.coin-or.org/download/source/Cbc/Cbc-${version}.tgz";
+    sha256 = "0frbxkh6nbh46kaxsx5bmzridgip3v7aq75l8yak5npiiq4jlwv3";
+  };
+
+  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;
+    broken = stdenv.isAarch64; # Missing <immintrin.h> after 2.10.0
+    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..0beee1eb2915
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/clp/default.nix
@@ -0,0 +1,22 @@
+{ stdenv, fetchurl, zlib }:
+
+stdenv.mkDerivation rec {
+  version = "1.17.2";
+  name = "clp-${version}";
+  src = fetchurl {
+    url = "https://www.coin-or.org/download/source/Clp/Clp-${version}.tgz";
+    sha256 = "1fkmgpn0zaraymi6s3isrrscgjxggcs2yjrx7jfy4hb1jacx71zz";
+  };
+
+  propagatedBuildInputs = [ zlib ];
+
+  doCheck = true;
+
+  meta = with stdenv.lib; {
+    license = licenses.epl10;
+    homepage = "https://github.com/coin-or/Clp";
+    description = "An open-source linear programming solver written in C++";
+    platforms = platforms.darwin ++ [ "x86_64-linux" ];
+    maintainers = [ 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..465c7318c0e3
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/cntk/default.nix
@@ -0,0 +1,91 @@
+{ config, lib, stdenv, fetchgit, fetchFromGitHub, cmake
+, openblas, opencv3, libzip, boost, protobuf, openmpi
+, onebitSGDSupport ? false
+, cudaSupport ? config.cudaSupport or false, cudatoolkit, nvidia_x11
+, cudnnSupport ? cudaSupport, 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.7";
+
+  # Submodules
+  src = fetchgit {
+    url = "https://github.com/Microsoft/CNTK";
+    rev = "v${version}";
+    sha256 = "18l9k7s966a26ywcf7flqyhm61788pcb9fj3wk61jrmgkhy2pcns";
+  };
+
+  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;
+    platforms = [ "x86_64-linux" ];
+    maintainers = with maintainers; [ abbradar ];
+  };
+}
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..a14839d3eccc
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/cplex/default.nix
@@ -0,0 +1,87 @@
+{ stdenv, makeWrapper, openjdk, gtk2, xorg, glibcLocales, releasePath ? null }:
+
+# 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 releasePath == null 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
+  '';
+
+  passthru = {
+    libArch = "x86-64_linux";
+    libSuffix = "${version}0";
+  };
+  
+  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..23ab2184266a
--- /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.1";
+  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.1/form-4.2.1.tar.gz";
+    sha256 = "0a0smc10gm85vxd85942n5azy88w5qs5avbqrw0lw0yb9injswpj";
+  };
+
+  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..7eb10d1f9525
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/gap/default.nix
@@ -0,0 +1,180 @@
+{ stdenv
+, lib
+, fetchurl
+, fetchpatch
+, makeWrapper
+, m4
+, gmp
+# one of
+# - "minimal" (~400M):
+#     Install the bare minimum of packages required by gap to start.
+#     This is likely to break a lot of stuff. Do not expect upstream support with
+#     this configuration.
+# - "standard" (~700M):
+#     Install the "standard packages" which gap autoloads by default. These
+#     packages are effectively considered a part of gap.
+# - "full" (~1.7G):
+#     Install all available packages. This takes a lot of space.
+, packageSet ? "standard"
+# Kept for backwards compatibility. Overrides packageSet to "full".
+, keepAllPackages ? false
+}:
+let
+  # packages absolutely required for gap to start
+  # `*` represents the version where applicable
+  requiredPackages = [
+    "GAPDoc-*"
+    "primgrp-*"
+    "SmallGrp-*"
+    "transgrp"
+  ];
+  # packages autoloaded by default if available
+  autoloadedPackages = [
+    "atlasrep"
+    "autpgrp-*"
+    "alnuth-*"
+    "crisp-*"
+    "ctbllib"
+    "FactInt-*"
+    "fga"
+    "irredsol-*"
+    "laguna-*"
+    "polenta-*"
+    "polycyclic-*"
+    "resclasses-*"
+    "sophus-*"
+    "tomlib-*"
+  ];
+  keepAll = keepAllPackages || (packageSet == "full");
+  packagesToKeep = requiredPackages ++ lib.optionals (packageSet == "standard") autoloadedPackages;
+
+  # Generate bash script that removes all packages from the `pkg` subdirectory
+  # that are not on the whitelist. The whitelist consists of strings expected by
+  # `find`'s `-name`.
+  removeNonWhitelistedPkgs = whitelist: ''
+    find pkg -type d -maxdepth 1 -mindepth 1 \
+  '' + (lib.concatStringsSep "\n" (map (str: "-not -name '${str}' \\") whitelist)) + ''
+    -exec echo "Removing package {}" \; \
+    -exec rm -r '{}' \;
+  '';
+in
+stdenv.mkDerivation rec {
+  pname = "gap";
+  # https://www.gap-system.org/Releases/
+  version = "4.10.2";
+
+  src = fetchurl {
+    url = "https://www.gap-system.org/pub/gap/gap-${lib.versions.major version}.${lib.versions.minor version}/tar.bz2/gap-${version}.tar.bz2";
+    sha256 = "0cp6ddk0469zzv1m1vair6gm27ic6c5m77ri8rn0znq3gaps6x94";
+  };
+
+  # remove all non-essential packages (which take up a lot of space)
+  preConfigure = lib.optionalString (!keepAll) (removeNonWhitelistedPkgs packagesToKeep) + ''
+    patchShebangs .
+  '';
+
+  configureFlags = [ "--with-gmp=system" ];
+
+  buildInputs = [
+    m4
+    gmp
+  ];
+
+  nativeBuildInputs = [
+    makeWrapper
+  ];
+
+  patches = [
+    # https://github.com/gap-system/gap/pull/3294
+    (fetchpatch {
+      name = "add-make-install-targets.patch";
+      url = "https://github.com/gap-system/gap/commit/3361c172e6c5ff3bb3f01ba9d6f1dd4ad42cea80.patch";
+      sha256 = "1kwp9qnfvmlbpf1c3rs6j5m2jz22rj7a4hb5x1gj9vkpiyn5pdyj";
+    })
+  ];
+
+  # "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";
+
+  doInstallCheck = true;
+  installCheckTarget = "testinstall";
+
+  preInstallCheck = ''
+    # gap tests check that the home directory exists
+    export HOME="$TMP/gap-home"
+    mkdir -p "$HOME"
+
+    # make sure gap is in PATH
+    export PATH="$out/bin:$PATH"
+
+    # make sure we don't accidentally use the wrong gap binary
+    rm -r bin
+
+    # like the defaults the Makefile, but use gap from PATH instead of the
+    # one from builddir
+    installCheckFlagsArray+=(
+      "TESTGAP=gap --quitonbreak -b -m 100m -o 1g -q -x 80 -r -A"
+      "TESTGAPauto=gap --quitonbreak -b -m 100m -o 1g -q -x 80 -r"
+    )
+  '';
+
+  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
+  '';
+
+  installTargets = [
+    "install-libgap"
+    "install-headers"
+  ];
+
+  # full `make install` is not yet implemented, just for libgap and headers
+  postInstall = ''
+    # Install config.h, which is not currently handled by `make install-headers`
+    cp gen/config.h "$out/include/gap"
+
+    mkdir -p "$out/bin" "$out/share/gap/"
+
+    mkdir -p "$out/share/gap"
+    echo "Copying files to target directory"
+    cp -ar . "$out/share/gap/build-dir"
+
+    makeWrapper "$out/share/gap/build-dir/bin/gap.sh" "$out/bin/gap" \
+      --set GAP_DIR $out/share/gap/build-dir
+  '';
+
+  preFixup = ''
+    # patchelf won't strip references to the build dir if it still exists
+    rm -rf pkg
+  '';
+
+  meta = with lib; {
+    description = "Computational discrete algebra system";
+    maintainers = with maintainers;
+    [
+      raskin
+      chrisjefferson
+      timokau
+    ];
+    platforms = platforms.all;
+    broken = stdenv.isDarwin;
+    # 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 = 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..3232d08aa339
--- /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-535-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 = "1mbjwa9isw390i0k1yh6r9wmh8zkczian0v25w2vxb2a8vv0hjk0";
+  };
+
+  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/getdp/default.nix b/nixpkgs/pkgs/applications/science/math/getdp/default.nix
new file mode 100644
index 000000000000..74e4b052fdb5
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/getdp/default.nix
@@ -0,0 +1,25 @@
+{ stdenv, fetchurl, cmake, gfortran, openblas, openmpi, python3 }:
+
+stdenv.mkDerivation rec {
+  name = "getdp-${version}";
+  version = "3.0.4";
+  src = fetchurl {
+    url = "http://getdp.info/src/getdp-${version}-source.tgz";
+    sha256 = "0v3hg03lzw4hz28hm45hpv0gyydqz0wav7xvb5n0v0jrm47mrspv";
+  };
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = [ gfortran openblas openmpi python3 ];
+
+  meta = with stdenv.lib; {
+    description = "A General Environment for the Treatment of Discrete Problems";
+    longDescription = ''
+      GetDP is a free finite element solver using mixed elements to discretize de Rham-type complexes in one, two and three dimensions.
+      The main feature of GetDP is the closeness between the input data defining discrete problems (written by the user in ASCII data files) and the symbolic mathematical expressions of these problems.
+    '';
+    homepage = http://getdp.info/;
+    license = stdenv.lib.licenses.gpl2Plus;
+    maintainers = with maintainers; [ wucke13 ];
+    platforms = platforms.linux;
+  };
+}
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..197845bfa3c1
--- /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.6";
+
+  src = fetchurl {
+    url    = "${meta.homepage}/${name}.tar.bz2";
+    sha256 = "03cq93qjfgxgr7zxadrjfbn43lk5f0x2lmd90ggx10p6jq47157v";
+  };
+
+  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..fbdbac003dcd
--- /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.4.1"; in
+
+stdenv.mkDerivation {
+  name = "gmsh-${version}";
+
+  src = fetchurl {
+    url = "http://gmsh.info/src/gmsh-${version}-source.tgz";
+    sha256 = "1p7hibmsgv961lfkzdxlgcvmcb0q155m2sp60r97cjsfzhw68g45";
+  };
+
+  buildInputs = [ 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 = [ cmake 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..ee9bdcc6f1b0
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/gurobi/default.nix
@@ -0,0 +1,58 @@
+{ stdenv, lib, fetchurl, autoPatchelfHook, python }:
+
+let
+  majorVersion = "8.1";
+in stdenv.mkDerivation rec {
+  name = "gurobi-${version}";
+  version = "${majorVersion}.0";
+
+  src = with stdenv.lib; fetchurl {
+    url = "http://packages.gurobi.com/${versions.majorMinor version}/gurobi${version}_linux64.tar.gz";
+    sha256 = "1yjqbzqnq4jjkjm616d36bgd3rmqr0a1ii17n0prpdjzmdlq63dz";
+  };
+
+  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/
+  '';
+
+  passthru.libSuffix = lib.replaceStrings ["."] [""] majorVersion;
+
+  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/11.nix b/nixpkgs/pkgs/applications/science/math/mathematica/11.nix
new file mode 100644
index 000000000000..521cb70099b9
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mathematica/11.nix
@@ -0,0 +1,150 @@
+{ stdenv
+, coreutils
+, patchelf
+, requireFile
+, callPackage
+, alsaLib
+, dbus
+, fontconfig
+, freetype
+, gcc
+, glib
+, ncurses
+, opencv
+, openssl
+, unixODBC
+, xkeyboard_config
+, xorg
+, zlib
+, libxml2
+, libuuid
+, lang ? "en"
+, libGL
+, libGLU
+}:
+
+let
+  l10n =
+    import ./l10ns.nix {
+      lib = stdenv.lib;
+      inherit requireFile lang;
+      majorVersion = "11";
+    };
+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/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..ca9a87abe13b
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mathematica/default.nix
@@ -0,0 +1,150 @@
+{ stdenv
+, coreutils
+, patchelf
+, requireFile
+, callPackage
+, alsaLib
+, dbus
+, fontconfig
+, freetype
+, gcc
+, glib
+, ncurses
+, opencv
+, openssl
+, unixODBC
+, xkeyboard_config
+, xorg
+, zlib
+, libxml2
+, libuuid
+, lang ? "en"
+, libGL
+, libGLU
+}:
+
+let
+  l10n =
+    import ./l10ns.nix {
+      lib = stdenv.lib;
+      inherit requireFile lang;
+    };
+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);
+
+  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
+      sed -i -e "2iexport QT_XKB_CONFIG_ROOT=\"${xkeyboard_config}/share/X11/xkb\"\n" $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
+  '';
+
+  dontBuild = true;
+
+  # all binaries are already stripped
+  dontStrip = true;
+
+  # we did this in prefixup already
+  dontPatchELF = true;
+
+  meta = with stdenv.lib; {
+    description = "Wolfram Mathematica computational software system";
+    homepage = http://www.wolfram.com/mathematica/;
+    license = licenses.unfree;
+    maintainers = with maintainers; [ herberteuler ];
+    platforms = [ "x86_64-linux" ];
+  };
+}
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..51fb489be7ec
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mathematica/l10ns.nix
@@ -0,0 +1,54 @@
+{ lib
+, requireFile
+, lang
+, majorVersion ? null
+}:
+
+let allVersions = with lib; flip map
+  # N.B. Versions in this list should be ordered from newest to oldest.
+  [
+    {
+      version = "12.0.0";
+      lang = "en";
+      language = "English";
+      sha256 = "b9fb71e1afcc1d72c200196ffa434512d208fa2920e207878433f504e58ae9d7";
+    }
+    {
+      version = "11.3.0";
+      lang = "en";
+      language = "English";
+      sha256 = "0fcfe208c1eac8448e7be3af0bdb84370b17bd9c5d066c013928c8ee95aed10e";
+    }
+    {
+      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;
+    };
+  });
+minVersion =
+  with lib;
+  if majorVersion == null
+  then elemAt (builtins.splitVersion (elemAt allVersions 0).version) 0
+  else majorVersion;
+maxVersion = toString (1 + builtins.fromJSON minVersion);
+in
+with lib;
+findFirst (l: (l.lang == lang
+               && l.version >= minVersion
+               && l.version < maxVersion))
+          (throw "Version ${minVersion} in language ${lang} not supported")
+          allVersions
diff --git a/nixpkgs/pkgs/applications/science/math/maxima/5.41.nix b/nixpkgs/pkgs/applications/science/math/maxima/5.41.nix
new file mode 100644
index 000000000000..583391d08dde
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/maxima/5.41.nix
@@ -0,0 +1,102 @@
+{ stdenv, fetchurl, fetchpatch, sbcl, texinfo, perl, python, makeWrapper, rlwrap ? null
+, tk ? null, gnuplot ? null, ecl ? null, ecl-fasl ? false
+}:
+
+let
+  name    = "maxima";
+  # old version temporarily kept for sage, see discussion at
+  # https://github.com/NixOS/nixpkgs/commit/82254747af35f3e0e0d6f78023ded3a81e25331b
+  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/default.nix b/nixpkgs/pkgs/applications/science/math/maxima/default.nix
new file mode 100644
index 000000000000..5843f38a74a8
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/maxima/default.nix
@@ -0,0 +1,104 @@
+{ stdenv, fetchurl, fetchpatch, sbcl, texinfo, perl, python, makeWrapper, rlwrap ? null
+, tk ? null, gnuplot ? null, ecl ? null, ecl-fasl ? false
+}:
+
+let
+  name    = "maxima";
+  version = "5.42.2";
+
+  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 = "0kdncy6137sg3rradirxzj10mkcvafxd892zlclwhr9sa7b12zhn";
+  };
+
+  buildInputs = stdenv.lib.filter (x: x != null) [
+    sbcl ecl texinfo perl python makeWrapper
+    gnuplot   # required in the test suite
+  ];
+
+  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";
+    })
+  ];
+
+  # The test suite is disabled since 5.42.2 because of the following issues:
+  #
+  #   Errors found in /build/maxima-5.42.2/share/linearalgebra/rtest_matrixexp.mac, problems:
+  #   (20 21 22)
+  #   Error found in rtest_arag, problem:
+  #   (error break)
+  #   3 tests failed out of 3,881 total tests.
+  #
+  # These failures don't look serious. It would be nice to fix them, but I
+  # don't know how and probably won't have the time to find out.
+  doCheck = false;    # try to re-enable after next version update
+
+  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..e2e4ba63b07e
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/mxnet/default.nix
@@ -0,0 +1,55 @@
+{ config, stdenv, lib, fetchurl, bash, cmake
+, opencv3, gtest, openblas, liblapack, perl
+, cudaSupport ? config.cudaSupport or false, cudatoolkit, nvidia_x11
+, cudnnSupport ? cudaSupport, cudnn
+}:
+
+assert cudnnSupport -> cudaSupport;
+
+stdenv.mkDerivation rec {
+  name = "mxnet-${version}";
+  version = "1.4.1";
+
+  src = fetchurl {
+    url = "https://github.com/apache/incubator-mxnet/releases/download/${version}/apache-mxnet-src-${version}-incubating.tar.gz";
+    sha256 = "1d0lhlpdaxycjzpwwrpgjd3v2q2ka89v5rr13ddxayy7ld2hxiaj";
+  };
+
+  nativeBuildInputs = [ cmake perl ];
+
+  buildInputs = [ opencv3 gtest openblas liblapack ]
+              ++ lib.optionals cudaSupport [ cudatoolkit nvidia_x11 ]
+              ++ lib.optional cudnnSupport cudnn;
+
+  cmakeFlags =
+    [ "-DUSE_MKL_IF_AVAILABLE=OFF" ]
+    ++ (if cudaSupport then [
+      "-DUSE_OLDCMAKECUDA=ON"  # see https://github.com/apache/incubator-mxnet/issues/10743
+      "-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..c2f8ba1d55ec
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/nasc/default.nix
@@ -0,0 +1,60 @@
+{ stdenv
+, fetchFromGitHub
+, pkgconfig
+, gtk3
+, glib
+, pantheon
+, libsoup
+, gtksourceview
+, libgee
+, cmake
+, libqalculate
+, cln
+, wrapGAppsHook
+}:
+
+stdenv.mkDerivation rec {
+  pname = "nasc";
+  version = "0.5.4";
+
+  src = fetchFromGitHub {
+    owner = "parnold-x";
+    repo = pname;
+    rev = version;
+    sha256 = "036v3dx8yasp19j88lflibqnpfi5d0nk7qkcnr80zn1lvawf4wgn";
+  };
+
+  nativeBuildInputs = [
+    cmake
+    pantheon.vala
+    pkgconfig
+    wrapGAppsHook
+  ];
+
+  buildInputs = [
+    cln
+    libsoup
+    gtk3
+    glib
+    gtksourceview
+    libgee
+    libqalculate
+    pantheon.elementary-icon-theme
+    pantheon.granite
+  ];
+
+  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..226e13c004d7
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/nauty/default.nix
@@ -0,0 +1,43 @@
+{ stdenv
+, lib
+, 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" ];
+  configureFlags = {
+    # Prevent nauty from sniffing some cpu features. While those are very
+    # widely available, it can lead to nasty bugs when they are not available:
+    # https://groups.google.com/forum/#!topic/sage-packaging/Pe4SRDNYlhA
+    "default"        = [ "--disable-clz" "--disable-popcnt" ];
+    "westmere"       = [ "--disable-clz" ];
+    "sandybridge"    = [ "--disable-clz" ];
+    "ivybridge"      = [ "--disable-clz" ];
+  }.${stdenv.hostPlatform.platform.gcc.arch or "default"} or [];
+  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 = with lib; {
+    inherit version;
+    description = ''Programs for computing automorphism groups of graphs and digraphs'';
+    license = licenses.asl20;
+    maintainers = with maintainers; [ raskin timokau ];
+    platforms = 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..72827112c50c
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/pari/default.nix
@@ -0,0 +1,94 @@
+{ stdenv
+, fetchurl
+, fetchpatch
+, gmp
+, readline
+, libX11
+, tex
+, perl
+, withThread ? true, libpthreadstubs
+}:
+
+assert withThread -> libpthreadstubs != null;
+
+stdenv.mkDerivation rec {
+  pname = "pari";
+  version = "2.11.1";
+
+  src = fetchurl {
+    url = "https://pari.math.u-bordeaux.fr/pub/pari/unix/${pname}-${version}.tar.gz";
+    sha256 = "1jfax92jpydjd02fwl30r6b8kfzqqd6sm4yx94gidyz9lqjb7a94";
+  };
+
+  patches = [
+    # Fix a off-by-one bug that can potentially lead to segfaults (accepted upstream)
+    # https://pari.math.u-bordeaux.fr/cgi-bin/bugreport.cgi?bug=2117
+    # https://trac.sagemath.org/ticket/27335
+    (fetchpatch {
+      name = "fix-off-by-one-error.patch";
+      # only relevant parts of https://pari.math.u-bordeaux.fr/cgi-bin/gitweb.cgi?p=pari.git;a=patch;h=aa1ee6e0898d177e6bcf49237d82c804bc410985
+      url = "https://git.sagemath.org/sage.git/plain/build/pkgs/pari/patches/red_montgomery.patch?id=bbea55c96e1f05302b3c7f593cf64492497047c5";
+      sha256 = "0vqkmhgv9splsdswp6zjnkj50z76rc1m6k9iy3cf9dxwqw3h3nr6";
+    })
+  ];
+
+  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 timokau ];
+    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..86bd2e843678
--- /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.11pl2";
+
+  src = fetchurl {
+    url = "https://pari.math.u-bordeaux.fr/pub/pari/GP2C/${name}.tar.gz";
+    sha256 = "0wqsf05wgkqvmmsx7jinvzdqav6rl56sr8haibgs31nzz4x9xz9g";
+  };
+
+  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..75a46bb182ae
--- /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.25";
+  pname = "pynac";
+
+  src = fetchFromGitHub {
+    owner = "pynac";
+    repo = "pynac";
+    rev = "pynac-${version}";
+    sha256 = "0nnifvg6kzx0lq6gz7znind8g30v3d2pjfwgsdiks3vv9kv9nbj3";
+  };
+
+  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..b4d82b9583c4
--- /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 {
+  pname = "qalculate-gtk";
+  version = "3.3.0";
+
+  src = fetchFromGitHub {
+    owner = "qalculate";
+    repo = "qalculate-gtk";
+    rev = "v${version}";
+    sha256 = "1z2d32dcvdd66114j3km58xfk80hc5rd0zrh2fgz1azv8r4cqq1b";
+  };
+
+  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..caf51c3da251
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/default.nix
@@ -0,0 +1,172 @@
+{ 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) 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 env-locations pynac singular;
+        linbox = pkgs.linbox.override { withSage = true; };
+        pkg-config = pkgs.pkgconfig; # not to confuse with pythonPackages.pkgconfig
+      };
+    };
+  };
+
+  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 maxima-ecl;
+    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 ecl singular palp flint pynac pythonEnv maxima-ecl;
+    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 maxima-ecl;
+  };
+
+  # 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 maxima-ecl;
+    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
+
+  arb = pkgs.arb.override { inherit flint; };
+
+  singular = pkgs.singular.override { inherit flint; };
+
+  # https://trac.sagemath.org/ticket/26625
+  maxima-ecl = pkgs.maxima-ecl;
+
+  # *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..bda2d23b9e52
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/env-locations.nix
@@ -0,0 +1,49 @@
+{ writeTextFile
+, pari_data
+, pari
+, singular
+, maxima-ecl
+, conway_polynomials
+, graphs
+, elliptic_curves
+, polytopes_db
+, gap
+, 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 GAP_SO='${gap}/lib/libgap.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}/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/do-not-test-find-library.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/do-not-test-find-library.patch
new file mode 100644
index 000000000000..3f844e1b1ef5
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/do-not-test-find-library.patch
@@ -0,0 +1,95 @@
+diff --git a/src/sage/env.py b/src/sage/env.py
+index 061b94f3f1..67cd091540 100644
+--- a/src/sage/env.py
++++ b/src/sage/env.py
+@@ -189,88 +189,13 @@ var('MAXIMA_FAS')
+ var('SAGE_BANNER', '')
+ var('SAGE_IMPORTALL', 'yes')
+ 
+-
+-def _get_shared_lib_filename(libname, *additional_libnames):
+-    """
+-    Return the full path to a shared library file installed in the standard
+-    location for the system within the ``LIBDIR`` prefix (or
+-    ``$SAGE_LOCAL/lib`` in the case of manual build of Sage).
+-
+-    This can also be passed more than one library name (e.g. for cases where
+-    some library may have multiple names depending on the platform) in which
+-    case the first one found is returned.
+-
+-    This supports most *NIX variants (in which ``lib<libname>.so`` is found
+-    under ``$SAGE_LOCAL/lib``), macOS (same, but with the ``.dylib``
+-    extension), and Cygwin (under ``$SAGE_LOCAL/bin/cyg<libname>.dll``,
+-    or ``$SAGE_LOCAL/bin/cyg<libname>-*.dll`` for versioned DLLs).
+-
+-    For distributions like Debian that use a multiarch layout, we also try the
+-    multiarch lib paths (i.e. ``/usr/lib/<arch>/``).
+-
+-    Returns ``None`` if the file does not exist.
+-
+-    EXAMPLES::
+-
+-        sage: import sys
+-        sage: from fnmatch import fnmatch
+-        sage: from sage.env import _get_shared_lib_filename
+-        sage: lib_filename = _get_shared_lib_filename("Singular",
+-        ....:                                         "singular-Singular")
+-        sage: if sys.platform == 'cygwin':
+-        ....:     pattern = "*/cygSingular-*.dll"
+-        ....: elif sys.platform == 'darwin':
+-        ....:     pattern = "*/libSingular.dylib"
+-        ....: else:
+-        ....:     pattern = "*/lib*Singular.so"
+-        sage: fnmatch(lib_filename, pattern)
+-        True
+-        sage: _get_shared_lib_filename("an_absurd_lib") is None
+-        True
+-    """
+-
+-    for libname in (libname,) + additional_libnames:
+-        if sys.platform == 'cygwin':
+-            bindir = sysconfig.get_config_var('BINDIR')
+-            pats = ['cyg{}.dll'.format(libname), 'cyg{}-*.dll'.format(libname)]
+-            filenames = []
+-            for pat in pats:
+-                filenames += glob.glob(os.path.join(bindir, pat))
+-
+-            # Note: This is not very robust, since if there are multi DLL
+-            # versions for the same library this just selects one more or less
+-            # at arbitrary.  However, practically speaking, on Cygwin, there
+-            # will only ever be one version
+-            if filenames:
+-                return filenames[-1]
+-        else:
+-            if sys.platform == 'darwin':
+-                ext = 'dylib'
+-            else:
+-                ext = 'so'
+-
+-            libdirs = [sysconfig.get_config_var('LIBDIR')]
+-            multilib = sysconfig.get_config_var('MULTILIB')
+-            if multilib:
+-                libdirs.insert(0, os.path.join(libdirs[0], multilib))
+-
+-            for libdir in libdirs:
+-                basename = 'lib{}.{}'.format(libname, ext)
+-                filename = os.path.join(libdir, basename)
+-                if os.path.exists(filename):
+-                    return filename
+-
+-    # Just return None if no files were found
+-    return None
+-
+-
+ # locate singular shared object
+ # On Debian it's libsingular-Singular so try that as well
+-SINGULAR_SO = _get_shared_lib_filename('Singular', 'singular-Singular')
++SINGULAR_SO = '/default'
+ var('SINGULAR_SO', SINGULAR_SO)
+ 
+ # locate libgap shared object
+-GAP_SO= _get_shared_lib_filename('gap','')
++GAP_SO= '/default'
+ var('GAP_SO', GAP_SO)
+ 
+ # post process
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/fix-ecl-race.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/fix-ecl-race.patch
new file mode 100644
index 000000000000..6056416c3a28
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/fix-ecl-race.patch
@@ -0,0 +1,19 @@
+diff --git a/src/sage/doctest/forker.py b/src/sage/doctest/forker.py
+index 02e18e67e7..2ebf6eb35f 100644
+--- a/src/sage/doctest/forker.py
++++ b/src/sage/doctest/forker.py
+@@ -1075,6 +1075,14 @@ class SageDocTestRunner(doctest.DocTestRunner, object):
+             sage: set(ex2.predecessors) == set([ex0,ex1])
+             True
+         """
++
++        # Fix ECL dir race conditions by using a separate dir for each process
++        # (https://trac.sagemath.org/ticket/26968)
++        os.environ['MAXIMA_USERDIR'] = "{}/sage-maxima-{}".format(
++            tempfile.gettempdir(),
++            os.getpid()
++        )
++
+         if isinstance(globs, RecordingDict):
+             globs.start()
+         example.sequence_number = len(self.history)
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/sphinx-docbuild-subprocesses.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/sphinx-docbuild-subprocesses.patch
new file mode 100644
index 000000000000..933344aa5591
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/sphinx-docbuild-subprocesses.patch
@@ -0,0 +1,57 @@
+diff --git a/src/sage_setup/docbuild/__init__.py b/src/sage_setup/docbuild/__init__.py
+index 0f2700168a..60f71357d2 100644
+--- a/src/sage_setup/docbuild/__init__.py
++++ b/src/sage_setup/docbuild/__init__.py
+@@ -86,26 +86,6 @@ def builder_helper(type):
+     """
+     Returns a function which builds the documentation for
+     output type ``type``.
+-
+-    TESTS:
+-
+-    Check that :trac:`25161` has been resolved::
+-
+-        sage: from sage_setup.docbuild import DocBuilder, setup_parser
+-        sage: DocBuilder._options = setup_parser().parse_args([])[0] # builder_helper needs _options to be set
+-
+-        sage: import sage_setup.docbuild.sphinxbuild
+-        sage: def raiseBaseException():
+-        ....:     raise BaseException("abort pool operation")
+-        sage: original_runsphinx, sage_setup.docbuild.sphinxbuild.runsphinx = sage_setup.docbuild.sphinxbuild.runsphinx, raiseBaseException
+-
+-        sage: from sage_setup.docbuild import builder_helper, build_many, build_ref_doc
+-        sage: helper = builder_helper("html")
+-        sage: try:
+-        ....:     build_many(build_ref_doc, [("docname", "en", "html", {})])
+-        ....: except Exception as E:
+-        ....:     "Non-exception during docbuild: abort pool operation" in str(E)
+-        True
+     """
+     def f(self, *args, **kwds):
+         output_dir = self._output_dir(type)
+@@ -127,10 +107,9 @@ def builder_helper(type):
+         logger.debug(build_command)
+ 
+         # Run Sphinx with Sage's special logger
+-        sys.argv = ["sphinx-build"] + build_command.split()
+-        from .sphinxbuild import runsphinx
++        args = "python -um sage_setup.docbuild.sphinxbuild -N".split() + build_command.split()
+         try:
+-            runsphinx()
++            subprocess.check_call(args)
+         except Exception:
+             if ABORT_ON_ERROR:
+                 raise
+diff --git a/src/sage_setup/docbuild/sphinxbuild.py b/src/sage_setup/docbuild/sphinxbuild.py
+index 9a2fba79bc..77c8ed3592 100644
+--- a/src/sage_setup/docbuild/sphinxbuild.py
++++ b/src/sage_setup/docbuild/sphinxbuild.py
+@@ -318,3 +318,8 @@ def runsphinx():
+         sys.stderr = saved_stderr
+         sys.stdout.flush()
+         sys.stderr.flush()
++
++if __name__ == '__main__':
++    import sys
++    sys.argv[0] = "sphinx-build"
++    runsphinx()
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/sympow-cache.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/sympow-cache.patch
new file mode 100644
index 000000000000..20020d610f80
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/sympow-cache.patch
@@ -0,0 +1,21 @@
+diff --git a/src/sage/lfunctions/sympow.py b/src/sage/lfunctions/sympow.py
+index 1640ac4f6a..03578be7b8 100644
+--- a/src/sage/lfunctions/sympow.py
++++ b/src/sage/lfunctions/sympow.py
+@@ -50,6 +50,7 @@ from __future__ import print_function, absolute_import
+ 
+ import os
+ 
++from sage.env import DOT_SAGE
+ from sage.structure.sage_object import SageObject
+ from sage.misc.all import pager, verbose
+ import sage.rings.all
+@@ -76,7 +77,7 @@ class Sympow(SageObject):
+         """
+         Used to call sympow with given args
+         """
+-        cmd = 'sympow %s'%args
++        cmd = 'env SYMPOW_CACHEDIR="%s/sympow///" sympow %s' % (DOT_SAGE, args)
+         v = os.popen(cmd).read().strip()
+         verbose(v, level=2)
+         return v
diff --git a/nixpkgs/pkgs/applications/science/math/sage/patches/threejs-offline.patch b/nixpkgs/pkgs/applications/science/math/sage/patches/threejs-offline.patch
new file mode 100644
index 000000000000..62b2f114bd62
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/patches/threejs-offline.patch
@@ -0,0 +1,64 @@
+diff --git a/build/pkgs/threejs/spkg-src b/build/pkgs/threejs/spkg-src
+index 91780d813c..254b850a24 100755
+--- a/build/pkgs/threejs/spkg-src
++++ b/build/pkgs/threejs/spkg-src
+@@ -20,9 +20,17 @@ URL3="https://raw.githubusercontent.com/mrdoob/three.js/${GIT_VERSION}/LICENSE"
+ echo "Downloading $URL3"
+ curl -OL "$URL3"
+ 
++# Set up directory structure
++
++mkdir build
++mv three.min.js build
++
++mkdir -p examples/js/controls
++mv OrbitControls.js examples/js/controls
++
+ # Package
+-tar czf "$SAGE_ROOT/upstream/threejs-${GIT_VERSION}.tar.gz" 'three.min.js' 'OrbitControls.js' 'LICENSE'
+-rm -rf 'three.min.js' 'OrbitControls.js' 'LICENSE'
++tar czf "$SAGE_ROOT/upstream/threejs-${GIT_VERSION}.tar.gz" build examples 'LICENSE'
++rm -rf 'build' 'examples' 'LICENSE'
+ 
+ # Update package info
+ echo "${GIT_VERSION}" > 'package-version.txt'
+diff --git a/src/sage/repl/rich_output/backend_ipython.py b/src/sage/repl/rich_output/backend_ipython.py
+index 7c27d48a21..8bf4861a35 100644
+--- a/src/sage/repl/rich_output/backend_ipython.py
++++ b/src/sage/repl/rich_output/backend_ipython.py
+@@ -411,10 +411,15 @@ class BackendIPythonCommandline(BackendIPython):
+             sage: backend.threejs_offline_scripts()
+             '...<script ...</script>...'
+         """
+-        from sage.env import SAGE_SHARE
++        from sage.env import THREEJS_DIR
+ 
+-        scripts = [os.path.join(SAGE_SHARE, 'threejs', script)
+-                   for script in ['three.min.js', 'OrbitControls.js']]
++        scripts = [
++            os.path.join(THREEJS_DIR, script)
++            for script in [
++                'build/three.min.js',
++                'examples/js/controls/OrbitControls.js',
++            ]
++        ]
+ 
+         if sys.platform == 'cygwin':
+             import cygwin
+@@ -594,13 +599,13 @@ class BackendIPythonNotebook(BackendIPython):
+             sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
+             sage: backend = BackendIPythonNotebook()
+             sage: backend.threejs_offline_scripts()
+-            '...<script src="/nbextensions/threejs/three.min...<\\/script>...'
++            '...<script src="/nbextensions/threejs/build/three.min...<\\/script>...'
+         """
+         from sage.repl.rich_output import get_display_manager
+         CDN_scripts = get_display_manager().threejs_scripts(online=True)
+         return """
+-<script src="/nbextensions/threejs/three.min.js"></script>
+-<script src="/nbextensions/threejs/OrbitControls.js"></script>
++<script src="/nbextensions/threejs/build/three.min.js"></script>
++<script src="/nbextensions/threejs/examples/js/controls/OrbitControls.js"></script>
+ <script>
+   if ( !window.THREE ) document.write('{}');
+ </script>
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..1bfe02f50df1
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/python-openid.nix
@@ -0,0 +1,40 @@
+{ 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 = [
+    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 django twill ];
+  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..8fd69f62171a
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage-env.nix
@@ -0,0 +1,169 @@
+{ stdenv
+, lib
+, writeTextFile
+, python
+, sagelib
+, env-locations
+, gfortran
+, bash
+, coreutils
+, gnused
+, gnugrep
+, binutils
+, pythonEnv
+, python3
+, pkg-config
+, pari
+, gap
+, 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
+    ecl
+    maxima-ecl
+    singular
+    giac
+    palp
+    # needs to be rWrapper since the default `R` doesn't include R's default libraries
+    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_PREFIX:${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
+        gap
+        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
+        gap
+        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..04a2cde9ba99
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage-src.nix
@@ -0,0 +1,139 @@
+{ stdenv
+, fetchFromGitHub
+, fetchpatch
+, runtimeShell
+}:
+
+# 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.8";
+  pname = "sage-src";
+
+  src = fetchFromGitHub {
+    owner = "sagemath";
+    repo = "sage";
+    rev = version;
+    sha256 = "0jm7zdkz8wfgrmf6620jfr8kgvprrz3qfl8gzx6rl5z5cm734b6x";
+  };
+
+  # 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
+
+    # 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
+
+    # Fixes a potential race condition which can lead to transient doctest failures.
+    ./patches/fix-ecl-race.patch
+
+    # Not necessary since library location is set explicitly
+    # https://trac.sagemath.org/ticket/27660#ticket
+    ./patches/do-not-test-find-library.patch
+
+
+    # https://trac.sagemath.org/ticket/28007
+    ./patches/threejs-offline.patch
+
+    # Parallelize docubuild using subprocesses, fixing an isolation issue. See
+    # https://groups.google.com/forum/#!topic/sage-packaging/YGOm8tkADrE
+    ./patches/sphinx-docbuild-subprocesses.patch
+  ];
+
+  # Since sage unfortunately does not release bugfix releases, packagers must
+  # fix those bugs themselves. This is for critical bugfixes, where "critical"
+  # == "causes (transient) doctest failures / somebody complained".
+  bugfixPatches = [ ];
+
+  # 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, name ? "sage-diff-${base}-${rev}.patch", ...}@args: (
+      fetchpatch ({
+        inherit name;
+        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
+    # Should be fixed with glpk > 4.65.
+    # 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/26932
+    (fetchSageDiff {
+      name = "givaro-4.1.0_fflas-ffpack-2.4.0_linbox-1.6.0.patch";
+      base = "8.8.beta4";
+      rev = "c11d9cfa23ff9f77681a8f12742f68143eed4504";
+      sha256 = "0xzra7mbgqvahk9v45bjwir2mqz73hrhhy314jq5nxrb35ysdxyi";
+    })
+
+    # After updating smypow to (https://trac.sagemath.org/ticket/3360) we can
+    # now set the cache dir to be withing the .sage directory. This is not
+    # strictly necessary, but keeps us from littering in the user's HOME.
+    ./patches/sympow-cache.patch
+  ];
+
+  patches = nixPatches ++ bugfixPatches ++ 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 '#!${runtimeShell}
+    python "$@"' > build/bin/sage-python23
+
+    # Make sure sage can at least be imported without setting any environment
+    # variables. It won't be close to feature complete though.
+    sed -i \
+      "s|var('SAGE_LOCAL',.*|var('SAGE_LOCAL', '$out/src')|" \
+      src/sage/env.py
+
+    # 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..591fa192d563
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage-tests.nix
@@ -0,0 +1,57 @@
+{ stdenv
+, lib
+, sage-with-env
+, makeWrapper
+, files ? null # "null" means run all tests
+, longTests ? true # run tests marked as "long time" (roughly doubles runtime)
+# Run as many tests as possible in approximately n seconds. This will give each
+# file to test a "time budget" and stop tests if it is exceeded. 300 is the
+# upstream default value.
+# https://trac.sagemath.org/ticket/25270 for details.
+, timeLimit ? null
+}:
+
+# 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 "";
+  timeSpecifier = if timeLimit == null then "" else "--short ${toString timeLimit}";
+  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
+  ];
+
+  dontUnpack = true;
+  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"
+
+    echo "Running sage tests with arguments ${timeSpecifier} ${patienceSpecifier} ${testArgs}"
+    "sage" -t --nthreads "$NIX_BUILD_CORES" --optional=sage ${timeSpecifier} ${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..e4b1aeae016a
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage-with-env.nix
@@ -0,0 +1,133 @@
+{ stdenv
+, lib
+, makeWrapper
+, sage-env
+, openblasCompat
+, pkg-config
+, three
+, singular
+, gap
+, 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
+    gap
+    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 dep == null 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
+
+    # threejs version is in format 0.<version>.minor, but sage currently still
+    # relies on installed_packages for the online version of threejs to work
+    # and expects the format r<version>. This is a hotfix for now.
+    # upstream: https://trac.sagemath.org/ticket/26434
+    rm "installed/threejs"*
+    touch "installed/threejs-r${lib.versions.minor three.version}"
+  '';
+
+  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..f6dc21d00184
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sage.nix
@@ -0,0 +1,68 @@
+{ 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
+  ];
+
+  dontUnpack = true;
+  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;
+    quicktest = sage-tests.override { longTests = false; timeLimit = 600; }; # as many tests as possible in ~10m
+    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..91c880673a12
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sagedoc.nix
@@ -0,0 +1,84 @@
+{ 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"
+
+    # needed to link them in the sage docs using intersphinx
+    export PPLPY_DOCS=${python.pkgs.pplpy.doc}/share/doc/pplpy
+
+    ${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..1040d6d4ba15
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sagelib.nix
@@ -0,0 +1,152 @@
+{ sage-src
+, env-locations
+, perl
+, buildPythonPackage
+, arb
+, openblasCompat
+, brial
+, cliquer
+, cypari2
+, cysignals
+, cython
+, ecl
+, eclib
+, ecm
+, flint
+, gd
+, givaro
+, glpk
+, gsl
+, iml
+, jinja2
+, lcalc
+, lrcalc
+, gap
+, linbox
+, m4ri
+, m4rie
+, libmpc
+, mpfi
+, ntl
+, numpy
+, pari
+, pkgconfig
+, pkg-config
+, planarity
+, ppl
+, pynac
+, python
+, ratpoints
+, readline
+, rankwidth
+, symmetrica
+, zn_poly
+, fflas-ffpack
+, boost
+, singular
+, pip
+, jupyter_core
+, libhomfly
+, libbraiding
+, gmpy2
+, pplpy
+}:
+
+# 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
+    pkg-config
+    pip # needed to query installed packages
+  ];
+
+  buildInputs = [
+    gd
+    readline
+    iml
+  ];
+
+  propagatedBuildInputs = [
+    cypari2
+    jinja2
+    numpy
+    pkgconfig
+    boost
+    arb
+    brial
+    cliquer
+    ecl
+    eclib
+    ecm
+    fflas-ffpack
+    flint
+    givaro
+    glpk
+    gsl
+    lcalc
+    gap
+    libmpc
+    linbox
+    lrcalc
+    m4ri
+    m4rie
+    mpfi
+    ntl
+    openblasCompat
+    pari
+    planarity
+    ppl
+    pynac
+    rankwidth
+    ratpoints
+    singular
+    symmetrica
+    zn_poly
+    pip
+    cython
+    cysignals
+    libhomfly
+    libbraiding
+    gmpy2
+    pplpy
+  ];
+
+  buildPhase = ''
+    export SAGE_ROOT="$PWD"
+    export SAGE_LOCAL="$SAGE_ROOT"
+    export SAGE_SHARE="$SAGE_LOCAL/share"
+
+    # set locations of dependencies (needed for nbextensions like threejs)
+    . ${env-locations}/sage-env-locations
+
+    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..03b5b7a3bbf9
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/sage/sagenb.nix
@@ -0,0 +1,52 @@
+{ stdenv
+, 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 = "1.1.2";
+
+  src = fetchFromGitHub {
+    owner = "sagemath";
+    repo = "sagenb";
+    rev = version;
+    sha256 = "0bxvhr03qh2nsjdfc4pyfiqrn9jhp3vf7irsc9gqx0185jlblbxs";
+  };
+
+  propagatedBuildInputs = [
+    twisted
+    flask
+    flask-oldsessions
+    flask-openid
+    flask-autoindex
+    flask-babel
+  ];
+
+  # tests depend on sage
+  doCheck = false;
+
+  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..21ce53e70c51
--- /dev/null
+++ b/nixpkgs/pkgs/applications/science/math/scilab-bin/default.nix
@@ -0,0 +1,104 @@
+{ stdenv, fetchurl, lib, xorg }:
+
+let
+  name = "scilab-bin-${ver}";
+
+  ver = "6.0.2";
+
+  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
+        "05clcdgry90drirl3swbxn5q36fmgknnhs6h5pr7mmrzfr6r818w"
+      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..01fb58403cad
--- /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 ? true
+, gtk2, withGtk ? false # working ?
+#, withF2c ? false
+, ocaml, withOCaml ? true
+#, withJava ? false
+#, atlasMath, withAtlas ? false
+, xlibsWrapper, withX ? true
+}:
+
+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..13ccd70c83f9
--- /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 = "19.03.0";
+
+  src = fetchFromGitHub {
+    owner = "andrejv";
+    repo = "wxmaxima";
+    rev = "Version-${version}";
+    sha256 = "0s7bdykc77slqix28cyaa6x8wvxrn8461mkdgxflvi2apwsl56aa";
+  };
+
+  buildInputs = [ wxGTK maxima gnome3.adwaita-icon-theme ];
+
+  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 = https://wxmaxima-developers.github.io/wxmaxima/;
+    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;
+  };
+}