diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ab7b30092185c..bef8365dcbc51 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,7 +18,7 @@ Julia now has a [package manager](https://github.com/JuliaLang/METADATA.jl). Mos The Julia team uses [GitHub issues](https://github.com/JuliaLang/julia/issues) to track and discuss problems, feature requests, and pull requests. -You can make pull requests for incomplete features to get code review. The convention is to prefix the pull request title with "WIP:" or "RFC:" as appropriate to indicate that the work is incomplete, so that it is not accidentally merged. +You can make pull requests for incomplete features to get code review. The convention is to prefix the pull request title with "WIP:" for Work In Progress, or "RFC:" for Request for Comments when work is completed and ready for merging. This will prevent accidental merging of work that is in progress. Before submitting, make sure that all tests pass by running `make testall`. Add your own tests for the new functionality in `test/`. If your contribution includes changes to Makefiles or external dependencies, make sure you can build Julia from a clean tree using `git clean -fdx` or equivalent (be careful – this command will delete any files lying around that aren't checked into git). Make sure that [Travis](http://www.travis-ci.org) greenlights the pull request with a `Good to merge` message. diff --git a/LICENSE.md b/LICENSE.md index ce6e540a514d3..b1b41431cc9e1 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -51,6 +51,7 @@ External libraries, if used, include their own licenses: - [DOUBLE-CONVERSION](https://code.google.com/p/double-conversion/) - [DSFMT](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/LICENSE.txt) - [OPENLIBM](https://github.com/JuliaLang/openlibm/blob/master/LICENSE.md) +- [FADDEEVA](http://ab-initio.mit.edu/Faddeeva) - [FEMTOLISP](https://github.com/JeffBezanson/femtolisp) - [FFTW](http://fftw.org/doc/License-and-Copyright.html) - [GLPK](http://www.gnu.org/software/glpk) diff --git a/Make.inc b/Make.inc index 9df0550199b28..95f6819445ad5 100644 --- a/Make.inc +++ b/Make.inc @@ -1,13 +1,13 @@ # -*- mode: makefile-gmake -*- +# include twice to pickup user definitions +-include $(JULIAHOME)/Make.user + JULIA_VERSION = $(shell cat $(JULIAHOME)/VERSION) JULIA_COMMIT = $(shell git rev-parse --short=10 HEAD) -USR = $(JULIAHOME)/usr -USRBIN = $(USR)/bin -USRINC = $(USR)/include -LLVMROOT = $(USR) -BUILD = $(USR) +LLVMROOT = $(BUILD) +BUILD = $(JULIAHOME)/usr # List of "private" libraries, e.g. ones that get installed to lib/julia JL_PRIVATE_LIBS = Rmath openlibm julia-release suitesparse_wrapper tk_wrapper gmp_wrapper glpk_wrapper random @@ -24,9 +24,33 @@ JL_PRIVATE_LIBDIR = lib/$(MULTIARCH)/julia JL_LIBDIR = lib/$(MULTIARCH)/ endif -OS = $(shell uname) +# Cross-compile +#HOST = i686-w64-mingw32 + +ifeq ($(HOST),) +CROSS_COMPILE= +else +ifeq ($(HOST),i686-w64-mingw32) +override OS = WINNT +override ARCH = i686 +#override OPENBLAS_DYNAMIC_ARCH = 1 +override CROSS_COMPILE=$(HOST)- +export WINEPATH := $(BUILD)/lib;$(shell $(CROSS_COMPILE)gcc -print-search-dirs | grep programs | sed 's/^programs: =//' | sed 's/:/;/g');$(WINEPATH) +else +$(error "unknown HOST variable set") +endif +endif + +# Figure out OS and architecture +BUILD_OS = $(shell uname) +OS = $(BUILD_OS) ARCH = $(shell uname -m) +# Use 64-bit libraries by default on 64-bit architectures +ifeq ($(ARCH), x86_64) +USE_LIB64 = 1 +endif + USE_MKL = 0 MKLLIB = /path/to/mkl/lib/intel64 @@ -53,9 +77,6 @@ USE_COPY_STACKS = 1 # Compiler specific stuff -FC = gfortran -JFFLAGS = -O2 $(fPIC) - ifeq ($(CC), clang) USEGCC = 0 USECLANG = 1 @@ -76,8 +97,8 @@ endif endif ifeq ($(USEGCC),1) -CC = gcc -CXX = g++ +CC = $(CROSS_COMPILE)gcc +CXX = $(CROSS_COMPILE)g++ JCFLAGS = -std=gnu99 -pipe $(fPIC) -fno-strict-aliasing -D_FILE_OFFSET_BITS=64 JCXXFLAGS = -pipe $(fPIC) -fno-rtti DEBUGFLAGS = -ggdb3 -DDEBUG @@ -88,8 +109,8 @@ endif endif ifeq ($(USECLANG),1) -CC = clang -CXX = clang++ +CC = $(CROSS_COMPILE)clang +CXX = $(CROSS_COMPILE)clang++ JCFLAGS = -pipe $(fPIC) -fno-strict-aliasing -D_FILE_OFFSET_BITS=64 JCXXFLAGS = -pipe $(fPIC) -fno-rtti DEBUGFLAGS = -g -DDEBUG @@ -101,6 +122,14 @@ JCFLAGS += -D_LARGEFILE_SOURCE -D_DARWIN_USE_64_BIT_INODE=1 endif endif +FC = $(CROSS_COMPILE)gfortran +JFFLAGS = -O2 $(fPIC) +CPP = $(CC) -E +AR := $(CROSS_COMPILE)ar +AS := $(CROSS_COMPILE)as +LD := $(CROSS_COMPILE)ld +RANLIB := $(CROSS_COMPILE)ranlib + # if not absolute, then relative to JULIA_HOME JCFLAGS += '-DJL_SYSTEM_IMAGE_PATH="../$(JL_PRIVATE_LIBDIR)/sys.ji"' @@ -149,7 +178,7 @@ endif ifeq ($(USE_SYSTEM_LIBUNWIND), 1) LIBUNWIND=-lunwind-generic -lunwind else -LIBUNWIND=$(USR)/lib/libunwind-generic.a $(USR)/lib/libunwind.a +LIBUNWIND=$(BUILD)/lib/libunwind-generic.a $(BUILD)/lib/libunwind.a endif ifeq ($(USE_SYSTEM_LLVM), 1) @@ -161,19 +190,19 @@ endif ifeq ($(USE_SYSTEM_READLINE), 1) READLINE = -lreadline else -READLINE = $(USR)/lib/libreadline.a +READLINE = $(BUILD)/lib/libreadline.a endif ifneq ($(OS),WINNT) READLINE += -lncurses else -READLINE += $(USR)/lib/libhistory.a +READLINE += $(BUILD)/lib/libhistory.a endif ifeq ($(USE_SYSTEM_PCRE), 1) PCRE_CONFIG = pcre-config else -PCRE_CONFIG = $(USRBIN)/pcre-config +PCRE_CONFIG = $(BUILD)/bin/pcre-config endif ifeq ($(USE_SYSTEM_BLAS), 1) @@ -185,7 +214,7 @@ LIBBLAS = -lblas LIBBLASNAME = libblas endif else -LIBBLAS = -L$(USR)/lib -lopenblas +LIBBLAS = -L$(BUILD)/lib -lopenblas LIBBLASNAME = libopenblas endif @@ -307,7 +336,7 @@ $$(abspath $(1)): @mkdir -p $$@ endef -ifeq ($(OS), WINNT) +ifeq ($(BUILD_OS), WINNT) define mingw_to_dos $(subst /,\\,$(subst $(shell $(2) pwd),$(shell $(2) cmd //C cd),$(abspath $(1)))) endef diff --git a/Makefile b/Makefile index 9908d2a927337..543d5286cae91 100644 --- a/Makefile +++ b/Makefile @@ -9,23 +9,23 @@ DIRS = $(BUILD)/bin $(BUILD)/lib $(BUILD)/$(JL_PRIVATE_LIBDIR) $(BUILD)/share/ju $(foreach dir,$(DIRS),$(eval $(call dir_target,$(dir)))) $(foreach link,extras base test doc examples ui,$(eval $(call symlink_target,$(link),$(BUILD)/share/julia))) -MAKEs = $(MAKE) +QUIET_MAKE = ifeq ($(USE_QUIET), 1) -MAKEs += -s +QUIET_MAKE = -s endif debug release: | $(DIRS) $(BUILD)/share/julia/extras $(BUILD)/share/julia/base $(BUILD)/share/julia/test $(BUILD)/share/julia/doc $(BUILD)/share/julia/examples $(BUILD)/share/julia/ui - @$(MAKEs) julia-$@ + @$(MAKE) $(QUIET_MAKE) julia-$@ @export JL_PRIVATE_LIBDIR=$(JL_PRIVATE_LIBDIR) && \ - $(MAKEs) LD_LIBRARY_PATH=$(BUILD)/lib JULIA_EXECUTABLE=$(JULIA_EXECUTABLE_$@) $(BUILD)/$(JL_PRIVATE_LIBDIR)/sys.ji + $(MAKE) $(QUIET_MAKE) LD_LIBRARY_PATH=$(BUILD)/lib JULIA_EXECUTABLE=$(JULIA_EXECUTABLE_$@) $(BUILD)/$(JL_PRIVATE_LIBDIR)/sys.ji julia-debug julia-release: @-git submodule update - @$(MAKEs) -C deps - @$(MAKEs) -C src lib$@ - @$(MAKEs) -C base - @$(MAKEs) -C extras - @$(MAKEs) -C ui $@ + @$(MAKE) $(QUIET_MAKE) -C deps + @$(MAKE) $(QUIET_MAKE) -C src lib$@ + @$(MAKE) $(QUIET_MAKE) -C base + @$(MAKE) $(QUIET_MAKE) -C extras + @$(MAKE) $(QUIET_MAKE) -C ui $@ @ln -sf $(BUILD)/bin/$@-$(DEFAULT_REPL) julia $(BUILD)/share/julia/helpdb.jl: doc/helpdb.jl | $(BUILD)/share/julia @@ -42,8 +42,8 @@ JL_LIBS = julia-release julia-debug # private libraries, that are installed in $(PREFIX)/lib/julia JL_PRIVATE_LIBS = amd arpack cholmod colamd fftw3 fftw3f fftw3_threads \ fftw3f_threads glpk glpk_wrapper gmp gmp_wrapper grisu \ - history openlibm pcre random readline Rmath spqr \ - suitesparse_wrapper tk_wrapper umfpack z openblas + history Faddeeva_wrapper openlibm pcre random readline \ + Rmath spqr suitesparse_wrapper tk_wrapper umfpack z openblas PREFIX ?= julia-$(JULIA_COMMIT) install: release @@ -70,6 +70,8 @@ ifeq ($(shell uname),MINGW32_NT-6.1) -for dllname in "libgfortran-3" "libquadmath-0" "libgcc_s_dw2-1" "libstdc++-6,pthreadgc2" ; do \ cp /mingw/bin/$${dllname}.dll $(PREFIX)/$(JL_LIBDIR) ; \ done +else + @echo 'Warning: system libraries "libgfortran-3" "libquadmath-0" "libgcc_s_dw2-1" "libstdc++-6,pthreadgc2" not included in install' endif endif @@ -96,6 +98,7 @@ clean: | $(CLEAN_TARGETS) rm -f julia-$${buildtype}-$${repltype}; \ done \ done + @rm -f julia @rm -f *~ *# *.tar.gz @rm -fr $(BUILD)/$(JL_PRIVATE_LIBDIR) @@ -105,13 +108,18 @@ cleanall: clean # @$(MAKE) -C deps clean-uv .PHONY: default debug release julia-debug julia-release \ - test testall test-* clean cleanall + test testall test-* clean cleanall webrepl test: release - @$(MAKEs) -C test default + @$(MAKE) $(QUIET_MAKE) -C test default testall: release - @$(MAKEs) -C test all + @$(MAKE) $(QUIET_MAKE) -C test all test-%: release - @$(MAKEs) -C test $* + @$(MAKE) $(QUIET_MAKE) -C test $* + +webrepl: + make -C deps install-lighttpd + make -C ui/webserver + diff --git a/README.md b/README.md index 1ffc9475e0b18..a47d5f5586268 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ This is the GitHub repository of Julia source code, including instructions for c - **Homepage:** -- **Binaries:** +- **Binaries:** - **Packages:** - **Mailing lists:** - **IRC:** @@ -202,11 +202,6 @@ SuiteSparse is a special case, since it is typically only installed as a static ## Binary Installation Because of the rapid pace of development at this point, we recommend installing the latest Julia from source, but platform-specific tarballs with pre-compiled binaries are also [available for download](https://github.com/JuliaLang/julia/downloads). -To install from source, download the appropriate tarball and untar it somewhere. -For example, if you are on an OS X (Darwin) x86/64 system, do the following: - - wget https://github.com/downloads/JuliaLang/julia/julia-c4865bd18d-Darwin-i386.tar.gz - tar zxvf julia-c4865bd18d-Darwin-i386.tar.gz You can either run the `julia` executable using its full path in the directory created above, or add that directory to your executable path so that you can run the julia program from anywhere (in the current shell session): @@ -219,7 +214,8 @@ Now you should be able to run julia like this: If everything works correctly, you will see a Julia banner and an interactive prompt into which you can enter expressions for evaluation. You can read about [getting started](http://julialang.org/manual/getting-started) in the manual. -An [Arch Linux package](https://aur.archlinux.org/packages.php?ID=56877) is also available. +An [Arch Linux package](https://aur.archlinux.org/packages.php?ID=56877) is also available. Julia has also been added to [Debian](http://packages.debian.org/sid/julia). On OS X, julia is available through [homebrew](http://mxcl.github.com/homebrew/). + ## Editor & Terminal Setup @@ -242,7 +238,7 @@ On Linux systems, the `Shift-Enter` binding can be set by placing the following Julia has a web REPL with very preliminary graphics capabilities. The web REPL is currently a showcase to try out new ideas. The web REPL is social - multiple people signing in with a common session name can collaborate within a session. -1. Do `make -C deps install-lighttpd` to download and build the webserver. +1. Do `make webrepl` to build the julia webserver. 2. Start the web REPL service with `./usr/bin/launch-julia-webserver`. 3. Point your browser to `http://localhost:2000/`. 4. Try `plot(cumsum(randn(1000)))` and other things. diff --git a/base/Makefile b/base/Makefile index 7cb15df71af66..541d36b5f2cfa 100644 --- a/base/Makefile +++ b/base/Makefile @@ -6,7 +6,7 @@ PCRE_CONST = 0x[0-9a-fA-F]+|[-+]?\s*[0-9]+ all: pcre_h.jl errno_h.jl build_h.jl file_constants.jl pcre_h.jl: - $(QUIET_PERL) $(CC) -E -dM $(shell $(PCRE_CONFIG) --prefix)/include/pcre.h | perl -nle '/^\s*#define\s+PCRE_(\w*)\s*\(?($(PCRE_CONST))\)?\s*$$/ and print "const $$1 = int32($$2)"' | sort > $@ + $(QUIET_PERL) $(CPP) -dM $(shell $(PCRE_CONFIG) --prefix)/include/pcre.h | perl -nle '/^\s*#define\s+PCRE_(\w*)\s*\(?($(PCRE_CONST))\)?\s*$$/ and print "const $$1 = uint32($$2)"' | sort > $@ errno_h.jl: $(QUIET_PERL) echo '#include "errno.h"' | $(CC) -E -dM - | perl -nle 'print "const $$1 = int32($$2)" if /^#define\s+(E\w+)\s+(\d+)\s*$$/' | sort > $@ @@ -18,6 +18,12 @@ build_h.jl: ../Make.inc ../src/os_detect.h $(QUIET_PERL) $(CC) -E -P -DJULIA ../src/os_detect.h | grep OS_NAME > $@ @echo "const libblas_name = \"$(LIBBLASNAME)\"" >> $@ @echo "const liblapack_name = \"$(LIBLAPACKNAME)\"" >> $@ +ifeq ($(USE_LIB64), 1) + @echo "const USE_LIB64 = true" >> $@ +else + @echo "const USE_LIB64 = false" >> $@ +endif + clean: rm -f *# *~ diff --git a/base/abstractarray.jl b/base/abstractarray.jl index 734d8140676f8..263fd1594422a 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -5,11 +5,6 @@ typealias AbstractVector{T} AbstractArray{T,1} typealias AbstractMatrix{T} AbstractArray{T,2} -typealias Indices{T<:Integer} Union(Integer, AbstractVector{T}) -typealias Dimspec Union(Int,Dims) - -typealias RangeIndex Union(Int, Range{Int}, Range1{Int}) - ## Basic functions ## size{T,n}(t::AbstractArray{T,n}, d) = (d>n ? 1 : size(t)[d]) @@ -54,7 +49,8 @@ function trailingsize(A, n) end ## Bounds checking ## -function check_bounds(sz::Int, I::Integer) +function check_bounds(sz::Int, I::Real) + I = to_index(I) if I < 1 || I > sz throw(BoundsError()) end @@ -72,34 +68,27 @@ function check_bounds{T<:Integer}(sz::Int, I::Ranges{T}) end end -function check_bounds{T <: Integer}(sz::Int, I::AbstractVector{T}) +function check_bounds{T <: Real}(sz::Int, I::AbstractVector{T}) for i in I + i = to_index(i) if i < 1 || i > sz throw(BoundsError()) end end end -function check_bounds(A::AbstractVector, I::AbstractVector{Bool}) - if !isequal(size(A), size(I)) throw(BoundsError()) end -end - -function check_bounds(A::AbstractArray, I::AbstractVector{Bool}) - if !isequal(size(A), size(I)) throw(BoundsError()) end -end - function check_bounds(A::AbstractArray, I::AbstractArray{Bool}) if !isequal(size(A), size(I)) throw(BoundsError()) end end -check_bounds(A::AbstractVector, I::Indices) = check_bounds(length(A), I) +check_bounds(A::AbstractArray, I) = check_bounds(length(A), I) -function check_bounds(A::AbstractMatrix, I::Indices, J::Indices) +function check_bounds(A::AbstractMatrix, I, J) check_bounds(size(A,1), I) check_bounds(size(A,2), J) end -function check_bounds(A::AbstractArray, I::Indices, J::Indices) +function check_bounds(A::AbstractArray, I, J) check_bounds(size(A,1), I) sz = size(A,2) for i = 3:ndims(A) @@ -108,7 +97,7 @@ function check_bounds(A::AbstractArray, I::Indices, J::Indices) check_bounds(sz, J) end -function check_bounds(A::AbstractArray, I::Indices...) +function check_bounds(A::AbstractArray, I::Union(Real,AbstractArray)...) n = length(I) if n > 0 for dim = 1:(n-1) @@ -454,11 +443,7 @@ end ## Indexing: ref ## -ref(t::AbstractArray, i::Integer) = error("indexing not defined for ", typeof(t)) -ref(t::AbstractArray, i::Real) = ref(t, to_index(i)) -ref(t::AbstractArray, i::Real, j::Real) = ref(t, to_index(i), to_index(j)) -ref(t::AbstractArray, i::Real, j::Real, k::Real) = ref(t, to_index(i), to_index(j), to_index(k)) -ref(t::AbstractArray, r::Real...) = ref(t,map(to_index,r)...) +ref(t::AbstractArray, i::Real) = error("indexing not defined for ", typeof(t)) # index A[:,:,...,i,:,:,...] where "i" is in dimension "d" # TODO: more optimized special cases @@ -508,16 +493,10 @@ end ## Indexing: assign ## # 1-d indexing is assumed defined on subtypes -assign(t::AbstractArray, x, i::Integer) = +assign(t::AbstractArray, x, i::Real) = error("assign not defined for ",typeof(t)) assign(t::AbstractArray, x) = throw(MethodError(assign, (t, x))) -assign(t::AbstractArray, x, i::Real) = assign(t, x, to_index(i)) -assign(t::AbstractArray, x, i::Real, j::Real) = assign(t, x, to_index(i),to_index(j)) -assign(t::AbstractArray, x, i::Real, j::Real, k::Real) = - assign(t, x, to_index(i),to_index(j),to_index(k)) -assign(t::AbstractArray, x, r::Real...) = assign(t, x, map(to_index,r)...) - ## Concatenation ## #TODO: ERROR CHECK @@ -799,7 +778,7 @@ function hvcat{T<:Number}(rows::(Int...), xs::T...) a end -function _jl_hvcat_fill(a, xs) +function hvcat_fill(a, xs) k = 1 nr, nc = size(a) for i=1:nr @@ -824,7 +803,7 @@ function hvcat(rows::(Int...), xs::Number...) for i=2:length(xs) T = promote_type(T,typeof(xs[i])) end - _jl_hvcat_fill(Array(T, nr, nc), xs) + hvcat_fill(Array(T, nr, nc), xs) end ## Reductions and scans ## @@ -1073,12 +1052,40 @@ function ind2sub{T<:Integer}(dims::(Integer,Integer...), ind::AbstractVector{T}) return t end -indices(I::Indices) = I -indices(I::AbstractVector{Bool}) = find(I) -indices(I::(Indices...)) = map(indices, I) +indices(I) = I +indices(I::AbstractArray{Bool,1}) = find(I) +indices(I::Tuple) = map(indices, I) ## iteration utilities ## +# TODO: something sensible should happen when each_col et. al. are used with a +# pure function argument +function each_col!(f::Function, a::AbstractMatrix) + m = size(a,1) + for i = 1:m:numel(a) + f(sub(a, i:(i+m-1))) + end + return a +end + +function each_row!(f::Function, a::AbstractMatrix) + m = size(a,1) + for i = 1:m + f(sub(a, i:m:numel(a))) + end + return a +end + +function each_vec!(f::Function, a::AbstractMatrix, dim::Integer) + if dim == 1; return each_col!(f,a); end + if dim == 2; return each_row!(f,a); end + error("invalid matrix dimensions: ", dim) +end + +each_col(f::Function, a::AbstractMatrix) = each_col!(f,copy(a)) +each_row(f::Function, a::AbstractMatrix) = each_row!(f,copy(a)) +each_vec(f::Function, a::AbstractMatrix, d::Integer) = each_vec!(f,copy(a),d) + # slow, but useful function cartesian_map(body, t::(Int...), it...) idx = length(t)-length(it) @@ -1198,3 +1205,4 @@ end bsxfun(f, a, b) = f(a, b) bsxfun(f, a::AbstractArray, b) = f(a, b) bsxfun(f, a, b::AbstractArray) = f(a, b) +bsxfun(f, a, b, c...) = bsxfun(f, bsxfun(f, a, b), c...) diff --git a/base/array.jl b/base/array.jl index c49c4a5a1101b..c07c38f842a70 100644 --- a/base/array.jl +++ b/base/array.jl @@ -15,6 +15,7 @@ size(a::Array) = arraysize(a) size(a::Array, d) = arraysize(a, d) size(a::Matrix) = (arraysize(a,1), arraysize(a,2)) length(a::Array) = arraylen(a) +sizeof(a::Array) = sizeof(eltype(a)) * numel(a) function stride(a::Array, i::Integer) s = 1 @@ -240,19 +241,19 @@ convert{T,n,S}(::Type{Array{T,n}}, x::Array{S,n}) = copy_to(similar(x,T), x) ref(a::Array) = arrayref(a,1) -ref(A::Array, i0::Integer) = arrayref(A,int(i0)) -ref(A::Array, i0::Integer, i1::Integer) = arrayref(A,int(i0),int(i1)) -ref(A::Array, i0::Integer, i1::Integer, i2::Integer) = - arrayref(A,int(i0),int(i1),int(i2)) -ref(A::Array, i0::Integer, i1::Integer, i2::Integer, i3::Integer) = - arrayref(A,int(i0),int(i1),int(i2),int(i3)) -ref(A::Array, i0::Integer, i1::Integer, i2::Integer, i3::Integer, i4::Integer) = - arrayref(A,int(i0),int(i1),int(i2),int(i3),int(i4)) -ref(A::Array, i0::Integer, i1::Integer, i2::Integer, i3::Integer, i4::Integer, i5::Integer) = - arrayref(A,int(i0),int(i1),int(i2),int(i3),int(i4),int(i5)) +ref(A::Array, i0::Real) = arrayref(A,to_index(i0)) +ref(A::Array, i0::Real, i1::Real) = arrayref(A,to_index(i0),to_index(i1)) +ref(A::Array, i0::Real, i1::Real, i2::Real) = + arrayref(A,to_index(i0),to_index(i1),to_index(i2)) +ref(A::Array, i0::Real, i1::Real, i2::Real, i3::Real) = + arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3)) +ref(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real) = + arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4)) +ref(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real) = + arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4),to_index(i5)) -ref(A::Array, i0::Integer, i1::Integer, i2::Integer, i3::Integer, i4::Integer, i5::Integer, I::Int...) = - arrayref(A,int(i0),int(i1),int(i2),int(i3),int(i4),int(i5),I...) +ref(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real, I::Int...) = + arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4),to_index(i5),I...) # Fast copy using copy_to for Range1 function ref(A::Array, I::Range1{Int}) @@ -262,12 +263,13 @@ function ref(A::Array, I::Range1{Int}) end # note: this is also useful for Ranges -function ref{T<:Integer}(A::AbstractArray, I::AbstractVector{T}) - return [ A[i] for i in I ] +function ref{T<:Real}(A::AbstractArray, I::AbstractVector{T}) + return [ A[i] for i in indices(I) ] end # 2d indexing -function ref(A::Array, I::Range1{Int}, j::Int) +function ref(A::Array, I::Range1{Int}, j::Real) + j = to_index(j) check_bounds(A, I, j) X = similar(A,length(I)) copy_to_unsafe(X, 1, A, (j-1)*size(A,1) + first(I), length(I)) @@ -298,13 +300,14 @@ function ref(A::Array, I::Range1{Int}, J::AbstractVector{Int}) return X end -ref{T<:Integer}(A::Array, I::AbstractVector{T}, j::Integer) = [ A[i,j] for i=I ] -ref{T<:Integer}(A::Array, I::Integer, J::AbstractVector{T}) = [ A[i,j] for i=I,j=J ] +ref{T<:Real}(A::Array, I::AbstractVector{T}, j::Real) = [ A[i,j] for i=indices(I) ] +ref{T<:Real}(A::Array, I::Real, J::AbstractVector{T}) = [ A[i,j] for i=I,j=indices(J) ] # This next is a 2d specialization of the algorithm used for general # multidimensional indexing -function ref{T<:Integer}(A::Array, I::AbstractVector{T}, J::AbstractVector{T}) +function ref{T<:Real}(A::Array, I::AbstractVector{T}, J::AbstractVector{T}) check_bounds(A, I, J) + I = indices(I); J = indices(J) X = similar(A, ref_shape(I, J)) storeind = 1 for j = J @@ -319,7 +322,7 @@ end # Multidimensional indexing let ref_cache = nothing global ref -function ref(A::Array, I::Indices...) +function ref(A::Array, I::Union(Real,AbstractArray)...) check_bounds(A, I...) I = indices(I) X = similar(A, ref_shape(I...)) @@ -338,7 +341,7 @@ end # logical indexing -function _jl_ref_bool_1d(A::Array, I::AbstractArray{Bool}) +function ref_bool_1d(A::Array, I::AbstractArray{Bool}) check_bounds(A, I) n = sum(I) out = similar(A, n) @@ -352,39 +355,39 @@ function _jl_ref_bool_1d(A::Array, I::AbstractArray{Bool}) out end -ref(A::Vector, I::AbstractVector{Bool}) = _jl_ref_bool_1d(A, I) -ref(A::Vector, I::AbstractArray{Bool}) = _jl_ref_bool_1d(A, I) -ref(A::Array, I::AbstractVector{Bool}) = _jl_ref_bool_1d(A, I) -ref(A::Array, I::AbstractArray{Bool}) = _jl_ref_bool_1d(A, I) +ref(A::Vector, I::AbstractVector{Bool}) = ref_bool_1d(A, I) +ref(A::Vector, I::AbstractArray{Bool}) = ref_bool_1d(A, I) +ref(A::Array, I::AbstractVector{Bool}) = ref_bool_1d(A, I) +ref(A::Array, I::AbstractArray{Bool}) = ref_bool_1d(A, I) # @Jeff: more efficient is to check the bool vector, and then do # indexing without checking. Turn off checking for the second stage? -ref(A::Matrix, I::Integer, J::AbstractVector{Bool}) = A[I,find(J)] -ref(A::Matrix, I::AbstractVector{Bool}, J::Integer) = A[find(I),J] +ref(A::Matrix, I::Real, J::AbstractVector{Bool}) = A[I,find(J)] +ref(A::Matrix, I::AbstractVector{Bool}, J::Real) = A[find(I),J] ref(A::Matrix, I::AbstractVector{Bool}, J::AbstractVector{Bool}) = A[find(I),find(J)] -ref{T<:Integer}(A::Matrix, I::AbstractVector{T}, J::AbstractVector{Bool}) = A[I,find(J)] -ref{T<:Integer}(A::Matrix, I::AbstractVector{Bool}, J::AbstractVector{T}) = A[find(I),J] +ref{T<:Real}(A::Matrix, I::AbstractVector{T}, J::AbstractVector{Bool}) = A[I,find(J)] +ref{T<:Real}(A::Matrix, I::AbstractVector{Bool}, J::AbstractVector{T}) = A[find(I),J] ## Indexing: assign ## assign{T}(A::Array{T,0}, x) = arrayset(A, convert(T,x), 1) -assign(A::Array{Any}, x::ANY, i::Integer) = arrayset(A, x, int(i)) - -assign{T}(A::Array{T}, x, i0::Integer) = arrayset(A, convert(T,x), int(i0)) -assign{T}(A::Array{T}, x, i0::Integer, i1::Integer) = - arrayset(A, convert(T,x), int(i0), int(i1)) -assign{T}(A::Array{T}, x, i0::Integer, i1::Integer, i2::Integer) = - arrayset(A, convert(T,x), int(i0), int(i1), int(i2)) -assign{T}(A::Array{T}, x, i0::Integer, i1::Integer, i2::Integer, i3::Integer) = - arrayset(A, convert(T,x), int(i0), int(i1), int(i2), int(i3)) -assign{T}(A::Array{T}, x, i0::Integer, i1::Integer, i2::Integer, i3::Integer, i4::Integer) = - arrayset(A, convert(T,x), int(i0), int(i1), int(i2), int(i3), int(i4)) -assign{T}(A::Array{T}, x, i0::Integer, i1::Integer, i2::Integer, i3::Integer, i4::Integer, i5::Integer) = - arrayset(A, convert(T,x), int(i0), int(i1), int(i2), int(i3), int(i4), int(i5)) -assign{T}(A::Array{T}, x, i0::Integer, i1::Integer, i2::Integer, i3::Integer, i4::Integer, i5::Integer, I::Int...) = - arrayset(A, convert(T,x), int(i0), int(i1), int(i2), int(i3), int(i4), int(i5), I...) - -function assign{T<:Integer}(A::Array, x, I::AbstractVector{T}) +assign(A::Array{Any}, x::ANY, i::Real) = arrayset(A, x, to_index(i)) + +assign{T}(A::Array{T}, x, i0::Real) = arrayset(A, convert(T,x), to_index(i0)) +assign{T}(A::Array{T}, x, i0::Real, i1::Real) = + arrayset(A, convert(T,x), to_index(i0), to_index(i1)) +assign{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real) = + arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2)) +assign{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real) = + arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3)) +assign{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real) = + arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4)) +assign{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real) = + arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4), to_index(i5)) +assign{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real, I::Int...) = + arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4), to_index(i5), I...) + +function assign{T<:Real}(A::Array, x, I::AbstractVector{T}) for i in I A[i] = x end @@ -397,7 +400,7 @@ function assign{T}(A::Array{T}, X::Array{T}, I::Range1{Int}) return A end -function assign{T<:Integer}(A::Array, X::AbstractArray, I::AbstractVector{T}) +function assign{T<:Real}(A::Array, X::AbstractArray, I::AbstractVector{T}) if length(X) != length(I); error("argument dimensions must match"); end count = 1 for i in I @@ -407,7 +410,8 @@ function assign{T<:Integer}(A::Array, X::AbstractArray, I::AbstractVector{T}) return A end -function assign{T<:Integer}(A::Array, x, i::Integer, J::AbstractVector{T}) +function assign{T<:Real}(A::Array, x, i::Real, J::AbstractVector{T}) + i = to_index(i) check_bounds(A, i, J) m = size(A, 1) if !isa(x,AbstractArray) @@ -426,7 +430,8 @@ function assign{T<:Integer}(A::Array, x, i::Integer, J::AbstractVector{T}) return A end -function assign{T<:Integer}(A::Array, x, I::AbstractVector{T}, j::Integer) +function assign{T<:Real}(A::Array, x, I::AbstractVector{T}, j::Real) + j = to_index(j) check_bounds(A, I, j) m = size(A, 1) offset = (j-1)*m @@ -447,7 +452,8 @@ function assign{T<:Integer}(A::Array, x, I::AbstractVector{T}, j::Integer) return A end -function assign{T}(A::Array{T}, X::Array{T}, I::Range1{Int}, j::Integer) +function assign{T}(A::Array{T}, X::Array{T}, I::Range1{Int}, j::Real) + j = to_index(j) check_bounds(A, I, j) if length(X) != length(I); error("argument dimensions must match"); end copy_to_unsafe(A, first(I) + (j-1)*size(A,1), X, 1, length(I)) @@ -488,7 +494,7 @@ function assign{T}(A::Array{T}, X::Array{T}, I::Range1{Int}, J::AbstractVector{I return A end -function assign{T<:Integer}(A::Array, x, I::AbstractVector{T}, J::AbstractVector{T}) +function assign{T<:Real}(A::Array, x, I::AbstractVector{T}, J::AbstractVector{T}) check_bounds(A, I, J) m = size(A, 1) if !isa(x,AbstractArray) @@ -519,9 +525,8 @@ end let assign_cache = nothing, assign_scalar_cache = nothing global assign -function assign(A::Array, x, I0::Indices, I::Indices...) - check_bounds(A, I0, I...) - I0 = indices(I0) +function assign(A::Array, x, I::Union(Real,AbstractArray)...) + check_bounds(A, I...) I = indices(I) if !isa(x,AbstractArray) if is(assign_scalar_cache,nothing) @@ -530,7 +535,7 @@ function assign(A::Array, x, I0::Indices, I::Indices...) gen_array_index_map(assign_scalar_cache, storeind -> quote A[$storeind] = x end, - tuple(I0, I...), + I, (:A, :x), A, x) else @@ -538,7 +543,7 @@ function assign(A::Array, x, I0::Indices, I::Indices...) assign_cache = Dict() end X = x - nel = length(I0) + nel = 1 for idx in I nel *= length(idx) end @@ -546,11 +551,8 @@ function assign(A::Array, x, I0::Indices, I::Indices...) error("argument dimensions must match") end if ndims(X) > 1 - if size(X,1) != length(I0) - error("argument dimensions must match") - end for i = 1:length(I) - if size(X,i+1) != length(I[i]) + if size(X,i) != length(I[i]) error("argument dimensions must match") end end @@ -562,7 +564,7 @@ function assign(A::Array, x, I0::Indices, I::Indices...) A[$storeind] = X[refind] refind += 1 end, - tuple(I0, I...), + I, (:A, :X, :refind), A, X, 1) end @@ -572,7 +574,7 @@ end # logical indexing -function _jl_assign_bool_scalar_1d(A::Array, x, I::AbstractArray{Bool}) +function assign_bool_scalar_1d(A::Array, x, I::AbstractArray{Bool}) check_bounds(A, I) for i = 1:numel(I) if I[i] @@ -582,7 +584,7 @@ function _jl_assign_bool_scalar_1d(A::Array, x, I::AbstractArray{Bool}) A end -function _jl_assign_bool_vector_1d(A::Array, X::AbstractArray, I::AbstractArray{Bool}) +function assign_bool_vector_1d(A::Array, X::AbstractArray, I::AbstractArray{Bool}) check_bounds(A, I) c = 1 for i = 1:numel(I) @@ -594,20 +596,20 @@ function _jl_assign_bool_vector_1d(A::Array, X::AbstractArray, I::AbstractArray{ A end -assign(A::Array, X::AbstractArray, I::AbstractVector{Bool}) = _jl_assign_bool_vector_1d(A, X, I) -assign(A::Array, X::AbstractArray, I::AbstractArray{Bool}) = _jl_assign_bool_vector_1d(A, X, I) -assign(A::Array, x, I::AbstractVector{Bool}) = _jl_assign_bool_scalar_1d(A, x, I) -assign(A::Array, x, I::AbstractArray{Bool}) = _jl_assign_bool_scalar_1d(A, x, I) +assign(A::Array, X::AbstractArray, I::AbstractVector{Bool}) = assign_bool_vector_1d(A, X, I) +assign(A::Array, X::AbstractArray, I::AbstractArray{Bool}) = assign_bool_vector_1d(A, X, I) +assign(A::Array, x, I::AbstractVector{Bool}) = assign_bool_scalar_1d(A, x, I) +assign(A::Array, x, I::AbstractArray{Bool}) = assign_bool_scalar_1d(A, x, I) -assign(A::Array, x, I::Integer, J::AbstractVector{Bool}) = assign(A, x, I,find(J)) +assign(A::Array, x, I::Real, J::AbstractVector{Bool}) = assign(A, x, I,find(J)) -assign(A::Array, x, I::AbstractVector{Bool}, J::Integer) = assign(A,x,find(I),J) +assign(A::Array, x, I::AbstractVector{Bool}, J::Real) = assign(A,x,find(I),J) assign(A::Array, x, I::AbstractVector{Bool}, J::AbstractVector{Bool}) = assign(A, x, find(I),find(J)) -assign{T<:Integer}(A::Array, x, I::AbstractVector{T}, J::AbstractVector{Bool}) = assign(A, x, I,find(J)) +assign{T<:Real}(A::Array, x, I::AbstractVector{T}, J::AbstractVector{Bool}) = assign(A, x, I,find(J)) -assign{T<:Integer}(A::Array, x, I::AbstractVector{Bool}, J::AbstractVector{T}) = assign(A, x, find(I),J) +assign{T<:Real}(A::Array, x, I::AbstractVector{Bool}, J::AbstractVector{T}) = assign(A, x, find(I),J) ## Dequeue functionality ## @@ -822,7 +824,7 @@ function .^{T<:Integer}(A::Integer, B::Array{T}) return F end -function _jl_power_array_int_body{T}(F::Array{T}, A, B) +function power_array_int_body{T}(F::Array{T}, A, B) for i=1:numel(A) F[i] = A[i]^convert(T,B) end @@ -831,7 +833,7 @@ end function .^{T<:Integer}(A::Array{T}, B::Integer) F = similar(A, B < 0 ? Float64 : promote_type(T,typeof(B))) - _jl_power_array_int_body(F, A, B) + power_array_int_body(F, A, B) end for f in (:+, :-, :.*, :div, :mod, :&, :|, :$) @@ -1269,7 +1271,7 @@ indmin(a::Array) = findmin(a)[2] reduced_dims(A, region) = ntuple(ndims(A), i->(contains(region, i) ? 1 : size(A,i))) -areduce(f::Function, A, region::Dimspec, v0) = +areduce(f::Function, A, region, v0) = areduce(f, A, region, v0, similar(A, reduced_dims(A, region))) # TODO: @@ -1313,7 +1315,7 @@ function gen_areduce_func(n, f) end global areduce -function areduce(f::Function, A, region::Dimspec, v0, R) +function areduce(f::Function, A, region, v0, R) ndimsA = ndims(A) if is(areduce_cache,nothing) @@ -1346,19 +1348,19 @@ function areduce(f::Function, A, region::Dimspec, v0, R) end end -max{T}(A::AbstractArray{T}, b::(), region::Dimspec) = areduce(max,A,region,typemin(T)) -min{T}(A::AbstractArray{T}, b::(), region::Dimspec) = areduce(min,A,region,typemax(T)) -sum{T}(A::AbstractArray{T}, region::Dimspec) = areduce(+,A,region,zero(T)) -prod{T}(A::AbstractArray{T}, region::Dimspec) = areduce(*,A,region,one(T)) +max{T}(A::AbstractArray{T}, b::(), region) = areduce(max,A,region,typemin(T)) +min{T}(A::AbstractArray{T}, b::(), region) = areduce(min,A,region,typemax(T)) +sum{T}(A::AbstractArray{T}, region) = areduce(+,A,region,zero(T)) +prod{T}(A::AbstractArray{T}, region) = areduce(*,A,region,one(T)) -all(A::AbstractArray{Bool}, region::Dimspec) = areduce(all,A,region,true) -any(A::AbstractArray{Bool}, region::Dimspec) = areduce(any,A,region,false) -sum(A::AbstractArray{Bool}, region::Dimspec) = areduce(+,A,region,0,similar(A,Int,reduced_dims(A,region))) +all(A::AbstractArray{Bool}, region) = areduce(all,A,region,true) +any(A::AbstractArray{Bool}, region) = areduce(any,A,region,false) +sum(A::AbstractArray{Bool}, region) = areduce(+,A,region,0,similar(A,Int,reduced_dims(A,region))) sum(A::AbstractArray{Bool}) = count(A) sum(A::StridedArray{Bool}) = count(A) prod(A::AbstractArray{Bool}) = error("use all() instead of prod() for boolean arrays") -prod(A::AbstractArray{Bool}, region::Dimspec) = +prod(A::AbstractArray{Bool}, region) = error("use all() instead of prod() for boolean arrays") function sum{T}(A::StridedArray{T}) diff --git a/base/ascii.jl b/base/ascii.jl index 91235b076416a..9d1daf0a67f81 100644 --- a/base/ascii.jl +++ b/base/ascii.jl @@ -8,7 +8,7 @@ ## required core functionality ## length(s::ASCIIString) = length(s.data) -ref(s::ASCIIString, i::Int) = char(s.data[i]) +ref(s::ASCIIString, i::Int) = (x=s.data[i]; x < 0x80 ? char(x) : '\ufffd') ## overload methods for efficiency ## diff --git a/base/base.jl b/base/base.jl index f74f32c9c6a6e..ae714736e4710 100644 --- a/base/base.jl +++ b/base/base.jl @@ -98,6 +98,15 @@ names(m::Module, all::Bool) = ccall(:jl_module_names, Array{Symbol,1}, (Any,Int3 names(m::Module) = names(m,false) module_name(m::Module) = ccall(:jl_module_name, Symbol, (Any,), m) module_parent(m::Module) = ccall(:jl_module_parent, Module, (Any,), m) +function names(v) + if typeof(v) === CompositeKind + return v.names + elseif typeof(typeof(v)) === CompositeKind + return typeof(v).names + else + error("cannot call names() on a non-composite type") + end +end # index colon type Colon diff --git a/base/bitarray.jl b/base/bitarray.jl index 81e856c82cd96..1c6fef5389b5a 100644 --- a/base/bitarray.jl +++ b/base/bitarray.jl @@ -1,11 +1,11 @@ # prelimnary definitions: constants, macros # and functions used throughout the code const _msk64 = ~uint64(0) -macro _mskr(l) quote _msk64 >>> (64-$(esc(l))) end end -macro _div64(l) quote $(esc(l)) >>> 6 end end -macro _mod64(l) quote $(esc(l)) & 63 end end -macro _msk_end(l) quote @_mskr @_mod64 $(esc(l)) end end -_jl_num_bit_chunks(n::Int) = @_div64 (n+63) +macro _mskr(l) :(_msk64 >>> (64-$(esc(l)))) end +macro _div64(l) :($(esc(l)) >>> 6) end +macro _mod64(l) :($(esc(l)) & 63) end +macro _msk_end(l) :(@_mskr @_mod64 $(esc(l))) end +num_bit_chunks(n::Int) = @_div64 (n+63) ## BitArray @@ -19,7 +19,7 @@ type BitArray{N} <: AbstractArray{Bool, N} dims = 0 end n = prod(dims) - nc = _jl_num_bit_chunks(n) + nc = num_bit_chunks(n) chunks = Array(Uint64, nc) if nc > 0 chunks[end] = uint64(0) @@ -45,12 +45,9 @@ size(B::BitArray) = tuple(B.dims...) ## Aux functions ## -function _jl_get_chunks_id(i::Integer) - j = int(i-1) - return (@_div64 j)+1, @_mod64 j -end +get_chunks_id(i::Integer) = @_div64(int(i-1))+1, @_mod64(int(i-1)) -function _jl_glue_src_bitchunks(src::Vector{Uint64}, k::Int, ks1::Int, msk_s0::Uint64, ls0::Int) +function glue_src_bitchunks(src::Vector{Uint64}, k::Int, ks1::Int, msk_s0::Uint64, ls0::Int) chunk = ((src[k] & msk_s0) >>> ls0) if ks1 > k && ls0 > 0 chunk_n = (src[k + 1] & ~msk_s0) @@ -59,15 +56,15 @@ function _jl_glue_src_bitchunks(src::Vector{Uint64}, k::Int, ks1::Int, msk_s0::U return chunk end -function _jl_copy_chunks(dest::Vector{Uint64}, pos_d::Integer, src::Vector{Uint64}, pos_s::Integer, numbits::Integer) +function copy_chunks(dest::Vector{Uint64}, pos_d::Integer, src::Vector{Uint64}, pos_s::Integer, numbits::Integer) if numbits == 0 return end - kd0, ld0 = _jl_get_chunks_id(pos_d) - kd1, ld1 = _jl_get_chunks_id(pos_d + numbits - 1) - ks0, ls0 = _jl_get_chunks_id(pos_s) - ks1, ls1 = _jl_get_chunks_id(pos_s + numbits - 1) + kd0, ld0 = get_chunks_id(pos_d) + kd1, ld1 = get_chunks_id(pos_d + numbits - 1) + ks0, ls0 = get_chunks_id(pos_s) + ks1, ls1 = get_chunks_id(pos_s + numbits - 1) delta_kd = kd1 - kd0 delta_ks = ks1 - ks0 @@ -85,7 +82,7 @@ function _jl_copy_chunks(dest::Vector{Uint64}, pos_d::Integer, src::Vector{Uint6 msk_s0 = (u << ls0) end - chunk_s0 = _jl_glue_src_bitchunks(src, ks0, ks1, msk_s0, ls0) + chunk_s0 = glue_src_bitchunks(src, ks0, ks1, msk_s0, ls0) dest[kd0] = (dest[kd0] & msk_d0) | ((chunk_s0 << ld0) & ~msk_d0) @@ -94,7 +91,7 @@ function _jl_copy_chunks(dest::Vector{Uint64}, pos_d::Integer, src::Vector{Uint6 end for i = 1 : kd1 - kd0 - 1 - chunk_s1 = _jl_glue_src_bitchunks(src, ks0 + i, ks1, msk_s0, ls0) + chunk_s1 = glue_src_bitchunks(src, ks0 + i, ks1, msk_s0, ls0) chunk_s = (chunk_s0 >>> (63 - ld0) >>> 1) | (chunk_s1 << ld0) @@ -104,7 +101,7 @@ function _jl_copy_chunks(dest::Vector{Uint64}, pos_d::Integer, src::Vector{Uint6 end if ks1 >= ks0 + delta_kd - chunk_s1 = _jl_glue_src_bitchunks(src, ks0 + delta_kd, ks1, msk_s0, ls0) + chunk_s1 = glue_src_bitchunks(src, ks0 + delta_kd, ks1, msk_s0, ls0) else chunk_s1 = uint64(0) end @@ -184,7 +181,7 @@ function copy_to(dest::BitArray, pos_d::Integer, src::BitArray, pos_s::Integer, if pos_s+numbits-1 > numel(src) || pos_d+numbits-1 > numel(dest) || pos_d < 1 || pos_s < 1 throw(BoundsError()) end - _jl_copy_chunks(dest.chunks, pos_d, src.chunks, pos_s, numbits) + copy_chunks(dest.chunks, pos_d, src.chunks, pos_s, numbits) return dest end @@ -256,36 +253,36 @@ function ref(B::BitArray, i::Integer) if i < 1 || i > length(B) throw(BoundsError()) end - i1, i2 = _jl_get_chunks_id(i) + i1, i2 = get_chunks_id(i) return (B.chunks[i1] >>> i2) & one(Uint64) == one(Uint64) end # 0d bitarray ref(B::BitArray{0}) = B[1] -ref(B::BitArray, i0::Integer, i1::Integer) = B[i0 + size(B,1)*(i1-1)] -ref(B::BitArray, i0::Integer, i1::Integer, i2::Integer) = - B[i0 + size(B,1)*((i1-1) + size(B,2)*(i2-1))] -ref(B::BitArray, i0::Integer, i1::Integer, i2::Integer, i3::Integer) = - B[i0 + size(B,1)*((i1-1) + size(B,2)*((i2-1) + size(B,3)*(i3-1)))] +ref(B::BitArray, i0::Real, i1::Real) = B[to_index(i0) + size(B,1)*(to_index(i1)-1)] +ref(B::BitArray, i0::Real, i1::Real, i2::Real) = + B[to_index(i0) + size(B,1)*((to_index(i1)-1) + size(B,2)*(to_index(i2)-1))] +ref(B::BitArray, i0::Real, i1::Real, i2::Real, i3::Real) = + B[to_index(i0) + size(B,1)*((to_index(i1)-1) + size(B,2)*((to_index(i2)-1) + size(B,3)*(to_index(i3)-1)))] -# ref(::BitArray, ::Integer) is shadowed (?) -function ref(B::BitArray, I::Integer...) +# ref(::BitArray, ::Real) is shadowed (?) +function ref(B::BitArray, I::Real...) ndims = length(I) - index = I[1] + index = to_index(I[1]) stride = 1 for k=2:ndims stride *= size(B, k - 1) - index += (I[k] - 1) * stride + index += (to_index(I[k]) - 1) * stride end return B[index] end # note: we can gain some performance if the first dimension is a range; -# TODO: extend to I:Indices... (i.e. not necessarily contiguous) +# TODO: extend to I:Union(Real,AbstractArray)... (i.e. not necessarily contiguous) let ref_cache = nothing global ref - function ref(B::BitArray, I0::Range1{Int}, I::Union(Integer, Range1{Int})...) + function ref(B::BitArray, I0::Range1{Int}, I::Union(Real,Range1{Int})...) # the < should become a != once # the stricter indexing behaviour is enforced if ndims(B) < 1 + length(I) @@ -294,7 +291,7 @@ let ref_cache = nothing X = BitArray(ref_shape(I0, I...)) nI = 1 + length(I) - I = map(x->(isa(x,Integer) ? (x:x) : x), I[1:nI-1]) + I = map(x->(isa(x,Real) ? (to_index(x):to_index(x)) : indices(x)), I[1:nI-1]) f0 = first(I0) l0 = length(I0) @@ -314,7 +311,7 @@ let ref_cache = nothing stride_lst[nI] = 0 if ndims(X) == 1 - _jl_copy_chunks(X.chunks, 1, B.chunks, ind, l0) + copy_chunks(X.chunks, 1, B.chunks, ind, l0) return X end @@ -326,7 +323,7 @@ let ref_cache = nothing ivars->begin bodies = cell(nI, 2) bodies[1] = quote - _jl_copy_chunks(X.chunks, storeind, B.chunks, ind, l0) + copy_chunks(X.chunks, storeind, B.chunks, ind, l0) storeind += l0 ind += stride_lst[loop_ind] end @@ -350,7 +347,7 @@ end # note: the Range1{Int} case is still handled by the version above # (which is fine) -function ref{T<:Integer}(B::BitArray, I::AbstractVector{T}) +function ref{T<:Real}(B::BitArray, I::AbstractVector{T}) X = BitArray(length(I)) ind = 1 for i in I @@ -362,7 +359,7 @@ end let ref_cache = nothing global ref - function ref(B::BitArray, I::Indices...) + function ref(B::BitArray, I::Union(Real,AbstractArray)...) I = indices(I) X = BitArray(ref_shape(I...)) @@ -379,7 +376,7 @@ end # logical indexing -function _jl_ref_bool_1d(B::BitArray, I::AbstractArray{Bool}) +function ref_bool_1d(B::BitArray, I::AbstractArray{Bool}) n = sum(I) out = BitArray(n) c = 1 @@ -392,24 +389,26 @@ function _jl_ref_bool_1d(B::BitArray, I::AbstractArray{Bool}) out end -ref(B::BitVector, I::AbstractVector{Bool}) = _jl_ref_bool_1d(B, I) -ref(B::BitVector, I::AbstractArray{Bool}) = _jl_ref_bool_1d(B, I) -ref(B::BitArray, I::AbstractVector{Bool}) = _jl_ref_bool_1d(B, I) -ref(B::BitArray, I::AbstractArray{Bool}) = _jl_ref_bool_1d(B, I) +ref(B::BitVector, I::AbstractVector{Bool}) = ref_bool_1d(B, I) +ref(B::BitVector, I::AbstractArray{Bool}) = ref_bool_1d(B, I) +ref(B::BitArray, I::AbstractVector{Bool}) = ref_bool_1d(B, I) +ref(B::BitArray, I::AbstractArray{Bool}) = ref_bool_1d(B, I) -ref(B::BitMatrix, I::Integer, J::AbstractVector{Bool}) = B[I, find(J)] -ref(B::BitMatrix, I::AbstractVector{Bool}, J::Integer) = B[find(I), J] +ref(B::BitMatrix, I::Real, J::AbstractVector{Bool}) = B[I, find(J)] +ref(B::BitMatrix, I::AbstractVector{Bool}, J::Real) = B[find(I), J] ref(B::BitMatrix, I::AbstractVector{Bool}, J::AbstractVector{Bool}) = B[find(I), find(J)] -ref{T<:Integer}(B::BitMatrix, I::AbstractVector{T}, J::AbstractVector{Bool}) = B[I, find(J)] -ref{T<:Integer}(B::BitMatrix, I::AbstractVector{Bool}, J::AbstractVector{T}) = B[find(I), J] +ref(B::BitMatrix, I::Range1{Int}, J::AbstractVector{Bool}) = B[I, find(J)] +ref{T<:Real}(B::BitMatrix, I::AbstractVector{T}, J::AbstractVector{Bool}) = B[I, find(J)] +ref{T<:Real}(B::BitMatrix, I::AbstractVector{Bool}, J::AbstractVector{T}) = B[find(I), J] ## Indexing: assign ## -function assign(B::BitArray, x, i::Integer) +function assign(B::BitArray, x, i::Real) + i = to_index(i) if i < 1 || i > length(B) throw(BoundsError()) end - i1, i2 = _jl_get_chunks_id(i) + i1, i2 = get_chunks_id(i) u = uint64(1) y = convert(Bool, x) if !y @@ -420,29 +419,29 @@ function assign(B::BitArray, x, i::Integer) return B end -assign(B::BitArray, x, i0::Integer, i1::Integer) = - B[i0 + size(B,1)*(i1-1)] = x +assign(B::BitArray, x, i0::Real, i1::Real) = + B[to_index(i0) + size(B,1)*(to_index(i1)-1)] = x -assign(B::BitArray, x, i0::Integer, i1::Integer, i2::Integer) = - B[i0 + size(B,1)*((i1-1) + size(B,2)*(i2-1))] = x +assign(B::BitArray, x, i0::Real, i1::Real, i2::Real) = + B[to_index(i0) + size(B,1)*((to_index(i1)-1) + size(B,2)*(to_index(i2)-1))] = x -assign(B::BitArray, x, i0::Integer, i1::Integer, i2::Integer, i3::Integer) = - B[i0 + size(B,1)*((i1-1) + size(B,2)*((i2-1) + size(B,3)*(i3-1)))] = x +assign(B::BitArray, x, i0::Real, i1::Real, i2::Real, i3::Real) = + B[to_index(i0) + size(B,1)*((to_index(i1)-1) + size(B,2)*((to_index(i2)-1) + size(B,3)*(to_index(i3)-1)))] = x -function assign(B::BitArray, x, I0::Integer, I::Integer...) - index = I0 +function assign(B::BitArray, x, I0::Real, I::Real...) + index = to_index(I0) stride = 1 for k = 1:length(I) stride = stride * size(B, k) - index += (I[k] - 1) * stride + index += (to_index(I[k]) - 1) * stride end B[index] = x return B end let assign_cache = nothing - global _jl_assign_array2bitarray_ranges - function _jl_assign_array2bitarray_ranges(B::BitArray, X::BitArray, I0::Range1{Int}, I::Range1{Int}...) + global assign_array2bitarray_ranges + function assign_array2bitarray_ranges(B::BitArray, X::BitArray, I0::Range1{Int}, I::Range1{Int}...) nI = 1 + length(I) if ndims(B) != nI error("wrong number of dimensions in assigment") @@ -460,7 +459,7 @@ let assign_cache = nothing f0 = first(I0) l0 = length(I0) if nI == 1 - _jl_copy_chunks(B.chunks, f0, X.chunks, 1, l0) + copy_chunks(B.chunks, f0, X.chunks, 1, l0) return B end if is(assign_cache,nothing) @@ -484,7 +483,7 @@ let assign_cache = nothing ivars->begin bodies = cell(nI, 2) bodies[1] = quote - _jl_copy_chunks(B.chunks, ind, X.chunks, refind, l0) + copy_chunks(B.chunks, ind, X.chunks, refind, l0) refind += l0 ind += stride_lst[loop_ind] end @@ -511,10 +510,10 @@ end # TODO: extend to I:Indices... (i.e. not necessarily contiguous) function assign(B::BitArray, X::BitArray, I0::Range1{Int}, I::Union(Integer, Range1{Int})...) I = map(x->(isa(x,Integer) ? (x:x) : x), I) - _jl_assign_array2bitarray_ranges(B, X, I0, I...) + assign_array2bitarray_ranges(B, X, I0, I...) end -function assign{T<:Integer}(B::BitArray, X::AbstractArray, I::AbstractVector{T}) +function assign{T<:Real}(B::BitArray, X::AbstractArray, I::AbstractVector{T}) if length(X) != length(I); error("argument dimensions must match"); end count = 1 for i in I @@ -524,33 +523,32 @@ function assign{T<:Integer}(B::BitArray, X::AbstractArray, I::AbstractVector{T}) return B end -function assign(B::BitArray, X::AbstractArray, i0::Integer) +function assign(B::BitArray, X::AbstractArray, i0::Real) if length(X) != 1 error("argument dimensions must match") end - return B[i0] = X[1] + return assign(B, X[1], i0) end -function assign(B::BitArray, X::AbstractArray, i0::Integer, i1::Integer) +function assign(B::BitArray, X::AbstractArray, i0::Real, i1::Real) if length(X) != 1 error("argument dimensions must match") end - return B[i0, i1] = X[1] + return assign(B, X[1], i0, i1) end -function assign(B::BitArray, X::AbstractArray, I0::Integer, I::Integer...) +function assign(B::BitArray, X::AbstractArray, I0::Real, I::Real...) if length(X) != 1 error("argument dimensions must match") end - return B[I0, I...] = X[1] + return assign(B, X[1], i0, I...) end let assign_cache = nothing global assign - function assign(B::BitArray, X::AbstractArray, I0::Indices, I::Indices...) - I0 = indices(I0) + function assign(B::BitArray, X::AbstractArray, I::Union(Real,AbstractArray)...) I = indices(I) - nel = length(I0) + nel = 1 for idx in I nel *= length(idx) end @@ -558,11 +556,8 @@ let assign_cache = nothing error("argument dimensions must match") end if ndims(X) > 1 - if size(X,1) != length(I0) - error("argument dimensions must match") - end for i = 1:length(I) - if size(X,i+1) != length(I[i]) + if size(X,i) != length(I[i]) error("argument dimensions must match") end end @@ -572,14 +567,14 @@ let assign_cache = nothing end gen_cartesian_map(assign_cache, ivars->:(B[$(ivars...)] = X[refind]; refind += 1), - tuple(I0, I...), + I, (:B, :X, :refind), B, X, 1) return B end end -function assign{T<:Integer}(B::BitArray, x, I::AbstractVector{T}) +function assign{T<:Real}(B::BitArray, x, I::AbstractVector{T}) for i in I B[i] = x end @@ -588,14 +583,13 @@ end let assign_cache = nothing global assign - function assign(B::BitArray, x, I0::Indices, I::Indices...) - I0 = indices(I0) + function assign(B::BitArray, x, I::Union(Real,AbstractArray)...) I = indices(I) if is(assign_cache,nothing) assign_cache = Dict() end gen_cartesian_map(assign_cache, ivars->:(B[$(ivars...)] = x), - tuple(I0, I...), + I, (:B, :x), B, x) return B @@ -604,7 +598,7 @@ end # logical indexing -function _jl_assign_bool_scalar_1d(A::BitArray, x, I::AbstractArray{Bool}) +function assign_bool_scalar_1d(A::BitArray, x, I::AbstractArray{Bool}) n = sum(I) for i = 1:numel(I) if I[i] @@ -614,7 +608,7 @@ function _jl_assign_bool_scalar_1d(A::BitArray, x, I::AbstractArray{Bool}) A end -function _jl_assign_bool_vector_1d(A::BitArray, X::AbstractArray, I::AbstractArray{Bool}) +function assign_bool_vector_1d(A::BitArray, X::AbstractArray, I::AbstractArray{Bool}) n = sum(I) c = 1 for i = 1:numel(I) @@ -626,21 +620,21 @@ function _jl_assign_bool_vector_1d(A::BitArray, X::AbstractArray, I::AbstractArr A end -assign(A::BitArray, X::AbstractArray, I::AbstractVector{Bool}) = _jl_assign_bool_vector_1d(A, X, I) -assign(A::BitArray, X::AbstractArray, I::AbstractArray{Bool}) = _jl_assign_bool_vector_1d(A, X, I) -assign(A::BitArray, x, I::AbstractVector{Bool}) = _jl_assign_bool_scalar_1d(A, x, I) -assign(A::BitArray, x, I::AbstractArray{Bool}) = _jl_assign_bool_scalar_1d(A, x, I) +assign(A::BitArray, X::AbstractArray, I::AbstractVector{Bool}) = assign_bool_vector_1d(A, X, I) +assign(A::BitArray, X::AbstractArray, I::AbstractArray{Bool}) = assign_bool_vector_1d(A, X, I) +assign(A::BitArray, x, I::AbstractVector{Bool}) = assign_bool_scalar_1d(A, x, I) +assign(A::BitArray, x, I::AbstractArray{Bool}) = assign_bool_scalar_1d(A, x, I) -assign(A::BitMatrix, x::AbstractArray, I::Integer, J::AbstractVector{Bool}) = +assign(A::BitMatrix, x::AbstractArray, I::Real, J::AbstractVector{Bool}) = (A[I,find(J)] = x) -assign(A::BitMatrix, x, I::Integer, J::AbstractVector{Bool}) = +assign(A::BitMatrix, x, I::Real, J::AbstractVector{Bool}) = (A[I,find(J)] = x) -assign(A::BitMatrix, x::AbstractArray, I::AbstractVector{Bool}, J::Integer) = +assign(A::BitMatrix, x::AbstractArray, I::AbstractVector{Bool}, J::Real) = (A[find(I),J] = x) -assign(A::BitMatrix, x, I::AbstractVector{Bool}, J::Integer) = +assign(A::BitMatrix, x, I::AbstractVector{Bool}, J::Real) = (A[find(I),J] = x) assign(A::BitMatrix, x::AbstractArray, I::AbstractVector{Bool}, J::AbstractVector{Bool}) = @@ -652,13 +646,13 @@ assign(A::BitMatrix, x, I::AbstractVector{Bool}, J::AbstractVector{Bool}) = assign{T<:Integer}(A::BitMatrix, x::AbstractArray, I::AbstractVector{T}, J::AbstractVector{Bool}) = (A[I,find(J)] = x) -assign{T<:Integer}(A::BitMatrix, x, I::AbstractVector{T}, J::AbstractVector{Bool}) = +assign{T<:Real}(A::BitMatrix, x, I::AbstractVector{T}, J::AbstractVector{Bool}) = (A[I,find(J)] = x) -assign{T<:Integer}(A::BitMatrix, x::AbstractArray, I::AbstractVector{Bool}, J::AbstractVector{T}) = +assign{T<:Real}(A::BitMatrix, x::AbstractArray, I::AbstractVector{Bool}, J::AbstractVector{T}) = (A[find(I),J] = x) -assign{T<:Integer}(A::BitMatrix, x, I::AbstractVector{Bool}, J::AbstractVector{T}) = +assign{T<:Real}(A::BitMatrix, x, I::AbstractVector{Bool}, J::AbstractVector{T}) = (A[find(I),J] = x) ## Dequeue functionality ## @@ -686,13 +680,13 @@ function append!(B::BitVector, items::BitVector) return B end k0 = length(B.chunks) - k1 = _jl_num_bit_chunks(n0 + n1) + k1 = num_bit_chunks(n0 + n1) if k1 > k0 ccall(:jl_array_grow_end, Void, (Any, Uint), B.chunks, k1 - k0) B.chunks[end] = uint64(0) end B.dims[1] += n1 - _jl_copy_chunks(B.chunks, n0+1, items.chunks, 1, n1) + copy_chunks(B.chunks, n0+1, items.chunks, 1, n1) return B end @@ -708,7 +702,7 @@ function grow(B::BitVector, n::Integer) return del(B, n0+n+1:n0) end k0 = length(B.chunks) - k1 = _jl_num_bit_chunks(n0 + int(n)) + k1 = num_bit_chunks(n0 + int(n)) if k1 > k0 ccall(:jl_array_grow_end, Void, (Any, Uint), B.chunks, k1 - k0) B.chunks[end] = uint64(0) @@ -785,7 +779,7 @@ function insert(B::BitVector, i::Integer, item) x = falses(i - n) append!(B, x) else - k, j = _jl_get_chunks_id(i) + k, j = get_chunks_id(i) l = @_mod64 length(B) if l == 0 @@ -811,7 +805,7 @@ function del(B::BitVector, i::Integer) throw(BoundsError()) end - k, j = _jl_get_chunks_id(i) + k, j = get_chunks_id(i) msk_bef = _msk64 >>> (63 - j) msk_aft = ~msk_bef @@ -850,11 +844,11 @@ function del(B::BitVector, r::Range1{Int}) return B end - _jl_copy_chunks(B.chunks, i_f, B.chunks, i_l+1, n-i_l) + copy_chunks(B.chunks, i_f, B.chunks, i_l+1, n-i_l) delta_l = i_l - i_f + 1 new_l = length(B) - delta_l - delta_k = length(B.chunks) - _jl_num_bit_chunks(new_l) + delta_k = length(B.chunks) - num_bit_chunks(new_l) if delta_k > 0 ccall(:jl_array_del_end, Void, (Any, Uint), B.chunks, delta_k) @@ -1141,7 +1135,7 @@ function flipdim(A::BitArray, d::Integer) for j=0:stride:(N-stride) offs = j + 1 + (i-1)*M boffs = j + 1 + (ri-1)*M - _jl_copy_chunks(B.chunks, boffs, A.chunks, offs, M) + copy_chunks(B.chunks, boffs, A.chunks, offs, M) end end end @@ -1173,17 +1167,14 @@ function rot180(A::BitMatrix) return B end -# implemented as a macro to improve performance -macro _jl_reverse_bits(dest, src) - quote - z = $(esc(src)) - z = ((z >>> 1) & 0x5555555555555555) | ((z << 1) & 0xaaaaaaaaaaaaaaaa) - z = ((z >>> 2) & 0x3333333333333333) | ((z << 2) & 0xcccccccccccccccc) - z = ((z >>> 4) & 0x0f0f0f0f0f0f0f0f) | ((z << 4) & 0xf0f0f0f0f0f0f0f0) - z = ((z >>> 8) & 0x00ff00ff00ff00ff) | ((z << 8) & 0xff00ff00ff00ff00) - z = ((z >>> 16) & 0x0000ffff0000ffff) | ((z << 16) & 0xffff0000ffff0000) - $(esc(dest)) = ((z >>> 32) & 0x00000000ffffffff) | ((z << 32) & 0xffffffff00000000) - end +function reverse_bits(src::Uint64) + z = src + z = ((z >>> 1) & 0x5555555555555555) | ((z << 1) & 0xaaaaaaaaaaaaaaaa) + z = ((z >>> 2) & 0x3333333333333333) | ((z << 2) & 0xcccccccccccccccc) + z = ((z >>> 4) & 0x0f0f0f0f0f0f0f0f) | ((z << 4) & 0xf0f0f0f0f0f0f0f0) + z = ((z >>> 8) & 0x00ff00ff00ff00ff) | ((z << 8) & 0xff00ff00ff00ff00) + z = ((z >>> 16) & 0x0000ffff0000ffff) | ((z << 16) & 0xffff0000ffff0000) + return ((z >>> 32) & 0x00000000ffffffff) | ((z << 32) & 0xffffffff00000000) end function reverse!(B::BitVector) @@ -1198,10 +1189,10 @@ function reverse!(B::BitVector) for i = 1 : hnc j = ((i - 1) << 6) - @_jl_reverse_bits aux_chunks[1] B.chunks[i] - _jl_copy_chunks(B.chunks, j+1, B.chunks, n-63-j, 64) - @_jl_reverse_bits B.chunks[i] B.chunks[i] - _jl_copy_chunks(B.chunks, n-63-j, aux_chunks, 1, 64) + aux_chunks[1] = reverse_bits(B.chunks[i]) + copy_chunks(B.chunks, j+1, B.chunks, n-63-j, 64) + B.chunks[i] = reverse_bits(B.chunks[i]) + copy_chunks(B.chunks, n-63-j, aux_chunks, 1, 64) end if pnc == 0 @@ -1213,9 +1204,9 @@ function reverse!(B::BitVector) l = (@_mod64 (n+63)) + 1 msk = @_mskr l - @_jl_reverse_bits aux_chunks[1] (B.chunks[i] & msk) + aux_chunks[1] = reverse_bits(B.chunks[i] & msk) aux_chunks[1] >>>= (64 - l) - _jl_copy_chunks(B.chunks, j+1, aux_chunks, 1, l) + copy_chunks(B.chunks, j+1, aux_chunks, 1, l) return B end @@ -1227,7 +1218,7 @@ function (<<)(B::BitVector, i::Int64) i %= n if i == 0; return copy(B); end A = falses(n); - _jl_copy_chunks(A.chunks, 1, B.chunks, i+1, n-i) + copy_chunks(A.chunks, 1, B.chunks, i+1, n-i) return A end (<<)(B::BitVector, i::Int32) = B << int64(i) @@ -1238,7 +1229,7 @@ function (>>>)(B::BitVector, i::Int64) i %= n if i == 0; return copy(B); end A = falses(n); - _jl_copy_chunks(A.chunks, i+1, B.chunks, 1, n-i) + copy_chunks(A.chunks, i+1, B.chunks, 1, n-i) return A end (>>>)(B::BitVector, i::Int32) = B >>> int64(i) @@ -1252,8 +1243,8 @@ function rotl(B::BitVector, i::Integer) i %= n if i == 0; return copy(B); end A = BitArray(n); - _jl_copy_chunks(A.chunks, 1, B.chunks, i+1, n-i) - _jl_copy_chunks(A.chunks, n-i+1, B.chunks, 1, i) + copy_chunks(A.chunks, 1, B.chunks, i+1, n-i) + copy_chunks(A.chunks, n-i+1, B.chunks, 1, i) return A end @@ -1262,8 +1253,8 @@ function rotr(B::BitVector, i::Integer) i %= n if i == 0; return copy(B); end A = BitArray(n); - _jl_copy_chunks(A.chunks, i+1, B.chunks, 1, n-i) - _jl_copy_chunks(A.chunks, 1, B.chunks, n-i+1, i) + copy_chunks(A.chunks, i+1, B.chunks, 1, n-i) + copy_chunks(A.chunks, 1, B.chunks, n-i+1, i) return A end @@ -1292,7 +1283,7 @@ function findfirst(B::BitArray) end # aux function: same as findfirst(~B), but performed without temporaries -function _jl_findfirstnot(B::BitArray) +function findfirstnot(B::BitArray) Bc = B.chunks l = length(Bc) if l == 0 @@ -1313,7 +1304,7 @@ end # returns the index of the first matching element function findfirst(B::BitArray, v) if v == false - return _jl_findfirstnot(B) + return findfirstnot(B) elseif v == true return findfirst(B) else @@ -1332,7 +1323,7 @@ function findfirst(testf::Function, B::BitArray) elseif !f0 && f1 return findfirst(B) else - return _jl_findfirstnot(B) + return findfirstnot(B) end end @@ -1406,7 +1397,7 @@ nonzeros(B::BitArray) = trues(nnz(B)) ## Reductions ## -sum(A::BitArray, region::Dimspec) = areduce(+,A,region,0,Array(Int,reduced_dims(A,region))) +sum(A::BitArray, region) = areduce(+,A,region,0,Array(Int,reduced_dims(A,region))) sum(B::BitArray) = nnz(B) @@ -1495,23 +1486,20 @@ transpose(B::BitVector) = reshape(copy(B), 1, length(B)) # fast 8x8 bit transpose from Henry S. Warrens's "Hacker's Delight" # http://www.hackersdelight.org/HDcode/transpose8.c.txt -# implemented as a macro to improve performance -macro _jl_transpose8x8(x) - quote - y = $(esc(x)) - t = (y $ (y >>> 7)) & 0x00aa00aa00aa00aa; - y = y $ t $ (t << 7) - t = (y $ (y >>> 14)) & 0x0000cccc0000cccc - y = y $ t $ (t << 14) - t = (y $ (y >>> 28)) & 0x00000000f0f0f0f0 - $(esc(x)) = y $ t $ (t << 28) - end +function transpose8x8(x::Uint64) + y = x + t = (y $ (y >>> 7)) & 0x00aa00aa00aa00aa + y = y $ t $ (t << 7) + t = (y $ (y >>> 14)) & 0x0000cccc0000cccc + y = y $ t $ (t << 14) + t = (y $ (y >>> 28)) & 0x00000000f0f0f0f0 + return y $ t $ (t << 28) end -function _jl_form_8x8_chunk(B::BitMatrix, i1::Int, i2::Int, m::Int, cgap::Int, cinc::Int, nc::Int, msk8::Uint64) +function form_8x8_chunk(B::BitMatrix, i1::Int, i2::Int, m::Int, cgap::Int, cinc::Int, nc::Int, msk8::Uint64) x = uint64(0) - k, l = _jl_get_chunks_id(i1 + (i2 - 1) * m) + k, l = get_chunks_id(i1 + (i2 - 1) * m) r = 0 for j = 1 : 8 if k > nc @@ -1530,8 +1518,8 @@ function _jl_form_8x8_chunk(B::BitMatrix, i1::Int, i2::Int, m::Int, cgap::Int, c end # note: assumes B is filled with 0's -function _jl_put_8x8_chunk(B::BitMatrix, i1::Int, i2::Int, x::Uint64, m::Int, cgap::Int, cinc::Int, nc::Int, msk8::Uint64) - k, l = _jl_get_chunks_id(i1 + (i2 - 1) * m) +function put_8x8_chunk(B::BitMatrix, i1::Int, i2::Int, x::Uint64, m::Int, cgap::Int, cinc::Int, nc::Int, msk8::Uint64) + k, l = get_chunks_id(i1 + (i2 - 1) * m) r = 0 for j = 1 : 8 if k > nc @@ -1570,15 +1558,15 @@ function transpose(B::BitMatrix) end for j = 1 : 8 : l2 - x = _jl_form_8x8_chunk(B, i, j, l1, cgap1, cinc1, nc, msk8_1) - @_jl_transpose8x8 x + x = form_8x8_chunk(B, i, j, l1, cgap1, cinc1, nc, msk8_1) + x = transpose8x8(x) msk8_2 = uint64(0xff) if (l2 < j + 7) msk8_2 >>>= j + 7 - l2 end - _jl_put_8x8_chunk(Bt, j, i, x, l2, cgap2, cinc2, nc, msk8_2) + put_8x8_chunk(Bt, j, i, x, l2, cgap2, cinc2, nc, msk8_2) end end return Bt @@ -1666,7 +1654,7 @@ function hcat(B::BitVector...) end M = BitArray(height, length(B)) for j = 1:length(B) - _jl_copy_chunks(M.chunks, (height*(j-1))+1, B[j].chunks, 1, height) + copy_chunks(M.chunks, (height*(j-1))+1, B[j].chunks, 1, height) end return M end @@ -1679,7 +1667,7 @@ function vcat(V::BitVector...) B = BitArray(n) j = 1 for Vk in V - _jl_copy_chunks(B.chunks, j, Vk.chunks, 1, length(Vk)) + copy_chunks(B.chunks, j, Vk.chunks, 1, length(Vk)) j += length(Vk) end return B @@ -1703,7 +1691,7 @@ function hcat(A::Union(BitMatrix,BitVector)...) for k=1:nargs Ak = A[k] n = numel(Ak) - _jl_copy_chunks(B.chunks, pos, Ak.chunks, 1, n) + copy_chunks(B.chunks, pos, Ak.chunks, 1, n) pos += n end return B @@ -1722,7 +1710,7 @@ function vcat(A::BitMatrix...) pos_s = ones(Int, nargs) for j = 1:ncols for k=1:nargs - _jl_copy_chunks(B.chunks, pos_d, A[k].chunks, pos_s[k], nrowsA[k]) + copy_chunks(B.chunks, pos_d, A[k].chunks, pos_s[k], nrowsA[k]) pos_s[k] += nrowsA[k] pos_d += nrowsA[k] end diff --git a/base/blas.jl b/base/blas.jl index 4339d7f8843c8..c1a99f805f41b 100644 --- a/base/blas.jl +++ b/base/blas.jl @@ -1,4 +1,13 @@ -typealias LapackType Union(Float64,Float32,Complex128,Complex64) +typealias BlasFloat Union(Float64,Float32,Complex128,Complex64) +typealias BlasChar Char + +if USE_LIB64 + typealias BlasInt Int64 + blas_int(x) = int64(x) +else + typealias BlasInt Int32 + blas_int(x) = int32(x) +end module BLAS @@ -25,13 +34,18 @@ export copy!, const libblas = Base.libblas_name +import Base.BlasFloat +import Base.BlasChar +import Base.BlasInt +import Base.blas_int + # SUBROUTINE DCOPY(N,DX,INCX,DY,INCY) for (fname, elty) in ((:dcopy_,:Float64), (:scopy_,:Float32), (:zcopy_,:Complex128), (:ccopy_,:Complex64)) @eval begin function copy!(n::Integer, DX::Union(Ptr{$elty},Array{$elty}), incx::Integer, DY::Union(Ptr{$elty},Array{$elty}), incy::Integer) ccall(($(string(fname)),libblas), Void, - (Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), &n, DX, &incx, DY, &incy) DY end @@ -44,20 +58,23 @@ for (fname, elty) in ((:dscal_,:Float64), (:sscal_,:Float32), @eval begin function scal!(n::Integer, DA::$elty, DX::Union(Ptr{$elty},Array{$elty}), incx::Integer) ccall(($(string(fname)),libblas), Void, - (Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &n, &DA, DX, &incx) DX end function scal(n::Integer, DA::$elty, DX_orig::Union(Ptr{$elty},Array{$elty}), incx::Integer) DX = copy(DX_orig) ccall(($(string(fname)),libblas), Void, - (Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &n, &DA, DX, &incx) DX end end end +scal!(A::Array, DA) = scal!(length(A), DA, A, 1) +scal(A::Array, DA) = scal(length(A), DA, A, 1) + # ccall is unable to return complex values (Issue #85) #@blas_dot :zdotc_ Complex128 #@blas_dot :cdotc_ Complex64 @@ -66,7 +83,7 @@ for (fname, elty) in ((:ddot_,:Float64), (:sdot_,:Float32)) @eval begin function dot(n::Integer, DX::Union(Ptr{$elty},Array{$elty}), incx::Integer, DY::Union(Ptr{$elty},Array{$elty}), incy::Integer) ccall(($(string(fname)),libblas), $elty, - (Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), &n, DX, &incx, DY, &incy) end end @@ -80,12 +97,14 @@ for (fname, elty, ret_type) in ((:dnrm2_,:Float64,:Float64), @eval begin function nrm2(n::Integer, X::Union(Ptr{$elty},Array{$elty}), incx::Integer) ccall(($(string(fname)),libblas), $ret_type, - (Ptr{Int32}, Ptr{$elty}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), &n, X, &incx) end end end +nrm2(A::Array) = nrm2(length(A), A, 1) + # SUBROUTINE DAXPY(N,DA,DX,INCX,DY,INCY) # DY <- DA*DX + DY #* .. Scalar Arguments .. @@ -100,7 +119,7 @@ for (fname, elty) in ((:daxpy_,:Float64), (:saxpy_,:Float32), dx::Union(Ptr{$elty},Array{$elty}), incx::Integer, dy::Union(Ptr{$elty},Array{$elty}), incy::Integer) ccall(($(string(fname)),libblas), Void, - (Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), &n, &alpha, dx, &incx, dy, &incy) return dy end @@ -139,7 +158,7 @@ end for (fname, elty) in ((:dsyrk_,:Float64), (:ssyrk_,:Float32), (:zsyrk_,:Complex128), (:csyrk_,:Complex64)) @eval begin - function syrk!(uplo, trans, alpha::($elty), A::StridedVecOrMat{$elty}, + function syrk!(uplo::BlasChar, trans::BlasChar, alpha::($elty), A::StridedVecOrMat{$elty}, beta::($elty), C::StridedMatrix{$elty}) m, n = size(C) if m != n error("syrk!: matrix C must be square") end @@ -147,18 +166,18 @@ for (fname, elty) in ((:dsyrk_,:Float64), (:ssyrk_,:Float32), if nn != n error("syrk!: dimension mismatch") end k = size(A, trans == 'N' ? 2 : 1) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &trans, &n, &k, &alpha, A, &stride(A,2), &beta, C, &stride(C,2)) C end - function syrk(uplo, trans, alpha::($elty), A::StridedVecOrMat{$elty}) + function syrk(uplo::BlasChar, trans::BlasChar, alpha::($elty), A::StridedVecOrMat{$elty}) n = size(A, trans == 'N' ? 1 : 2) k = size(A, trans == 'N' ? 2 : 1) C = Array($elty, (n, n)) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &trans, &n, &k, &alpha, A, &stride(A,2), &0., C, &stride(C,2)) C end @@ -175,7 +194,7 @@ end # COMPLEX A(LDA,*),C(LDC,*) for (fname, elty) in ((:zherk_,:Complex128), (:cherk_,:Complex64)) @eval begin - function herk!(uplo, trans, alpha::($elty), A::StridedVecOrMat{$elty}, + function herk!(uplo::BlasChar, trans, alpha::($elty), A::StridedVecOrMat{$elty}, beta::($elty), C::StridedMatrix{$elty}) m, n = size(C) if m != n error("syrk!: matrix C must be square") end @@ -183,18 +202,18 @@ for (fname, elty) in ((:zherk_,:Complex128), (:cherk_,:Complex64)) if nn != n error("syrk!: dimension mismatch") end k = size(A, trans == 'N' ? 2 : 1) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &trans, &n, &k, &alpha, A, &stride(A,2), &beta, C, &stride(C,2)) C end - function herk(uplo, trans, alpha::($elty), A::StridedVecOrMat{$elty}) + function herk(uplo::BlasChar, trans, alpha::($elty), A::StridedVecOrMat{$elty}) n = size(A, trans == 'N' ? 1 : 2) k = size(A, trans == 'N' ? 2 : 1) C = Array($elty, (n, n)) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &trans, &n, &k, &alpha, A, &stride(A,2), &0., C, &stride(C,2)) C end @@ -213,25 +232,25 @@ end for (fname, elty) in ((:dgbmv_,:Float64), (:sgbmv_,:Float32), (:zgbmv_,:Complex128), (:cgbmv_,:Complex64)) @eval begin - function gbmv!(trans, m::Integer, kl::Integer, ku::Integer, + function gbmv!(trans::BlasChar, m::Integer, kl::Integer, ku::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}, beta::($elty), y::StridedVector{$elty}) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &trans, &m, &size(A,2), &kl, &ku, &alpha, A, &stride(A,2), x, &stride(x,1), &beta, y, &stride(y,1)) y end - function gbmv(trans, m::Integer, kl::Integer, ku::Integer, + function gbmv(trans::BlasChar, m::Integer, kl::Integer, ku::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}) n = stride(A,2) y = Array($elty, n) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &trans, &m, &n, &kl, &ku, &alpha, A, &stride(A,2), x, &stride(x,1), &0., y, &1) y @@ -252,22 +271,22 @@ end for (fname, elty) in ((:dsbmv_,:Float64), (:ssbmv_,:Float32), (:zsbmv_,:Complex128), (:csbmv_,:Complex64)) @eval begin - function sbmv!(uplo, k::Integer, + function sbmv!(uplo::BlasChar, k::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}, beta::($elty), y::StridedVector{$elty}) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &size(A,2), &k, &alpha, A, &stride(A,2), x, &stride(x,1), &beta, y, &stride(y,1)) y end - function sbmv(uplo, k::Integer, alpha::($elty), A::StridedMatrix{$elty}, + function sbmv(uplo::BlasChar, k::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}) n = size(A,2) y = Array($elty, n) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &size(A,2), &k, &alpha, A, &stride(A,2), x, &stride(x,1), &0., y, &1) y end @@ -285,30 +304,30 @@ end for (fname, elty) in ((:dgemm_,:Float64), (:sgemm_,:Float32), (:zgemm_,:Complex128), (:cgemm_,:Complex64)) @eval begin - function gemm!(transA, transB, alpha::($elty), A::StridedMatrix{$elty}, + function gemm!(transA::BlasChar, transB::BlasChar, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}, beta::($elty), C::StridedMatrix{$elty}) m = size(A, transA == 'N' ? 1 : 2) k = size(A, transA == 'N' ? 2 : 1) n = size(B, transB == 'N' ? 2 : 1) if m != size(C,1) || n != size(C,2) error("gemm!: mismatched dimensions") end ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &transA, &transB, &m, &n, &k, &alpha, A, &stride(A,2), B, &stride(B,2), &beta, C, &stride(C,2)) C end - function gemm(transA, transB, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) + function gemm(transA::BlasChar, transB::BlasChar, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) m = size(A, transA == 'N' ? 1 : 2) k = size(A, transA == 'N' ? 2 : 1) if k != size(B, transB == 'N' ? 1 : 2) error("gemm!: mismatched dimensions") end n = size(B, transB == 'N' ? 2 : 1) C = Array($elty, (m, n)) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &transA, &transB, &m, &n, &k, &alpha, A, &stride(A,2), B, &stride(B,2), &0., C, &stride(C,2)) C @@ -327,20 +346,20 @@ end for (fname, elty) in ((:dgemv_,:Float64), (:sgemv_,:Float32), (:zgemv_,:Complex128), (:cgemv_,:Complex64)) @eval begin - function gemv!(trans, alpha::($elty), A::StridedMatrix{$elty}, + function gemv!(trans::BlasChar, alpha::($elty), A::StridedMatrix{$elty}, X::StridedVector{$elty}, beta::($elty), Y::StridedVector{$elty}) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &trans, &size(A,1), &size(A,2), &alpha, A, &stride(A,2), X, &stride(X,1), &beta, Y, &stride(Y,1)) Y end - function gemv!(trans, alpha::($elty), A::StridedMatrix{$elty}, X::StridedVector{$elty}) + function gemv!(trans::BlasChar, alpha::($elty), A::StridedMatrix{$elty}, X::StridedVector{$elty}) Y = Array($elty, size(A,1)) ccall(($(string(fname)),libblas), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &trans, &size(A,1), &size(A,2), &alpha, A, &stride(A,2), X, &stride(X,1), &0., Y, &1) Y @@ -372,21 +391,21 @@ for (vfname, mfname, elty) in (:zsymv_,:zsymm_,:Complex128), (:csymv_,:csymm_,:Complex64)) @eval begin - function symv!(uplo, alpha::($elty), A::StridedMatrix{$elty}, X::StridedVector{$elty}, + function symv!(uplo::BlasChar, alpha::($elty), A::StridedMatrix{$elty}, X::StridedVector{$elty}, beta::($elty), Y::StridedVector{$elty}) m, n = size(A) if m != n error("symm!: matrix A is $m by $n but must be square") end if m != length(X) || m != length(Y) error("symm!: dimension mismatch") end ccall(($(string(vfname)),libblas), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &n, &alpha, A, &stride(A,2), X, &stride(X,1), &beta, Y, &stride(Y,1)) Y end - function symv(uplo, alpha::($elty), A::StridedMatrix{$elty}, X::StridedVector{$elty}) + function symv(uplo::BlasChar, alpha::($elty), A::StridedMatrix{$elty}, X::StridedVector{$elty}) symv!(uplo, alpha, A, X, zero($elty), similar(X)) end - function symm!(side, uplo, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}, + function symm!(side::BlasChar, uplo::BlasChar, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}, beta::($elty), C::StridedMatrix{$elty}) side = uppercase(convert(Char, side)) m, n = size(C) @@ -394,13 +413,13 @@ for (vfname, mfname, elty) in if k != j error("symm!: matrix A is $k by $j but must be square") end if j != (side == 'L' ? m : n) || size(B,2) != n error("symm!: Dimension mismatch") end ccall(($(string(mfname)),libblas), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), &side, &uplo, &m, &n, &alpha, A, &stride(A,2), B, &stride(B,2), &beta, C, &stride(C,2)) C end - function symm(side, uplo, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) + function symm(side::BlasChar, uplo::BlasChar, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) symm!(side, uplo, alpha, A, B, zero($elty), similar(B)) end end @@ -410,7 +429,7 @@ end # module # Use BLAS copy for small arrays where it is faster than memcpy, and for strided copying -function copy_to{T<:LapackType}(dest::Ptr{T}, src::Ptr{T}, n::Integer) +function copy_to{T<:BlasFloat}(dest::Ptr{T}, src::Ptr{T}, n::Integer) if n < 200 BLAS.copy!(n, src, 1, dest, 1) else @@ -419,14 +438,14 @@ function copy_to{T<:LapackType}(dest::Ptr{T}, src::Ptr{T}, n::Integer) return dest end -function copy_to{T<:LapackType}(dest::Array{T}, src::Array{T}) +function copy_to{T<:BlasFloat}(dest::Array{T}, src::Array{T}) n = numel(src) if n > numel(dest); throw(BoundsError()); end copy_to(pointer(dest), pointer(src), n) return dest end -function copy_to{T<:LapackType,Ti<:Integer}(dest::Array{T}, rdest::Union(Range1{Ti},Range{Ti}), +function copy_to{T<:BlasFloat,Ti<:Integer}(dest::Array{T}, rdest::Union(Range1{Ti},Range{Ti}), src::Array{T}, rsrc::Union(Range1{Ti},Range{Ti})) if min(rdest) < 1 || max(rdest) > length(dest) || min(rsrc) < 1 || max(rsrc) > length(src) throw(BoundsError()) diff --git a/base/boot.jl b/base/boot.jl index d21a7dbfb8cb8..916a73d61046c 100644 --- a/base/boot.jl +++ b/base/boot.jl @@ -118,26 +118,37 @@ import Main import Intrinsics.ccall -export ..., ANY, ASCIIString, AbstractArray, AbstractKind, Any, Array, - BitsKind, Bool, BoundsError, Box, ByteString, Char, CompositeKind, - Main, DirectIndexString, DivideByZeroError, DomainError, EOFError, - Exception, Expr, FloatingPoint, Float32, Float64, Function, GotoNode, IOError, - InexactError, Integer, Int, Int8, Int16, Int32, Int64, Int128, - InterruptException, - IntrinsicFunction, LabelNode, LambdaStaticData, LineNumberNode, - MemoryError, Method, MethodTable, Module, NTuple, None, Nothing, Number, - OverflowError, Ptr, QuoteNode, Real, Signed, StackOverflowError, String, - Symbol, SymbolNode, Task, Top, TopNode, Tuple, Type, TypeConstructor, - TypeName, TypeVar, UTF8String, Uint, Uint8, Uint16, Uint32, Uint64, Uint128, - UndefRefError, Union, UnionKind, Unsigned, Void, +export + # key types + AbstractKind, Any, BitsKind, CompositeKind, ..., ANY, NTuple, None, Top, + Tuple, Type, TypeConstructor, TypeName, TypeVar, Union, UnionKind, Void, + AbstractArray, + # special objects + Box, Function, IntrinsicFunction, LambdaStaticData, Method, MethodTable, + Module, Nothing, Symbol, Task, Array, + # numeric types + Bool, FloatingPoint, Float32, Float64, Number, Integer, Int, Int8, Int16, + Int32, Int64, Int128, Ptr, Real, Signed, Uint, Uint8, Uint16, Uint32, + Uint64, Uint128, Unsigned, + # string types + Char, ASCIIString, ByteString, DirectIndexString, String, UTF8String, + # errors + BoundsError, DivideByZeroError, DomainError, EOFError, Exception, + IOError, InexactError, InterruptException, MemoryError, OverflowError, + StackOverflowError, UndefRefError, + # AST representation + Expr, GotoNode, LabelNode, LineNumberNode, QuoteNode, SymbolNode, TopNode, GetfieldNode, - # functions - setfield, applicable, apply, apply_type, arraylen, arrayref, arrayset, - arraysize, convert_default, convert_tuple, fieldtype, getfield, - include, invoke, is, ===, isa, isdefined, method_exists, - subtype, throw, tuple, tuplelen, tupleref, typeassert, typeof, yieldto, + # object model functions + apply, arraylen, arrayref, arrayset, arraysize, fieldtype, getfield, + setfield, yieldto, throw, tuple, tuplelen, tupleref, is, ===, isdefined, + convert_default, convert_tuple, + # type reflection + subtype, typeassert, typeof, apply_type, isa, + # method reflection + applicable, invoke, method_exists, # constants - JULIA_HOME, nothing, + JULIA_HOME, nothing, Main, # intrinsics module Intrinsics #ccall, abs_float, add_float, add_int, and_int, ashr_int, diff --git a/base/char.jl b/base/char.jl index fb7ea1b975e17..1526e8427c1d6 100644 --- a/base/char.jl +++ b/base/char.jl @@ -42,20 +42,10 @@ promote_rule(::Type{Char}, ::Type{Uint128}) = Uint128 ## character operations & comparisons ## --(x::Char) = -int(x) -+(x::Char, y::Char) = int(x) + int(y) --(x::Char, y::Char) = int(x) - int(y) -*(x::Char, y::Char) = int(x) * int(y) - -div(x::Char, y::Char) = div(int(x), int(y)) -fld(x::Char, y::Char) = div(int(x), int(y)) -rem(x::Char, y::Char) = rem(int(x), int(y)) -mod(x::Char, y::Char) = rem(int(x), int(y)) - -~(x::Char) = ~uint32(x) -(&)(x::Char, y::Char) = uint32(x) & uint32(y) -|(x::Char, y::Char) = uint32(x) | uint32(y) -($)(x::Char, y::Char) = uint32(x) $ uint32(y) +-(x::Char, y::Char) = int(x)-int(y) ++(x::Char, y::Char) = char(int(x)+int(y)) # TODO: delete me ++(x::Char, y::Int ) = char(int(x)+y) ++(x::Int , y::Char) = y+x <<(x::Char, y::Int32) = uint32(x) << y >>(x::Char, y::Int32) = uint32(x) >>> y diff --git a/base/client.jl b/base/client.jl index 4dc82a656de16..4fb180133735c 100644 --- a/base/client.jl +++ b/base/client.jl @@ -1,9 +1,9 @@ ## client.jl - frontend handling command line options, environment setup, ## and REPL -const _jl_color_normal = "\033[0m" +const color_normal = "\033[0m" -function _jl_answer_color() +function answer_color() c = get(ENV, "JL_ANSWER_COLOR", "") return c == "black" ? "\033[1m\033[30m" : c == "red" ? "\033[1m\033[31m" : @@ -12,12 +12,11 @@ function _jl_answer_color() c == "magenta" ? "\033[1m\033[35m" : c == "cyan" ? "\033[1m\033[36m" : c == "white" ? "\033[1m\033[37m" : - c == "normal" ? _jl_color_normal : + c == "normal" ? color_normal : "\033[1m\033[34m" end - -_jl_banner() = print(_jl_have_color ? _jl_banner_color : _jl_banner_plain) +banner() = print(have_color ? banner_color : banner_plain) exit(n) = ccall(:jl_exit, Void, (Int32,), n) @@ -29,7 +28,7 @@ function repl_callback(ast::ANY, show_value) global _repl_enough_stdin = true stop_reading(STDIN) STDIN.readcb = false - put(_jl_repl_channel, (ast, show_value)) + put(repl_channel, (ast, show_value)) end # called to show a REPL result @@ -64,13 +63,12 @@ function add_backtrace(e, bt) end end -function _jl_eval_user_input(ast::ANY, show_value) +function eval_user_input(ast::ANY, show_value) iserr, lasterr, bt = false, (), nothing while true try - ccall(:restore_signals, Void, ()) - if _jl_have_color - print(_jl_color_normal) + if have_color + print(color_normal) end if iserr show(add_backtrace(lasterr,bt)) @@ -80,8 +78,8 @@ function _jl_eval_user_input(ast::ANY, show_value) value = eval(Main,ast) global ans = value if !is(value,nothing) && show_value - if _jl_have_color - print(_jl_answer_color()) + if have_color + print(answer_color()) end try repl_show(value) catch err @@ -126,28 +124,31 @@ function readBuffer(stream::TTY, nread) end function run_repl() - global const _jl_repl_channel = RemoteRef() + global const repl_channel = RemoteRef() - if _jl_have_color + if have_color ccall(:jl_enable_color, Void, ()) end atexit() do - if _jl_have_color - print(_jl_color_normal) + if have_color + print(color_normal) end println() end + # install Ctrl-C interrupt handler (InterruptException) + ccall(:jl_install_sigint_handler, Void, ()) + while true ccall(:repl_callback_enable, Void, ()) global _repl_enough_stdin = false start_reading(STDIN, readBuffer) - (ast, show_value) = take(_jl_repl_channel) + (ast, show_value) = take(repl_channel) if show_value == -1 # exit flag break end - _jl_eval_user_input(ast, show_value!=0) + eval_user_input(ast, show_value!=0) end end @@ -173,8 +174,6 @@ end function process_options(args::Array{Any,1}) global ARGS - # install Ctrl-C interrupt handler (InterruptException) - ccall(:jl_install_sigint_handler, Void, ()) quiet = false repl = true startup = true @@ -242,16 +241,16 @@ function process_options(args::Array{Any,1}) return (quiet,repl,startup) end -const _jl_roottask = current_task() -const _jl_roottask_wi = WorkItem(_jl_roottask) +const roottask = current_task() +const roottask_wi = WorkItem(roottask) -_jl_is_interactive = false -isinteractive() = (_jl_is_interactive::Bool) +is_interactive = false +isinteractive() = (is_interactive::Bool) -@unix_only julia_pkgdir() = abs_path(get(ENV,"JULIA_PKGDIR",string(ENV["HOME"],"/.julia"))) +@unix_only julia_pkgdir() = abspath(get(ENV,"JULIA_PKGDIR",string(ENV["HOME"],"/.julia"))) @windows_only begin const JULIA_USER_DATA_DIR = string(ENV["AppData"],"/julia") - julia_pkgdir() = abs_path(get(ENV,"JULIA_PKGDIR",string(JULIA_USER_DATA_DIR,"/packages"))) + julia_pkgdir() = abspath(get(ENV,"JULIA_PKGDIR",string(JULIA_USER_DATA_DIR,"/packages"))) end function _start() @@ -281,17 +280,17 @@ function _start() push(PGRP.locs,Location("",0)) PGRP.np = 1 # make scheduler aware of current (root) task - enq_work(_jl_roottask_wi) + enq_work(roottask_wi) yield() end global const LOAD_PATH = ByteString[ ".", julia_pkgdir(), - abs_path("$JULIA_HOME/../share/julia"), - abs_path("$JULIA_HOME/../share/julia/base"), - abs_path("$JULIA_HOME/../share/julia/extras"), - abs_path("$JULIA_HOME/../share/julia/ui"), + abspath("$JULIA_HOME/../share/julia"), + abspath("$JULIA_HOME/../share/julia/base"), + abspath("$JULIA_HOME/../share/julia/extras"), + abspath("$JULIA_HOME/../share/julia/ui"), ] (quiet,repl,startup) = process_options(ARGS) @@ -301,12 +300,12 @@ function _start() try_include(strcat(ENV["HOME"],"/.juliarc.jl")) end - @unix_only global _jl_have_color = begins_with(get(ENV,"TERM",""),"xterm") || + @unix_only global have_color = begins_with(get(ENV,"TERM",""),"xterm") || success(`tput setaf 0`) @windows_only global _jl_have_color = true - global _jl_is_interactive = true + global is_interactive = true if !quiet - _jl_banner() + banner() end run_repl() end @@ -318,12 +317,12 @@ function _start() exit(0) #HACK: always exit using jl_exit end -const _jl_atexit_hooks = {} +const atexit_hooks = {} -atexit(f::Function) = (enqueue(_jl_atexit_hooks, f); nothing) +atexit(f::Function) = (enqueue(atexit_hooks, f); nothing) function _atexit() - for f in _jl_atexit_hooks + for f in atexit_hooks try f() catch err diff --git a/base/combinatorics.jl b/base/combinatorics.jl index 26ff247dd3af2..2d6e24cd19198 100644 --- a/base/combinatorics.jl +++ b/base/combinatorics.jl @@ -1,3 +1,5 @@ +import Sort.@in_place_matrix_op + function factorial(n::Integer) if n < 0 return zero(n) diff --git a/base/complex.jl b/base/complex.jl index 006cb1bd45be1..c9fdf915c9b54 100644 --- a/base/complex.jl +++ b/base/complex.jl @@ -14,7 +14,7 @@ imag(x::Real) = zero(x) isfinite(z::Complex) = isfinite(real(z)) && isfinite(imag(z)) reim(z) = (real(z), imag(z)) -function _jl_show(io, z::Complex, compact::Bool) +function complex_show(io, z::Complex, compact::Bool) r, i = reim(z) if isnan(r) || isfinite(i) compact ? showcompact(io,r) : show(io,r) @@ -34,8 +34,8 @@ function _jl_show(io, z::Complex, compact::Bool) print(io, "complex(",r,",",i,")") end end -show(io, z::Complex) = _jl_show(io, z, false) -showcompact(io, z::Complex) = _jl_show(io, z, true) +show(io, z::Complex) = complex_show(io, z, false) +showcompact(io, z::Complex) = complex_show(io, z, true) convert{T<:Real}(::Type{T}, z::Complex) = (imag(z)==0 ? convert(T,real(z)) : throw(InexactError())) @@ -254,15 +254,14 @@ end function sqrt(z::Complex) rz = float(real(z)) iz = float(imag(z)) - T = promote_type(typeof(rz),typeof(z)) - r = sqrt(0.5*(hypot(rz,iz)+abs(rz))) + r = sqrt((hypot(rz,iz)+abs(rz))/2) if r == 0 - return convert(T,complex(0.0, iz)) + return complex(zero(iz), iz) end if rz >= 0 - return convert(T,complex(r, 0.5*iz/r)) + return complex(r, iz/r/2) end - return convert(T,complex(0.5*abs(iz)/r, iz >= 0 ? r : -r)) + return complex(abs(iz)/r/2, iz >= 0 ? r : -r) end cis(theta::Real) = complex(cos(theta),sin(theta)) diff --git a/base/darray.jl b/base/darray.jl index dcaf753e0149d..c447101557908 100644 --- a/base/darray.jl +++ b/base/darray.jl @@ -174,7 +174,7 @@ function localize_copy(src::SubDArray, dest::DArray) end # piece numbers covered by a subarray -function _jl_sub_da_pieces(s::SubDArray) +function sub_da_pieces(s::SubDArray) dd = s.parent.distdim sdi = s.indexes[dd] if isa(sdi,Integer) @@ -189,10 +189,10 @@ function _jl_sub_da_pieces(s::SubDArray) return lo:hi end -procs(s::SubDArray) = s.parent.pmap[_jl_sub_da_pieces(s)] +procs(s::SubDArray) = s.parent.pmap[sub_da_pieces(s)] function dist(s::SubDArray) - pcs = _jl_sub_da_pieces(s) + pcs = sub_da_pieces(s) sizes = [ length(pieceindex(s, p)) for p = pcs ] cumsum([1, sizes]) end @@ -347,12 +347,12 @@ function distribute{T}(a::Array{T}, distdim) # create a remotely-visible reference to the array rr = RemoteRef() put(rr, a) - darray((T,lsz,da)->_jl_distribute_one(T,lsz,da,distdim,owner,rr), + darray((T,lsz,da)->distribute_one(T,lsz,da,distdim,owner,rr), T, size(a), distdim) end # fetch one processor's piece of an array being distributed -function _jl_distribute_one(T, lsz, da, distdim, owner, orig_array) +function distribute_one(T, lsz, da, distdim, owner, orig_array) if prod(lsz)==0 return Array(T, lsz) end @@ -391,7 +391,7 @@ function changedist{T}(A::DArray{T}, to_dist) return darray((T,sz,da)->A[myindexes(da)...], T, size(A), to_dist, A.pmap) end -function _jl_da_reshape(T, sz, da, A) +function da_reshape(T, sz, da, A) mi = myindexes(da) i0s = map(first, mi) i1s = map(last, mi) @@ -405,7 +405,7 @@ function reshape(A::DArray, dims::Dims) if prod(dims) != numel(A) error("reshape: invalid dimensions") end - darray((T,sz,da)->_jl_da_reshape(T,sz,da,A), + darray((T,sz,da)->da_reshape(T,sz,da,A), eltype(A), dims, maxdim(dims), A.pmap) end @@ -473,7 +473,7 @@ ref(d::DArray, I::Int...) = ref_elt(d, I) ref(d::DArray) = d -function _jl_da_sub(d::DArray, I::Range1{Int}...) +function da_sub(d::DArray, I::Range1{Int}...) offs = d.dist[d.localpiece]-1 J = ntuple(ndims(d), i -> (i == d.distdim ? I[i]-offs : I[i])) @@ -495,9 +495,9 @@ function ref{T}(d::DArray{T}, I::Range1{Int}...) K = [ i==d.distdim ? (dist[p]:(dist[p+1]-1)) : I[i] for i=1:ndims(d) ] if np == 1 # use remote_call_fetch if we only need to communicate with 1 proc - deps[p] = remote_call_fetch(d.pmap[pmap[p]], _jl_da_sub, d, K...) + deps[p] = remote_call_fetch(d.pmap[pmap[p]], da_sub, d, K...) else - deps[p] = remote_call(d.pmap[pmap[p]], _jl_da_sub, d, K...) + deps[p] = remote_call(d.pmap[pmap[p]], da_sub, d, K...) end end for p = 1:np @@ -690,7 +690,7 @@ assign(d::DArray, v, I::Union(Int,AbstractVector{Int})...) = ## matrix multiply ## -function _jl_node_multiply2{T}(A::AbstractArray{T}, B, sz) +function node_multiply2{T}(A::AbstractArray{T}, B, sz) locl = Array(T, sz) if !isempty(locl) Bdata = localize(B) @@ -710,16 +710,16 @@ function _jl_node_multiply2{T}(A::AbstractArray{T}, B, sz) end function (*){T}(A::DArray{T,2,1}, B::DArray{T,2,2}) - darray((T,sz,da)->_jl_node_multiply2(A,B,sz), T, (size(A,1),size(B,2)), 2, + darray((T,sz,da)->node_multiply2(A,B,sz), T, (size(A,1),size(B,2)), 2, B.pmap) end function (*){T}(A::DArray{T,2}, B::DArray{T,2,2}) - darray((T,sz,da)->_jl_node_multiply2(A,B,sz), T, (size(A,1),size(B,2)), 2, + darray((T,sz,da)->node_multiply2(A,B,sz), T, (size(A,1),size(B,2)), 2, B.pmap) end -function _jl_node_multiply1{T}(A::AbstractArray{T}, B, sz) +function node_multiply1{T}(A::AbstractArray{T}, B, sz) locl = Array(T, sz) if !isempty(locl) Adata = localize(A) @@ -739,7 +739,7 @@ function _jl_node_multiply1{T}(A::AbstractArray{T}, B, sz) end function (*){T}(A::DArray{T,2,1}, B::DArray{T,2}) - darray((T,sz,da)->_jl_node_multiply1(A,B,sz), T, (size(A,1),size(B,2)), 1, + darray((T,sz,da)->node_multiply1(A,B,sz), T, (size(A,1),size(B,2)), 1, A.pmap) end @@ -880,7 +880,7 @@ prod(d::DArray) = reduce(*, d) min(d::DArray) = reduce(min, d) max(d::DArray) = reduce(max, d) -areduce(f::Function, d::DArray, r::Dimspec, v0, T::Type) = error("not yet implemented") +areduce(f::Function, d::DArray, r, v0, T::Type) = error("not yet implemented") cumsum(d::DArray) = error("not yet implemented") cumprod(d::DArray) = error("not yet implemented") diff --git a/base/datafmt.jl b/base/datafmt.jl index f33327c78b28a..0f3fdca1d6f3e 100644 --- a/base/datafmt.jl +++ b/base/datafmt.jl @@ -1,13 +1,13 @@ ## file formats ## -const _jl_invalid_dlm = char(0xfffffffe) +const invalid_dlm = char(0xfffffffe) -function _jl_dlm_readrow(io::IO, dlm, eol::Char) +function dlm_readrow(io::IO, dlm, eol::Char) row_string = readuntil(io, eol) while length(row_string)==1 && row_string[1] == eol row_string = readuntil(io, eol) end - if dlm == _jl_invalid_dlm + if dlm == invalid_dlm row = split(row_string) else row = split(row_string, dlm, true) @@ -19,18 +19,18 @@ function _jl_dlm_readrow(io::IO, dlm, eol::Char) end # all strings -function _jl_dlmread(a, io, dlm, nr, nc, row, eol) +function dlmread(a, io, dlm, nr, nc, row, eol) for i=1:nr a[i,:] = row if i < nr - row = _jl_dlm_readrow(io, dlm, eol) + row = dlm_readrow(io, dlm, eol) end end a end # all numeric, with NaN for invalid data -function _jl_dlmread{T<:Number}(a::Array{T}, io, dlm, nr, nc, row, eol) +function dlmread{T<:Number}(a::Array{T}, io, dlm, nr, nc, row, eol) tmp = Array(Float64,1) for i=1:nr for j=1:nc @@ -41,15 +41,15 @@ function _jl_dlmread{T<:Number}(a::Array{T}, io, dlm, nr, nc, row, eol) end end if i < nr - row = _jl_dlm_readrow(io, dlm, eol) + row = dlm_readrow(io, dlm, eol) end end end # float64 or string -_jl_dlmread(a::Array{Any}, io, dlm, nr, nc, row, eol) = - _jl_dlmread(a, io, dlm, nr, nc, row, eol, 1, 1) -function _jl_dlmread(a::Array{Any}, io, dlm, nr, nc, row, eol, i0, j0) +dlmread(a::Array{Any}, io, dlm, nr, nc, row, eol) = + dlmread(a, io, dlm, nr, nc, row, eol, 1, 1) +function dlmread(a::Array{Any}, io, dlm, nr, nc, row, eol, i0, j0) tmp = Array(Float64,1) j = j0 for i=i0:nr @@ -64,28 +64,28 @@ function _jl_dlmread(a::Array{Any}, io, dlm, nr, nc, row, eol, i0, j0) end j = 1 if i < nr - row = _jl_dlm_readrow(io, dlm, eol) + row = dlm_readrow(io, dlm, eol) end end a end # float64 or cell depending on data -function _jl_dlmread_auto(a, io, dlm, nr, nc, row, eol) +function dlmread_auto(a, io, dlm, nr, nc, row, eol) tmp = Array(Float64, 1) for i=1:nr for j=1:nc el = row[j] if !float64_isvalid(el, tmp) a = convert(Array{Any,2}, a) - _jl_dlmread(a, io, dlm, nr, nc, row, eol, i, j) + dlmread(a, io, dlm, nr, nc, row, eol, i, j) return a else a[i,j] = tmp[1] end end if i < nr - row = _jl_dlm_readrow(io, dlm, eol) + row = dlm_readrow(io, dlm, eol) end end a @@ -121,36 +121,36 @@ function countlines(io::Stream, eol::Char) nl end -function _jl_dlmread_setup(fname::String, dlm, eol) +function dlmread_setup(fname::String, dlm, eol) if length(dlm) == 0 error("dlmread: no separator characters specified") end nr = countlines(fname,eol) io = open(fname) - row = _jl_dlm_readrow(io, dlm, eol) + row = dlm_readrow(io, dlm, eol) nc = length(row) return (io, nr, nc, row) end -dlmread(fname::String, T::Type) = dlmread(fname, _jl_invalid_dlm, T, '\n') +dlmread(fname::String, T::Type) = dlmread(fname, invalid_dlm, T, '\n') dlmread(fname::String, dlm, T::Type) = dlmread(fname, dlm, T, '\n') function dlmread(fname::String, dlm, T::Type, eol::Char) - (io, nr, nc, row) = _jl_dlmread_setup(fname, dlm, eol) + (io, nr, nc, row) = dlmread_setup(fname, dlm, eol) a = Array(T, nr, nc) - _jl_dlmread(a, io, dlm, nr, nc, row, eol) + dlmread(a, io, dlm, nr, nc, row, eol) close(io) return a end -dlmread(fname::String) = dlmread(fname, _jl_invalid_dlm, '\n') +dlmread(fname::String) = dlmread(fname, invalid_dlm, '\n') dlmread(fname::String, dlm) = dlmread(fname, dlm, '\n') function dlmread(fname::String, dlm, eol::Char) - (io, nr, nc, row) = _jl_dlmread_setup(fname, dlm, eol) + (io, nr, nc, row) = dlmread_setup(fname, dlm, eol) a = Array(Float64, nr, nc) - a = _jl_dlmread_auto(a, io, dlm, nr, nc, row, eol) + a = dlmread_auto(a, io, dlm, nr, nc, row, eol) close(io) return a end diff --git a/base/dict.jl b/base/dict.jl index cb249f65dbe88..cc25a79b7824d 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -2,10 +2,10 @@ abstract Associative{K,V} -const _jl_secret_table_token = :__c782dbf1cf4d6a2e5e3865d7e95634f2e09b5902__ +const secret_table_token = :__c782dbf1cf4d6a2e5e3865d7e95634f2e09b5902__ -has(t::Associative, key) = !is(get(t, key, _jl_secret_table_token), - _jl_secret_table_token) +has(t::Associative, key) = !is(get(t, key, secret_table_token), + secret_table_token) function show{K,V}(io, t::Associative{K,V}) if isempty(t) @@ -106,8 +106,8 @@ function _tablesz(i::Integer) end function ref(t::Associative, key) - v = get(t, key, _jl_secret_table_token) - if is(v,_jl_secret_table_token) + v = get(t, key, secret_table_token) + if is(v,secret_table_token) throw(KeyError(key)) end return v @@ -162,18 +162,18 @@ bitmix(a::Union(Int64,Uint64), b::Union(Int64, Uint64)) = shl_int(unbox(Uint64,b), 32)))) if WORD_SIZE == 64 - _jl_hash64(x::Float64) = + hash64(x::Float64) = ccall(:int64hash, Uint64, (Uint64,), box(Uint64,unbox(Float64,x))) - _jl_hash64(x::Union(Int64,Uint64)) = + hash64(x::Union(Int64,Uint64)) = ccall(:int64hash, Uint64, (Uint64,), x) else - _jl_hash64(x::Float64) = + hash64(x::Float64) = ccall(:int64to32hash, Uint32, (Uint64,), box(Uint64,unbox(Float64,x))) - _jl_hash64(x::Union(Int64,Uint64)) = + hash64(x::Union(Int64,Uint64)) = ccall(:int64to32hash, Uint32, (Uint64,), x) end -hash(x::Integer) = _jl_hash64(uint64(x)) +hash(x::Integer) = hash64(uint64(x)) @eval function hash(x::FloatingPoint) if trunc(x) == x # hash as integer if equal to some integer. note the result of @@ -189,7 +189,7 @@ hash(x::Integer) = _jl_hash64(uint64(x)) end end end - isnan(x) ? $(_jl_hash64(NaN)) : _jl_hash64(float64(x)) + isnan(x) ? $(hash64(NaN)) : hash64(float64(x)) end function hash(t::Tuple) @@ -316,6 +316,19 @@ function rehash{K,V}(h::Dict{K,V}, newsz) return h end +function resize(d::Dict, newsz) + oldsz = length(d.slots) + if newsz <= oldsz + # todo: shrink + # be careful: rehash() assumes everything fits. it was only designed + # for growing. + return d + end + # grow at least 25% + newsz = max(newsz, (oldsz*5)>>2) + rehash(d, newsz) +end + function del_all{K,V}(h::Dict{K,V}) fill!(h.slots, 0x0) sz = length(h.slots) @@ -328,6 +341,7 @@ end function assign{K,V}(h::Dict{K,V}, v, key) key = convert(K,key) + v = convert(V, v) sz = length(h.keys) @@ -502,8 +516,8 @@ WeakKeyDict() = WeakKeyDict{Any,Any}() assign{K}(wkh::WeakKeyDict{K}, v, key) = add_weak_key(wkh.ht, convert(K,key), v) function key{K}(wkh::WeakKeyDict{K}, kk, deflt) - k = key(wkh.ht, kk, _jl_secret_table_token) - if is(k, _jl_secret_table_token) + k = key(wkh.ht, kk, secret_table_token) + if is(k, secret_table_token) return deflt end return k.value::K diff --git a/base/export.jl b/base/export.jl index a12b42a824ca1..063c313e8e044 100644 --- a/base/export.jl +++ b/base/export.jl @@ -1,7 +1,6 @@ export # Modules Grisu, - Printf, PCRE, FFTW, DSP, @@ -10,6 +9,7 @@ export LibRandom, RNG, Math, + Sort, # Types AbstractMatrix, @@ -21,7 +21,6 @@ export BitMatrix, BitVector, CharString, - Chars, Cmd, Cmds, Colon, @@ -36,20 +35,17 @@ export EachSearch, Enumerate, EnvHash, - Executable, FDSet, FileDes, FileOffset, - Filter, + Filter, GenericString, IO, IOStream, IOString, ImaginaryUnit, - Indices, IntSet, LocalProcess, - Location, Matrix, ObjectIdDict, Pipe, @@ -74,7 +70,6 @@ export Regex, RegexMatch, RegexMatchIterator, - Dimspec, RemoteRef, RepString, RevString, @@ -394,6 +389,7 @@ export csc, cscd, csch, + dawson, degrees2radians, den, digamma, @@ -401,6 +397,8 @@ export eps, erf, erfc, + erfcx, + erfi, exp, exp2, expm1, @@ -592,6 +590,8 @@ export ipermute, isperm, issorted, + issorted_r, + issorted_by, last, linspace, logspace, @@ -620,10 +620,20 @@ export rotl90, rotr90, search_sorted, + search_sorted_r, + search_sorted_by, search_sorted_first, + search_sorted_first_r, + search_sorted_first_by, search_sorted_last, + search_sorted_last_r, + search_sorted_last_by, select, + select_r, + select_by, select!, + select_r!, + select_by!, shuffle, shuffle!, size, @@ -634,6 +644,7 @@ export sort_by, sort_by!, sortperm, + sortperm!, sortr, sortr!, squeeze, @@ -650,10 +661,19 @@ export findfirst, ref_shape, assign_shape_check, - indices, make_loop_nest, check_bounds, +# sort routines + insertionsort, + insertionsort!, + quicksort, + quicksort!, + mergesort, + mergesort!, + timsort, + timsort!, + # linear algebra axpy, chol, @@ -700,6 +720,8 @@ export randsym, rank, rref, + scale, + scale!, solve, svd, svdvals, @@ -788,6 +810,7 @@ export pairs, reduce, ref, + resize, similar, toggle, toggle_each, @@ -912,6 +935,7 @@ export base, # statistics and random numbers + autocor, betarnd, chi2rnd, cor, @@ -921,9 +945,13 @@ export cov_pearson, cov_spearman, decile, + dist, exprnd, hist, histc, + inverse_rle, + iqr, + kurtosis, mad, mean, median, @@ -951,12 +979,14 @@ export randival!, randn, randn!, + rle, + skewness, srand, std, tiedrank, var, weighted_mean, - + # signal processing bfft, bfftn, @@ -1067,8 +1097,10 @@ export # loading source files evalfile, find_in_path, + include, include_string, - load, + load, # deprecated + reload, require, julia_pkgdir, @@ -1078,7 +1110,6 @@ export gc, gc_disable, gc_enable, - isbuiltin, isconst, isgeneric, @@ -1194,23 +1225,23 @@ export dirname_basename, file_path, path_expand, - abs_path, + abspath, abs_path_split, split_extension, split_path, fileparts, - isrooted, + isabspath, tilde_expand, # filesystem operations cd, - cwd, + pwd, is_file_readable, ls, - file_copy, - file_remove, - file_create, - path_rename, + cp, + rm, + touch, + mv, mkdir, rmdir, tempdir, @@ -1218,7 +1249,6 @@ export mktemp, mktempdir, download_file, - realpath, filemode, filesize, mtime, @@ -1307,6 +1337,7 @@ export @cmd, @time, @elapsed, + @timed, @windows_only, @unix_only, @osx_only, diff --git a/base/fftw.jl b/base/fftw.jl index 92c57bec7a302..10a16a2d95b84 100644 --- a/base/fftw.jl +++ b/base/fftw.jl @@ -20,7 +20,7 @@ end const FORWARD = int32(-1) const BACKWARD = int32(1) -## _jl_FFTW Flags from fftw3.h +## FFTW Flags from fftw3.h const MEASURE = uint32(0) const DESTROY_INPUT = uint32(1 << 0) diff --git a/base/file.jl b/base/file.jl index 03a9da7ba966b..b45248c66c2c4 100644 --- a/base/file.jl +++ b/base/file.jl @@ -80,7 +80,7 @@ end const fullfile = file_path # Test for an absolute path -function isrooted(path::String) +function isabspath(path::String) # Check whether it begins with the os_separator. On Windows, matches # \\servername syntax, so this is a relevant check for everyone m = match(Regex(strcat("^", os_separator_match.pattern)), path) @@ -107,15 +107,15 @@ end error("~user tilde expansion not yet implemented") end -# Get the absolute path to a file. Uses file system for cwd() when +# Get the absolute path to a file. Uses file system for pwd() when # needed, the rest is all string manipulation. In particular, it # doesn't check whether the file exists. function abs_path_split(fname::String) fname = tilde_expand(fname) - if isrooted(fname) + if isabspath(fname) comp = split(fname, os_separator_match) else - comp = [split(cwd(), os_separator_match), split(fname, os_separator_match)] + comp = [split(pwd(), os_separator_match), split(fname, os_separator_match)] end n = length(comp) pmask = trues(n) @@ -143,7 +143,7 @@ function abs_path_split(fname::String) end return comp end -function abs_path(fname::String) +function abspath(fname::String) comp = abs_path_split(fname) return join(comp, os_separator) end @@ -184,7 +184,7 @@ end end # get and set current directory -function cwd() +function pwd() b = Array(Uint8,1024) @unix_only p = ccall(:getcwd, Ptr{Uint8}, (Ptr{Uint8}, Uint), b, length(b)) @windows_only p = ccall(:_getcwd, Ptr{Uint8}, (Ptr{Uint8}, Uint), b, length(b)) @@ -248,33 +248,12 @@ ls() = run(`ls -l`) ls(args::Cmd) = run(`ls -l $args`) ls(args::String...) = run(`ls -l $args`) -function path_expand(path::String) - chomp(readlines(`bash -c "echo $path"`)[1]) -end - -function file_copy(source::String, destination::String) - run(`cp $source $destination`) -end - -function file_create(filename::String) - run(`touch $filename`) -end - -function file_remove(filename::String) - @unix_only begin - ret = ccall(:unlink, Int32, (Ptr{Uint8},), bytestring(filename)) - system_error(:unlink, ret != 0) - end - @windows_only begin - ret = ccall(:DeleteFileA, stdcall, Int32, (Ptr{Uint8},), bytestring(filename)) - system_error(:unlink, ret == 0) - end -end +path_expand(path::String) = chomp(readlines(`bash -c "echo $path"`)[1]) -function path_rename(old_pathname::String, new_pathname::String) - ret = ccall(:rename, Int32, (Ptr{Uint8},Ptr{Uint8}), bytestring(old_pathname), bytestring(new_pathname)) - system_error(:rename, ret != 0) -end +rm(path::String) = run(`rm $path`) +cp(src::String, dst::String) = run(`cp $src $dst`) +mv(src::String, dst::String) = run(`mv $src $dst`) +touch(path::String) = run(`touch $path`) # Obtain a temporary filename. function tempname() diff --git a/base/git.jl b/base/git.jl index 1b739dd483980..1ce249450614b 100644 --- a/base/git.jl +++ b/base/git.jl @@ -20,7 +20,7 @@ branch() = readchomp(`git rev-parse --symbolic-full-name --abbrev-ref HEAD`) head() = readchomp(`git rev-parse HEAD`) function each_tagged_version() - git_dir = abs_path(dir()) + git_dir = abspath(dir()) @task for line in each_line(`git --git-dir=$git_dir show-ref --tags`) m = match(r"^([0-9a-f]{40}) refs/tags/(v\S+)$", line) if m != nothing && ismatch(Base.VERSION_REGEX, m.captures[2]) @@ -48,7 +48,7 @@ function each_submodule(f::Function, recursive::Bool, dir::ByteString) end end end -each_submodule(f::Function, r::Bool) = each_submodule(f, r, cwd()) +each_submodule(f::Function, r::Bool) = each_submodule(f, r, pwd()) function read_config(file::String) cfg = Dict() diff --git a/base/grisu.jl b/base/grisu.jl index 1ff47b55eb90b..4fae97c89d7e5 100644 --- a/base/grisu.jl +++ b/base/grisu.jl @@ -47,11 +47,15 @@ function grisu_sig(x::Real, n::Integer) end function _show(io, x::FloatingPoint, mode::Int32, n::Int) - if isnan(x); return write(io, isa(x,Float32) ? "NaN32" : "NaN"); end - if x < 0 write(io,'-') end - if isinf(x); return write(io, isa(x,Float32) ? "Inf32" : "Inf"); end + if isnan(x) return write(io, isa(x,Float32) ? "NaN32" : "NaN") end + if isinf(x) + if x < 0 write(io,'-') end + write(io, isa(x,Float32) ? "Inf32" : "Inf") + return + end @grisu_ccall x mode n pdigits = pointer(DIGITS) + neg = NEG[1] len = LEN[1] pt = POINT[1] if mode == PRECISION @@ -59,6 +63,7 @@ function _show(io, x::FloatingPoint, mode::Int32, n::Int) len -= 1 end end + if neg write(io,'-') end if pt <= -4 || pt > 6 # .00001 to 100000. # => #.#######e### write(io, pdigits, 1) diff --git a/base/inference.jl b/base/inference.jl index 1ec1a29bd6a81..2a7e0bcf366a6 100644 --- a/base/inference.jl +++ b/base/inference.jl @@ -54,7 +54,6 @@ methods(f::Union(Function,CompositeKind),t,lim) = ccall(:jl_matching_methods, An typeseq(a,b) = subtype(a,b)&&subtype(b,a) -isbuiltin(f) = ccall(:jl_is_builtin, Int32, (Any,), f) != 0 isgeneric(f) = (isa(f,Function)||isa(f,CompositeKind)) && isa(f.env,MethodTable) isleaftype(t) = ccall(:jl_is_leaf_type, Int32, (Any,), t) != 0 @@ -558,86 +557,82 @@ function invoke_tfunc(f, types, argtypes) end function abstract_call(f, fargs, argtypes, vtypes, sv::StaticVarInfo, e) - if isbuiltin(f) - if is(f,apply) && length(fargs)>0 - af = isconstantfunc(fargs[1], sv) - if !is(af,false) - aargtypes = argtypes[2:] - if allp(x->isa(x,Tuple), aargtypes) && - !anyp(isvatuple, aargtypes[1:(length(aargtypes)-1)]) - e.head = :call1 - # apply with known func with known tuple types - # can be collapsed to a call to the applied func - at = length(aargtypes) > 0 ? - limit_tuple_type(apply(tuple,aargtypes...)) : () - return abstract_call(_ieval(af), (), at, vtypes, sv, ()) - end - af = _ieval(af) - if is(af,tuple) && length(fargs)==2 - # tuple(xs...) - aat = aargtypes[1] - if aat <: AbstractArray - # tuple(array...) - # TODO: > 1 array of the same type - tn = AbstractArray.name - while isa(aat, AbstractKind) || isa(aat, BitsKind) || - isa(aat, CompositeKind) - if is(aat.name, tn) - et = aat.parameters[1] - if !isa(et,TypeVar) - return (et...) - end - end - if is(aat, Any) - break + if is(f,apply) && length(fargs)>0 + af = isconstantfunc(fargs[1], sv) + if !is(af,false) + aargtypes = argtypes[2:] + if allp(x->isa(x,Tuple), aargtypes) && + !anyp(isvatuple, aargtypes[1:(length(aargtypes)-1)]) + e.head = :call1 + # apply with known func with known tuple types + # can be collapsed to a call to the applied func + at = length(aargtypes) > 0 ? + limit_tuple_type(apply(tuple,aargtypes...)) : () + return abstract_call(_ieval(af), (), at, vtypes, sv, ()) + end + af = _ieval(af) + if is(af,tuple) && length(fargs)==2 + # tuple(xs...) + aat = aargtypes[1] + if aat <: AbstractArray + # tuple(array...) + # TODO: > 1 array of the same type + tn = AbstractArray.name + while isa(aat, AbstractKind) || isa(aat, BitsKind) || + isa(aat, CompositeKind) + if is(aat.name, tn) + et = aat.parameters[1] + if !isa(et,TypeVar) + return (et...) end - aat = aat.super end - end - return Tuple - end - else - ft = abstract_eval(fargs[1], vtypes, sv) - if isType(ft) - # TODO: improve abstract_call_constructor - st = ft.parameters[1] - if isa(st,TypeVar) && isa(st.ub,CompositeKind) - return st.ub - end - if isa(st,CompositeKind) - return st + if is(aat, Any) + break + end + aat = aat.super end end + return Tuple end - end - if is(f,invoke) && length(fargs)>1 - af = isconstantfunc(fargs[1], sv) - if !is(af,false) && (af=_ieval(af);isgeneric(af)) - sig = argtypes[2] - if isa(sig,Tuple) && allp(isType, sig) - sig = map(t->t.parameters[1], sig) - return invoke_tfunc(af, sig, argtypes[3:]) + else + ft = abstract_eval(fargs[1], vtypes, sv) + if isType(ft) + # TODO: improve abstract_call_constructor + st = ft.parameters[1] + if isa(st,TypeVar) && isa(st.ub,CompositeKind) + return st.ub + end + if isa(st,CompositeKind) + return st end end end - if !is(f,apply) && isa(e,Expr) && (isa(f,Function) || isa(f,IntrinsicFunction)) - e.head = :call1 - end - if is(f,getfield) - val = isconstantref(e, sv) - if !is(val,false) - return abstract_eval_constant(_ieval(val)) + end + if isgeneric(f) + return abstract_call_gf(f, fargs, argtypes, e) + end + if is(f,invoke) && length(fargs)>1 + af = isconstantfunc(fargs[1], sv) + if !is(af,false) && (af=_ieval(af);isgeneric(af)) + sig = argtypes[2] + if isa(sig,Tuple) && allp(isType, sig) + sig = map(t->t.parameters[1], sig) + return invoke_tfunc(af, sig, argtypes[3:]) end end - rt = builtin_tfunction(f, fargs, argtypes) - #print("=> ", rt, "\n") - return rt - elseif isgeneric(f) - return abstract_call_gf(f, fargs, argtypes, e) - else - #print("=> ", Any, "\n") - return Any end + if !is(f,apply) && isa(e,Expr) && (isa(f,Function) || isa(f,IntrinsicFunction)) + e.head = :call1 + end + if is(f,getfield) + val = isconstantref(e, sv) + if !is(val,false) + return abstract_eval_constant(_ieval(val)) + end + end + rt = builtin_tfunction(f, fargs, argtypes) + #print("=> ", rt, "\n") + return rt end function abstract_eval_arg(a, vtypes, sv) @@ -742,13 +737,13 @@ function abstract_eval(e::TopNode, vtypes, sv::StaticVarInfo) return abstract_eval_global(_basemod(), e.name) end -const _jl_Type_Array = Type{Array} +const Type_Array = Type{Array} function abstract_eval_constant(x::ANY) if isa(x,AbstractKind) || isa(x,BitsKind) || isa(x,CompositeKind) || isa(x,UnionKind) || isa(x,TypeConstructor) if is(x,Array) - return _jl_Type_Array + return Type_Array end return Type{x} end @@ -1069,13 +1064,21 @@ function typeinf(linfo::LambdaStaticData,atypes::Tuple,sparams::Tuple, def, cop) s[1][v] = Undef end if la > 0 - if is(atypes,Tuple) - atypes = tuple(NTuple{la,Any}..., Tuple[1]) - end lastarg = ast.args[1][la] if is_rest_arg(lastarg) - s[1][args[la]] = limit_tuple_depth(atypes[la:]) + if atypes === Tuple + if la > 1 + atypes = tuple(NTuple{la-1,Any}..., Tuple[1]) + end + s[1][args[la]] = Tuple + else + s[1][args[la]] = limit_tuple_depth(atypes[la:]) + end la -= 1 + else + if atypes === Tuple + atypes = tuple(NTuple{la,Any}..., Tuple[1]) + end end end for i=1:la @@ -1412,7 +1415,7 @@ function resolve_relative(sym, from, to, typ, orig) end m = _basemod() if is(from,m) || is(from,Core) - return _jl_tn(sym) + return tn(sym) end end return GetfieldNode(from, sym, typ) @@ -1644,20 +1647,20 @@ function inlineable(f, e::Expr, sv, enclosing_ast) return (sym_replace(expr, args, spnames, argexprs, spvals), stmts) end -_jl_tn(sym::Symbol) = +tn(sym::Symbol) = ccall(:jl_new_struct, Any, (Any,Any...), TopNode, sym, Any) -const _jl_top_tupleref = _jl_tn(:tupleref) -const _jl_top_tuple = _jl_tn(:tuple) +const top_tupleref = tn(:tupleref) +const top_tuple = tn(:tuple) function mk_tupleref(texpr, i) - e = :(($_jl_top_tupleref)($texpr, $i)) + e = :(($top_tupleref)($texpr, $i)) e.typ = exprtype(texpr)[i] e end function mk_tuplecall(args) - Expr(:call1, {_jl_top_tuple, args...}, tuple(map(exprtype, args)...)) + Expr(:call1, {top_tuple, args...}, tuple(map(exprtype, args)...)) end const basenumtype = Union(Int32,Int64,Float32,Float64,Complex64,Complex128,Rational) @@ -1730,10 +1733,10 @@ function inlining_pass(e::Expr, sv, ast) if isa(a1,basenumtype) || ((isa(a1,Symbol) || isa(a1,SymbolNode)) && exprtype(a1) <: basenumtype) if e.args[3]==2 - e.args = {_jl_tn(:*), a1, a1} + e.args = {tn(:*), a1, a1} f = * elseif e.args[3]==3 - e.args = {_jl_tn(:*), a1, a1, a1} + e.args = {tn(:*), a1, a1, a1} f = * end end @@ -1943,7 +1946,7 @@ end function finfer(f, types) x = methods(f,types)[1] (tree, ty) = typeinf(x[3], x[1], x[2]) - if isa(tree,Tuple) + if !isa(tree,Expr) return ccall(:jl_uncompress_ast, Any, (Any,Any), x[3], tree) end tree diff --git a/base/intfuncs.jl b/base/intfuncs.jl index 1c2649d253f94..a785602253d04 100644 --- a/base/intfuncs.jl +++ b/base/intfuncs.jl @@ -155,7 +155,7 @@ end # decimal digits in an unsigned integer -const _jl_powers_of_ten = [ +const powers_of_ten = [ 0x0000000000000001, 0x000000000000000a, 0x0000000000000064, 0x00000000000003e8, 0x0000000000002710, 0x00000000000186a0, 0x00000000000f4240, 0x0000000000989680, 0x0000000005f5e100, 0x000000003b9aca00, 0x00000002540be400, 0x000000174876e800, @@ -165,7 +165,7 @@ const _jl_powers_of_ten = [ function ndigits0z(x::Union(Uint8,Uint16,Uint32,Uint64)) lz = (sizeof(x)<<3)-leading_zeros(x) nd = (1233*lz)>>12+1 - nd -= x < _jl_powers_of_ten[nd] + nd -= x < powers_of_ten[nd] end function ndigits0z(x::Uint128) n = 0 @@ -178,9 +178,9 @@ end ndigits0z(x::Integer) = ndigits0z(unsigned(abs(x))) if WORD_SIZE == 32 -const _jl_ndigits_max_mul = 69000000 +const ndigits_max_mul = 69000000 else -const _jl_ndigits_max_mul = 290000000000000000 +const ndigits_max_mul = 290000000000000000 end function ndigits0z(n::Unsigned, b::Integer) @@ -189,7 +189,7 @@ function ndigits0z(n::Unsigned, b::Integer) if b == 16 return (sizeof(n)<<1)-(leading_zeros(n)>>2); end if b == 10 return ndigits0z(n); end nd = 1 - if n <= _jl_ndigits_max_mul + if n <= ndigits_max_mul # multiplication method is faster, but doesn't work for extreme values d = b while n >= d @@ -217,7 +217,7 @@ ndigits(x::Integer) = ndigits(unsigned(abs(x))) ## integer to string functions ## -const _jl_dig_syms = uint8(['0':'9','a':'z','A':'Z']) +const dig_syms = uint8(['0':'9','a':'z','A':'Z']) function bin(x::Unsigned, pad::Int, neg::Bool) i = neg + max(pad,sizeof(x)<<3-leading_zeros(x)) @@ -259,7 +259,7 @@ function hex(x::Unsigned, pad::Int, neg::Bool) i = neg + max(pad,(sizeof(x)<<1)-(leading_zeros(x)>>2)) a = Array(Uint8,i) while i > neg - a[i] = _jl_dig_syms[(x&0xf)+1] + a[i] = dig_syms[(x&0xf)+1] x >>= 4 i -= 1 end @@ -279,7 +279,7 @@ function base(symbols::Array{Uint8}, b::Int, x::Unsigned, pad::Int, neg::Bool) if neg; a[1]='-'; end ASCIIString(a) end -base(b::Int, x::Unsigned, p::Int, n::Bool) = base(_jl_dig_syms, b, x, p, n) +base(b::Int, x::Unsigned, p::Int, n::Bool) = base(dig_syms, b, x, p, n) base(s::Array{Uint8}, x::Unsigned, p::Int, n::Bool) = base(s, length(s), x, p, n) base(b::Union(Int,Array{Uint8}), x::Unsigned, p::Int) = base(b,x,p,false) base(b::Union(Int,Array{Uint8}), x::Unsigned) = base(b,x,1,false) diff --git a/base/intset.jl b/base/intset.jl index 12bc8e5c65242..db66cfac32e84 100644 --- a/base/intset.jl +++ b/base/intset.jl @@ -12,7 +12,7 @@ similar(s::IntSet) = IntSet() copy(s::IntSet) = union!(IntSet(), s) -function grow(s::IntSet, top::Integer) +function resize(s::IntSet, top::Integer) if top >= s.limit lim = ((top+31) & -32)>>>5 olsz = length(s.bits) @@ -32,7 +32,7 @@ function add(s::IntSet, n::Integer) return s else lim = int(n + div(n,2)) - grow(s, lim) + resize(s, lim) end end s.bits[n>>5 + 1] |= (uint32(1)<<(n&31)) @@ -50,7 +50,7 @@ function del(s::IntSet, n::Integer) if n >= s.limit if s.fill1s lim = int(n + div(n,2)) - grow(s, lim) + resize(s, lim) else return s end @@ -76,7 +76,7 @@ end function toggle(s::IntSet, n::Integer) if n >= s.limit lim = int(n + dim(n,2)) - grow(s, lim) + resize(s, lim) end s.bits[n>>5 + 1] $= (uint32(1)<<(n&31)) return s @@ -157,7 +157,7 @@ end # Math functions function union!(s::IntSet, s2::IntSet) if s2.limit > s.limit - grow(s, s2.limit) + resize(s, s2.limit) end lim = length(s2.bits) for n = 1:lim @@ -178,7 +178,7 @@ add_each(s::IntSet, s2::IntSet) = union!(s, s2) function intersect!(s::IntSet, s2::IntSet) if s2.limit > s.limit - grow(s, s2.limit) + resize(s, s2.limit) end lim = length(s2.bits) for n = 1:lim @@ -207,7 +207,7 @@ complement(s::IntSet) = complement!(copy(s)) function xor!(s::IntSet, s2::IntSet) if s2.limit > s.limit - grow(s, s2.limit) + resize(s, s2.limit) end lim = length(s2.bits) for n = 1:lim diff --git a/base/io.jl b/base/io.jl index 09a6c492a2d21..3b419c3d69a02 100644 --- a/base/io.jl +++ b/base/io.jl @@ -111,7 +111,7 @@ function read(s::IO, ::Type{Char}) end # mimic utf8.next function - trailing = Base._jl_utf8_trailing[ch+1] + trailing = Base.utf8_trailing[ch+1] c::Uint32 = 0 for j = 1:trailing c += ch @@ -119,13 +119,18 @@ function read(s::IO, ::Type{Char}) ch = read(s, Uint8) end c += ch - c -= Base._jl_utf8_offset[trailing+1] + c -= Base.utf8_offset[trailing+1] char(c) end -function readuntil(s::IO, delim) +function readuntil(s::IO, delim::Char) + if delim < 0x80 + data = readuntil(s, uint8(delim)) + enc = byte_string_classify(data) + return (enc==1) ? ASCIIString(data) : UTF8String(data) + end out = memio() - while (!eof(s)) + while !eof(s) c = read(s, Char) write(out, c) if c == delim @@ -135,18 +140,30 @@ function readuntil(s::IO, delim) takebuf_string(out) end +function readuntil{T}(s::IO, delim::T) + out = T[] + while !eof(s) + c = read(s, T) + push(out, c) + if c == delim + break + end + end + out +end + readline(s::IO) = readuntil(s, '\n') function readall(s::IO) out = memio() - while (!eof(s)) + while !eof(s) a = read(s, Uint8) write(out, a) end takebuf_string(out) end -readchomp(x) = chomp(readall(x)) +readchomp(x) = chomp!(readall(x)) ## high-level iterator interfaces ## @@ -304,7 +321,7 @@ function write{T}(s::IOStream, a::Array{T}) ccall(:jl_write, Uint, (Ptr{Void}, Ptr{Void}, Uint), s.ios, a, numel(a)*sizeof(T)) else - invoke(write, (Any, Array), s, a) + invoke(write, (IO, Array), s, a) end end @@ -336,11 +353,15 @@ function read(s::IOStream, ::Type{Uint8}) uint8(b) end -function read{T<:Union(Int8,Uint8,Int16,Uint16,Int32,Uint32,Int64,Uint64,Int128,Uint128,Float32,Float64,Complex64,Complex128)}(s::IOStream, a::Array{T}) - nb = numel(a)*sizeof(T) - if ccall(:ios_readall, Uint, - (Ptr{Void}, Ptr{Void}, Uint), s.ios, a, nb) < nb - throw(EOFError()) +function read{T}(s::IOStream, a::Array{T}) + if isa(T,BitsKind) + nb = numel(a)*sizeof(T) + if ccall(:ios_readall, Uint, + (Ptr{Void}, Ptr{Void}, Uint), s.ios, a, nb) < nb + throw(EOFError()) + end + else + invoke(read, (IO, Array), s, a) end a end @@ -392,9 +413,8 @@ end write(x) = write(OUTPUT_STREAM::IOStream, x) -function readuntil(s::IOStream, delim) - # TODO: faster versions that avoid the encoding check - ccall(:jl_readuntil, ByteString, (Ptr{Void}, Uint8), s.ios, delim) +function readuntil(s::IOStream, delim::Uint8) + ccall(:jl_readuntil, Array{Uint8,1}, (Ptr{Void}, Uint8), s.ios, delim) end function readall(s::IOStream) @@ -507,7 +527,7 @@ function mmap_bitarray{N}(dims::NTuple{N,Int}, s::IOStream, offset::FileOffset) dims = 0 end n = prod(dims) - nc = _jl_num_bit_chunks(n) + nc = num_bit_chunks(n) B = BitArray{N}() chunks = mmap_array(Uint64, (nc,), s, offset) if iswrite diff --git a/base/iostring.jl b/base/iostring.jl index 894384c13a873..2f03063cb644a 100644 --- a/base/iostring.jl +++ b/base/iostring.jl @@ -196,11 +196,10 @@ function memchr(buf::IOString, delim) q = ccall(:memchr,Ptr{Uint8},(Ptr{Uint8},Int32,Int32),p,delim,nb_available(buf)) nb = (q == C_NULL ? 0 : q-p+1) end -function readuntil(io::IOString, delim) +function readuntil(io::IOString, delim::Uint8) nb = memchr(io, delim) if nb == 0 nb = nb_available(io) end - readbytes(io,nb) + read(io, Array(Uint8, nb)) end - diff --git a/base/iterator.jl b/base/iterator.jl index fb3d7709eff98..a680e4a3bba0c 100644 --- a/base/iterator.jl +++ b/base/iterator.jl @@ -51,8 +51,8 @@ type Filter{I} end filter(flt::Function, itr) = Filter(flt, itr) -start(f::Filter) = _jl_start_filter(f.flt, f.itr) -function _jl_start_filter(pred, itr) +start(f::Filter) = start_filter(f.flt, f.itr) +function start_filter(pred, itr) s = start(itr) while !done(itr,s) v,t = next(itr,s) @@ -64,8 +64,8 @@ function _jl_start_filter(pred, itr) s end -next(f::Filter, s) = _jl_advance_filter(f.flt, f.itr, s) -function _jl_advance_filter(pred, itr, s) +next(f::Filter, s) = advance_filter(f.flt, f.itr, s) +function advance_filter(pred, itr, s) v,s = next(itr,s) while !done(itr,s) w,t = next(itr,s) diff --git a/base/lapack.jl b/base/lapack.jl index 3c506deba5cd7..1c9f8e7e9f775 100644 --- a/base/lapack.jl +++ b/base/lapack.jl @@ -3,10 +3,15 @@ module LAPACK const liblapack = Base.liblapack_name -typealias LapackChar Char +import Base.BlasFloat +import Base.BlasChar +import Base.BlasInt +import Base.blas_int + type LapackException <: Exception - info::Int32 + info::BlasInt end + type LapackDimMisMatch <: Exception name::ASCIIString end @@ -39,13 +44,13 @@ for (gbtrf, gbtrs, elty) in # DOUBLE PRECISION AB( LDAB, * ) function gbtrf!(kl::Integer, ku::Integer, m::Integer, AB::StridedMatrix{$elty}) chkstride1(AB) - info = Array(Int32, 1) + info = Array(BlasInt, 1) n = size(AB, 2) mnmn = min(m, n) - ipiv = Array(Int32, mnmn) + ipiv = Array(BlasInt, mnmn) ccall(($(string(gbtrf)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, &kl, &ku, AB, &stride(AB,2), ipiv, info) if info[1] != 0 throw(LapackException(info[1])) end AB, ipiv @@ -57,16 +62,16 @@ for (gbtrf, gbtrs, elty) in # * .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION AB( LDAB, * ), B( LDB, * ) - function gbtrs!(trans::LapackChar, kl::Integer, ku::Integer, m::Integer, - AB::StridedMatrix{$elty}, ipiv::Vector{Int32}, + function gbtrs!(trans::BlasChar, kl::Integer, ku::Integer, m::Integer, + AB::StridedMatrix{$elty}, ipiv::Vector{BlasInt}, B::StridedVecOrMat{$elty}) chkstride1(AB, B) - info = Array(Int32, 1) + info = Array(BlasInt, 1) n = size(AB,2) if m != n || m != size(B,1) throw(LapackDimMisMatch("gbtrs!")) end ccall(($(string(gbtrs)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), &trans, &n, &kl, &ku, &size(B,2), AB, &stride(AB,2), ipiv, B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end @@ -88,17 +93,17 @@ for (gebal, gebak, elty, relty) in # INTEGER IHI, ILP, INFO, LDA, N # .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), SCALE( * ) - function gebal!(job::LapackChar, A::StridedMatrix{$elty}) + function gebal!(job::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) chksquare(A) n = size(A, 2) - info = Array(Int32, 1) - ihi = Array(Int32, 1) - ilo = Array(Int32, 1) + info = Array(BlasInt, 1) + ihi = Array(BlasInt, 1) + ilo = Array(BlasInt, 1) scale = Array($relty, n) ccall(($(string(gebal)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{Int32}, Ptr{$relty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{BlasInt}), &job, &n, A, &stride(A,2), ilo, ihi, scale, info) if info[1] != 0 throw(LapackException(info[1])) end ilo[1], ihi[1], scale @@ -109,15 +114,15 @@ for (gebal, gebak, elty, relty) in # INTEGER IHI, ILP, INFO, LDV, M, N # .. Array Arguments .. # DOUBLE PRECISION SCALE( * ), V( LDV, * ) - function gebak!(job::LapackChar, side::LapackChar, - ilo::Int32, ihi::Int32, scale::Vector{$elty}, + function gebak!(job::BlasChar, side::BlasChar, + ilo::BlasInt, ihi::BlasInt, scale::Vector{$elty}, V::StridedMatrix{$elty}) chkstride1(V) chksquare(V) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(gebak)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &job, &side, &size(V,1), &ilo, &ihi, scale, &n, V, &stride(V,2), info) if info[1] != 0 throw(LapackException(info[1])) end V @@ -155,17 +160,17 @@ for (gebrd, gelqf, geqlf, geqrf, geqp3, gerqf, getrf, elty) in tauq = Array($elty, k) taup = Array($elty, k) work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(gebrd)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, A, &stride(A,2), d, s, tauq, taup, work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -177,21 +182,21 @@ for (gebrd, gelqf, geqlf, geqrf, geqp3, gerqf, getrf, elty) in # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) function gelqf!(A::StridedMatrix{$elty}) chkstride1(A) - info = Array(Int32, 1) - m = int32(size(A, 1)) - n = int32(size(A, 2)) - lda = int32(stride(A, 2)) + info = Array(BlasInt, 1) + m = blas_int(size(A, 1)) + n = blas_int(size(A, 2)) + lda = blas_int(stride(A, 2)) tau = Array($elty, n) - lwork = int32(-1) + lwork = blas_int(-1) work = Array($elty, (1,)) for i in 1:2 # first call returns lwork as work[1] ccall(($(string(gelqf)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, A, &lda, tau, work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -204,21 +209,21 @@ for (gebrd, gelqf, geqlf, geqrf, geqp3, gerqf, getrf, elty) in # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) function geqlf!(A::StridedMatrix{$elty}) chkstride1(A) - info = Array(Int32, 1) - m = int32(size(A, 1)) - n = int32(size(A, 2)) - lda = int32(stride(A, 2)) + info = Array(BlasInt, 1) + m = blas_int(size(A, 1)) + n = blas_int(size(A, 2)) + lda = blas_int(stride(A, 2)) tau = Array($elty, n) - lwork = int32(-1) + lwork = blas_int(-1) work = Array($elty, (1,)) for i in 1:2 # first call returns lwork as work[1] ccall(($(string(geqlf)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, A, &lda, tau, work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -233,31 +238,31 @@ for (gebrd, gelqf, geqlf, geqrf, geqp3, gerqf, getrf, elty) in function geqp3!(A::StridedMatrix{$elty}) chkstride1(A) m, n = size(A) - jpvt = zeros(Int32, n) + jpvt = zeros(BlasInt, n) tau = Array($elty, n) work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) Rtyp = typeof(real(A[1])) cmplx = iscomplex(A) if cmplx rwork = Array(Rtyp, 2n) end for i in 1:2 if cmplx ccall(($(string(geqp3)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{Rtyp}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{Rtyp}, Ptr{BlasInt}), &m, &n, A, &stride(A,2), jpvt, tau, work, &lwork, rwork, info) else ccall(($(string(geqp3)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}), &m, &n, A, &stride(A,2), jpvt, tau, work, &lwork, info) end if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -277,16 +282,16 @@ for (gebrd, gelqf, geqlf, geqrf, geqp3, gerqf, getrf, elty) in m, n = size(A) tau = Array($elty, n) work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 # first call returns lwork as work[1] ccall(($(string(geqrf)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, A, &stride(A,2), tau, work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -299,19 +304,19 @@ for (gebrd, gelqf, geqlf, geqrf, geqp3, gerqf, getrf, elty) in # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) function gerqf!(A::StridedMatrix{$elty}) chkstride1(A) - info = Array(Int32, 1) + info = Array(BlasInt, 1) m, n = size(A) tau = Array($elty, n) - lwork = int32(-1) + lwork = blas_int(-1) work = Array($elty, 1) for i in 1:2 # first call returns lwork as work[1] ccall(($(string(gerqf)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, A, &stride(A,2), tau, work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -325,13 +330,13 @@ for (gebrd, gelqf, geqlf, geqrf, geqp3, gerqf, getrf, elty) in # DOUBLE PRECISION A( LDA, * ) function getrf!(A::StridedMatrix{$elty}) chkstride1(A) - info = Array(Int32, 1) + info = Array(BlasInt, 1) m, n = size(A) lda = stride(A, 2) - ipiv = Array(Int32, min(m,n)) + ipiv = Array(BlasInt, min(m,n)) ccall(($(string(getrf)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, A, &lda, ipiv, info) if info[1] < 0 throw(LapackException(info[1])) end A, ipiv, info[1] @@ -350,24 +355,24 @@ for (gels, gesv, getrs, getri, elty) in # * .. Scalar Arguments .. # CHARACTER TRANS # INTEGER INFO, LDA, LDB, LWORK, M, N, NRHS - function gels!(trans::LapackChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) + function gels!(trans::BlasChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) chkstride1(A, B) btrn = trans == 'T' m, n = size(A) if size(B,1) != (btrn ? n : m) throw(LapackDimMisMatch("gels!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) work = Array($elty, 1) - lwork = int32(-1) + lwork = blas_int(-1) for i in 1:2 ccall(($(string(gels)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &(btrn?'T':'N'), &m, &n, &size(B,2), A, &stride(A,2), B, &stride(B,2), work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -387,11 +392,11 @@ for (gels, gesv, getrs, getri, elty) in chksquare(A) n = size(A,1) if size(B,1) != n throw(LapackDimMisMatch("gesv!")) end - ipiv = Array(Int32, n) - info = Array(Int32, 1) + ipiv = Array(BlasInt, n) + info = Array(BlasInt, 1) ccall(($(string(gesv)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &n, &size(B,2), A, &stride(A,2), ipiv, B, &stride(B,2), info) if info[1] < 0 throw(LapackException(info[1])) end B, A, ipiv, info[1] @@ -403,15 +408,15 @@ for (gels, gesv, getrs, getri, elty) in # .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function getrs!(trans::LapackChar, A::StridedMatrix{$elty}, ipiv::Vector{Int32}, B::StridedVecOrMat{$elty}) + function getrs!(trans::BlasChar, A::StridedMatrix{$elty}, ipiv::Vector{BlasInt}, B::StridedVecOrMat{$elty}) chkstride1(A, B) m, n = size(A) if m != n || size(B, 1) != m error("getrs!: dimension mismatch") end nrhs = size(B, 2) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(getrs)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &trans, &n, &size(B,2), A, &stride(A,2), ipiv, B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end B @@ -422,22 +427,22 @@ for (gels, gesv, getrs, getri, elty) in #* .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function getri!(A::StridedMatrix{$elty}, ipiv::Vector{Int32}) + function getri!(A::StridedMatrix{$elty}, ipiv::Vector{BlasInt}) chkstride1(A) m, n = size(A) if m != n || n != numel(ipiv) error("getri!: dimension mismatch") end lda = stride(A, 2) - info = Array(Int32, 1) + info = Array(BlasInt, 1) lwork = -1 work = Array($elty, 1) for i in 1:2 ccall(($(string(getri)),liblapack), Void, - (Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &n, A, &lda, ipiv, work, &lwork, info) if info[1] != 0 error("getri!: error $(info[1])") end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -462,24 +467,24 @@ for (gelsd, elty) in ((:dgelsd_, Float64), m, n = size(A) if size(B,1) != m; throw(LAPACK.LapackDimMisMatch("gelsd!")); end s = Array($elty, min(m, n)) - rnk = Array(Int32, 1) - info = Array(Int32, 1) + rnk = Array(BlasInt, 1) + info = Array(BlasInt, 1) work = Array($elty, 1) - lwork = int32(-1) - iwork = Array(Int32, 1) + lwork = blas_int(-1) + iwork = Array(BlasInt, 1) for i in 1:2 ccall(($(string(gelsd)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, &size(B,2), A, &max(1,stride(A,2)), B, &max(1,stride(B,2)), s, &rcond, rnk, work, &lwork, iwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) - iwork = Array(Int32, iwork[1]) + iwork = Array(BlasInt, iwork[1]) end end isa(B, Vector) ? B[1:n] : B[1:n,:], rnk[1] @@ -505,26 +510,26 @@ for (gelsd, elty, relty) in ((:zgelsd_, Complex128, Float64), m, n = size(A) if size(B,1) != m; throw(LAPACK.LapackDimMisMatch("gelsd!")); end s = Array($elty, min(m, n)) - rnk = Array(Int32, 1) - info = Array(Int32, 1) + rnk = Array(BlasInt, 1) + info = Array(BlasInt, 1) work = Array($elty, 1) - lwork = int32(-1) + lwork = blas_int(-1) rwork = Array($relty, 1) - iwork = Array(Int32, 1) + iwork = Array(BlasInt, 1) for i in 1:2 ccall(($(string(gelsd)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{$relty}, - Ptr{$relty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$relty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, + Ptr{$relty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$relty}, Ptr{BlasInt}, Ptr{BlasInt}), &m, &n, &size(B,2), A, &max(1,stride(A,2)), B, &max(1,stride(B,2)), s, &rcond, rnk, work, &lwork, rwork, iwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) - rwork = Array($relty, int(rwork[1])) - iwork = Array(Int32, iwork[1]) + rwork = Array($relty, blas_int(rwork[1])) + iwork = Array(BlasInt, iwork[1]) end end isa(B, Vector) ? B[1:n] : B[1:n,:], rnk[1] @@ -548,7 +553,7 @@ for (geev, gesvd, gesdd, elty) in # * .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), VL( LDVL, * ), VR( LDVR, * ), # $ WI( * ), WORK( * ), WR( * ) - function geev!(jobvl::LapackChar, jobvr::LapackChar, A::StridedMatrix{$elty}) + function geev!(jobvl::BlasChar, jobvr::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) chksquare(A) m, n = size(A) @@ -566,29 +571,29 @@ for (geev, gesvd, gesdd, elty) in WI = Array($elty, n) end work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i = 1:2 if cmplx ccall(($(string(geev)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Rtyp}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{Rtyp}, Ptr{BlasInt}), &jobvl, &jobvr, &n, A, &stride(A,2), W, VL, &n, VR, &n, work, &lwork, rwork, info) else ccall(($(string(geev)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{BlasInt}), &jobvl, &jobvr, &n, A, &stride(A,2), WR, WI, VL, &n, VR, &n, work, &lwork, info) end if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -604,7 +609,7 @@ for (geev, gesvd, gesdd, elty) in # INTEGER IWORK( * ) # DOUBLE PRECISION A( LDA, * ), S( * ), U( LDU, * ), # VT( LDVT, * ), WORK( * ) - function gesdd!(job::LapackChar, A::StridedMatrix{$elty}) + function gesdd!(job::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) m, n = size(A) minmn = min(m, n) @@ -622,36 +627,36 @@ for (geev, gesvd, gesdd, elty) in VT = Array($elty, (n, 0)) end work = Array($elty, 1) - lwork = int32(-1) + lwork = blas_int(-1) Rtyp = typeof(real(A[1])) S = Array(Rtyp, minmn) cmplx = iscomplex(A) if cmplx rwork = Array(Rtyp, job == 'N' ? 5*minmn : minmn*max(5*minmn+7,2*max(m,n)+2*minmn+1)) end - iwork = Array(Int32, 8*minmn) - info = Array(Int32, 1) + iwork = Array(BlasInt, 8*minmn) + info = Array(BlasInt, 1) for i = 1:2 if cmplx ccall(($(string(gesdd)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Rtyp}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{Rtyp}, Ptr{BlasInt}, Ptr{BlasInt}), &job, &m, &n, A, &stride(A,2), S, U, &max(1,stride(U,2)), VT, &max(1,stride(VT,2)), work, &lwork, rwork, iwork, info) else ccall(($(string(gesdd)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{BlasInt}), &job, &m, &n, A, &stride(A,2), S, U, &max(1,stride(U,2)), VT, &max(1,stride(VT,2)), work, &lwork, iwork, info) end if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -669,7 +674,7 @@ for (geev, gesvd, gesdd, elty) in # * .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), S( * ), U( LDU, * ), # $ VT( LDVT, * ), WORK( * ) - function gesvd!(jobu::LapackChar, jobvt::LapackChar, A::StridedMatrix{$elty}) + function gesvd!(jobu::BlasChar, jobvt::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) Rtyp = typeof(real(A[1])) m, n = size(A) @@ -680,29 +685,29 @@ for (geev, gesvd, gesdd, elty) in work = Array($elty, 1) cmplx = iscomplex(A) if cmplx rwork = Array(Rtyp, 5minmn) end - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 if cmplx ccall(($(string(gesvd)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{Rtyp}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{Rtyp}, Ptr{BlasInt}), &jobu, &jobvt, &m, &n, A, &stride(A,2), S, U, &max(1,stride(U,2)), VT, &max(1,stride(VT,2)), work, &lwork, rwork, info) else ccall(($(string(gesvd)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{BlasInt}), &jobu, &jobvt, &m, &n, A, &stride(A,2), S, U, &max(1,stride(U,2)), VT, &max(1,stride(VT,2)), work, &lwork, info) end if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -733,10 +738,10 @@ for (gtsv, gttrf, gttrs, elty) in throw(LapackDimMisMatch("gtsv!")) end if n != size(B,1) throw(LapackDimMisMatch("gtsv!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(gtsv)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &n, &size(B,2), dl, d, du, B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end B @@ -753,11 +758,11 @@ for (gtsv, gttrf, gttrs, elty) in throw(LapackDimMisMatch("gttrf!")) end du2 = Array($elty, n-2) - ipiv = Array(Int32, n) - info = Array(Int32, 1) + ipiv = Array(BlasInt, n) + info = Array(BlasInt, 1) ccall(($(string(gttrf)),liblapack), Void, - (Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{BlasInt}), &n, dl, d, du, du2, ipiv, info) if info[1] != 0 throw(LapackException(info[1])) end dl, d, du, du2, ipiv @@ -769,18 +774,18 @@ for (gtsv, gttrf, gttrs, elty) in # .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION B( LDB, * ), D( * ), DL( * ), DU( * ), DU2( * ) - function gttrs!(trans::LapackChar, dl::Vector{$elty}, d::Vector{$elty}, - du::Vector{$elty}, du2::Vector{$elty}, ipiv::Vector{Int32}, + function gttrs!(trans::BlasChar, dl::Vector{$elty}, d::Vector{$elty}, + du::Vector{$elty}, du2::Vector{$elty}, ipiv::Vector{BlasInt}, B::StridedVecOrMat{$elty}) chkstride1(B) n = length(d) if length(dl) != n - 1 || length(du) != n - 1 throw(LapackDimMisMatch("gttrs!")) end if n != size(B,1) throw(LapackDimMisMatch("gttrs!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(gttrs)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &trans, &n, &size(B,2), dl, d, du, du2, ipiv, B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end B @@ -803,16 +808,16 @@ for (orglq, orgqr, ormlq, ormqr, elty) in function orglq!(A::StridedMatrix{$elty}, tau::Vector{$elty}, k::Integer) chkstride1(A) work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(orglq)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &size(A,1), &size(A,2), &k, A, &stride(A,2), tau, work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -826,16 +831,16 @@ for (orglq, orgqr, ormlq, ormqr, elty) in function orgqr!(A::StridedMatrix{$elty}, tau::Vector{$elty}, k::Integer) chkstride1(A) work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(orgqr)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &size(A,1), &size(A,2), &k, A, &stride(A,2), tau, work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -848,24 +853,24 @@ for (orglq, orgqr, ormlq, ormqr, elty) in # INTEGER INFO, K, LDA, LDC, LWORK, M, N # .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) - function ormlq!(side::LapackChar, trans::LapackChar, A::StridedMatrix{$elty}, + function ormlq!(side::BlasChar, trans::BlasChar, A::StridedMatrix{$elty}, k::Integer, tau::Vector{$elty}, C::StridedVecOrMat{$elty}) chkstride1(A, C) m = size(C, 1) n = size(C, 2) # m, n = size(C) won't work if C is a Vector work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(ormlq)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &side, &trans, &m, &n, &k, A, &stride(A,2), tau, C, &stride(C,2), work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -878,24 +883,24 @@ for (orglq, orgqr, ormlq, ormqr, elty) in # INTEGER INFO, K, LDA, LDC, M, N # .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) - function ormqr!(side::LapackChar, trans::LapackChar, A::StridedMatrix{$elty}, + function ormqr!(side::BlasChar, trans::BlasChar, A::StridedMatrix{$elty}, k::Integer, tau::Vector{$elty}, C::StridedVecOrMat{$elty}) chkstride1(A, C) m = size(C, 1) n = size(C, 2) # m, n = size(C) won't work if C is a Vector work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(ormqr)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &side, &trans, &m, &n, &k, A, &stride(A,2), tau, C, &stride(C,2), work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -920,15 +925,15 @@ for (posv, potrf, potri, potrs, pstrf, elty, rtyp) in # INTEGER INFO, LDA, LDB, N, NRHS # .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function posv!(uplo::LapackChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) + function posv!(uplo::BlasChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) chkstride1(A, B) chksquare(A) n = size(A,1) if size(B,1) != n throw(LapackDimMisMatch("posv!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(posv)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &n, &size(B,2), A, &stride(A,2), B, &stride(B,2), info) if info[1] < 0 throw(LapackException(info[1])) end A, B, info[1] @@ -941,12 +946,12 @@ for (posv, potrf, potri, potrs, pstrf, elty, rtyp) in # INTEGER INFO, LDA, N # * .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ) - function potrf!(uplo::LapackChar, A::StridedMatrix{$elty}) + function potrf!(uplo::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) chksquare(A) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(potrf)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &size(A,1), A, &stride(A,2), info) if info[1] < 0 throw(LapackException(info[1])) end A, info[1] @@ -959,11 +964,11 @@ for (posv, potrf, potri, potrs, pstrf, elty, rtyp) in # INTEGER INFO, LDA, N # .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ) - function potri!(uplo::LapackChar, A::StridedMatrix{$elty}) + function potri!(uplo::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(potri)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &size(A,1), A, &stride(A,2), info) if info[1] < 0 throw(LapackException(info[1])) end A, info[1] @@ -974,15 +979,15 @@ for (posv, potrf, potri, potrs, pstrf, elty, rtyp) in # INTEGER INFO, LDA, LDB, N, NRHS # .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function potrs!(uplo::LapackChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) + function potrs!(uplo::BlasChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) chkstride1(A, B) chksquare(A) n = size(A,2) if size(B,1) != n error("potrs!: dimension mismatch") end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(potrs)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &n, &size(B,2), A, &stride(A,2), B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end B @@ -995,17 +1000,17 @@ for (posv, potrf, potri, potrs, pstrf, elty, rtyp) in # .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), WORK( 2*N ) # INTEGER PIV( N ) - function pstrf!(uplo::LapackChar, A::StridedMatrix{$elty}, tol::Real) + function pstrf!(uplo::BlasChar, A::StridedMatrix{$elty}, tol::Real) chkstride1(A) chksquare(A) n = size(A,1) - piv = Array(Int32, n) - rank = Array(Int32, 1) + piv = Array(BlasInt, n) + rank = Array(BlasInt, 1) work = Array($rtyp, 2n) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(pstrf)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, - Ptr{Int32}, Ptr{$rtyp}, Ptr{$rtyp}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$rtyp}, Ptr{$rtyp}, Ptr{BlasInt}), &uplo, &n, A, &stride(A,2), piv, rank, &tol, work, info) if info[1] < 0 throw(LapackException(info[1])) end A, piv, rank[1], info[1] @@ -1030,10 +1035,10 @@ for (ptsv, pttrf, pttrs, elty, relty) in chkstride1(B) n = length(D) if length(E) != n - 1 || n != size(B,1) throw(LapackDimMismatch("ptsv!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(ptsv)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$relty}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &n, &size(B,2), D, E, B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end B @@ -1046,9 +1051,9 @@ for (ptsv, pttrf, pttrs, elty, relty) in function pttrf!(D::Vector{$relty}, E::Vector{$elty}) n = length(D) if length(E) != (n-1) throw(LapackDimMisMatch("pttrf!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(pttrf)),liblapack), Void, - (Ptr{Int32}, Ptr{$relty}, Ptr{$elty}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}), &n, D, E, info) if info[1] != 0 throw(LapackException(info[1])) end D, E @@ -1068,10 +1073,10 @@ for (pttrs, elty, relty) in chkstride1(B) n = length(D) if length(E) != (n-1) || size(B,1) != n throw(LapackDimMisMatch("pttrs!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(pttrs)),liblapack), Void, - (Ptr{Int32}, Ptr{Int32}, Ptr{$relty}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &n, &size(B,2), D, E, B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end B @@ -1090,14 +1095,14 @@ for (pttrs, elty, relty) in # * .. Array Arguments .. # DOUBLE PRECISION D( * ) # COMPLEX*16 B( LDB, * ), E( * ) - function pttrs!(uplo::LapackChar, D::Vector{$relty}, E::Vector{$elty}, B::StridedVecOrMat{$elty}) + function pttrs!(uplo::BlasChar, D::Vector{$relty}, E::Vector{$elty}, B::StridedVecOrMat{$elty}) chkstride1(B) n = length(D) if length(E) != (n-1) || size(B,1) != n throw(LapackDimMisMatch("pttrs!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(pttrs)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$relty}, Ptr{$elty}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &n, &size(B,2), D, E, B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end B @@ -1118,15 +1123,15 @@ for (trtri, trtrs, elty) in # INTEGER INFO, LDA, N # .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ) - function trtri!(uplo::LapackChar, diag::LapackChar, A::StridedMatrix{$elty}) + function trtri!(uplo::BlasChar, diag::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) m, n = size(A) if m != n error("trtri!: dimension mismatch") end lda = stride(A, 2) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($trtri,liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}), &uplo, &diag, &n, A, &lda, info) if info[1] < 0 error("trtri!: error $(info[1])") end A, info[1] @@ -1137,16 +1142,16 @@ for (trtri, trtrs, elty) in # INTEGER INFO, LDA, LDB, N, NRHS # * .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function trtrs!(uplo::LapackChar, trans::LapackChar, diag::LapackChar, + function trtrs!(uplo::BlasChar, trans::BlasChar, diag::BlasChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) chkstride1(A) chksquare(A) n = size(A,2) if size(B,1) != n throw(LapackDimMisMatch("trtrs!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(trtrs)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &trans, &diag, &n, &size(B,2), A, &stride(A,2), B, &stride(B,2), info) if info[1] < 0 throw(LapackException(info[1])) end @@ -1163,15 +1168,15 @@ for (stev, elty) in # , (:cstev_,:Complex64) ) @eval begin - function stev!(job::LapackChar, dv::Vector{$elty}, ev::Vector{$elty}) + function stev!(job::BlasChar, dv::Vector{$elty}, ev::Vector{$elty}) n = length(dv) if length(ev) != (n-1) throw(LapackDimMisMatch("stev!")) end Zmat = Array($elty, (n, job != 'N' ? n : 0)) work = Array($elty, max(1, 2n-2)) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(stev)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), &job, &n, dv, ev, Zmat, &n, work, info) if info[1] != 0 throw(LapackException(info[1])) end dv, Zmat @@ -1194,15 +1199,15 @@ for (syconv, syev, sysv, sytrf, sytri, sytrs, elty) in # * .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function syconv!(uplo::LapackChar, A::StridedMatrix{$elty}, ipiv::Vector{Int32}) + function syconv!(uplo::BlasChar, A::StridedMatrix{$elty}, ipiv::Vector{BlasInt}) chkstride1(A) chksquare(A) n = size(A,1) work = Array($elty, n) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(syconv)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &'C', &n, A, &stride(A,2), ipiv, work, info) if info[1] != 0 throw(LapackException(info[1])) end A, work @@ -1213,7 +1218,7 @@ for (syconv, syev, sysv, sytrf, sytri, sytrs, elty) in # INTEGER INFO, LDA, LWORK, N # * .. Array Arguments .. # DOUBLE PRECISION A( LDA, * ), W( * ), WORK( * ) - function syev!(jobz::LapackChar, uplo::LapackChar, A::StridedMatrix{$elty}) + function syev!(jobz::BlasChar, uplo::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) chksquare(A) cmplx = iscomplex(A) @@ -1221,26 +1226,26 @@ for (syconv, syev, sysv, sytrf, sytri, sytrs, elty) in n = size(A, 1) W = Array(Rtyp, n) work = Array($elty, 1) - lwork = int32(-1) + lwork = blas_int(-1) if cmplx rwork = Array(Rtyp, max(1, 3n-2)) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) for i in 1:2 if cmplx ccall(($(string(syev)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Rtyp}, Ptr{$elty}, Ptr{Int32}, Ptr{Rtyp}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{Rtyp}, Ptr{$elty}, Ptr{BlasInt}, Ptr{Rtyp}, Ptr{BlasInt}), &jobz, &uplo, &n, A, &stride(A,2), W, work, &lwork, rwork, info) else ccall(($(string(syev)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Rtyp}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{Rtyp}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &jobz, &uplo, &n, A, &stride(A,2), W, work, &lwork, info) end if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -1254,24 +1259,24 @@ for (syconv, syev, sysv, sytrf, sytri, sytrs, elty) in # .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), WORK( * ) - function sysv!(uplo::LapackChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) + function sysv!(uplo::BlasChar, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) chkstride1(A,B) chksquare(A) n = size(A,1) if n != size(B,1) throw(LapackDimMismatch("sysv!")) end - ipiv = Array(Int32, n) + ipiv = Array(BlasInt, n) work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(sysv)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &n, &size(B,2), A, &stride(A,2), ipiv, B, &stride(B,2), work, &lwork, info) if info[1] < 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -1284,22 +1289,22 @@ for (syconv, syev, sysv, sytrf, sytri, sytrs, elty) in # * .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function sytrf!(uplo::LapackChar, A::StridedMatrix{$elty}) + function sytrf!(uplo::BlasChar, A::StridedMatrix{$elty}) chkstride1(A) chksquare(A) n = size(A,1) - ipiv = Array(Int32, n) + ipiv = Array(BlasInt, n) work = Array($elty, 1) - lwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(sytrf)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &n, A, &stride(A,2), ipiv, work, &lwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) end end @@ -1312,21 +1317,21 @@ for (syconv, syev, sysv, sytrf, sytri, sytrs, elty) in # * .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION A( LDA, * ), WORK( * ) -# function sytri!(uplo::LapackChar, A::StridedMatrix{$elty}, ipiv::Vector{Int32}) +# function sytri!(uplo::BlasChar, A::StridedMatrix{$elty}, ipiv::Vector{BlasInt}) # chkstride1(A) # chksquare(A) # n = size(A,1) # work = Array($elty, 1) -# lwork = int32(-1) -# info = Array(Int32, 1) +# lwork = blas_int(-1) +# info = Array(BlasInt, 1) # for i in 1:2 # ccall(($(string(sytri)),liblapack), Void, -# (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, -# Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), +# (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, +# Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), # &uplo, &n, A, &stride(A,2), ipiv, work, &lwork, info) # if info[1] != 0 throw(LapackException(info[1])) end # if lwork < 0 -# lwork = int32(real(work[1])) +# lwork = blas_int(real(work[1])) # work = Array($elty, lwork) # end # end @@ -1339,15 +1344,15 @@ for (syconv, syev, sysv, sytrf, sytri, sytrs, elty) in # .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function sytri!(uplo::LapackChar, A::StridedMatrix{$elty}, ipiv::Vector{Int32}) + function sytri!(uplo::BlasChar, A::StridedMatrix{$elty}, ipiv::Vector{BlasInt}) chkstride1(A) chksquare(A) n = size(A,1) work = Array($elty, n) - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(sytri)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), &uplo, &n, A, &stride(A,2), ipiv, work, info) if info[1] != 0 throw(LapackException(info[1])) end A @@ -1360,16 +1365,16 @@ for (syconv, syev, sysv, sytrf, sytri, sytrs, elty) in # .. Array Arguments .. # INTEGER IPIV( * ) # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function sytrs!(uplo::LapackChar, A::StridedMatrix{$elty}, - ipiv::Vector{Int32}, B::StridedVecOrMat{$elty}) + function sytrs!(uplo::BlasChar, A::StridedMatrix{$elty}, + ipiv::Vector{BlasInt}, B::StridedVecOrMat{$elty}) chkstride1(A,B) chksquare(A) n = size(A,1) if n != size(B,1) throw(LapackDimMismatch("sytrs!")) end - info = Array(Int32, 1) + info = Array(BlasInt, 1) ccall(($(string(sytrs)),liblapack), Void, - (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), &uplo, &n, &size(B,2), A, &stride(A,2), ipiv, B, &stride(B,2), info) if info[1] != 0 throw(LapackException(info[1])) end B @@ -1380,7 +1385,7 @@ for (syevr, elty) in ((:dsyevr_,:Float64), (:ssyevr_,:Float32)) @eval begin - function syevr!(jobz::LapackChar, range::LapackChar, uplo::LapackChar, A::StridedMatrix{$elty}, vl::FloatingPoint, vu::FloatingPoint, il::Integer, iu::Integer, Z::StridedMatrix{$elty}, abstol::FloatingPoint) + function syevr!(jobz::BlasChar, range::BlasChar, uplo::BlasChar, A::StridedMatrix{$elty}, vl::FloatingPoint, vu::FloatingPoint, il::Integer, iu::Integer, Z::StridedMatrix{$elty}, abstol::FloatingPoint) # SUBROUTINE DSYEVR( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, # $ ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, # $ IWORK, LIWORK, INFO ) @@ -1396,7 +1401,7 @@ for (syevr, elty) in chksquare(A) n = size(A, 2) lda = max(1,stride(A,2)) - m = Array(Int32, 1) + m = Array(BlasInt, 1) w = Array($elty, n) if jobz == 'N' ldz = 1 @@ -1407,20 +1412,20 @@ for (syevr, elty) in else error("joz must be 'N' of 'V'") end - isuppz = Array(Int, 2*n) + isuppz = Array(BlasInt, 2*n) work = Array($elty, 1) - lwork = int32(-1) - iwork = Array(Int32, 1) - liwork = int32(-1) - info = Array(Int32, 1) + lwork = blas_int(-1) + iwork = Array(BlasInt, 1) + liwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(syevr)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, - Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, - Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{BlasInt}), &jobz, &range, &uplo, &n, A, &lda, &vl, &vu, &il, &iu, &abstol, m, @@ -1429,10 +1434,10 @@ for (syevr, elty) in info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(work[1]) + lwork = blas_int(work[1]) work = Array($elty, lwork) liwork = iwork[1] - iwork = Array(Int32, liwork) + iwork = Array(BlasInt, liwork) end end return w[1:m[1]] @@ -1443,7 +1448,7 @@ for (syevr, elty, relty) in ((:zheevr_,:Complex128,:Float64), (:cheevr_,:Complex64,:Float32)) @eval begin - function syevr!(jobz::LapackChar, range::LapackChar, uplo::LapackChar, A::StridedMatrix{$elty}, vl::FloatingPoint, vu::FloatingPoint, il::Integer, iu::Integer, Z::StridedMatrix{$elty}, abstol::FloatingPoint) + function syevr!(jobz::BlasChar, range::BlasChar, uplo::BlasChar, A::StridedMatrix{$elty}, vl::FloatingPoint, vu::FloatingPoint, il::Integer, iu::Integer, Z::StridedMatrix{$elty}, abstol::FloatingPoint) # SUBROUTINE ZHEEVR( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, # $ ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, # $ RWORK, LRWORK, IWORK, LIWORK, INFO ) @@ -1461,7 +1466,7 @@ for (syevr, elty, relty) in chksquare(A) n = size(A, 2) lda = max(1,stride(A,2)) - m = Array(Int32, 1) + m = Array(BlasInt, 1) w = Array($relty, n) if jobz == 'N' ldz = 1 @@ -1472,22 +1477,22 @@ for (syevr, elty, relty) in else error("joz must be 'N' of 'V'") end - isuppz = Array(Int, 2*n) + isuppz = Array(BlasInt, 2*n) work = Array($elty, 1) - lwork = int32(-1) + lwork = blas_int(-1) rwork = Array($relty, 1) - lrwork = int32(-1) - iwork = Array(Int32, 1) - liwork = int32(-1) - info = Array(Int32, 1) + lrwork = blas_int(-1) + iwork = Array(BlasInt, 1) + liwork = blas_int(-1) + info = Array(BlasInt, 1) for i in 1:2 ccall(($(string(syevr)),liblapack), Void, - (Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$elty}, Ptr{$elty}, - Ptr{Int32}, Ptr{Int32}, Ptr{$elty}, Ptr{Int32}, - Ptr{$elty}, Ptr{$elty}, Ptr{Int32}, Ptr{Int32}, - Ptr{$elty}, Ptr{Int32}, Ptr{$relty}, Ptr{Int32}, - Ptr{Int32}, Ptr{Int32}, Ptr{Int32}), + (Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), &jobz, &range, &uplo, &n, A, &lda, &vl, &vu, &il, &iu, &abstol, m, @@ -1496,12 +1501,12 @@ for (syevr, elty, relty) in iwork, &liwork, info) if info[1] != 0 throw(LapackException(info[1])) end if lwork < 0 - lwork = int32(real(work[1])) + lwork = blas_int(real(work[1])) work = Array($elty, lwork) - lrwork = int32(rwork[1]) + lrwork = blas_int(rwork[1]) rwork = Array($elty, lrwork) liwork = iwork[1] - iwork = Array(Int32, liwork) + iwork = Array(BlasInt, liwork) end end return w[1:m[1]] diff --git a/base/librandom.jl b/base/librandom.jl index 2eefbfaff0dc3..a9249769297b7 100644 --- a/base/librandom.jl +++ b/base/librandom.jl @@ -109,8 +109,8 @@ for (genrand_fill, gv_genrand_fill, genrand_fill_name, gv_genrand_fill_name) in else ccall(($(string(genrand_fill)),:librandom), Void, - (Ptr{Void}, Ptr{Float64}, Int32), - s.val, A, n & 0xfffffffe) + (Ptr{Void}, Ptr{Float64}, Int), + s.val, A, n & 0xfffffffffffffffe) if isodd(n) A[n] = rand() end @@ -127,8 +127,8 @@ for (genrand_fill, gv_genrand_fill, genrand_fill_name, gv_genrand_fill_name) in else ccall(($(string(gv_genrand_fill)),:librandom), Void, - (Ptr{Void}, Int32), - A, n & 0xfffffffe) + (Ptr{Void}, Int), + A, n & 0xfffffffffffffffe) if isodd(n) A[n] = rand() end diff --git a/base/linalg.jl b/base/linalg.jl index 45af6d870d5d2..e3a35a9c49501 100644 --- a/base/linalg.jl +++ b/base/linalg.jl @@ -1,5 +1,12 @@ ## linalg.jl: Some generic Linear Algebra definitions +function scale!{T<:Number}(X::StridedArray{T}, s::Real) + # FIXME: could use BLAS in more cases + for i in 1:numel(X) + X[i] *= s; + end +end + cross(a::Vector, b::Vector) = [a[2]*b[3]-a[3]*b[2], a[3]*b[1]-a[1]*b[3], a[1]*b[2]-a[2]*b[1]] @@ -23,7 +30,7 @@ diag(A::AbstractVector) = error("Perhaps you meant to use diagm().") #diagm{T}(v::Union(AbstractVector{T},AbstractMatrix{T})) -function norm(x::AbstractVector, p::Number) +function norm{T}(x::AbstractVector{T}, p::Number) if length(x) == 0 return zero(eltype(x)) elseif p == Inf @@ -31,11 +38,18 @@ function norm(x::AbstractVector, p::Number) elseif p == -Inf return min(abs(x)) else - return sum(abs(x).^p).^(1/p) + absx = abs(x) + dx = max(absx) + if dx != zero(T) + scale!(absx, 1/dx) + return dx * (sum(absx.^p).^(1/p)) + else + return sum(absx.^p).^(1/p) + end end end -norm(x::AbstractVector) = sqrt(real(dot(x,x))) +norm(x::AbstractVector) = norm(x, 2) function norm(A::AbstractMatrix, p) m, n = size(A) @@ -49,8 +63,8 @@ function norm(A::AbstractMatrix, p) return max(svdvals(A)) elseif p == Inf return max(sum(abs(A),2)) - elseif p == "fro" - return sqrt(sum(diag(A'*A))) + elseif p == :fro + return norm(reshape(A, numel(A))) else error("invalid parameter to matrix norm") end @@ -72,8 +86,25 @@ trace(A::AbstractMatrix) = sum(diag(A)) #det(a::AbstractMatrix) inv(a::AbstractMatrix) = a \ one(a) -cond(a::AbstractMatrix, p) = norm(a, p) * norm(inv(a), p) -cond(a::AbstractMatrix) = cond(a, 2) + +function cond(a::AbstractMatrix) + s = svdvals(a) + condno = max(s) / min(s) + # Return Inf if condno is NaN (input is all zeros) + isnan(condno) ? Inf : condno +end + +function cond(a::AbstractMatrix, p) + if p == 2 + return cond(a) + else + try + return norm(a, p) * norm(inv(a), p) + catch e + isa(e,LapackException) ? (return Inf) : rethrow(e) + end + end +end #issym(A::AbstractMatrix) #ishermitian(A::AbstractMatrix) diff --git a/base/linalg_bitarray.jl b/base/linalg_bitarray.jl index 724395a35985a..86c4ded60ea07 100644 --- a/base/linalg_bitarray.jl +++ b/base/linalg_bitarray.jl @@ -16,15 +16,15 @@ end #C = falses(nA, nB) #if mA != mB; error("*: argument shapes do not match"); end #if mA == 0; return C; end - #col_ch = _jl_num_bit_chunks(mA) + #col_ch = num_bit_chunks(mA) ## TODO: avoid using aux chunks and copy (?) #aux_chunksA = zeros(Uint64, col_ch) #aux_chunksB = [zeros(Uint64, col_ch) for j=1:nB] #for j = 1:nB - #_jl_copy_chunks(aux_chunksB[j], 1, B.chunks, (j-1)*mA+1, mA) + #copy_chunks(aux_chunksB[j], 1, B.chunks, (j-1)*mA+1, mA) #end #for i = 1:nA - #_jl_copy_chunks(aux_chunksA, 1, A.chunks, (i-1)*mA+1, mA) + #copy_chunks(aux_chunksA, 1, A.chunks, (i-1)*mA+1, mA) #for j = 1:nB #for k = 1:col_ch ## TODO: improve @@ -42,7 +42,7 @@ function triu(B::BitMatrix, k::Int) A = falses(m,n) for i = max(k+1,1):n j = clamp((i - 1) * m + 1, 1, i * m) - _jl_copy_chunks(A.chunks, j, B.chunks, j, min(i-k, m)) + copy_chunks(A.chunks, j, B.chunks, j, min(i-k, m)) end return A end @@ -53,7 +53,7 @@ function tril(B::BitMatrix, k::Int) A = falses(m, n) for i = 1:min(n, m+k) j = clamp((i - 1) * m + i - k, 1, i * m) - _jl_copy_chunks(A.chunks, j, B.chunks, j, max(m-i+k+1, 0)) + copy_chunks(A.chunks, j, B.chunks, j, max(m-i+k+1, 0)) end return A end @@ -127,7 +127,7 @@ function kron(a::BitVector, b::BitVector) zS = zero(S) for j = 1:n if b[j] != zS - _jl_copy_chunks(R.chunks, (j-1)*m+1, a.chunks, 1, m) + copy_chunks(R.chunks, (j-1)*m+1, a.chunks, 1, m) end end return R @@ -160,10 +160,10 @@ end ishermitian(A::BitMatrix) = issym(A) -function _jl_nonzero_chunks(chunks::Vector{Uint64}, pos0::Int, pos1::Int) +function nonzero_chunks(chunks::Vector{Uint64}, pos0::Int, pos1::Int) - k0, l0 = _jl_get_chunks_id(pos0) - k1, l1 = _jl_get_chunks_id(pos1) + k0, l0 = get_chunks_id(pos0) + k1, l1 = get_chunks_id(pos1) delta_k = k1 - k0 @@ -201,7 +201,7 @@ function istriu(A::BitMatrix) m, n = size(A) for j = 1:min(n,m-1) stride = (j-1)*m - if _jl_nonzero_chunks(A.chunks, stride+j+1, stride+m) + if nonzero_chunks(A.chunks, stride+j+1, stride+m) return false end end @@ -215,7 +215,7 @@ function istril(A::BitMatrix) end for j = 2:n stride = (j-1)*m - if _jl_nonzero_chunks(A.chunks, stride+1, stride+min(j-1,m)) + if nonzero_chunks(A.chunks, stride+1, stride+min(j-1,m)) return false end end diff --git a/base/linalg_dense.jl b/base/linalg_dense.jl index b1c832089b0e1..0f33465f0bdc1 100644 --- a/base/linalg_dense.jl +++ b/base/linalg_dense.jl @@ -40,20 +40,28 @@ function istril(A::Matrix) return true end +scale!(X::Array{Float32}, s::Float64) = BLAS.scal!(numel(X), float32(s), X, 1) + +scale!(X::Array{Float64}, s::Float64) = BLAS.scal!(numel(X), s, X, 1) + +scale!(X::Array{Complex64}, s::Float64) = (ccall(("sscal_",Base.libblas_name), Void, (Ptr{Base.BlasInt}, Ptr{Float32}, Ptr{Complex64}, Ptr{Base.BlasInt}), &(2*numel(X)), &float32(s), X, &1); X) + +scale!(X::Array{Complex128}, s::Float64) = (ccall(("dscal_",Base.libblas_name), Void, (Ptr{Base.BlasInt}, Ptr{Float64}, Ptr{Complex128}, Ptr{Base.BlasInt}), &(2*numel(X)), &s, X, &1); X) + #Test whether a matrix is positive-definite -isposdef!{T<:LapackType}(A::Matrix{T}, upper::Bool) = +isposdef!{T<:BlasFloat}(A::Matrix{T}, upper::Bool) = LAPACK.potrf!(upper ? 'U' : 'L', A)[2] == 0 -isposdef!{T<:LapackType}(A::Matrix{T}) = ishermitian(A) && isposdef!(A, true) +isposdef!{T<:BlasFloat}(A::Matrix{T}) = ishermitian(A) && isposdef!(A, true) -isposdef{T<:LapackType}(A::Matrix{T}, upper::Bool) = isposdef!(copy(A), upper) -isposdef{T<:LapackType}(A::Matrix{T}) = isposdef!(copy(A)) +isposdef{T<:BlasFloat}(A::Matrix{T}, upper::Bool) = isposdef!(copy(A), upper) +isposdef{T<:BlasFloat}(A::Matrix{T}) = isposdef!(copy(A)) isposdef{T<:Number}(A::Matrix{T}, upper::Bool) = isposdef!(float64(A), upper) isposdef{T<:Number}(A::Matrix{T}) = isposdef!(float64(A)) -norm{T<:LapackType}(x::Vector{T}) = BLAS.nrm2(length(x), x, 1) +norm{T<:BlasFloat}(x::Vector{T}) = BLAS.nrm2(length(x), x, 1) -function norm{T<:LapackType, TI<:Integer}(x::Vector{T}, rx::Union(Range1{TI},Range{TI})) +function norm{T<:BlasFloat, TI<:Integer}(x::Vector{T}, rx::Union(Range1{TI},Range{TI})) if min(rx) < 1 || max(rx) > length(x) throw(BoundsError()) end @@ -117,9 +125,34 @@ function gradient(F::Vector, h::Vector) return g end -diag(A::Matrix) = [ A[i,i] for i=1:min(size(A,1),size(A,2)) ] +function diag{T}(A::Matrix{T}, k::Integer) + m, n = size(A) + if k >= 0 && k < n + nV = min(m, n-k) + elseif k < 0 && -k < m + nV = min(m+k, n) + else + throw(BoundsError()) + end + + V = zeros(T, nV) + + if k > 0 + for i=1:nV + V[i] = A[i, i+k] + end + else + for i=1:nV + V[i] = A[i-k, i] + end + end + + return V +end + +diag(A) = diag(A, 0) -function diagm{T}(v::Union(Vector{T},Matrix{T})) +function diagm{T}(v::VecOrMat{T}, k::Integer) if isa(v, Matrix) if (size(v,1) != 1 && size(v,2) != 1) error("Input should be nx1 or 1xn") @@ -127,13 +160,22 @@ function diagm{T}(v::Union(Vector{T},Matrix{T})) end n = numel(v) - a = zeros(T, n, n) - for i=1:n - a[i,i] = v[i] + if k >= 0 + a = zeros(T, n+k, n+k) + for i=1:n + a[i,i+k] = v[i] + end + else + a = zeros(T, n-k, n-k) + for i=1:n + a[i-k,i] = v[i] + end end return a -end +end + +diagm(v) = diagm(v, 0) function trace{T}(A::Matrix{T}) t = zero(T) @@ -235,7 +277,7 @@ end ## Destructive matrix exponential using algorithm from Higham, 2008, ## "Functions of Matrices: Theory and Computation", SIAM -function expm!{T<:LapackType}(A::StridedMatrix{T}) +function expm!{T<:BlasFloat}(A::StridedMatrix{T}) m, n = size(A) if m != n error("expm!: Matrix A must be square") end if m < 2 return exp(A) end @@ -307,7 +349,7 @@ function expm!{T<:LapackType}(A::StridedMatrix{T}) P3 = zeros(T, n, n) P4 = zeros(T, n, n) CC14 = CC[14]; CC12 = CC[12]; CC10 = CC[10] - CC8 = CC[8]; CC6 = CC[6]; CC4 = CC[4]; CC2 = CC[2]; + CC8 = CC[8]; CC6 = CC[6]; CC4 = CC[4]; CC2 = CC[2] CC13 = CC[13]; CC11 = CC[11]; CC9 = CC[9] CC7 = CC[7]; CC5 = CC[5]; CC3 = CC[3]; CC1 = CC[1] for i=1:length(I) @@ -361,7 +403,7 @@ function expm!{T<:LapackType}(A::StridedMatrix{T}) end ## Swap rows j and jp and columns j and jp in X -function rcswap!{T<:Number}(j::Int, jp::Int, X::StridedMatrix{T}) +function rcswap!{T<:Number}(j::Integer, jp::Integer, X::StridedMatrix{T}) for k in 1:size(X, 2) tmp = X[k,j] X[k,j] = X[k,jp] @@ -383,9 +425,9 @@ abstract Factorization{T} ## LD for BunchKaufman, LR for CholeskyDense, LU for LUDense and ## define size methods for Factorization types using it. -type BunchKaufman{T<:LapackType} <: Factorization{T} +type BunchKaufman{T<:BlasFloat} <: Factorization{T} LD::Matrix{T} - ipiv::Vector{Int32} + ipiv::Vector{BlasInt} upper::Bool function BunchKaufman(A::Matrix{T}, upper::Bool) LD, ipiv = LAPACK.sytrf!(upper ? 'U' : 'L' , copy(A)) @@ -393,7 +435,7 @@ type BunchKaufman{T<:LapackType} <: Factorization{T} end end -BunchKaufman{T<:LapackType}(A::StridedMatrix{T}, upper::Bool) = BunchKaufman{T}(A, upper) +BunchKaufman{T<:BlasFloat}(A::StridedMatrix{T}, upper::Bool) = BunchKaufman{T}(A, upper) BunchKaufman{T<:Real}(A::StridedMatrix{T}, upper::Bool) = BunchKaufman(float64(A), upper) BunchKaufman{T<:Number}(A::StridedMatrix{T}) = BunchKaufman(A, true) @@ -406,10 +448,10 @@ function inv(B::BunchKaufman) symmetrize!(LAPACK.sytri!(B.upper ? 'U' : 'L', copy(B.LD), B.ipiv), B.upper) end -\{T<:LapackType}(B::BunchKaufman{T}, R::StridedVecOrMat{T}) = +\{T<:BlasFloat}(B::BunchKaufman{T}, R::StridedVecOrMat{T}) = LAPACK.sytrs!(B.upper ? 'U' : 'L', B.LD, B.ipiv, copy(R)) -type CholeskyDense{T<:LapackType} <: Factorization{T} +type CholeskyDense{T<:BlasFloat} <: Factorization{T} LR::Matrix{T} upper::Bool function CholeskyDense(A::Matrix{T}, upper::Bool) @@ -424,7 +466,7 @@ size(C::CholeskyDense,d::Integer) = size(C.LR,d) factors(C::CholeskyDense) = C.LR -\{T<:LapackType}(C::CholeskyDense{T}, B::StridedVecOrMat{T}) = +\{T<:BlasFloat}(C::CholeskyDense{T}, B::StridedVecOrMat{T}) = LAPACK.potrs!(C.upper ? 'U' : 'L', C.LR, copy(B)) function det{T}(C::CholeskyDense{T}) @@ -441,20 +483,20 @@ function inv(C::CholeskyDense) end ## Should these functions check that the matrix is Hermitian? -chold!{T<:LapackType}(A::Matrix{T}, upper::Bool) = CholeskyDense{T}(A, upper) -chold!{T<:LapackType}(A::Matrix{T}) = chold!(A, true) -chold{T<:LapackType}(A::Matrix{T}, upper::Bool) = chold!(copy(A), upper) +chold!{T<:BlasFloat}(A::Matrix{T}, upper::Bool) = CholeskyDense{T}(A, upper) +chold!{T<:BlasFloat}(A::Matrix{T}) = chold!(A, true) +chold{T<:BlasFloat}(A::Matrix{T}, upper::Bool) = chold!(copy(A), upper) chold{T<:Number}(A::Matrix{T}, upper::Bool) = chold(float64(A), upper) chold{T<:Number}(A::Matrix{T}) = chold(A, true) ## Matlab (and R) compatible chol{T<:Number}(A::Matrix{T}) = factors(chold(A)) -type CholeskyDensePivoted{T<:LapackType} <: Factorization{T} +type CholeskyDensePivoted{T<:BlasFloat} <: Factorization{T} LR::Matrix{T} upper::Bool - piv::Vector{Int32} - rank::Int32 + piv::Vector{BlasInt} + rank::BlasInt tol::Real function CholeskyDensePivoted(A::Matrix{T}, upper::Bool, tol::Real) A, piv, rank, info = LAPACK.pstrf!(upper ? 'U' : 'L' , A, tol) @@ -468,7 +510,7 @@ size(C::CholeskyDensePivoted,d::Integer) = size(C.LR,d) factors(C::CholeskyDensePivoted) = C.LR, C.piv -\{T<:LapackType}(C::CholeskyDensePivoted{T}, B::StridedVecOrMat{T}) = +\{T<:BlasFloat}(C::CholeskyDensePivoted{T}, B::StridedVecOrMat{T}) = LAPACK.potrs!(C.upper ? 'U' : 'L', C.LR, copy(B)[C.piv])[invperm(C.piv)] rank(C::CholeskyDensePivoted) = C.rank @@ -484,24 +526,24 @@ function inv(C::CholeskyDensePivoted) end ## Should these functions check that the matrix is Hermitian? -cholpd!{T<:LapackType}(A::Matrix{T}, upper::Bool, tol::Real) = CholeskyDensePivoted{T}(A, upper, tol) -cholpd!{T<:LapackType}(A::Matrix{T}, upper::Bool) = cholpd!(A, upper, -1.) -cholpd!{T<:LapackType}(A::Matrix{T}, tol::Real) = cholpd!(A, true, tol) -cholpd!{T<:LapackType}(A::Matrix{T}) = cholpd!(A, true, -1.) +cholpd!{T<:BlasFloat}(A::Matrix{T}, upper::Bool, tol::Real) = CholeskyDensePivoted{T}(A, upper, tol) +cholpd!{T<:BlasFloat}(A::Matrix{T}, upper::Bool) = cholpd!(A, upper, -1.) +cholpd!{T<:BlasFloat}(A::Matrix{T}, tol::Real) = cholpd!(A, true, tol) +cholpd!{T<:BlasFloat}(A::Matrix{T}) = cholpd!(A, true, -1.) cholpd{T<:Number}(A::Matrix{T}, upper::Bool, tol::Real) = cholpd(float64(A), upper, tol) cholpd{T<:Number}(A::Matrix{T}, upper::Bool) = cholpd(float64(A), upper, -1.) cholpd{T<:Number}(A::Matrix{T}, tol::Real) = cholpd(float64(A), true, tol) cholpd{T<:Number}(A::Matrix{T}) = cholpd(float64(A), true, -1.) -cholpd{T<:LapackType}(A::Matrix{T}, upper::Bool, tol::Real) = cholpd!(copy(A), upper, tol) -cholpd{T<:LapackType}(A::Matrix{T}, upper::Bool) = cholpd!(copy(A), upper, -1.) -cholpd{T<:LapackType}(A::Matrix{T}, tol::Real) = cholpd!(copy(A), true, tol) -cholpd{T<:LapackType}(A::Matrix{T}) = cholpd!(copy(A), true, -1.) +cholpd{T<:BlasFloat}(A::Matrix{T}, upper::Bool, tol::Real) = cholpd!(copy(A), upper, tol) +cholpd{T<:BlasFloat}(A::Matrix{T}, upper::Bool) = cholpd!(copy(A), upper, -1.) +cholpd{T<:BlasFloat}(A::Matrix{T}, tol::Real) = cholpd!(copy(A), true, tol) +cholpd{T<:BlasFloat}(A::Matrix{T}) = cholpd!(copy(A), true, -1.) type LUDense{T} <: Factorization{T} lu::Matrix{T} - ipiv::Vector{Int32} - info::Int32 - function LUDense(lu::Matrix{T}, ipiv::Vector{Int32}, info::Int32) + ipiv::Vector{BlasInt} + info::BlasInt + function LUDense(lu::Matrix{T}, ipiv::Vector{BlasInt}, info::BlasInt) m, n = size(lu) m == n ? new(lu, ipiv, info) : error("LUDense only defined for square matrices") end @@ -525,12 +567,12 @@ function factors{T}(lu::LUDense{T}) L, U, P end -function lud!{T<:LapackType}(A::Matrix{T}) +function lud!{T<:BlasFloat}(A::Matrix{T}) lu, ipiv, info = LAPACK.getrf!(A) LUDense{T}(lu, ipiv, info) end -lud{T<:LapackType}(A::Matrix{T}) = lud!(copy(A)) +lud{T<:BlasFloat}(A::Matrix{T}) = lud!(copy(A)) lud{T<:Number}(A::Matrix{T}) = lud(float64(A)) ## Matlab-compatible @@ -549,12 +591,12 @@ function det(A::Matrix) return det(lud(A)) end -function (\){T<:LapackType}(lu::LUDense{T}, B::StridedVecOrMat{T}) +function (\){T<:BlasFloat}(lu::LUDense{T}, B::StridedVecOrMat{T}) if lu.info > 0; error("Singular system"); end LAPACK.getrs!('N', lu.lu, lu.ipiv, copy(B)) end -function inv{T<:LapackType}(lu::LUDense{T}) +function inv{T<:BlasFloat}(lu::LUDense{T}) m, n = size(lu.lu) if m != n; error("inv only defined for square matrices"); end if lu.info > 0; return error("Singular system"); end @@ -572,11 +614,11 @@ end size(A::QRDense) = size(A.hh) size(A::QRDense,n) = size(A.hh,n) -qrd!{T<:LapackType}(A::StridedMatrix{T}) = QRDense{T}(LAPACK.geqrf!(A)...) -qrd{T<:LapackType}(A::StridedMatrix{T}) = qrd!(copy(A)) +qrd!{T<:BlasFloat}(A::StridedMatrix{T}) = QRDense{T}(LAPACK.geqrf!(A)...) +qrd{T<:BlasFloat}(A::StridedMatrix{T}) = qrd!(copy(A)) qrd{T<:Real}(A::StridedMatrix{T}) = qrd(float64(A)) -function factors{T<:LapackType}(qrd::QRDense{T}) +function factors{T<:BlasFloat}(qrd::QRDense{T}) aa = copy(qrd.hh) R = triu(aa[1:min(size(aa)),:]) # must be *before* call to orgqr! LAPACK.orgqr!(aa, qrd.tau, size(aa,2)), R @@ -585,15 +627,15 @@ end qr{T<:Number}(x::StridedMatrix{T}) = factors(qrd(x)) ## Multiplication by Q from the QR decomposition -(*){T<:LapackType}(A::QRDense{T}, B::StridedVecOrMat{T}) = +(*){T<:BlasFloat}(A::QRDense{T}, B::StridedVecOrMat{T}) = LAPACK.ormqr!('L', 'N', A.hh, size(A.hh,2), A.tau, copy(B)) ## Multiplication by Q' from the QR decomposition -Ac_mul_B{T<:LapackType}(A::QRDense{T}, B::StridedVecOrMat{T}) = +Ac_mul_B{T<:BlasFloat}(A::QRDense{T}, B::StridedVecOrMat{T}) = LAPACK.ormqr!('L', iscomplex(A.tau)?'C':'T', A.hh, size(A.hh,2), A.tau, copy(B)) ## Least squares solution. Should be more careful about cases with m < n -function (\){T<:LapackType}(A::QRDense{T}, B::StridedVecOrMat{T}) +function (\){T<:BlasFloat}(A::QRDense{T}, B::StridedVecOrMat{T}) n = length(A.tau) ans, info = LAPACK.trtrs!('U','N','N',A.hh[1:n,:],(A'*B)[1:n,:]) if info > 0; error("Singular system"); end @@ -603,8 +645,8 @@ end type QRPDense{T} <: Factorization{T} hh::Matrix{T} tau::Vector{T} - jpvt::Vector{Int32} - function QRPDense(hh::Matrix{T}, tau::Vector{T}, jpvt::Vector{Int32}) + jpvt::Vector{BlasInt} + function QRPDense(hh::Matrix{T}, tau::Vector{T}, jpvt::Vector{BlasInt}) m, n = size(hh) if length(tau) != min(m,n) || length(jpvt) != n error("QRPDense: mismatched dimensions") @@ -615,33 +657,33 @@ end size(x::QRPDense) = size(x.hh) size(x::QRPDense,d) = size(x.hh,d) ## Multiplication by Q from the QR decomposition -(*){T<:LapackType}(A::QRPDense{T}, B::StridedVecOrMat{T}) = +(*){T<:BlasFloat}(A::QRPDense{T}, B::StridedVecOrMat{T}) = LAPACK.ormqr!('L', 'N', A.hh, size(A,2), A.tau, copy(B)) ## Multiplication by Q' from the QR decomposition -Ac_mul_B{T<:LapackType}(A::QRPDense{T}, B::StridedVecOrMat{T}) = +Ac_mul_B{T<:BlasFloat}(A::QRPDense{T}, B::StridedVecOrMat{T}) = LAPACK.ormqr!('L', iscomplex(A.tau)?'C':'T', A.hh, size(A,2), A.tau, copy(B)) -qrpd!{T<:LapackType}(A::StridedMatrix{T}) = QRPDense{T}(LAPACK.geqp3!(A)...) -qrpd{T<:LapackType}(A::StridedMatrix{T}) = qrpd!(copy(A)) +qrpd!{T<:BlasFloat}(A::StridedMatrix{T}) = QRPDense{T}(LAPACK.geqp3!(A)...) +qrpd{T<:BlasFloat}(A::StridedMatrix{T}) = qrpd!(copy(A)) qrpd{T<:Real}(x::StridedMatrix{T}) = qrpd(float64(x)) -function factors{T<:LapackType}(x::QRPDense{T}) +function factors{T<:BlasFloat}(x::QRPDense{T}) aa = copy(x.hh) R = triu(aa[1:min(size(aa)),:]) LAPACK.orgqr!(aa, x.tau, size(aa,2)), R, x.jpvt end -qrp{T<:LapackType}(x::StridedMatrix{T}) = factors(qrpd(x)) +qrp{T<:BlasFloat}(x::StridedMatrix{T}) = factors(qrpd(x)) qrp{T<:Real}(x::StridedMatrix{T}) = qrp(float64(x)) -function (\){T<:LapackType}(A::QRPDense{T}, B::StridedVecOrMat{T}) +function (\){T<:BlasFloat}(A::QRPDense{T}, B::StridedVecOrMat{T}) n = length(A.tau) x, info = LAPACK.trtrs!('U','N','N',A.hh[1:n,:],(A'*B)[1:n,:]) if info > 0; error("Singular system"); end isa(B, Vector) ? x[invperm(A.jpvt)] : x[:,invperm(A.jpvt)] end -function eig{T<:LapackType}(A::StridedMatrix{T}, vecs::Bool) +function eig{T<:BlasFloat}(A::StridedMatrix{T}, vecs::Bool) n = size(A, 2) if n == 0; return vecs ? (zeros(T, 0), zeros(T, 0, 0)) : zeros(T, 0, 0); end @@ -693,7 +735,7 @@ eigvals(x::StridedMatrix) = eig(x, false) # lesser memory. It should be made available through a keyword argument # at a later date. # -# function svd{T<:LapackType}(A::StridedMatrix{T},vecs::Bool,thin::Bool) +# function svd{T<:BlasFloat}(A::StridedMatrix{T},vecs::Bool,thin::Bool) # m,n = size(A) # if m == 0 || n == 0 # if vecs; return (eye(m, thin ? n : m), zeros(0), eye(n,n)); end @@ -708,7 +750,7 @@ eigvals(x::StridedMatrix) = eig(x, false) # svd(A::StridedMatrix, thin::Bool) = svd(A,true,thin) # svdvals(A) = svd(A,false,true)[2] -function svd{T<:LapackType}(A::StridedMatrix{T},vecs::Bool,thin::Bool) +function svd{T<:BlasFloat}(A::StridedMatrix{T},vecs::Bool,thin::Bool) m,n = size(A) if m == 0 || n == 0 if vecs; return (eye(m, thin ? n : m), zeros(0), eye(n,n)); end @@ -723,7 +765,7 @@ svd(A::StridedMatrix) = svd(A,true,false) svd(A::StridedMatrix, thin::Bool) = svd(A,true,thin) svdvals(A) = svd(A,false,true)[2] -function (\){T<:LapackType}(A::StridedMatrix{T}, B::StridedVecOrMat{T}) +function (\){T<:BlasFloat}(A::StridedMatrix{T}, B::StridedVecOrMat{T}) Acopy = copy(A) m, n = size(Acopy) X = copy(B) @@ -751,10 +793,10 @@ function (\){T<:LapackType}(A::StridedMatrix{T}, B::StridedVecOrMat{T}) LAPACK.gelsd!(Acopy, X)[1] end -(\){T1<:LapackType, T2<:LapackType}(A::StridedMatrix{T1}, B::StridedVecOrMat{T2}) = +(\){T1<:BlasFloat, T2<:BlasFloat}(A::StridedMatrix{T1}, B::StridedVecOrMat{T2}) = (\)(convert(Array{promote_type(T1,T2)},A), convert(Array{promote_type(T1,T2)},B)) -(\){T1<:LapackType, T2<:Real}(A::StridedMatrix{T1}, B::StridedVecOrMat{T2}) = (\)(A, convert(Array{T1}, B)) -(\){T1<:Real, T2<:LapackType}(A::StridedMatrix{T1}, B::StridedVecOrMat{T2}) = (\)(convert(Array{T2}, A), B) +(\){T1<:BlasFloat, T2<:Real}(A::StridedMatrix{T1}, B::StridedVecOrMat{T2}) = (\)(A, convert(Array{T1}, B)) +(\){T1<:Real, T2<:BlasFloat}(A::StridedMatrix{T1}, B::StridedVecOrMat{T2}) = (\)(convert(Array{T2}, A), B) (\){T1<:Real, T2<:Real}(A::StridedMatrix{T1}, B::StridedVecOrMat{T2}) = (\)(float64(A), float64(B)) (\){T1<:Number, T2<:Number}(A::StridedMatrix{T1}, B::StridedVecOrMat{T2}) = (\)(complex128(A), complex128(B)) @@ -765,30 +807,30 @@ end ## Lower priority: Add LQ, QL and RQ factorizations ## Moore-Penrose inverse -function pinv{T<:LapackType}(A::StridedMatrix{T}) +function pinv{T<:BlasFloat}(A::StridedMatrix{T}) u,s,vt = svd(A, true) sinv = zeros(T, length(s)) index = s .> eps(real(one(T)))*max(size(A))*max(s) sinv[index] = 1 ./ s[index] vt'diagmm(sinv, u') end -pinv(A::StridedMatrix{Int}) = pinv(float(A)) +pinv{T<:Integer}(A::StridedMatrix{T}) = pinv(float(A)) pinv(a::StridedVector) = pinv(reshape(a, length(a), 1)) ## Basis for null space -function null{T<:LapackType}(A::StridedMatrix{T}) +function null{T<:BlasFloat}(A::StridedMatrix{T}) m,n = size(A) if m >= n; return zeros(T, n, 0); end; u,s,vt = svd(A) vt[m+1:,:]' end -null(A::StridedMatrix{Int}) = null(float(A)) +null{T<:Integer}(A::StridedMatrix{T}) = null(float(A)) null(a::StridedVector) = null(reshape(a, length(a), 1)) #### Specialized matrix types #### ## Symmetric tridiagonal matrices -type SymTridiagonal{T<:LapackType} <: AbstractMatrix{T} +type SymTridiagonal{T<:BlasFloat} <: AbstractMatrix{T} dv::Vector{T} # diagonal ev::Vector{T} # sub/super diagonal function SymTridiagonal(dv::Vector{T}, ev::Vector{T}) @@ -797,7 +839,7 @@ type SymTridiagonal{T<:LapackType} <: AbstractMatrix{T} end end -SymTridiagonal{T<:LapackType}(dv::Vector{T}, ev::Vector{T}) = SymTridiagonal{T}(copy(dv), copy(ev)) +SymTridiagonal{T<:BlasFloat}(dv::Vector{T}, ev::Vector{T}) = SymTridiagonal{T}(copy(dv), copy(ev)) function SymTridiagonal{T<:Real}(dv::Vector{T}, ev::Vector{T}) SymTridiagonal{Float64}(float64(dv),float64(ev)) end @@ -829,7 +871,7 @@ size(m::SymTridiagonal,d::Integer) = d<1 ? error("dimension out of range") : (d< eig(m::SymTridiagonal, vecs::Bool) = LAPACK.stev!(vecs ? 'V' : 'N', copy(m.dv), copy(m.ev)) eig(m::SymTridiagonal) = eig(m::SymTridiagonal, true) ## This function has been in Julia for some time. Could probably be dropped. -trideig{T<:LapackType}(d::Vector{T}, e::Vector{T}) = LAPACK.stev!('N', copy(d), copy(e))[1] +trideig{T<:BlasFloat}(d::Vector{T}, e::Vector{T}) = LAPACK.stev!('N', copy(d), copy(e))[1] ## Tridiagonal matrices ## type Tridiagonal{T} <: AbstractMatrix{T} @@ -839,7 +881,7 @@ type Tridiagonal{T} <: AbstractMatrix{T} dutmp::Vector{T} # scratch space for vector RHS solver, sup-diagonal rhstmp::Vector{T}# scratch space, rhs - function Tridiagonal(N::Int) + function Tridiagonal(N::Integer) dutmp = Array(T, N-1) rhstmp = Array(T, N) new(dutmp, rhstmp, dutmp, dutmp, rhstmp) # first three will be overwritten @@ -899,7 +941,7 @@ iround(M::Tridiagonal) = Tridiagonal(iround(M.dl), iround(M.d), iround(M.du)) ## Solvers #### Tridiagonal matrix routines #### -function \{T<:LapackType}(M::Tridiagonal{T}, rhs::StridedVecOrMat{T}) +function \{T<:BlasFloat}(M::Tridiagonal{T}, rhs::StridedVecOrMat{T}) if stride(rhs, 1) == 1 return LAPACK.gtsv!(copy(M.dl), copy(M.d), copy(M.du), copy(rhs)) end @@ -955,11 +997,14 @@ function solve(x::AbstractArray, xrng::Ranges{Int}, M::Tridiagonal, rhs::Abstrac end return x end + solve(x::StridedVector, M::Tridiagonal, rhs::StridedVector) = solve(x, 1:length(x), M, rhs, 1:length(rhs)) + function solve(M::Tridiagonal, rhs::StridedVector) x = similar(rhs) solve(x, M, rhs) end + function solve(X::StridedMatrix, M::Tridiagonal, B::StridedMatrix) if size(B, 1) != size(M, 1) error("dimension mismatch") @@ -975,6 +1020,7 @@ function solve(X::StridedMatrix, M::Tridiagonal, B::StridedMatrix) end return X end + function solve(M::Tridiagonal, B::StridedMatrix) X = similar(B) solve(X, M, B) @@ -1003,7 +1049,9 @@ function mult(x::AbstractArray, xrng::Ranges{Int}, M::Tridiagonal, v::AbstractAr x[xi] = dl[N-1]*v[vi] + d[N]*v[vi+vstride] return x end + mult(x::StridedVector, M::Tridiagonal, v::StridedVector) = mult(x, 1:length(x), M, v, 1:length(v)) + function mult(X::StridedMatrix, M::Tridiagonal, B::StridedMatrix) if size(B, 1) != size(M, 1) error("dimension mismatch") @@ -1019,15 +1067,18 @@ function mult(X::StridedMatrix, M::Tridiagonal, B::StridedMatrix) end return X end + mult(X::StridedMatrix, M1::Tridiagonal, M2::Tridiagonal) = mult(X, M1, full(M2)) + function *(M::Tridiagonal, B::Union(StridedVector,StridedMatrix)) X = similar(B) mult(X, M, B) end + *(A::Tridiagonal, B::Tridiagonal) = A*full(B) #### Factorizations for Tridiagonal #### -type LDLTTridiagonal{T<:LapackType,S<:LapackType} <: Factorization{T} +type LDLTTridiagonal{T<:BlasFloat,S<:BlasFloat} <: Factorization{T} D::Vector{S} E::Vector{T} function LDLTTridiagonal(D::Vector{S}, E::Vector{T}) @@ -1035,12 +1086,13 @@ type LDLTTridiagonal{T<:LapackType,S<:LapackType} <: Factorization{T} new(D, E) end end -LDLTTridiagonal{S<:LapackType,T<:LapackType}(D::Vector{S}, E::Vector{T}) = LDLTTridiagonal{T,S}(D, E) -ldltd!{T<:LapackType}(A::SymTridiagonal{T}) = LDLTTridiagonal(LAPACK.pttrf!(real(A.dv),A.ev)...) -ldltd{T<:LapackType}(A::SymTridiagonal{T}) = ldltd!(copy(A)) +LDLTTridiagonal{S<:BlasFloat,T<:BlasFloat}(D::Vector{S}, E::Vector{T}) = LDLTTridiagonal{T,S}(D, E) -function (\){T<:LapackType}(C::LDLTTridiagonal{T}, B::StridedVecOrMat{T}) +ldltd!{T<:BlasFloat}(A::SymTridiagonal{T}) = LDLTTridiagonal(LAPACK.pttrf!(real(A.dv),A.ev)...) +ldltd{T<:BlasFloat}(A::SymTridiagonal{T}) = ldltd!(copy(A)) + +function (\){T<:BlasFloat}(C::LDLTTridiagonal{T}, B::StridedVecOrMat{T}) if iscomplex(B) return LAPACK.pttrs!('L', C.D, C.E, copy(B)) end LAPACK.pttrs!(C.D, C.E, copy(B)) end @@ -1050,9 +1102,9 @@ type LUTridiagonal{T} <: Factorization{T} d::Vector{T} du::Vector{T} du2::Vector{T} - ipiv::Vector{Int32} + ipiv::Vector{BlasInt} function LUTridiagonal(dl::Vector{T}, d::Vector{T}, du::Vector{T}, - du2::Vector{T}, ipiv::Vector{Int32}) + du2::Vector{T}, ipiv::Vector{BlasInt}) n = length(d) if length(dl) != n - 1 || length(du) != n - 1 || length(ipiv) != n || length(du2) != n-2 error("LUTridiagonal: dimension mismatch") @@ -1060,11 +1112,11 @@ type LUTridiagonal{T} <: Factorization{T} new(dl, d, du, du2, ipiv) end end + #show(io, lu::LUTridiagonal) = print(io, "LU decomposition of ", summary(lu.lu)) lud!{T}(A::Tridiagonal{T}) = LUTridiagonal{T}(LAPACK.gttrf!(A.dl,A.d,A.du)...) -lud{T}(A::Tridiagonal{T}) = - LUTridiagonal{T}(LAPACK.gttrf!(copy(A.dl),copy(A.d),copy(A.du))...) +lud{T}(A::Tridiagonal{T}) = LUTridiagonal{T}(LAPACK.gttrf!(copy(A.dl),copy(A.d),copy(A.du))...) lu(A::Tridiagonal) = factors(lud(A)) function det{T}(lu::LUTridiagonal{T}) @@ -1074,7 +1126,7 @@ end det(A::Tridiagonal) = det(lud(A)) -(\){T<:LapackType}(lu::LUTridiagonal{T}, B::StridedVecOrMat{T}) = +(\){T<:BlasFloat}(lu::LUTridiagonal{T}, B::StridedVecOrMat{T}) = LAPACK.gttrs!('N', lu.dl, lu.d, lu.du, lu.du2, lu.ipiv, copy(B)) diff --git a/base/linalg_sparse.jl b/base/linalg_sparse.jl index fadb5a5dc36b7..317cebf3b0943 100644 --- a/base/linalg_sparse.jl +++ b/base/linalg_sparse.jl @@ -108,7 +108,7 @@ end ## triu, tril -function triu{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, k::Int) +function triu{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, k::Integer) m,n = size(S) colptr = Array(Ti, n+1) nnz = 0 @@ -139,7 +139,7 @@ function triu{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, k::Int) end triu{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, k::Integer) = triu(S, int(k)) -function tril{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, k::Int) +function tril{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, k::Integer) m,n = size(S) colptr = Array(Ti, n+1) nnz = 0 @@ -175,7 +175,7 @@ tril{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, k::Integer) = tril(S, int(k)) ## diff -function _jl_sparse_diff1{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}) +function sparse_diff1{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}) m,n = size(S) if m <= 1 return SparseMatrixCSC{Tv,Ti}(0, n, ones(n+1), Ti[], Tv[]) @@ -219,7 +219,7 @@ function _jl_sparse_diff1{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}) return SparseMatrixCSC{Tv,Ti}(m-1, n, colptr, rowval, nzval) end -function _jl_sparse_diff2{Tv,Ti}(a::SparseMatrixCSC{Tv,Ti}) +function sparse_diff2{Tv,Ti}(a::SparseMatrixCSC{Tv,Ti}) m,n = size(a) colptr = Array(Ti, max(n,1)) @@ -313,9 +313,9 @@ end function diff(a::SparseMatrixCSC, dim::Integer) if dim == 1 - _jl_sparse_diff1(a) + sparse_diff1(a) else - _jl_sparse_diff2(a) + sparse_diff2(a) end end diff --git a/base/math.jl b/base/math.jl index 62ad144f888b7..dc74322fe7a58 100644 --- a/base/math.jl +++ b/base/math.jl @@ -7,7 +7,8 @@ export sin, cos, tan, sinh, cosh, tanh, asin, acos, atan, acosd, acotd, acscd, asecd, asind, atand, atan2, radians2degrees, degrees2radians, log, log2, log10, log1p, logb, exp, exp2, expm1, - cbrt, sqrt, square, erf, erfc, ceil, floor, trunc, round, + cbrt, sqrt, square, erf, erfc, erfcx, erfi, dawson, + ceil, floor, trunc, round, significand, lgamma, hypot, gamma, lfact, max, min, ilogb, ldexp, frexp, clamp, modf, ^, airy, airyai, airyprime, airyaiprime, airybi, airybiprime, @@ -234,16 +235,23 @@ end end airy(z) = airy(0,z) +@vectorize_1arg Number airy airyprime(z) = airy(1,z) +@vectorize_1arg Number airyprime airyai(z) = airy(0,z) +@vectorize_1arg Number airyai airyaiprime(z) = airy(1,z) +@vectorize_1arg Number airyaiprime airybi(z) = airy(2,z) +@vectorize_1arg Number airybi airybiprime(z) = airy(3,z) +@vectorize_1arg Number airybiprime -airy(k, x::FloatingPoint) = oftype(x, real(airy(k, complex(x)))) -airy(k, x::Real) = airy(k, float(x)) -airy(k, z::Complex64) = complex64(airy(k, complex128(z))) -airy(k, z::Complex) = airy(k, complex128(z)) +airy(k::Number, x::FloatingPoint) = oftype(x, real(airy(k, complex(x)))) +airy(k::Number, x::Real) = airy(k, float(x)) +airy(k::Number, z::Complex64) = complex64(airy(k, complex128(z))) +airy(k::Number, z::Complex) = airy(convert(Int,k), complex128(z)) +@vectorize_2arg Number airy let const cy::Array{Float64,1} = Array(Float64,2) @@ -361,10 +369,12 @@ besselh(nu, z) = besselh(nu, 1, z) besselh(nu::Real, k::Integer, z::Complex64) = complex64(besselh(float64(nu), k, complex128(z))) besselh(nu::Real, k::Integer, z::Complex) = besselh(float64(nu), k, complex128(z)) besselh(nu::Real, k::Integer, x::Real) = besselh(float64(nu), k, complex128(x)) +@vectorize_2arg Number besselh besseli(nu::Real, z::Complex64) = complex64(bessely(float64(nu), complex128(z))) besseli(nu::Real, z::Complex) = besseli(float64(nu), complex128(z)) besseli(nu::Real, x::Real) = besseli(float64(nu), complex128(x)) +@vectorize_2arg Number besseli function besselj(nu::FloatingPoint, x::FloatingPoint) ans = besselj(float64(nu), complex128(x)) @@ -375,17 +385,24 @@ besselj(nu::Real, z::Complex64) = complex64(besselj(float64(nu), complex128(z))) besselj(nu::Real, z::Complex) = besselj(float64(nu), complex128(z)) besselj(nu::Integer, x::Real) = besselj(nu, float(x)) besselj(nu::Real, x::Real) = besselj(float(nu), float(x)) +@vectorize_2arg Number besselj besselk(nu::Real, z::Complex64) = complex64(besselk(float64(nu), complex128(z))) besselk(nu::Real, z::Complex) = besselk(float64(nu), complex128(z)) besselk(nu::Real, x::Real) = besselk(float64(nu), complex128(x)) +@vectorize_2arg Number besselk bessely(nu::Real, z::Complex64) = complex64(bessely(float64(nu), complex128(z))) bessely(nu::Real, z::Complex) = bessely(float64(nu), complex128(z)) bessely(nu::Real, x::Real) = bessely(float64(nu), complex128(x)) +@vectorize_2arg Number bessely hankelh1(nu, z) = besselh(nu, 1, z) +@vectorize_2arg Number hankelh1 + hankelh2(nu, z) = besselh(nu, 2, z) +@vectorize_2arg Number hankelh2 + function angle_restrict_symm(theta) P1 = 4 * 7.8539812564849853515625e-01 @@ -444,8 +461,8 @@ const digamma_EUL = 0.57721566490153286061 const digamma_coefs = [8.33333333333333333333e-2,-2.10927960927960927961e-2, 7.57575757575757575758e-3, -4.16666666666666666667e-3, 3.96825396825396825397e-3,-8.33333333333333333333e-3, 8.33333333333333333333e-2] + function digamma(x::Float64) - negative = false nz = 0.0 @@ -514,6 +531,8 @@ digamma(x::Real) = digamma(float64(x)) beta(x::Number, w::Number) = exp(lgamma(x)+lgamma(w)-lgamma(x+w)) lbeta(x::Number, w::Number) = lgamma(x)+lgamma(w)-lgamma(x+w) +@vectorize_2arg Number beta +@vectorize_2arg Number lbeta const eta_coeffs = [.99999999999999999997, @@ -617,10 +636,40 @@ end eta(x::Integer) = eta(float64(x)) eta(x::Real) = oftype(x,eta(float64(x))) eta(z::Complex) = oftype(z,eta(complex128(z))) +@vectorize_1arg Number eta function zeta(z::Number) zz = 2^z eta(z) * zz/(zz-2) end +@vectorize_1arg Number zeta + +const Faddeeva_tmp = Array(Float64,2) + +# wrappers for complex Faddeeva functions; these will get a lot simpler, +# and can call openlibm directly, once ccall supports C99 complex types. +for f in (:erf, :erfc, :erfcx, :erfi, :Dawson) + fname = (f === :Dawson) ? :dawson : f + @eval begin + function ($fname)(z::Complex128) + ccall(($(string("wrapFaddeeva_",f)),:libFaddeeva_wrapper), Void, (Ptr{Complex128},Ptr{Complex128},Float64,), Faddeeva_tmp, &z, zero(Float64)) + return complex128(Faddeeva_tmp[1],Faddeeva_tmp[2]) + end + function ($fname)(z::Complex64) + ccall(($(string("wrapFaddeeva_",f)),:libFaddeeva_wrapper), Void, (Ptr{Complex128},Ptr{Complex128},Float64,), Faddeeva_tmp, &complex128(z), float64(eps(Float32))) + return complex64(Faddeeva_tmp[1],Faddeeva_tmp[2]) + end + ($fname)(z::Complex) = ($fname)(complex128(z)) + end +end +for f in (:erfcx, :erfi, :Dawson) + fname = (f === :Dawson) ? :dawson : f + @eval begin + ($fname)(x::Float64) = ccall(($(string("Faddeeva_",f,"_re")),:libopenlibm), Float64, (Float64,), x) + ($fname)(x::Float32) = float32(ccall(($(string("Faddeeva_",f,"_re")),:libopenlibm), Float64, (Float64,), float64(x))) + ($fname)(x::Real) = ($fname)(float(x)) + @vectorize_1arg Number $fname + end +end end # module diff --git a/base/matmul.jl b/base/matmul.jl index 9e331f9b1be33..f8f5b17264df4 100644 --- a/base/matmul.jl +++ b/base/matmul.jl @@ -62,30 +62,30 @@ end # Matrix-vector multiplication -function (*){T<:LapackType}(A::StridedMatrix{T}, +function (*){T<:BlasFloat}(A::StridedMatrix{T}, X::StridedVector{T}) Y = similar(A, size(A,1)) gemv(Y, 'N', A, X) end -A_mul_B{T<:LapackType}(y::StridedVector{T}, A::StridedMatrix{T}, x::StridedVector{T}) = gemv(y, 'N', A, x) +A_mul_B{T<:BlasFloat}(y::StridedVector{T}, A::StridedMatrix{T}, x::StridedVector{T}) = gemv(y, 'N', A, x) A_mul_B(y::StridedVector, A::StridedMatrix, x::StridedVector) = generic_matvecmul(y, 'N', A, x) -function At_mul_B{T<:LapackType}(A::StridedMatrix{T}, x::StridedVector{T}) +function At_mul_B{T<:BlasFloat}(A::StridedMatrix{T}, x::StridedVector{T}) y = similar(A, size(A, 2)) gemv(y, 'T', A, x) end -At_mul_B{T<:LapackType}(y::StridedVector{T}, A::StridedMatrix{T}, x::StridedVector{T}) = gemv(y, 'T', A, x) +At_mul_B{T<:BlasFloat}(y::StridedVector{T}, A::StridedMatrix{T}, x::StridedVector{T}) = gemv(y, 'T', A, x) At_mul_B(y::StridedVector, A::StridedMatrix, x::StridedVector) = generic_matvecmul(y, 'T', A, x) # Matrix-matrix multiplication -(*){T<:LapackType}(A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper('N', 'N', A, B) -A_mul_B{T<:LapackType}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'N', 'N', A, B) +(*){T<:BlasFloat}(A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper('N', 'N', A, B) +A_mul_B{T<:BlasFloat}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'N', 'N', A, B) A_mul_B{T,S,R}(C::StridedMatrix{R}, A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul(C, 'N', 'N', A, B) -function At_mul_B{T<:LapackType}(A::StridedMatrix{T}, +function At_mul_B{T<:BlasFloat}(A::StridedMatrix{T}, B::StridedMatrix{T}) if is(A, B) syrk_wrapper('T', A) @@ -94,11 +94,11 @@ function At_mul_B{T<:LapackType}(A::StridedMatrix{T}, end end -At_mul_B{T<:LapackType}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'T', 'N', A, B) +At_mul_B{T<:BlasFloat}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'T', 'N', A, B) At_mul_B{T,S}(A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul('T', 'N', A, B) At_mul_B{T,S,R}(C::StridedMatrix{R}, A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul(C, 'T', 'N', A, B) -function A_mul_Bt{T<:LapackType}(A::StridedMatrix{T}, +function A_mul_Bt{T<:BlasFloat}(A::StridedMatrix{T}, B::StridedMatrix{T}) if is(A, B) syrk_wrapper('N', A) @@ -107,12 +107,12 @@ function A_mul_Bt{T<:LapackType}(A::StridedMatrix{T}, end end -A_mul_Bt{T<:LapackType}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'N', 'T', A, B) +A_mul_Bt{T<:BlasFloat}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'N', 'T', A, B) A_mul_Bt{T,S}(A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul('N', 'T', A, B) A_mul_Bt{T,S,R}(C::StridedMatrix{R}, A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul(C, 'N', 'T', A, B) -At_mul_Bt{T<:LapackType}(A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper('T', 'T', A, B) -At_mul_Bt{T<:LapackType}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'T', 'T', A, B) +At_mul_Bt{T<:BlasFloat}(A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper('T', 'T', A, B) +At_mul_Bt{T<:BlasFloat}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'T', 'T', A, B) At_mul_Bt{T,S}(A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul('T', 'T', A, B) At_mul_Bt{T,S,R}(C::StridedMatrix{R}, A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul(C, 'T', 'T', A, B) @@ -146,8 +146,8 @@ A_mul_Bc{T<:Union(Complex128,Complex64)}(C::StridedMatrix{T}, A::StridedMatrix{T A_mul_Bc{T,S}(A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul('N', 'C', A, B) A_mul_Bc{T,S,R}(C::StridedMatrix{R}, A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul(C, 'N', 'C', A, B) -Ac_mul_Bc{T<:LapackType}(A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper('C', 'C', A, B) -Ac_mul_Bc{T<:LapackType}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'C', 'C', A, B) +Ac_mul_Bc{T<:BlasFloat}(A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper('C', 'C', A, B) +Ac_mul_Bc{T<:BlasFloat}(C::StridedMatrix{T}, A::StridedMatrix{T}, B::StridedMatrix{T}) = gemm_wrapper(C, 'C', 'C', A, B) Ac_mul_Bt{T,S}(A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul('C', 'C', A, B) Ac_mul_Bt{T,S,R}(C::StridedMatrix{R}, A::StridedMatrix{T}, B::StridedMatrix{S}) = generic_matmatmul(C, 'C', 'C', A, B) @@ -195,7 +195,7 @@ end symmetrize_conj!(A) = symmetrize_conj!(A, true) -function gemv{T<:LapackType}(y::StridedVector{T}, +function gemv{T<:BlasFloat}(y::StridedVector{T}, tA, A::StridedMatrix{T}, x::StridedVector{T}) @@ -215,7 +215,7 @@ function gemv{T<:LapackType}(y::StridedVector{T}, BLAS.gemv!(tA, one(T), A, x, zero(T), y) end -function syrk_wrapper{T<:LapackType}(tA, A::StridedMatrix{T}) +function syrk_wrapper{T<:BlasFloat}(tA, A::StridedMatrix{T}) if tA == 'T' (nA, mA) = size(A) tAt = 'N' @@ -234,7 +234,7 @@ function syrk_wrapper{T<:LapackType}(tA, A::StridedMatrix{T}) symmetrize!(BLAS.syrk('U', tA, one(T), A)) end -function herk_wrapper{T<:LapackType}(tA, A::StridedMatrix{T}) +function herk_wrapper{T<:BlasFloat}(tA, A::StridedMatrix{T}) if tA == 'C' (nA, mA) = size(A) tAt = 'N' @@ -256,7 +256,7 @@ function herk_wrapper{T<:LapackType}(tA, A::StridedMatrix{T}) symmetrize_conj!(BLAS.herk('U', tA, one(T), A)) end -function gemm_wrapper{T<:LapackType}(tA, tB, +function gemm_wrapper{T<:BlasFloat}(tA, tB, A::StridedMatrix{T}, B::StridedMatrix{T}) mA, nA = lapack_size(tA, A) @@ -265,7 +265,7 @@ function gemm_wrapper{T<:LapackType}(tA, tB, gemm_wrapper(C, tA, tB, A, B) end -function gemm_wrapper{T<:LapackType}(C::StridedMatrix{T}, tA, tB, +function gemm_wrapper{T<:BlasFloat}(C::StridedMatrix{T}, tA, tB, A::StridedMatrix{T}, B::StridedMatrix{T}) mA, nA = lapack_size(tA, A) diff --git a/base/multi.jl b/base/multi.jl index ac28467f9a841..00b96bc1723b0 100644 --- a/base/multi.jl +++ b/base/multi.jl @@ -104,7 +104,7 @@ type Worker Worker(host::String, port::Integer, sock::TcpSocket, id::Int) = new(bytestring(host), uint16(port), sock, IOString(), {}, {}, id, false) -end + end Worker(host::String, port::Integer, sock::TcpSocket) = Worker(host, port, sock, 0) Worker(host::String, port::Integer) = Worker(host, port, @@ -178,12 +178,6 @@ end type LocalProcess end -type Location - host::String - port::Int16 - Location(h,p::Integer) = new(h,int16(p)) -end - type ProcessGroup myid::Int workers::Array{Any,1} @@ -201,7 +195,7 @@ const PGRP = ProcessGroup(0, {}, {}) function add_workers(PGRP::ProcessGroup, w::Array{Any,1}) n = length(w) - locs = map(x->Location(x.host,x.port), w) + locs = map(x->(x.host,x.port), w) # NOTE: currently only node 1 can add new nodes, since nobody else # has the full list of address:port newlocs = [PGRP.locs, locs] @@ -245,8 +239,7 @@ function worker_id_from_socket(s) end # establish a Worker connection for processes that connected to us -function _jl_identify_socket(otherid, sock) - global PGRP +function identify_socket(otherid, sock) i = otherid #locs = PGRP.locs @assert i > PGRP.myid @@ -263,7 +256,7 @@ end ## remote refs and core messages: do, call, fetch, wait, ref, put ## -const _jl_client_refs = WeakKeyDict() +const client_refs = WeakKeyDict() type RemoteRef where::Int @@ -273,11 +266,11 @@ type RemoteRef function RemoteRef(w, wh, id) r = new(w,wh,id) - found = key(_jl_client_refs, r, false) + found = key(client_refs, r, false) if !is(found,false) return found end - _jl_client_refs[r] = true + client_refs[r] = true finalizer(r, send_del_client) r end @@ -420,7 +413,7 @@ function deserialize(s, t::Type{RemoteRef}) if where == myid() add_client(rr2id(rr), myid()) end - # call ctor to make sure this rr gets added to the _jl_client_refs table + # call ctor to make sure this rr gets added to the client_refs table RemoteRef(where, rr.whence, rr.id) end @@ -726,10 +719,10 @@ function deliver_result(sock::Stream, msg, oid, value) end end -const _jl_empty_cell_ = {} +const empty_cell_ = {} function deliver_result(sock::(), msg, oid, value) # restart task that's waiting on oid - jobs = get(Waiting, oid, _jl_empty_cell_) + jobs = get(Waiting, oid, empty_cell_) for i = 1:length(jobs) j = jobs[i] if j[1]==msg @@ -740,7 +733,7 @@ function deliver_result(sock::(), msg, oid, value) break end end - if isempty(jobs) && !is(jobs,_jl_empty_cell_) + if isempty(jobs) && !is(jobs,empty_cell_) del(Waiting, oid) end nothing @@ -790,22 +783,21 @@ end type DisconnectException <: Exception end -function create_message_handler_loop(this::AsyncStream) #returns immediately +function create_message_handler_loop(sock::AsyncStream) #returns immediately enq_work(@task begin global PGRP #println("message_handler_loop") - refs = (PGRP::ProcessGroup).refs - start_reading(this) - wait_connected(this) + start_reading(sock) + wait_connected(sock) if PGRP.np == 0 # first connection; get process group info from client - PGRP.myid = deserialize(this) - PGRP.locs = locs = deserialize(this) + PGRP.myid = deserialize(sock) + PGRP.locs = locs = deserialize(sock) #print("\nLocation: ",locs,"\nId:",PGRP.myid,"\n") # joining existing process group PGRP.np = length(PGRP.locs) PGRP.workers = w = cell(PGRP.np) - w[1] = Worker("", 0, this, 1) + w[1] = Worker("", 0, sock, 1) for i = 2:(PGRP.myid-1) w[i] = Worker(locs[i].host, locs[i].port) w[i].id = i @@ -820,53 +812,53 @@ function create_message_handler_loop(this::AsyncStream) #returns immediately #println("loop") while true #try - msg = deserialize(this) + msg = deserialize(sock) #println("got msg: ",msg) # handle message if is(msg, :call) || is(msg, :call_fetch) || is(msg, :call_wait) - id = deserialize(this) - f = deserialize(this) - args = deserialize(this) + id = deserialize(sock) + f = deserialize(sock) + args = deserialize(sock) #print("$(myid()) got call $id\n") wi = schedule_call(id, f, args) if is(msg, :call_fetch) - wi.notify = (this, :call_fetch, id, wi.notify) + wi.notify = (sock, :call_fetch, id, wi.notify) elseif is(msg, :call_wait) - wi.notify = (this, :wait, id, wi.notify) + wi.notify = (sock, :wait, id, wi.notify) end elseif is(msg, :do) - f = deserialize(this) - args = deserialize(this) + f = deserialize(sock) + args = deserialize(sock) #print("got args: $args\n") let func=f, ar=args enq_work(WorkItem(()->apply(func, ar))) end elseif is(msg, :result) # used to deliver result of wait or fetch - mkind = deserialize(this) - oid = deserialize(this) - val = deserialize(this) + mkind = deserialize(sock) + oid = deserialize(sock) + val = deserialize(sock) deliver_result((), mkind, oid, val) elseif is(msg, :identify_socket) - otherid = deserialize(this) - _jl_identify_socket(otherid, this) + otherid = deserialize(sock) + identify_socket(otherid, sock) else # the synchronization messages - oid = deserialize(this)::(Int,Int) + oid = deserialize(sock)::(Int,Int) wi = lookup_ref(oid) if wi.done - deliver_result(this, msg, oid, work_result(wi)) + deliver_result(sock, msg, oid, work_result(wi)) else # add to WorkItem's notify list # TODO: should store the worker here, not the socket, # so we don't need to look up the worker later - wi.notify = (this, msg, oid, wi.notify) + wi.notify = (sock, msg, oid, wi.notify) end end #catch e # if isa(e,EOFError) #print("eof. $(myid()) exiting\n") - # stop_reading(this) + # stop_reading(sock) # # TODO: remove machine from group # throw(DisconnectException()) # else @@ -918,7 +910,7 @@ function start_remote_workers(machines, cmds, tunnel) for i=1:n outs[i],pps[i] = read_from(cmds[i]) outs[i].line_buffered = true - end + end for i=1:n local hostname::String, port::Int16 stream = outs[i] @@ -952,7 +944,7 @@ function start_remote_workers(machines, cmds, tunnel) catch err println("\tError parsing reply from worker $(wrker.id):\t",err) return false - end + end end true end) @@ -970,17 +962,17 @@ function parse_connection_info(str) end end -_jl_tunnel_port = 9201 +tunnel_port = 9201 # establish an SSH tunnel to a remote worker # returns P such that localhost:P connects to host:port ssh_tunnel(host, port) = ssh_tunnel(ENV["USER"], host, port) function ssh_tunnel(user, host, port) - global _jl_tunnel_port - localp = _jl_tunnel_port::Int + global tunnel_port + localp = tunnel_port::Int while !success(`ssh -f -o ExitOnForwardFailure=yes $(user)@$host -L $localp:$host:$port -N`) localp += 1 end - _jl_tunnel_port = localp+1 + tunnel_port = localp+1 localp end @@ -1418,7 +1410,7 @@ function event_loop(isclient) elseif isclient && isa(err,InterruptException) # root task is waiting for something on client. allow C-C # to interrupt. - interrupt_waiting_task(_jl_roottask_wi,err) + interrupt_waiting_task(roottask_wi,err) end iserr, lasterr = true, add_backtrace(err,bt) end diff --git a/base/number.jl b/base/number.jl index 4a7c9178f556a..220b4c101a24c 100644 --- a/base/number.jl +++ b/base/number.jl @@ -20,6 +20,8 @@ ndims(x::Number) = 0 ndims{T<:Number}(::Type{T}) = 0 length(x::Number) = 1 ref(x::Number) = x +ref(x::Number, i::Integer) = i == 1 ? x : throw(BoundsError()) +ref(x::Number, i::Real) = ref(x, to_index(i)) signbit(x::Real) = int(x < 0) sign(x::Real) = x < 0 ? -one(x) : x > 0 ? one(x) : x @@ -40,3 +42,5 @@ isempty(a::Number) = false contains(s::Number, n::Number) = (s == n) reinterpret{T<:Real}(::Type{T}, x::Real) = box(T,x) + +map(f, x::Number) = f(x) diff --git a/base/operators.jl b/base/operators.jl index cadb524985fa1..eac33ae83d253 100644 --- a/base/operators.jl +++ b/base/operators.jl @@ -211,8 +211,10 @@ function assign_shape_check(X::AbstractArray, I...) end end -# convert Real to integer index +# convert to integer index +to_index(i) = i to_index(i::Real) = convert(Int, i) +to_index(i::Int) = i # vectorization diff --git a/base/osutils.jl b/base/osutils.jl index 2c92d480c22fe..73d7bb659aee6 100644 --- a/base/osutils.jl +++ b/base/osutils.jl @@ -1,4 +1,4 @@ -function _jl_is_unix(os::Symbol) +function is_unix(os::Symbol) if (os==:Windows) return false; elseif (os==:Linux) return true; elseif (os==:FreeBSD) return true; @@ -12,7 +12,7 @@ macro windows_only(ex) end macro unix_only(ex) - _jl_is_unix(OS_NAME) ? esc(ex) : :nothing + is_unix(OS_NAME) ? esc(ex) : :nothing end macro osx_only(ex) @@ -20,7 +20,7 @@ macro osx_only(ex) end macro linux_only(ex) - _jl_is_unix(OS_NAME) && OS_NAME != :Darwin ? esc(ex) : :nothing + is_unix(OS_NAME) && OS_NAME != :Darwin ? esc(ex) : :nothing end -_jl_os_name(os::Symbol) = string(os) +os_name(os::Symbol) = string(os) diff --git a/base/pcre.jl b/base/pcre.jl index 7273d3d5818b9..bab8e9e51f79c 100644 --- a/base/pcre.jl +++ b/base/pcre.jl @@ -82,9 +82,9 @@ end function study(regex::Array{Uint8}, options::Integer) # NOTE: options should always be zero in current PCRE errstr = Array(Ptr{Uint8},1) - extra = (()->ccall((:pcre_study, :libpcre), Ptr{Void}, - (Ptr{Void}, Int32, Ptr{Ptr{Uint8}}), - regex, options, errstr))() + extra = ccall((:pcre_study, :libpcre), Ptr{Void}, + (Ptr{Void}, Int32, Ptr{Ptr{Uint8}}), + regex, options, errstr) if errstr[1] != C_NULL error("study: $(errstr[1])") end @@ -92,6 +92,9 @@ function study(regex::Array{Uint8}, options::Integer) end study(re::Array{Uint8}) = study(re, int32(0)) +free_study(extra::Ptr{Void}) = + ccall((:pcre_free_study, :libpcre), Void, (Ptr{Void},), extra) + function exec(regex::Array{Uint8}, extra::Ptr{Void}, str::ByteString, offset::Integer, options::Integer, cap::Bool) if offset < 0 || length(str) < offset diff --git a/base/pkg.jl b/base/pkg.jl index 86742e3116517..1cd856a10042e 100644 --- a/base/pkg.jl +++ b/base/pkg.jl @@ -244,7 +244,7 @@ function clone(url::String) tmpdir = mktempdir() run(`git clone $url $tmpdir`) cd(tmpdir) do - gitdir = abs_path(readchomp(`git rev-parse --git-dir`)) + gitdir = abspath(readchomp(`git rev-parse --git-dir`)) Git.each_submodule(false) do name, path, sha1 cd(path) do run(`git fetch-pack $gitdir $sha1`) @@ -481,7 +481,7 @@ version(pkg::String, ver::VersionNumber) = cd_pkgdir() do end end if isfile(file_path(pkg, "REQUIRE")) - file_copy( + cp( file_path(pkg, "REQUIRE"), file_path("METADATA", pkg, "versions", string(ver), "requires")) end @@ -539,11 +539,11 @@ with the correct remote name for your repository." cd(package_name) do run(`git init`) run(`git commit --allow-empty -m "Initial empty commit"`) - file_create("LICENSE.md") # Should insert MIT content - file_create("README.md") - file_create("REQUIRE") + touch("LICENSE.md") # Should insert MIT content + touch("README.md") + touch("REQUIRE") mkdir("src") - file_create(file_path("src", strcat(package_name, ".jl"))) + touch(file_path("src", strcat(package_name, ".jl"))) mkdir("test") run(`git add --all`) run(`git commit -m "Scaffold for Julia package $(package_name)"`) diff --git a/base/process.jl b/base/process.jl index d9f8b8ba6a8e9..bb60c299708b9 100644 --- a/base/process.jl +++ b/base/process.jl @@ -94,7 +94,7 @@ end # this could cause a segfault. this is really just for use by the # spawn function below so that we can exec more efficiently. # -function _jl_pre_exec(args::Vector{ByteString}) +function pre_exec(args::Vector{ByteString}) if length(args) < 1 error("exec: too few words to exec") end @@ -107,7 +107,7 @@ function _jl_pre_exec(args::Vector{ByteString}) end function exec(args::Vector{ByteString}) - ptrs = _jl_pre_exec(args) + ptrs = pre_exec(args) ccall(:execvp, Int32, (Ptr{Uint8}, Ptr{Ptr{Uint8}}), ptrs[1], ptrs) system_error(:exec, true) end @@ -514,7 +514,7 @@ function spawn(cmd::Cmd) for c = cmd.pipeline # minimize work after fork, in particular no writing c.status = ProcessRunning() - ptrs = isa(c.exec,Vector{ByteString}) ? _jl_pre_exec(c.exec) : nothing + ptrs = isa(c.exec,Vector{ByteString}) ? pre_exec(c.exec) : nothing dup2_fds = Array(Int32, 2*numel(c.pipes)) dup2_sinks = Array(Int32, 2*numel(c.sinks)) close_fds_ = copy(fds) @@ -726,5 +726,5 @@ function cmd_gen(parsed) end macro cmd(str) - :(cmd_gen($(_jl_shell_parse(str)))) + :(cmd_gen($(shell_parse(str)))) end diff --git a/base/regex.jl b/base/regex.jl index eabf2a0312724..bdb69e4f0eaf2 100644 --- a/base/regex.jl +++ b/base/regex.jl @@ -2,35 +2,27 @@ include("pcre.jl") +const DEFAULT_OPTS = PCRE.UTF8 + type Regex pattern::ByteString - options::Int32 + options::Uint32 regex::Array{Uint8} - extra::Ptr{Void} - function Regex(pat::String, opts::Integer, study::Bool) - pat = bytestring(pat); opts = int32(opts) - if (opts & ~PCRE.OPTIONS_MASK) != 0 + function Regex(pattern::String, options::Integer) + pattern = bytestring(pattern) + options = uint32(options) + if (options & ~PCRE.OPTIONS_MASK) != 0 error("invalid regex option(s)") end - re = PCRE.compile(pat, opts & PCRE.COMPILE_MASK) - ex = study ? PCRE.study(re) : C_NULL - new(pat, opts, re, ex) + regex = PCRE.compile(pattern, options & PCRE.COMPILE_MASK) + new(pattern, options, regex) end end -Regex(p::String, s::Bool) = Regex(p, 0, s) -Regex(p::String, o::Integer) = Regex(p, o, false) -Regex(p::String) = Regex(p, 0, false) - -copy(r::Regex) = r - -# TODO: make sure thing are escaped in a way PCRE -# likes so that Julia all the Julia string quoting -# constructs are correctly handled. -macro r_str(pattern, flags...) - options = PCRE.UTF8 - for fx in flags, f in fx +function Regex(pattern::String, flags::String) + options = DEFAULT_OPTS + for f in flags options |= f=='i' ? PCRE.CASELESS : f=='m' ? PCRE.MULTILINE : f=='s' ? PCRE.DOTALL : @@ -39,10 +31,15 @@ macro r_str(pattern, flags...) end Regex(pattern, options) end +Regex(pattern::String) = Regex(pattern, DEFAULT_OPTS) + +macro r_str(pattern, flags...) Regex(pattern, flags...) end + +copy(r::Regex) = r function show(io, re::Regex) imsx = PCRE.CASELESS|PCRE.MULTILINE|PCRE.DOTALL|PCRE.EXTENDED - if (re.options & ~imsx) == PCRE.UTF8 + if (re.options & ~imsx) == DEFAULT_OPTS print(io, 'r') print_quoted_literal(io, re.pattern) if (re.options & PCRE.CASELESS ) != 0; print(io, 'i'); end @@ -85,14 +82,14 @@ function show(io, m::RegexMatch) end ismatch(r::Regex, s::String, o::Integer) = - PCRE.exec(r.regex, r.extra, bytestring(s), 0, o, false) + PCRE.exec(r.regex, C_NULL, bytestring(s), 0, o, false) ismatch(r::Regex, s::String) = ismatch(r, s, r.options & PCRE.EXECUTE_MASK) contains(s::String, r::Regex, opts::Integer) = ismatch(r,s,opts) contains(s::String, r::Regex) = ismatch(r,s) function match(re::Regex, str::ByteString, idx::Integer, opts::Integer) - m, n = PCRE.exec(re.regex, re.extra, str, idx-1, opts, true) + m, n = PCRE.exec(re.regex, C_NULL, str, idx-1, opts, true) if isempty(m); return nothing; end mat = str[m[1]+1:m[2]] cap = Union(Nothing,ByteString)[ @@ -100,7 +97,10 @@ function match(re::Regex, str::ByteString, idx::Integer, opts::Integer) off = [ m[2i+1]::Int32+1 for i=1:n ] RegexMatch(mat, cap, m[1]+1, off) end -match(r::Regex, s::String, i::Integer, o::Integer) = match(r, bytestring(s), i, o) +function match(r::Regex, s::String, i::Integer, o::Integer) + error("regex matching is only available for bytestrings; use bytestring(s) to convert") + match(r, bytestring(s), i, o) +end match(r::Regex, s::String, i::Integer) = match(r, s, i, r.options & PCRE.EXECUTE_MASK) match(r::Regex, s::String) = match(r, s, start(s)) @@ -110,10 +110,11 @@ function search(str::ByteString, re::Regex, idx::Integer) return idx == len+2 ? (0,0) : error(BoundsError) end opts = re.options & PCRE.EXECUTE_MASK - m, n = PCRE.exec(re.regex, re.extra, str, idx-1, opts, true) + m, n = PCRE.exec(re.regex, C_NULL, str, idx-1, opts, true) isempty(m) ? (0,0) : (m[1]+1,m[2]+1) end -search(s::String, r::Regex, idx::Integer) = error("regex search is only available for bytestrings; use bytestring(s) to convert") +search(s::String, r::Regex, idx::Integer) = + error("regex search is only available for bytestrings; use bytestring(s) to convert") search(s::String, r::Regex) = search(s,r,start(s)) type RegexMatchIterator diff --git a/base/serialize.jl b/base/serialize.jl index 08a4229552502..dc7e8c52f540c 100644 --- a/base/serialize.jl +++ b/base/serialize.jl @@ -6,11 +6,11 @@ abstract LongTuple abstract LongExpr abstract UndefRefTag -const _jl_ser_version = 1 # do not make changes without bumping the version #! -const _jl_ser_tag = ObjectIdDict() -const _jl_deser_tag = ObjectIdDict() +const ser_version = 1 # do not make changes without bumping the version #! +const ser_tag = ObjectIdDict() +const deser_tag = ObjectIdDict() let i = 2 - global _jl_ser_tag, _jl_deser_tag + global ser_tag, deser_tag for t = {Symbol, Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64, Int128, Uint128, Float32, Float64, Char, Ptr, AbstractKind, UnionKind, BitsKind, CompositeKind, Function, @@ -36,20 +36,20 @@ let i = 2 false, true, nothing, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32} - _jl_ser_tag[t] = int32(i) - _jl_deser_tag[int32(i)] = t + ser_tag[t] = int32(i) + deser_tag[int32(i)] = t i += 1 end end # tags >= this just represent themselves, their whole representation is 1 byte -const _jl_VALUE_TAGS = _jl_ser_tag[()] +const VALUE_TAGS = ser_tag[()] -writetag(s, x) = write(s, uint8(_jl_ser_tag[x])) +writetag(s, x) = write(s, uint8(ser_tag[x])) function write_as_tag(s, x) - t = _jl_ser_tag[x] - if t < _jl_VALUE_TAGS + t = ser_tag[x] + if t < VALUE_TAGS write(s, uint8(0)) end write(s, uint8(t)) @@ -74,7 +74,7 @@ function serialize(s, t::Tuple) end function serialize(s, x::Symbol) - if has(_jl_ser_tag, x) + if has(ser_tag, x) return write_as_tag(s, x) end name = string(x) @@ -158,7 +158,7 @@ function serialize(s, m::Module) serialize(s, full_name(m)) end -function _jl_lambda_number(l::LambdaStaticData) +function lambda_number(l::LambdaStaticData) # a hash function that always gives the same number to the same # object on the same machine, and is unique over all machines. hash(uint64(object_id(l))+(uint64(myid())<<44)) @@ -201,8 +201,13 @@ end function serialize(s, linfo::LambdaStaticData) writetag(s, LambdaStaticData) - serialize(s, _jl_lambda_number(linfo)) + serialize(s, lambda_number(linfo)) serialize(s, linfo.ast) + if isdefined(linfo.def, :roots) + serialize(s, linfo.def.roots) + else + serialize(s, {}) + end serialize(s, linfo.sparams) serialize(s, linfo.inferred) serialize(s, linfo.module) @@ -221,7 +226,7 @@ function serialize_type_data(s, t) end function serialize(s, t::Union(AbstractKind,BitsKind,CompositeKind)) - if has(_jl_ser_tag,t) + if has(ser_tag,t) write_as_tag(s, t) else writetag(s, AbstractKind) @@ -230,7 +235,7 @@ function serialize(s, t::Union(AbstractKind,BitsKind,CompositeKind)) end function serialize_type(s, t::Union(CompositeKind,BitsKind)) - if has(_jl_ser_tag,t) + if has(ser_tag,t) writetag(s, t) else writetag(s, typeof(t)) @@ -239,7 +244,7 @@ function serialize_type(s, t::Union(CompositeKind,BitsKind)) end function serialize(s, x) - if has(_jl_ser_tag,x) + if has(ser_tag,x) return write_as_tag(s, x) end t = typeof(x) @@ -269,10 +274,10 @@ end function handle_deserialize(s, b) if b == 0 - return _jl_deser_tag[int32(read(s, Uint8))] + return deser_tag[int32(read(s, Uint8))] end - tag = _jl_deser_tag[b] - if b >= _jl_VALUE_TAGS + tag = deser_tag[b] + if b >= VALUE_TAGS return tag elseif is(tag,Tuple) len = int32(read(s, Uint8)) @@ -298,7 +303,7 @@ function deserialize(s, ::Type{Module}) m end -const _jl_known_lambda_data = Dict() +const known_lambda_data = Dict() function deserialize(s, ::Type{Function}) b = read(s, Uint8) @@ -322,16 +327,18 @@ end function deserialize(s, ::Type{LambdaStaticData}) lnumber = deserialize(s) ast = deserialize(s) + roots = deserialize(s) sparams = deserialize(s) infr = deserialize(s) mod = deserialize(s) - if has(_jl_known_lambda_data, lnumber) - return _jl_known_lambda_data[lnumber] + if has(known_lambda_data, lnumber) + return known_lambda_data[lnumber] else linfo = ccall(:jl_new_lambda_info, Any, (Any, Any), ast, sparams) linfo.inferred = infr linfo.module = mod - _jl_known_lambda_data[lnumber] = linfo + linfo.roots = roots + known_lambda_data[lnumber] = linfo return linfo end end @@ -361,7 +368,7 @@ function deserialize(s, ::Type{Array}) A = Array(elty, dims) for i = 1:numel(A) tag = int32(read(s, Uint8)) - if tag==0 || !is(_jl_deser_tag[tag], UndefRefTag) + if tag==0 || !is(deser_tag[tag], UndefRefTag) A[i] = handle_deserialize(s, tag) end end @@ -423,7 +430,7 @@ function deserialize(s, t::CompositeKind) x = ccall(:jl_new_struct_uninit, Any, (Any,), t) for n in t.names tag = int32(read(s, Uint8)) - if tag==0 || !is(_jl_deser_tag[tag], UndefRefTag) + if tag==0 || !is(deser_tag[tag], UndefRefTag) setfield(x, n, handle_deserialize(s, tag)) end end diff --git a/base/show.jl b/base/show.jl index de05ceb6e2697..3c43ffbf87084 100644 --- a/base/show.jl +++ b/base/show.jl @@ -8,12 +8,12 @@ show(io, x) = ccall(:jl_show_any, Void, (Any, Any,), io::Stream, x) showcompact(io, x) = show(io, x) showcompact(x) = showcompact(OUTPUT_STREAM::Stream, x) -macro show(ex) - quote - print($(sprint(show_unquoted, ex)*"\t= ")) - show($(esc(ex))) - println() +macro show(exs...) + blk = expr(:block) + for ex in exs + push(blk.args, :(println($(sprint(show_unquoted,ex)*" => "),repr($(esc(ex)))))) end + return blk end show(io, s::Symbol) = show_indented(io, s) @@ -136,9 +136,9 @@ function show_indented(io::IO, sym::Symbol, indent::Int) end end function default_show_quoted(io::IO, ex, indent::Int) - print(io, ":( ") + print(io, ":(") show_unquoted(io, ex, indent + indent_width) - print(io, " )") + print(io, ")") end ## AST printing helpers ## @@ -157,8 +157,8 @@ function show_expr_type(io::IO, ty) end end -show_linenumber(io::IO, line) = print(io,"\t# line ",line,':') -show_linenumber(io::IO, line, file) = print(io,"\t# ",file,", line ",line,':') +show_linenumber(io::IO, line) = print(io," # line ",line,':') +show_linenumber(io::IO, line, file) = print(io," # ",file,", line ",line,':') # show a block, e g if/for/etc function show_block(io::IO, head, args::Vector, body, indent::Int) @@ -227,13 +227,13 @@ function show_unquoted(io::IO, ex::Expr, indent::Int) elseif has(_expr_parens, head) # :tuple/:vcat/:cell1d op, cl = _expr_parens[head] print(io, op) - show_list(io, args, ", ", indent) + show_list(io, args, ",", indent) if is(head, :tuple) && nargs == 1; print(io, ','); end print(io, cl) elseif has(_expr_calls, head) && nargs >= 1 # :call/:ref/:curly op, cl = _expr_calls[head] show_unquoted(io, args[1], indent) - show_enclosed_list(io, op, args[2:end], ", ", cl, indent) + show_enclosed_list(io, op, args[2:end], ",", cl, indent) elseif is(head, :comparison) && nargs >= 3 && (nargs&1==1) show_enclosed_list(io, '(', args, "", ')', indent) elseif is(head, :(...)) && nargs == 1 @@ -242,7 +242,7 @@ function show_unquoted(io::IO, ex::Expr, indent::Int) elseif (nargs == 1 && contains((:return, :abstract, :const), head)) || contains((:local, :global), head) print(io, head, ' ') - show_list(io, args, ", ", indent) + show_list(io, args, ",", indent) elseif is(head, :macrocall) && nargs >= 1 show_list(io, args, ' ', indent) elseif is(head, :typealias) && nargs == 2 @@ -341,29 +341,29 @@ end function show(io, bt::BackTrace) show(io, bt.e) t = bt.trace - # we may not declare :_jl_eval_user_input + # we may not declare :eval_user_input # directly so that we get a compile error # in case its name changes in the future - const _jl_eval_function = try - symbol(string(_jl_eval_user_input)) + const eval_function = try + symbol(string(eval_user_input)) catch :(:) #for when client.jl is not yet defined end for i = 1:3:length(t) if i == 1 && t[i] == :error; continue; end - if t[i] == _jl_eval_function; break; end + if t[i] == eval_function; break; end print(io, "\n") lno = t[i+2] print(io, " in ", t[i], " at ", t[i+1]) if lno >= 1 try - print(io, ":", lno) + print(io, ":", lno) catch print('?') #for when dec is not yet defined - end end end end +end function show(io, m::Method) tv = m.tvars @@ -468,10 +468,10 @@ function idump(fn::Function, io::IO, x::CompositeKind, n::Int, indent) end end -# _jl_dumptype is for displaying abstract type hierarchies like Jameson +# dumptype is for displaying abstract type hierarchies like Jameson # Nash's wiki page: https://github.com/JuliaLang/julia/wiki/Types-Hierarchy -function _jl_dumptype(io::Stream, x::Type, n::Int, indent) +function dumptype(io::Stream, x::Type, n::Int, indent) # based on Jameson Nash's examples/typetree.jl println(io, x) if n == 0 # too deeply nested @@ -502,7 +502,7 @@ function _jl_dumptype(io::Stream, x::Type, n::Int, indent) println(io, indent, " ", s, " = ", t.name) elseif t != Any print(io, indent, " ") - _jl_dumptype(io, t, n - 1, strcat(indent, " ")) + dumptype(io, t, n - 1, strcat(indent, " ")) end end end @@ -512,8 +512,8 @@ end # For abstract types, use _dumptype only if it's a form that will be called # interactively. -idump(fn::Function, io::Stream, x::AbstractKind) = _jl_dumptype(io, x, 5, "") -idump(fn::Function, io::Stream, x::AbstractKind, n::Int) = _jl_dumptype(io, x, n, "") +idump(fn::Function, io::Stream, x::AbstractKind) = dumptype(io, x, 5, "") +idump(fn::Function, io::Stream, x::AbstractKind, n::Int) = dumptype(io, x, n, "") # defaults: idump(fn::Function, io::Stream, x) = idump(idump, io, x, 5, "") # default is 5 levels @@ -547,11 +547,11 @@ function dump(io::IO, x::Dict, n::Int, indent) end # More generic representation for common types: -dump(io::IO, x::AbstractKind, n::Int, indent) = println(io, x.name) -dump(io::IO, x::AbstractKind) = _jl_dumptype(io, x, 5, "") -dump(io::IO, x::AbstractKind, n::Int) = _jl_dumptype(io, x, n, "") -dump(io::IO, x::BitsKind, n::Int, indent) = println(io, x.name) -dump(io::IO, x::TypeVar, n::Int, indent) = println(io, x.name) +dump(io::IOStream, x::AbstractKind, n::Int, indent) = println(io, x.name) +dump(io::IOStream, x::AbstractKind) = dumptype(io, x, 5, "") +dump(io::IOStream, x::AbstractKind, n::Int) = dumptype(io, x, n, "") +dump(io::IOStream, x::BitsKind, n::Int, indent) = println(io, x.name) +dump(io::IOStream, x::TypeVar, n::Int, indent) = println(io, x.name) showall(x) = showall(OUTPUT_STREAM::Stream, x) @@ -584,8 +584,8 @@ function alignment(x::Rational) (strlen(m.captures[1]), strlen(m.captures[2])) end -const _jl_undef_ref_str = "#undef" -const _jl_undef_ref_alignment = (3,3) +const undef_ref_str = "#undef" +const undef_ref_alignment = (3,3) function alignment( X::AbstractMatrix, @@ -599,7 +599,7 @@ function alignment( if isassigned(X,i,j) aij = alignment(X[i,j]) else - aij = _jl_undef_ref_alignment + aij = undef_ref_alignment end l = max(l, aij[1]) r = max(r, aij[2]) @@ -629,8 +629,8 @@ function print_matrix_row(io, a = alignment(x) sx = sprint(showcompact, x) else - a = _jl_undef_ref_alignment - sx = _jl_undef_ref_str + a = undef_ref_alignment + sx = undef_ref_str end l = repeat(" ", A[k][1]-a[1]) r = repeat(" ", A[k][2]-a[2]) @@ -798,7 +798,7 @@ function show{T}(io, x::AbstractArray{T,0}) if isassigned(x) sx = sprint(showcompact, x[]) else - sx = _jl_undef_ref_str + sx = undef_ref_str end print(io, sx) end @@ -854,7 +854,7 @@ summary(a::BitArray) = # (following functions not exported - mainly intended for debug) -function _jl_print_bit_chunk(io::IO, c::Uint64, l::Integer) +function print_bit_chunk(io::IO, c::Uint64, l::Integer) for s = 0 : l - 1 d = (c >>> s) & 1 print(io, "01"[d + 1]) @@ -864,21 +864,21 @@ function _jl_print_bit_chunk(io::IO, c::Uint64, l::Integer) end end -_jl_print_bit_chunk(io::IO, c::Uint64) = _jl_print_bit_chunk(io, c, 64) +print_bit_chunk(io::IO, c::Uint64) = print_bit_chunk(io, c, 64) -_jl_print_bit_chunk(c::Uint64, l::Integer) = _jl_print_bit_chunk(stdout_stream, c, l) -_jl_print_bit_chunk(c::Uint64) = _jl_print_bit_chunk(stdout_stream, c) +print_bit_chunk(c::Uint64, l::Integer) = print_bit_chunk(stdout_stream, c, l) +print_bit_chunk(c::Uint64) = print_bit_chunk(stdout_stream, c) function bitshow(io::IO, B::BitArray) if length(B) == 0 return end for i = 1 : length(B.chunks) - 1 - _jl_print_bit_chunk(io, B.chunks[i]) + print_bit_chunk(io, B.chunks[i]) print(io, ": ") end l = (@_mod64 (length(B)-1)) + 1 - _jl_print_bit_chunk(io, B.chunks[end], l) + print_bit_chunk(io, B.chunks[end], l) end bitshow(B::BitArray) = bitshow(stdout_stream, B) diff --git a/base/sort.jl b/base/sort.jl index 65d2273df0d8c..0f8f159a58009 100644 --- a/base/sort.jl +++ b/base/sort.jl @@ -1,24 +1,131 @@ ## standard sort comparisons ## -_jl_fp_pos_lt(x::Float32, y::Float32) = slt_int(unbox(Float32,x),unbox(Float32,y)) -_jl_fp_pos_lt(x::Float64, y::Float64) = slt_int(unbox(Float64,x),unbox(Float64,y)) -_jl_fp_pos_le(x::Float32, y::Float32) = sle_int(unbox(Float32,x),unbox(Float32,y)) -_jl_fp_pos_le(x::Float64, y::Float64) = sle_int(unbox(Float64,x),unbox(Float64,y)) - -_jl_fp_neg_lt(x::Float32, y::Float32) = slt_int(unbox(Float32,y),unbox(Float32,x)) -_jl_fp_neg_lt(x::Float64, y::Float64) = slt_int(unbox(Float64,y),unbox(Float64,x)) -_jl_fp_neg_le(x::Float32, y::Float32) = sle_int(unbox(Float32,y),unbox(Float32,x)) -_jl_fp_neg_le(x::Float64, y::Float64) = sle_int(unbox(Float64,y),unbox(Float64,x)) +module Sort + +export + @in_place_matrix_op, + issorted, + issorted_r, + issorted_by, + order, + search_sorted, + search_sorted_r, + search_sorted_by, + search_sorted_first, + search_sorted_first_r, + search_sorted_first_by, + search_sorted_last, + search_sorted_last_r, + search_sorted_last_by, + select, + select!, + select_r, + select_r!, + select_by, + select_by!, + sort, + sort!, + sort_by, + sort_by!, + sortr, + sortr!, + sortperm, + sortperm!, + sortperm_r, + sortperm_r!, + sortperm_by, + sortperm_by!, + + insertionsort, + insertionsort!, + insertionsort_r, + insertionsort_r!, + insertionsort_by, + insertionsort_by!, + insertionsort_perm, + insertionsort_perm!, + insertionsort_perm_r, + insertionsort_perm_r!, + insertionsort_perm_by, + insertionsort_perm_by!, + mergesort, + mergesort!, + mergesort_r, + mergesort_r!, + mergesort_by, + mergesort_by!, + mergesort_perm, + mergesort_perm!, + mergesort_perm_r, + mergesort_perm_r!, + mergesort_perm_by, + mergesort_perm_by!, + quicksort, + quicksort!, + quicksort_r, + quicksort_r!, + quicksort_by, + quicksort_by!, + timsort, + timsort!, + timsort_r, + timsort_r!, + timsort_by, + timsort_by!, + timsort_perm, + timsort_perm!, + timsort_perm_r, + timsort_perm_r!, + timsort_perm_by, + timsort_perm_by! + +import Base.sort, Base.issorted, Base.sort, Base.sort!, Base.sortperm, Base.slt_int, + Base.unbox, Base.sle_int, Base.length + +fp_pos_lt(x::Float32, y::Float32) = slt_int(unbox(Float32,x),unbox(Float32,y)) +fp_pos_lt(x::Float64, y::Float64) = slt_int(unbox(Float64,x),unbox(Float64,y)) +fp_pos_le(x::Float32, y::Float32) = sle_int(unbox(Float32,x),unbox(Float32,y)) +fp_pos_le(x::Float64, y::Float64) = sle_int(unbox(Float64,x),unbox(Float64,y)) + +fp_neg_lt(x::Float32, y::Float32) = slt_int(unbox(Float32,y),unbox(Float32,x)) +fp_neg_lt(x::Float64, y::Float64) = slt_int(unbox(Float64,y),unbox(Float64,x)) +fp_neg_le(x::Float32, y::Float32) = sle_int(unbox(Float32,y),unbox(Float32,x)) +fp_neg_le(x::Float64, y::Float64) = sle_int(unbox(Float64,y),unbox(Float64,x)) ## internal sorting functionality ## -macro _jl_sort_functions(suffix, lt, args...) -insertionsort = esc(symbol("_jl_insertionsort$suffix")) -quicksort = esc(symbol("_jl_quicksort$suffix")) -mergesort = esc(symbol("_jl_mergesort$suffix")) -pivot_middle = esc(symbol("_jl_pivot_middle$suffix")) -lt = @eval (a,b)->$lt -quote +include("timsort.jl") + +for (suffix, lt, args) in (("", (a,b)->:(isless($a,$b)), ()), + ("_r", (a,b)->:(isless($b,$a)), ()), + ("", (a,b)->:(lt($a,$b)), (:(lt::Function),)), + ("_by", (a,b)->:(isless(by($a),by($b))), (:(by::Function),)), + ## special sorting for floating-point arrays ## + ("_fp_pos", (a,b)->:(fp_pos_lt($a,$b)), ()), + ("_fp_neg", (a,b)->:(fp_neg_lt($a,$b)), ())) + insertionsort = symbol("insertionsort$(suffix)") + insertionsort! = symbol("insertionsort$(suffix)!") + insertionsort_perm = symbol("insertionsort_perm$(suffix)") + insertionsort_perm! = symbol("insertionsort_perm$(suffix)!") + quicksort = symbol("quicksort$(suffix)") + quicksort! = symbol("quicksort$(suffix)!") + quicksort_perm = symbol("quicksort_perm$(suffix)") + quicksort_perm! = symbol("quicksort_perm$(suffix)!") + mergesort = symbol("mergesort$(suffix)") + mergesort! = symbol("mergesort$(suffix)!") + mergesort_perm = symbol("mergesort_perm$(suffix)") + mergesort_perm! = symbol("mergesort_perm$(suffix)!") + pivot_middle = symbol("pivot_middle$(suffix)") + issorted = symbol("issorted$(suffix)") + quickselect = symbol("quickselect$(suffix)") + select = symbol("select$(suffix)") + select! = symbol("select$(suffix)!") + search_sorted = symbol("search_sorted$(suffix)") + search_sorted_first = symbol("search_sorted_first$(suffix)") + search_sorted_last = symbol("search_sorted_last$(suffix)") + sortperm = symbol("sortperm$(suffix)") + sortperm! = symbol("sortperm$(suffix)!") +@eval begin # sorting should be stable # Thus, if a permutation is required, or records are being sorted @@ -26,7 +133,7 @@ quote # If only numbers are being sorted, a faster quicksort can be used. # fast sort for small arrays -function ($insertionsort)($(args...), a::AbstractVector, lo::Int, hi::Int) +function ($insertionsort!)($(args...), a::AbstractVector, lo::Int, hi::Int) for i = lo+1:hi j = i x = a[i] @@ -43,8 +150,11 @@ function ($insertionsort)($(args...), a::AbstractVector, lo::Int, hi::Int) return a end +($insertionsort!)($(args...), a::AbstractVector) = ($insertionsort!)($(args...), a, 1, length(a)) +($insertionsort)($(args...), a::AbstractVector, args2...) = ($insertionsort!)($(args...), copy(a), args2...) + # permutes an auxilliary array mirroring the sort -function ($insertionsort)($(args...), a::AbstractVector, p::AbstractVector{Int}, lo::Int, hi::Int) +function ($insertionsort_perm!)($(args...), a::AbstractVector, p::AbstractVector{Int}, lo::Int, hi::Int) for i = lo+1:hi j = i x = a[i] @@ -64,20 +174,28 @@ function ($insertionsort)($(args...), a::AbstractVector, p::AbstractVector{Int}, return a, p end -($pivot_middle)(a,b,c) = $(lt(:a,:b)) ? ($(lt(:b,:c)) ? b : c) : ($(lt(:a,:c)) ? a : c) +($insertionsort_perm!){T}($(args...), a::AbstractVector{T}, p::AbstractVector{Int}) = + ($insertionsort_perm!)($(args...), a, p, 1, length(a)) +($insertionsort_perm!){T}($(args...), a::AbstractVector{T}) = + ($insertionsort_perm!)($(args...), a, [1:length(a)]) +($insertionsort_perm){T}($(args...), a::AbstractVector{T}, args2...) = + ($insertionsort_perm!)($(args...), copy(a), [1:length(a)], args2...) + + +($pivot_middle)($(args...),a,b,c) = $(lt(:a,:b)) ? ($(lt(:b,:c)) ? b : c) : ($(lt(:a,:c)) ? a : c) # very fast but unstable -function ($quicksort)($(args...), a::AbstractVector, lo::Int, hi::Int) +function ($quicksort!)($(args...), a::AbstractVector, lo::Int, hi::Int) while hi > lo if hi-lo <= 20 - return $(expr(:call, insertionsort, args..., :a, :lo, :hi)) + return $(expr(:call, insertionsort!, args..., :a, :lo, :hi)) end i, j = lo, hi - # pivot = (a[lo]+a[hi])/2 # 1.14x - pivot = a[(lo+hi)>>>1] # 1.15x - # pivot = (a[lo]+a[hi]+a[(lo+hi)>>>1])/3 # 1.16x - # pivot = _jl_pivot_middle(a[lo], a[hi], a[(lo+hi)>>>1]) # 1.23x - # pivot = a[randival(lo,hi)] # 1.28x + # pivot = (a[lo]+a[hi])/2 # 1.14x + pivot = a[(lo+hi)>>>1] # 1.15x + # pivot = (a[lo]+a[hi]+a[(lo+hi)>>>1])/3 # 1.16x + # pivot = pivot_middle($(args...), a[lo], a[hi], a[(lo+hi)>>>1]) # 1.23x + # pivot = a[randival(lo,hi)] # 1.28x while i <= j while $(lt(:(a[i]), :pivot)); i += 1; end while $(lt(:pivot, :(a[j]))); j -= 1; end @@ -88,23 +206,26 @@ function ($quicksort)($(args...), a::AbstractVector, lo::Int, hi::Int) end end if lo < j - $(expr(:call, quicksort, args..., :a, :lo, :j)) + $(expr(:call, quicksort!, args..., :a, :lo, :j)) end lo = i end return a end +($quicksort!)($(args...), a::AbstractVector) = ($quicksort!)($(args...), a, 1, length(a)) +($quicksort)($(args...), a::AbstractVector) = ($quicksort!)($(args...), copy(a), 1, length(a)) + # less fast & not in-place, but stable -function ($mergesort)($(args...), a::AbstractVector, lo::Int, hi::Int, b::AbstractVector) +function ($mergesort!)($(args...), a::AbstractVector, lo::Int, hi::Int, b::AbstractVector) if lo < hi if hi-lo <= 20 - return ($insertionsort)($(args...), a, lo, hi) + return ($insertionsort!)($(args...), a, lo, hi) end m = (lo+hi)>>>1 - ($mergesort)($(args...), a, lo, m, b) - ($mergesort)($(args...), a, m+1, hi, b) + ($mergesort!)($(args...), a, lo, m, b) + ($mergesort!)($(args...), a, m+1, hi, b) # merge(lo,m,hi) i = 1 @@ -136,18 +257,22 @@ function ($mergesort)($(args...), a::AbstractVector, lo::Int, hi::Int, b::Abstra return a end +($mergesort!){T}($(args...), a::AbstractVector{T}) = ($mergesort!)($(args...), a, 1, length(a), Array(T,length(a))) +($mergesort){T}($(args...), a::AbstractVector{T}) = + ($mergesort!)($(args...), copy(a), 1, length(a), Array(T,length(a))) + # permutes auxilliary arrays mirroring the sort -function ($mergesort)($(args...), - a::AbstractVector, p::AbstractVector{Int}, lo::Int, hi::Int, - b::AbstractVector, pb::AbstractVector{Int}) +function ($mergesort_perm!)($(args...), + a::AbstractVector, p::AbstractVector{Int}, lo::Int, hi::Int, + b::AbstractVector, pb::AbstractVector{Int}) if lo < hi if hi-lo <= 20 - return ($insertionsort)($(args...), a, p, lo, hi) + return ($insertionsort_perm!)($(args...), a, p, lo, hi) end m = (lo+hi)>>>1 - ($mergesort)($(args...), a, p, lo, m, b, pb) - ($mergesort)($(args...), a, p, m+1, hi, b, pb) + ($mergesort_perm!)($(args...), a, p, lo, m, b, pb) + ($mergesort_perm!)($(args...), a, p, m+1, hi, b, pb) # merge(lo,m,hi) i = 1 @@ -183,32 +308,136 @@ function ($mergesort)($(args...), return a, p end -end; end # quote / macro +($mergesort_perm!){T}($(args...), a::AbstractVector{T}, p::AbstractVector{Int}) = + ($mergesort_perm!)($(args...), a, p, 1, length(a), Array(T,length(a)), Array(Int,length(a))) +($mergesort_perm!){T}($(args...), a::AbstractVector{T}) = + ($mergesort_perm!)($(args...), a, [1:length(a)]) +($mergesort_perm){T}($(args...), a::AbstractVector{T}, args2...) = + ($mergesort_perm!)($(args...), copy(a), [1:length(a)], args2...) + + +function ($issorted)($(args...), v::AbstractVector) + for i = 1:length(v)-1 + if $(lt(:(v[i+1]), :(v[i]))) + return false + end + end + return true +end + +function ($quickselect)($(args...), a::AbstractArray, k::Int, lo::Int, hi::Int) + if k < lo || k > hi; error("k is out of bounds"); end + + while true + + if lo == hi; return a[lo]; end + + i, j = lo, hi + pivot = ($pivot_middle)($(args...), a[lo], a[hi], a[(lo+hi)>>>1]) + while i < j + while $(lt(:(a[i]), :(pivot))); i += 1; end + while $(lt(:(pivot), :(a[j]))); j -= 1; end + #if isequal(a[i], a[j]) + if !$(lt(:(a[i]), :(a[j]))) && !$(lt(:(a[j]), :(a[i]))) + i += 1 + elseif i < j + a[i], a[j] = a[j], a[i] + end + end + pivot_ind = j + + len = pivot_ind - lo + 1 + if k == len + return a[pivot_ind] + elseif k < len + hi = pivot_ind - 1 + else + lo = pivot_ind + 1 + k = k - len + end + + end # while true... + +end + +($select!)($(args...), a::AbstractArray, k::Int) = ($quickselect)($(args...), a, k, 1, length(a)) +($select)($(args...), a::AbstractArray, k::Int) = ($quickselect)($(args...), copy(a), k, 1, length(a)) + +($search_sorted)($(args...), a::Vector, x) = ($search_sorted_first)($(args...), a, x, 1, length(a)) + +($search_sorted_last)($(args...), a::Vector, x) = ($search_sorted_last)($(args...), a, x, 1, length(a)) + +function ($search_sorted_last)($(args...), a::Vector, x, lo::Int, hi::Int) + ## Index of the last value of vector a that is less than or equal to x. + ## Returns 0 if x is less than all values of a. + ## + ## Good reference: http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary + lo = lo-1 + hi = hi+1 + while lo < hi-1 + i = (lo+hi)>>>1 + if $(lt(:(x), :(a[i]))) + hi = i + else + lo = i + end + end + lo +end + +($search_sorted_first)($(args...), a::Vector, x) = ($search_sorted_first)($(args...), a, x, 1, length(a)) + +function ($search_sorted_first)($(args...), a::Vector, x, lo::Int, hi::Int) + ## Index of the first value of vector a that is greater than or equal to x. + ## Returns length(a) + 1 if x is greater than all values in a. + ## + ## Good reference: http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary + lo = lo-1 + hi = hi+1 + while lo < hi-1 + i = (lo+hi)>>>1 + if $(lt(:(a[i]), :(x))) + lo = i + else + hi = i + end + end + hi +end + +($sortperm){T}($(args...), a::AbstractVector{T}, args2...) = ($mergesort_perm)($(args...), a, args2...) +($sortperm!){T}($(args...), a::AbstractVector{T}, args2...) = ($mergesort_perm!)($(args...), a, args2...) + +end; end # @eval / for + +search_sorted_last_r(a::Ranges, x::Real) = search_sorted_last(a, x) +search_sorted_first_r(a::Ranges, x::Real) = search_sorted_first(a, x) +search_sorted_r(a::Ranges, x::Real) = search_sorted(a, x) +search_sorted(a::Ranges, x::Real) = search_sorted_first(a, x) -@_jl_sort_functions "" :(isless($a,$b)) -@_jl_sort_functions "_r" :(isless($b,$a)) -@_jl_sort_functions "_lt" :(lt($a,$b)) lt::Function -@_jl_sort_functions "_by" :(isless(by($a),by($b))) by::Function +search_sorted_last(a::Ranges, x::Real) = + max(min(int(fld(x - a[1], step(a))) + 1, length(a)), 0) + +function search_sorted_first(a::Ranges, x::Real) + n = x - a[1] + s = step(a) + max(min(int(fld(n, s)) + (rem(n, s) != 0), length(a)), 0) + 1 +end ## external sorting functions ## -sort!{T<:Real}(a::AbstractVector{T}) = _jl_quicksort(a, 1, length(a)) -sortr!{T<:Real}(a::AbstractVector{T}) = _jl_quicksort_r(a, 1, length(a)) -sort!{T}(a::AbstractVector{T}) = _jl_mergesort(a, 1, length(a), Array(T,length(a))) -sortr!{T}(a::AbstractVector{T}) = _jl_mergesort_r(a, 1, length(a), Array(T,length(a))) +sort!{T<:Real}(a::AbstractVector{T}) = quicksort!(a, 1, length(a)) +sortr!{T<:Real}(a::AbstractVector{T}) = quicksort_r!(a, 1, length(a)) +sort!{T}(a::AbstractVector{T}) = mergesort!(a, 1, length(a), Array(T,length(a))) +sortr!{T}(a::AbstractVector{T}) = mergesort_r!(a, 1, length(a), Array(T,length(a))) sort!{T}(lt::Function, a::AbstractVector{T}) = - _jl_mergesort_lt(lt, a, 1, length(a), Array(T,length(a))) + mergesort!(lt, a, 1, length(a), Array(T,length(a))) sort_by!{T}(by::Function, a::AbstractVector{T}) = - _jl_mergesort_by(by, a, 1, length(a), Array(T,length(a))) - -## special sorting for floating-point arrays ## - -@_jl_sort_functions "_fp_pos" :(_jl_fp_pos_lt($a,$b)) -@_jl_sort_functions "_fp_neg" :(_jl_fp_neg_lt($a,$b)) + mergesort_by!(by, a, 1, length(a), Array(T,length(a))) # push NaNs to the end of a, returning # of non-NaNs -function _jl_nans_to_end{T<:FloatingPoint}(a::AbstractVector{T}) +function nans_to_end{T<:FloatingPoint}(a::AbstractVector{T}) n = length(a) if n <= 1 return n @@ -235,12 +464,12 @@ function _jl_nans_to_end{T<:FloatingPoint}(a::AbstractVector{T}) end function sort!{T<:FloatingPoint}(a::AbstractVector{T}) - n = _jl_nans_to_end(a) + n = nans_to_end(a) i, j = 1, n while true # TODO: faster positive negative int check? - while i <= j && _jl_fp_pos_lt(a[i],zero(T)); i += 1; end - while i <= j && _jl_fp_pos_le(zero(T),a[j]); j -= 1; end + while i <= j && fp_pos_lt(a[i],zero(T)); i += 1; end + while i <= j && fp_pos_le(zero(T),a[j]); j -= 1; end if i <= j a[i], a[j] = a[j], a[i] i += 1 @@ -249,38 +478,11 @@ function sort!{T<:FloatingPoint}(a::AbstractVector{T}) break end end - _jl_quicksort_fp_neg(a, 1, j) - _jl_quicksort_fp_pos(a, i, n) - return a -end - -# TODO: something sensible should happen when each_col et. al. are used with a -# pure function argument -function each_col!(f::Function, a::AbstractMatrix) - m = size(a,1) - for i = 1:m:numel(a) - f(sub(a, i:(i+m-1))) - end - return a -end - -function each_row!(f::Function, a::AbstractMatrix) - m = size(a,1) - for i = 1:m - f(sub(a, i:m:numel(a))) - end + quicksort_fp_neg!(a, 1, j) + quicksort_fp_pos!(a, i, n) return a end -function each_vec!(f::Function, a::AbstractMatrix, dim::Integer) - if dim == 1; return each_col!(f,a); end - if dim == 2; return each_row!(f,a); end - error("invalid matrix dimensions: $dim") -end - -each_col(f::Function, a::AbstractMatrix) = each_col!(f,copy(a)) -each_row(f::Function, a::AbstractMatrix) = each_row!(f,copy(a)) -each_vec(f::Function, a::AbstractMatrix, d::Integer) = each_vec!(f,copy(a),d) ## other sorting functions defined in terms of sort! ## @@ -315,6 +517,26 @@ end @in_place_matrix_op sortr @in_place_matrix_op sort_by by::Function +@in_place_matrix_op insertionsort +@in_place_matrix_op insertionsort lt::Function +@in_place_matrix_op insertionsort_r +@in_place_matrix_op insertionsort_by by::Function + +@in_place_matrix_op quicksort +@in_place_matrix_op quicksort lt::Function +@in_place_matrix_op quicksort_r +@in_place_matrix_op quicksort_by by::Function + +@in_place_matrix_op mergesort +@in_place_matrix_op mergesort lt::Function +@in_place_matrix_op mergesortr +@in_place_matrix_op mergesort_by by::Function + +@in_place_matrix_op timsort +@in_place_matrix_op timsort lt::Function +@in_place_matrix_op timsortr +@in_place_matrix_op timsort_by by::Function + # TODO: implement generalized in-place, ditch this function sort(a::AbstractArray, dim::Int) X = similar(a) @@ -332,107 +554,6 @@ function sort(a::AbstractArray, dim::Int) return X end -sortperm{T}(a::AbstractVector{T}) = - _jl_mergesort(copy(a), [1:length(a)], 1, length(a), - Array(T, length(a)), Array(Int, length(a))) - -function issorted(v::AbstractVector) - for i = 1:length(v)-1 - if isless(v[i+1], v[i]) - return false - end - end - return true -end - -function _jl_quickselect(a::AbstractArray, k::Int, lo::Int, hi::Int) - if k < lo || k > hi; error("k is out of bounds"); end - - while true - - if lo == hi; return a[lo]; end - - i, j = lo, hi - pivot = _jl_pivot_middle(a[lo], a[hi], a[(lo+hi)>>>1]) - while i < j - while isless(a[i], pivot); i += 1; end - while isless(pivot, a[j]); j -= 1; end - if isequal(a[i], a[j]) - i += 1 - elseif i < j - a[i], a[j] = a[j], a[i] - end - end - pivot_ind = j - - length = pivot_ind - lo + 1 - if k == length - return a[pivot_ind] - elseif k < length - hi = pivot_ind - 1 - else - lo = pivot_ind + 1 - k = k - length - end - - end # while true... - -end - -select(a::AbstractArray, k::Int) = _jl_quickselect(copy(a), k, 1, length(a)) -select!(a::AbstractArray, k::Int) = _jl_quickselect(a, k, 1, length(a)) - -search_sorted(a::Vector, x) = search_sorted(a, x, 1, length(a)) - -function search_sorted(a::Vector, x, lo::Int, hi::Int) - if isless(a[hi], x) - return hi+1 - end - while lo < hi-1 - i = (lo+hi)>>>1 - if isless(x,a[i]) - hi = i - else - lo = i - end - end - return isless(a[lo],x) ? hi : lo -end - -search_sorted_last(a::Vector, x) = search_sorted_last(a, x, 0, length(a)+1) - -function search_sorted_last(a::Vector, x, lo::Int, hi::Int) - ## Index of the last value of vector a that is less than or equal to x. - ## Returns 0 if x is less than all values of a. - ## - ## Good reference: http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary - while lo < hi-1 - i = (lo+hi)>>>1 - if isless(x,a[i]) - hi = i - else - lo = i - end - end - lo -end - -search_sorted_first(a::Vector, x) = search_sorted_first(a, x, 0, length(a)+1) - -function search_sorted_first(a::Vector, x, lo::Int, hi::Int) - ## Index of the first value of vector a that is greater than or equal to x. - ## Returns length(a) + 1 if x is greater than all values in a. - ## - ## Good reference: http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary - while lo < hi-1 - i = (lo+hi)>>>1 - if isless(a[i],x) - lo = i - else - hi = i - end - end - hi -end - order(a::AbstractVector) = sortperm(a)[2] + +end # module Sort diff --git a/base/sparse.jl b/base/sparse.jl index 7ff935f511d20..0174a03f41c2e 100644 --- a/base/sparse.jl +++ b/base/sparse.jl @@ -18,24 +18,14 @@ type SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti} nzval::Vector{Tv} # Nonzero values end -function SparseMatrixCSC(Tv::Type, m::Int, n::Int, numnz::Integer) - colptr = Array(Int, n+1) - rowval = Array(Int, numnz) - nzval = Array(Tv, numnz) - - colptr[1] = 1 - colptr[end] = numnz+1 - SparseMatrixCSC{Tv,Int}(m, n, colptr, rowval, nzval) -end - -function SparseMatrixCSC(Tv::Type, Ti::Type, m::Int, n::Int, numnz::Integer) +function SparseMatrixCSC(Tv::Type, Ti::Type, m::Integer, n::Integer, numnz::Integer) colptr = Array(Ti, n+1) rowval = Array(Ti, numnz) nzval = Array(Tv, numnz) colptr[1] = 1 colptr[end] = numnz+1 - SparseMatrixCSC{Tv,Ti}(m, n, colptr, rowval, nzval) + SparseMatrixCSC{Tv,Ti}(int(m), int(n), colptr, rowval, nzval) end function SparseMatrixCSC(m::Integer, n::Integer, colptr::Vector, rowval::Vector, nzval::Vector) @@ -43,7 +33,7 @@ function SparseMatrixCSC(m::Integer, n::Integer, colptr::Vector, rowval::Vector, end size(S::SparseMatrixCSC) = (S.m, S.n) -nnz(S::SparseMatrixCSC) = S.colptr[end]-1 +nnz(S::SparseMatrixCSC) = int(S.colptr[end]-1) function show(io, S::SparseMatrixCSC) println(io, S.m, "x", S.n, " sparse matrix with ", nnz(S), " nonzeros:") @@ -56,7 +46,7 @@ function show(io, S::SparseMatrixCSC) println(io, "\t[", rpad(S.rowval[k], pad), ", ", lpad(col, pad), "] = ", sprint(showcompact, S.nzval[k])) elseif k == half_screen_rows - println(io, "\t."); println(io, "\t."); println(io, "\t."); + println("\t\u22ee") end k += 1 end @@ -68,14 +58,14 @@ function reinterpret{T,Tv,Ti}(::Type{T}, a::SparseMatrixCSC{Tv,Ti}) if sizeof(T) != sizeof(Tv) error("SparseMatrixCSC reinterpret is only supported for element types of the same size") end - mA,nA = size(a) + mA, nA = size(a) colptr = copy(a.colptr) rowval = copy(a.rowval) - nzval = reinterpret(T, a.nzval) + nzval = reinterpret(Tv, a.nzval) return SparseMatrixCSC{T,Ti}(mA, nA, colptr, rowval, nzval) end -function _jl_sparse_compute_reshaped_colptr_and_rowval(colptrS, rowvalS, mS, nS, colptrA, rowvalA, mA, nA) +function sparse_compute_reshaped_colptr_and_rowval(colptrS, rowvalS, mS, nS, colptrA, rowvalA, mA, nA) colptrS[1] = 1 colA = 1 @@ -117,7 +107,7 @@ function reinterpret{T,Tv,Ti,N}(::Type{T}, a::SparseMatrixCSC{Tv,Ti}, dims::NTup rowval = Array(Ti, numnz) nzval = reinterpret(T, a.nzval) - _jl_sparse_compute_reshaped_colptr_and_rowval(colptr, rowval, mS, nS, a.colptr, a.rowval, mA, nA) + sparse_compute_reshaped_colptr_and_rowval(colptr, rowval, mS, nS, a.colptr, a.rowval, mA, nA) return SparseMatrixCSC{T,Ti}(mS, nS, colptr, rowval, nzval) end @@ -133,7 +123,7 @@ function reshape{Tv,Ti}(a::SparseMatrixCSC{Tv,Ti}, dims::NTuple{2,Int}) rowval = Array(Ti, numnz) nzval = a.nzval - _jl_sparse_compute_reshaped_colptr_and_rowval(colptr, rowval, mS, nS, a.colptr, a.rowval, mA, nA) + sparse_compute_reshaped_colptr_and_rowval(colptr, rowval, mS, nS, a.colptr, a.rowval, mA, nA) return SparseMatrixCSC{Tv,Ti}(mS, nS, colptr, rowval, nzval) end @@ -173,8 +163,8 @@ convert(::Type{Matrix}, S::SparseMatrixCSC) = dense(S) full(S::SparseMatrixCSC) = dense(S) -function dense{T}(S::SparseMatrixCSC{T}) - A = zeros(T, S.m, S.n) +function dense{Tv}(S::SparseMatrixCSC{Tv}) + A = zeros(Tv, S.m, S.n) for col = 1 : S.n, k = S.colptr[col] : (S.colptr[col+1]-1) A[S.rowval[k], col] = S.nzval[k] end @@ -203,7 +193,7 @@ sparse_IJ_sorted!(I,J,V::AbstractVector{Bool},m,n) = sparse_IJ_sorted!(I,J,V,m,n function sparse_IJ_sorted!{Ti<:Integer}(I::AbstractVector{Ti}, J::AbstractVector{Ti}, V::AbstractVector, - m::Int, n::Int, combine::Function) + m::Integer, n::Integer, combine::Function) cols = zeros(Ti, n+1) cols[1] = 1 # For cumsum purposes @@ -256,10 +246,12 @@ sparse(I,J,V::AbstractVector{Bool},m,n) = sparse(I, J, V, int(m), int(n), |) sparse(I,J,v::Number,m,n,combine::Function) = sparse(I, J, fill(v,length(I)), int(m), int(n), combine) -# Based on http://www.cise.ufl.edu/research/sparse/cholmod/CHOLMOD/Core/cholmod_triplet.c +# Based on Direct Methods for Sparse Linear Systems, T. A. Davis, SIAM, Philadelphia, Sept. 2006. +# Section 2.4: Triplet form +# http://www.cise.ufl.edu/research/sparse/CSparse/ function sparse{Tv,Ti<:Integer}(I::AbstractVector{Ti}, J::AbstractVector{Ti}, V::AbstractVector{Tv}, - nrow::Int, ncol::Int, combine::Function) + nrow::Integer, ncol::Integer, combine::Function) if length(I) == 0; return spzeros(eltype(V),nrow,ncol); end @@ -410,7 +402,7 @@ function findn_nzs{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}) return (I, J, V) end -function sprand(m::Int, n::Int, density::FloatingPoint, rng::Function, v) +function sprand(m::Integer, n::Integer, density::FloatingPoint, rng::Function, v) numnz = int(m*n*density) I = randival!(1, m, Array(Int, numnz)) J = randival!(1, n, Array(Int, numnz)) @@ -422,26 +414,26 @@ function sprand(m::Int, n::Int, density::FloatingPoint, rng::Function, v) return S end -sprand(m::Int, n::Int, density::FloatingPoint, rng::Function) = sprand(m,n,density,rng, 1.0) -sprand(m::Int, n::Int, density::FloatingPoint) = sprand(m,n,density,rand, 1.0) -sprandn(m::Int, n::Int, density::FloatingPoint) = sprand(m,n,density,randn, 1.0) -sprandbool(m::Int, n::Int, density::FloatingPoint) = sprand(m,n,density,randbool, true) +sprand(m::Integer, n::Integer, density::FloatingPoint, rng::Function) = sprand(m,n,density,rng, 1.0) +sprand(m::Integer, n::Integer, density::FloatingPoint) = sprand(m,n,density,rand, 1.0) +sprandn(m::Integer, n::Integer, density::FloatingPoint) = sprand(m,n,density,randn, 1.0) +sprandbool(m::Integer, n::Integer, density::FloatingPoint) = sprand(m,n,density,randbool, true) spones{T}(S::SparseMatrixCSC{T}) = SparseMatrixCSC(S.m, S.n, copy(S.colptr), copy(S.rowval), ones(T, S.colptr[end]-1)) -spzeros(m::Int) = spzeros(m, m) -spzeros(m::Int, n::Int) = spzeros(Float64, m, n) -spzeros(Tv::Type, m::Int) = spzeros(Tv, m, m) -spzeros(Tv::Type, m::Int, n::Int) = +spzeros(m::Integer) = spzeros(m, m) +spzeros(m::Integer, n::Integer) = spzeros(Float64, m, n) +spzeros(Tv::Type, m::Integer) = spzeros(Tv, m, m) +spzeros(Tv::Type, m::Integer, n::Integer) = SparseMatrixCSC(m, n, ones(Int, n+1), Array(Int, 0), Array(Tv, 0)) -speye(n::Int) = speye(Float64, n) -speye(T::Type, n::Int) = speye(T, n, n) -speye(m::Int, n::Int) = speye(Float64, m, n) +speye(n::Integer) = speye(Float64, n) +speye(T::Type, n::Integer) = speye(T, n, n) +speye(m::Integer, n::Integer) = speye(Float64, m, n) speye{T}(S::SparseMatrixCSC{T}) = speye(T, size(S, 1), size(S, 2)) -function speye(T::Type, m::Int, n::Int) +function speye(T::Type, m::Integer, n::Integer) x = min(m,n) rowval = [1:x] colptr = [rowval, fill(int(x+1), n+1-x)] @@ -457,7 +449,9 @@ end ## Transpose -# Based on: http://www.cise.ufl.edu/research/sparse/CSparse/CSparse/Source/cs_transpose.c +# Based on Direct Methods for Sparse Linear Systems, T. A. Davis, SIAM, Philadelphia, Sept. 2006. +# Section 2.5: Transpose +# http://www.cise.ufl.edu/research/sparse/CSparse/ function transpose{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}) (nT, mT) = size(S) nnzS = nnz(S) @@ -660,7 +654,7 @@ end # macro # Reductions # TODO: Should the results of sparse reductions be sparse? -function areduce{Tv,Ti}(f::Function, A::SparseMatrixCSC{Tv,Ti}, region::Dimspec, v0) +function areduce{Tv,Ti}(f::Function, A::SparseMatrixCSC{Tv,Ti}, region, v0) if region == 1 S = Array(Tv, 1, A.n) @@ -708,20 +702,20 @@ function areduce{Tv,Ti}(f::Function, A::SparseMatrixCSC{Tv,Ti}, region::Dimspec, end max{T}(A::SparseMatrixCSC{T}) = areduce(max,A,(1,2),typemin(T)) -max{T}(A::SparseMatrixCSC{T}, b::(), region::Dimspec) = areduce(max,A,region,typemin(T)) +max{T}(A::SparseMatrixCSC{T}, b::(), region) = areduce(max,A,region,typemin(T)) min{T}(A::SparseMatrixCSC{T}) = areduce(min,A,(1,2),typemax(T)) -min{T}(A::SparseMatrixCSC{T}, b::(), region::Dimspec) = areduce(min,A,region,typemax(T)) +min{T}(A::SparseMatrixCSC{T}, b::(), region) = areduce(min,A,region,typemax(T)) sum{T}(A::SparseMatrixCSC{T}) = areduce(+,A,(1,2),zero(T)) -sum{T}(A::SparseMatrixCSC{T}, region::Dimspec) = areduce(+,A,region,zero(T)) +sum{T}(A::SparseMatrixCSC{T}, region) = areduce(+,A,region,zero(T)) prod{T}(A::SparseMatrixCSC{T}) = areduce(*,A,(1,2),one(T)) -prod{T}(A::SparseMatrixCSC{T}, region::Dimspec) = areduce(*,A,region,one(T)) +prod{T}(A::SparseMatrixCSC{T}, region) = areduce(*,A,region,one(T)) -#all(A::SparseMatrixCSC{Bool}, region::Dimspec) = areduce(all,A,region,true) -#any(A::SparseMatrixCSC{Bool}, region::Dimspec) = areduce(any,A,region,false) -#sum(A::SparseMatrixCSC{Bool}, region::Dimspec) = areduce(+,A,region,0,Int) +#all(A::SparseMatrixCSC{Bool}, region) = areduce(all,A,region,true) +#any(A::SparseMatrixCSC{Bool}, region) = areduce(any,A,region,false) +#sum(A::SparseMatrixCSC{Bool}, region) = areduce(+,A,region,0,Int) #sum(A::SparseMatrixCSC{Bool}) = nnz(A) ## ref @@ -1395,7 +1389,9 @@ function expandptr{T<:Integer}(V::Vector{T}) res end -# Based on the function cs_fkeep from the CSparse library +# Based on Direct Methods for Sparse Linear Systems, T. A. Davis, SIAM, Philadelphia, Sept. 2006. +# Section 2.7: Removing entries from a matrix +# http://www.cise.ufl.edu/research/sparse/CSparse/ function fkeep!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, f, other) nzorig = nnz(A) nz = 1 diff --git a/base/stat.jl b/base/stat.jl index ff8a3e0446b67..04a08201762f7 100644 --- a/base/stat.jl +++ b/base/stat.jl @@ -32,15 +32,15 @@ show(io::IO, st::Stat) = print("Stat(mode=$(oct(st.mode,6)), size=$(st.size))") # stat & lstat functions -const _jl_stat_buf = Array(Uint8, ccall(:jl_sizeof_stat, Int, ())) -macro _jl_stat_call(sym,arg) +const stat_buf = Array(Uint8, ccall(:jl_sizeof_stat, Int, ())) +macro stat_call(sym,arg) quote - fill!(_jl_stat_buf,0) - r = ccall($(expr(:quote,sym)), Int32, (Ptr{Uint8},Ptr{Uint8}), $arg, _jl_stat_buf) + fill!(stat_buf,0) + r = ccall($(expr(:quote,sym)), Int32, (Ptr{Uint8},Ptr{Uint8}), $arg, stat_buf) uv_errno = _uv_lasterror(globalEventLoop()) ENOENT = 34 system_error("stat", r!=0 && uv_errno!=ENOENT) - st = Stat(_jl_stat_buf) + st = Stat(stat_buf) if ispath(st) != (r==0) error("WTF: stat returned zero type for a valid path!?") end @@ -48,9 +48,9 @@ macro _jl_stat_call(sym,arg) end end -stat(path::String) = @_jl_stat_call jl_stat path -stat(fd::Integer) = @_jl_stat_call jl_fstat fd -lstat(path::String) = @_jl_stat_call jl_lstat path +stat(path::String) = @stat_call jl_stat path +stat(fd::Integer) = @stat_call jl_fstat fd +lstat(path::String) = @stat_call jl_lstat path # mode type predicates diff --git a/base/statistics.jl b/base/statistics.jl index e41f8eff4ae5b..657f8970c6d7e 100644 --- a/base/statistics.jl +++ b/base/statistics.jl @@ -5,7 +5,7 @@ weighted_mean(v::AbstractArray, w::AbstractArray) = sum(v.*w)/sum(w) function median(v::AbstractArray) n = numel(v) if isodd(n) - return select(v, div(n+1, 2)) + return float(select(v, div(n+1, 2))) else vs = sort(v) return (vs[div(n, 2)] + vs[div(n, 2) + 1]) / 2 @@ -62,12 +62,61 @@ std(v::AbstractArray) = std(v, true) std(v::Ranges, corrected::Bool) = sqrt(var(v, corrected)) std(v::Ranges) = std(v, true) -## median absolute deviation with known center -mad(v::AbstractArray, center::Number) = median(abs(v - center)) +## median absolute deviation with known center with consistency adjustment +mad(v::AbstractArray, center::Number) = 1.4826 * median(abs(v - center)) ## median absolute deviation mad(v::AbstractArray) = mad(v, median(v)) +## maximum likelihood estimate of skewness with known mean m +function skewness(v::AbstractVector, m::Number) + n = length(v) + empirical_third_centered_moment = 0.0 + empirical_variance = 0.0 + for x_i in v + empirical_third_centered_moment += (x_i - m)^3 + empirical_variance += (x_i - m)^2 + end + empirical_third_centered_moment /= n + empirical_variance /= n + return empirical_third_centered_moment / (empirical_variance^1.5) +end + +## maximum likelihood estimate of skewness +skewness(v::AbstractVector) = skewness(v, mean(v)) + +## maximum likelihood estimate of kurtosis with known mean m +function kurtosis(v::AbstractVector, m::Number) + n = length(v) + empirical_fourth_centered_moment = 0.0 + empirical_variance = 0.0 + for x_i in v + empirical_fourth_centered_moment += (x_i - m)^4 + empirical_variance += (x_i - m)^2 + end + empirical_fourth_centered_moment /= n + empirical_variance /= n + return (empirical_fourth_centered_moment / (empirical_variance^2)) - 3.0 +end + +## maximum likelihood estimate of kurtosis +kurtosis(v::AbstractVector) = kurtosis(v, mean(v)) + +## distance matrix +function dist(m::AbstractMatrix) + n = size(m, 1) + d = Array(Float64, n, n) + for i in 1:n + d[i, i] = 0.0 + for j in (i + 1):n + x = norm(m[i, :] - m[j, :]) + d[i, j] = x + d[j, i] = x + end + end + return d +end + ## hist ## function hist(v::StridedVector, nbins::Integer) @@ -161,7 +210,7 @@ end ## pearson covariance functions ## # pearson covariance between two vectors, with known means -function _jl_cov_pearson1(x::AbstractArray, y::AbstractArray, mx::Number, my::Number, corrected::Bool) +function cov_pearson1(x::AbstractArray, y::AbstractArray, mx::Number, my::Number, corrected::Bool) n = numel(x) if n == 0 || (n == 1 && corrected) return NaN @@ -179,12 +228,12 @@ function cov_pearson(x::AbstractVector, y::AbstractVector, corrected::Bool) mx = mean(x) my = mean(y) - _jl_cov_pearson1(x, y, mx, my, corrected) + cov_pearson1(x, y, mx, my, corrected) end cov_pearson(x::AbstractVector, y::AbstractVector) = cov_pearson(x, y, true) # pearson covariance over all pairs of columns of a matrix -function _jl_cov_pearson(x::AbstractMatrix, mxs::AbstractMatrix, corrected::Bool) +function cov_pearson(x::AbstractMatrix, mxs::AbstractMatrix, corrected::Bool) n = size(x, 1) if n == 0 || (n == 1 && corrected) return NaN @@ -192,11 +241,11 @@ function _jl_cov_pearson(x::AbstractMatrix, mxs::AbstractMatrix, corrected::Bool x0 = x - repmat(mxs, n, 1) return (x0'*x0) / (n - (corrected ? 1 : 0)) end -cov_pearson(x::AbstractMatrix, corrected::Bool) = _jl_cov_pearson(x, mean(x, 1), corrected) +cov_pearson(x::AbstractMatrix, corrected::Bool) = cov_pearson(x, mean(x, 1), corrected) cov_pearson(x::AbstractMatrix) = cov_pearson(x, true) # pearson covariance over all pairs of columns of two matrices -function _jl_cov_pearson(x::AbstractMatrix, y::AbstractMatrix, +function cov_pearson(x::AbstractMatrix, y::AbstractMatrix, mxs::AbstractMatrix, mys::AbstractMatrix, corrected::Bool) n = size(x, 1) @@ -219,7 +268,7 @@ function cov_pearson(x::AbstractMatrix, y::AbstractMatrix, corrected::Bool) n = size(x, 1) mxs = mean(x, 1) mys = mean(y, 1) - return _jl_cov_pearson(x, y, mxs, mys, corrected) + return cov_pearson(x, y, mxs, mys, corrected) end cov_pearson(x::AbstractMatrix, y::AbstractMatrix) = cov_pearson(x, y, true) @@ -265,7 +314,7 @@ function cor_pearson(x::AbstractVector, y::AbstractVector, corrected::Bool) sx = std(x, mx, corrected) sy = std(y, my, corrected) - return _jl_cov_pearson1(x, y, mx, my, corrected) / (sx * sy) + return cov_pearson1(x, y, mx, my, corrected) / (sx * sy) end cor_pearson(x::AbstractVector, y::AbstractVector) = cor_pearson(x, y, true) @@ -277,7 +326,7 @@ function cor_pearson{T}(x::AbstractMatrix{T}, corrected::Bool) for i = 1:m sxs[i] = std(sub(x, (1:n, i)), mxs[i], corrected) end - R = _jl_cov_pearson(x, mxs, corrected) ./ (sxs' * sxs) + R = cov_pearson(x, mxs, corrected) ./ (sxs' * sxs) R[1:m+1:end] = one(T) # fix diagonal for numerical errors @@ -305,7 +354,7 @@ function cor_pearson(x::AbstractMatrix, y::AbstractMatrix, corrected::Bool) sys[i] = std(sub(y, (1:n, i)), mys[i], corrected) end - return _jl_cov_pearson(x, y, mxs, mys, corrected) ./ (sxs' * sys) + return cov_pearson(x, y, mxs, mys, corrected) ./ (sxs' * sys) end cor_pearson(x::AbstractMatrix, y::AbstractMatrix) = cor_pearson(x, y, true) @@ -338,42 +387,93 @@ cor_spearman(x::AbstractMatrix, y::AbstractMatrix) = cor_spearman(x, y, true) const cor = cor_pearson +## autocorrelation at a specific lag +autocor(v::AbstractVector, lag::Int) = cor(v[1:(end-lag)], v[(1 + lag):end]) + +## autocorrelation at a default lag of 1 +autocor(v::AbstractVector) = autocor(v, 1) + ## quantiles ## # for now, use the R/S definition of quantile; may want variants later # see ?quantile in R -- this is type 7 -function quantile(x, qs) +function quantile(v::AbstractVector, qs::AbstractVector) # make sure the quantiles are in [0,1] bqs = _bound_quantiles(qs) - - lx = length(x) + + lx = length(v) lqs = length(bqs) - + if lx > 0 && lqs > 0 index = 1 + (lx-1) * bqs lo = ifloor(index) hi = iceil(index) - sortedX = sort(x) + sortedV = sort(v) i = index .> lo - ret = float(sortedX[lo]) + ret = float(sortedV[lo]) i = [1:length(i)][i] h = (index - lo)[i] - ret[i] = (1-h) .* ret[i] + h .* sortedX[hi[i]] + ret[i] = (1-h) .* ret[i] + h .* sortedV[hi[i]] else ret = zeros(lqs) * NaN end - + ret end -quantile(x, q::Number) = quantile(x, [q])[1] -quartile(x) = quantile(x, [.25, .5, .75]) -quintile(x) = quantile(x, [.2:.2:.8]) -decile(x) = quantile(x, [.1:.1:.9]) - -function _bound_quantiles(qs) +quantile(v::AbstractVector, q::Number) = quantile(v, [q])[1] +quantile(v::AbstractVector) = quantile(v, [.0, .25, .5, .75, 1.0]) +quartile(v::AbstractVector) = quantile(v, [.25, .5, .75]) +quintile(v::AbstractVector) = quantile(v, [.2, .4, .6, .8]) +decile(v::AbstractVector) = quantile(v, [.1, .2, .3, .4, .5, .6, .7, .8, .9]) +iqr(v::AbstractVector) = quantile(v, [0.25, 0.75]) + +function _bound_quantiles(qs::AbstractVector) epsilon = 100 * eps() if (any(qs .< -epsilon) || any(qs .> 1 + epsilon)) error("quantiles out of [0,1] range!") end [min(1, max(0, q)) for q = qs] end + +## run-length encoding +function rle{T}(v::Vector{T}) + n = length(v) + current_value = v[1] + current_length = 1 + values = Array(T, n) + total_values = 1 + lengths = Array(Int, n) + total_lengths = 1 + for i in 2:n + if v[i] == current_value + current_length += 1 + else + values[total_values] = current_value + total_values += 1 + lengths[total_lengths] = current_length + total_lengths += 1 + current_value = v[i] + current_length = 1 + end + end + values[total_values] = current_value + lengths[total_lengths] = current_length + return (values[1:total_values], lengths[1:total_lengths]) +end + +## inverse run-length encoding +function inverse_rle{T}(values::Vector{T}, lengths::Vector{Int}) + total_n = sum(lengths) + pos = 0 + res = Array(T, total_n) + n = length(values) + for i in 1:n + v = values[i] + l = lengths[i] + for j in 1:l + pos += 1 + res[pos] = v + end + end + return res +end diff --git a/base/string.jl b/base/string.jl index b25c10be3b1bc..e0214574a381a 100644 --- a/base/string.jl +++ b/base/string.jl @@ -682,8 +682,9 @@ unescape_string(s::String) = sprint(length(s), print_unescaped, s) ## checking UTF-8 & ACSII validity ## -byte_string_classify(s::ByteString) = - ccall(:u8_isvalid, Int32, (Ptr{Uint8}, Int), s.data, length(s)) +byte_string_classify(data::Array{Uint8,1}) = + ccall(:u8_isvalid, Int32, (Ptr{Uint8}, Int), data, length(data)) +byte_string_classify(s::ByteString) = byte_string_classify(s.data) # 0: neither valid ASCII nor UTF-8 # 1: valid ASCII # 2: valid UTF-8 @@ -696,7 +697,7 @@ check_utf8 (s::ByteString) = is_valid_utf8(s) ? s : error("invalid UTF-8 sequen ## string interpolation parsing ## -function _jl_interp_parse(s::String, unescape::Function, printer::Function) +function interp_parse(s::String, unescape::Function, printer::Function) sx = {} i = j = start(s) while !done(s,j) @@ -730,26 +731,26 @@ function _jl_interp_parse(s::String, unescape::Function, printer::Function) expr(:call, :sprint, printer, sx...) end -_jl_interp_parse(s::String, u::Function) = _jl_interp_parse(s, u, print) -_jl_interp_parse(s::String) = _jl_interp_parse(s, x->check_utf8(unescape_string(x))) +interp_parse(s::String, u::Function) = interp_parse(s, u, print) +interp_parse(s::String) = interp_parse(s, x->check_utf8(unescape_string(x))) -function _jl_interp_parse_bytes(s::String) +function interp_parse_bytes(s::String) writer(io,x...) = for w=x; write(io,w); end - _jl_interp_parse(s, unescape_string, writer) + interp_parse(s, unescape_string, writer) end ## core string macros ## -macro str(s); _jl_interp_parse(s); end -macro S_str(s); _jl_interp_parse(s); end -macro I_str(s); _jl_interp_parse(s, x->unescape_chars(x,"\"")); end +macro str(s); interp_parse(s); end +macro S_str(s); interp_parse(s); end +macro I_str(s); interp_parse(s, x->unescape_chars(x,"\"")); end macro E_str(s); check_utf8(unescape_string(s)); end -macro B_str(s); _jl_interp_parse_bytes(s); end -macro b_str(s); ex = _jl_interp_parse_bytes(s); :(($ex).data); end +macro B_str(s); interp_parse_bytes(s); end +macro b_str(s); ex = interp_parse_bytes(s); :(($ex).data); end ## shell-like command parsing ## -function _jl_shell_parse(raw::String, interp::Bool) +function shell_parse(raw::String, interp::Bool) s = strip(raw) in_single_quotes = false @@ -840,10 +841,10 @@ function _jl_shell_parse(raw::String, interp::Bool) end expr(:tuple,exprs) end -_jl_shell_parse(s::String) = _jl_shell_parse(s,true) +shell_parse(s::String) = shell_parse(s,true) function shell_split(s::String) - parsed = _jl_shell_parse(s,false) + parsed = shell_parse(s,false) args = String[] for arg in parsed push(args, string(arg...)) @@ -1055,6 +1056,16 @@ chomp(s::ByteString) = (length(s) < 1 || s.data[end] != 0x0a) ? s : (length(s) < 2 || s.data[end-1] != 0x0d) ? s[1:end-1] : s[1:end-2] +# NOTE: use with caution -- breaks the immutable string convention! +function chomp!(s::ByteString) + if length(s) >= 1 && s.data[end] == 0x0a + n = (length(s) < 2 || s.data[end-1] != 0x0d) ? 1 : 2 + ccall(:jl_array_del_end, Void, (Any, Uint), s.data, n) + end + return s +end +chomp!(s::String) = chomp(s) # copying fallback for other string types + function lstrip(s::String) i = start(s) while !done(s,i) diff --git a/base/subarray.jl b/base/subarray.jl index 42d8acca5ad8e..6906a26bdc3cf 100644 --- a/base/subarray.jl +++ b/base/subarray.jl @@ -1,5 +1,7 @@ ## subarrays ## +typealias RangeIndex Union(Int, Range{Int}, Range1{Int}) + type SubArray{T,N,A<:AbstractArray,I<:(RangeIndex...,)} <: AbstractArray{T,N} parent::A indexes::I @@ -186,10 +188,10 @@ function ref{T,S<:Integer}(s::SubArray{T,1}, I::AbstractVector{S}) ref(s.parent, t) end -function ref(s::SubArray, I::Indices...) +function ref(s::SubArray, I::Union(Real,AbstractArray)...) I = indices(I) n = ndims(s.parent) - newindexes = Array(Indices, n) + newindexes = Array(Any, n) for i = 1:n t = s.indexes[i] #TODO: don't generate the dense vector indexes if they can be ranges @@ -249,7 +251,7 @@ function assign{T,S<:Integer}(s::SubArray{T,1}, v, I::AbstractVector{S}) assign(s.parent, v, t) end -function assign(s::SubArray, v, I::Indices...) +function assign(s::SubArray, v, I::Union(Real,AbstractArray)...) I = indices(I) j = 1 #the jth dimension in subarray n = ndims(s.parent) diff --git a/base/sysimg.jl b/base/sysimg.jl index 92fdcba3a340e..5562a660fba92 100644 --- a/base/sysimg.jl +++ b/base/sysimg.jl @@ -2,7 +2,9 @@ baremodule Base eval(x) = Core.eval(Base,x) eval(m,x) = Core.eval(m,x) -#ccall(:jl_load_progress_setmax, Void, (Int,), 72) + +include = Core.include + include("export.jl") if false @@ -122,6 +124,7 @@ using RNG # Combinatorics include("sort.jl") +using Sort include("combinatorics.jl") # distributed arrays and memory-mapped arrays @@ -150,11 +153,10 @@ include("fftw.jl") include("dsp.jl") using DSP -ccall(:jl_load_progress_setmax, Void, (Int,), 0); -println() +include = include_from_node1 # prime method cache with some things we know we'll need right after startup -compile_hint(cwd, ()) +compile_hint(pwd, ()) compile_hint(fdio, (Int32,)) compile_hint(ProcessGroup, (Int, Array{Any,1}, Array{Any,1})) compile_hint(select_read, (FDSet, Float64)) @@ -222,7 +224,7 @@ compile_hint(hash, (Int,)) compile_hint(isequal, (Symbol, Symbol)) compile_hint(isequal, (Bool, Bool)) compile_hint(WaitFor, (Symbol, RemoteRef)) -compile_hint(_jl_answer_color, ()) +compile_hint(answer_color, ()) compile_hint(get, (EnvHash, ASCIIString, ASCIIString)) compile_hint(notify_empty, (WorkItem,)) compile_hint(rr2id, (RemoteRef,)) @@ -235,7 +237,7 @@ compile_hint(assign, (Dict{Any,Any}, WorkItem, (Int,Int))) compile_hint(isequal, ((Int,Int),(Int,Int))) compile_hint(isequal, (Int,Int)) compile_hint(RemoteRef, (Int, Int, Int)) -compile_hint(_jl_eval_user_input, (Expr, Bool)) +compile_hint(eval_user_input, (Expr, Bool)) compile_hint(print, (Float64,)) compile_hint(a2t, (Array{Any,1},)) compile_hint(flush, (IOStream,)) @@ -261,8 +263,8 @@ compile_hint(CallStack, (Expr, Module, (Nothing,), EmptyCallStack)) compile_hint(convert, (Type{Module}, Module)) compile_hint(effect_free, (Expr,)) compile_hint(effect_free, (TopNode,)) -compile_hint(abs_path, (ASCIIString,)) -compile_hint(isrooted, (ASCIIString,)) +compile_hint(abspath, (ASCIIString,)) +compile_hint(isabspath, (ASCIIString,)) compile_hint(split, (ASCIIString,)) compile_hint(split, (ASCIIString, ASCIIString, Int, Bool)) compile_hint(split, (ASCIIString, Regex, Int, Bool)) @@ -275,7 +277,7 @@ compile_hint(ref, (BitArray{1}, Int,)) compile_hint(assign, (BitArray{1}, Bool, Int,)) compile_hint(fill!, (BitArray{1}, Bool)) compile_hint(nnz, (BitArray{1},)) -compile_hint(_jl_get_chunks_id, (Int,)) +compile_hint(get_chunks_id, (Int,)) compile_hint(occurs_more, (Uint8, Function, Int)) compile_hint(abstract_eval_arg, (Uint8, ObjectIdDict, StaticVarInfo)) compile_hint(occurs_outside_tupleref, (Function, Symbol, StaticVarInfo, Int)) diff --git a/base/timsort.jl b/base/timsort.jl new file mode 100644 index 0000000000000..fcf27fdddf061 --- /dev/null +++ b/base/timsort.jl @@ -0,0 +1,798 @@ +# timsort for julia +# +# This is an implementation of timsort based on the algorithm description at +# +# http://svn.python.org/projects/python/trunk/Objects/listsort.txt +# http://en.wikipedia.org/wiki/Timsort +# +# @kmsquire + + +typealias Run Range1{Int} + +const MIN_GALLOP = 7 + +type MergeState + runs::Vector{Run} + min_gallop::Int +end +MergeState() = MergeState(Run[], MIN_GALLOP) + +# Determine a good minimum run size for efficient merging +# For details, see "Computing minrun" in +# http://svn.python.org/projects/python/trunk/Objects/listsort.txt +function merge_compute_minrun(N::Int, bits::Int) + r = 0 + max_val = 2^bits + while N >= max_val + r |= (N & 1) + N >>= 1 + end + N + r +end + +merge_compute_minrun(N::Int) = merge_compute_minrun(N, 6) + +# Macro to create different versions of the sort function, +# cribbed from sort.jl +for (suffix, lt, args) in (("", (a,b)->:(isless($a,$b)), ()), + ("_r", (a,b)->:(isless($b,$a)), ()), + ("", (a,b)->:(lt($a,$b)), (:(lt::Function),)), + ("_by", (a,b)->:(isless(by($a),by($b))), (:(by::Function),))) + insertionsort! = symbol("insertionsort$(suffix)!") + insertionsort_perm! = symbol("insertionsort_perm$(suffix)!") + timsort = symbol("timsort$(suffix)") + timsort! = symbol("timsort$(suffix)!") + timsort_perm = symbol("timsort_perm$(suffix)") + timsort_perm! = symbol("timsort_perm$(suffix)!") + next_run = symbol("next_run$suffix") + merge_collapse = symbol("merge_collapse$suffix") + merge = symbol("merge$suffix") + merge_lo = symbol("merge_lo$suffix") + merge_hi = symbol("merge_hi$suffix") + + gallop_last = symbol("gallop_last$suffix") + gallop_first = symbol("gallop_first$suffix") + rgallop_last = symbol("rgallop_last$suffix") + rgallop_first = symbol("rgallop_first$suffix") +@eval begin + +# Galloping binary search starting at left +function ($gallop_last)($(args...), a::AbstractVector, x, lo::Int, hi::Int) + i = lo + inc = 1 + lo = lo-1 + hi = hi+1 + while i < hi && !($(lt(:x, :(a[i])))) + lo = i + i += inc + inc <<= 1 + end + hi = min(i+1, hi) + # Binary search + while lo < hi-1 + i = (lo+hi)>>>1 + if !($(lt(:x, :(a[i])))) + lo = i + else + hi = i + end + end + hi +end + + +# Galloping binary search starting at right +function ($rgallop_last)($(args...), a::AbstractVector, x, lo::Int, hi::Int) + i = hi + dec = 1 + lo = lo-1 + hi = hi+1 + while i > lo && $(lt(:x, :(a[i]))) + hi = i + i -= dec + dec <<= 1 + end + lo = max(lo, i-1) + # Binary search + while lo < hi-1 + i = (lo+hi)>>>1 + if !($(lt(:x, :(a[i])))) + lo = i + else + hi = i + end + end + hi +end + + +# Galloping binary search starting at left +function ($gallop_first)($(args...), a::AbstractVector, x, lo::Int, hi::Int) + i = lo + inc = 1 + lo = lo-1 + hi = hi+1 + while i < hi && $(lt(:(a[i]),:x)) + lo = i + i += inc + inc <<= 1 + end + hi = min(i+1, hi) + # Binary search + while lo < hi-1 + i = (lo+hi)>>>1 + if $(lt(:(a[i]), :x)) + lo = i + else + hi = i + end + end + hi +end + + +# Galloping binary search starting at right +function ($rgallop_first)($(args...), a::AbstractVector, x, lo::Int, hi::Int) + i = hi + dec = 1 + lo = lo-1 + hi = hi+1 + while i > lo && !($(lt(:(a[i]),:x))) + hi = i + i -= dec + dec <<= 1 + end + lo = max(lo, i-1) + # Binary search + while lo < hi-1 + i = (lo+hi)>>>1 + if $(lt(:(a[i]), :x)) + lo = i + else + hi = i + end + end + hi +end + + +# Get the next run +# Returns the a range a:b, or b:-1:a for a reversed sequence +function ($next_run)($(args...), v::AbstractVector, lo::Int, hi::Int) + if lo == hi + return lo:lo + end + + if !($(lt(:(v[lo+1]), :(v[lo])))) + for i = lo+2:hi + if $(lt(:(v[i]), :(v[i-1]))) + return lo:i-1 + end + end + return lo:hi + else + for i = lo+2:hi + if !($(lt(:(v[i]), :(v[i-1])))) + return i-1:-1:lo + end + end + return hi:-1:lo + end +end + + +# Merge consecutive runs +# For A,B,C = last three lengths, merge_collapse!() +# maintains 2 invariants: +# +# A > B + C +# B > C +# +# If any of these are violated, a merge occurs to +# correct it +function ($merge_collapse)($(args...), v::AbstractVector, state::MergeState, force::Bool) + + while length(state.runs) > 2 + (a,b,c) = state.runs[end-2:end] + + if length(a) > length(b)+length(c) && length(b) > length(c) && !force + break # invariants are satisfied, leave loop + end + + if length(a) < length(c) + ($merge)($(args...), v,a,b,state) + pop(state.runs) + pop(state.runs) + pop(state.runs) + push(state.runs, first(a):last(b)) + push(state.runs, c) + else + ($merge)($(args...), v,b,c,state) + pop(state.runs) + pop(state.runs) + push(state.runs, first(b):last(c)) + end + end + + if length(state.runs) == 2 + (a,b) = state.runs[end-1:end] + + if length(a) <= length(b) || force + ($merge)($(args...), v,a,b,state) + pop(state.runs) + pop(state.runs) + push(state.runs, first(a):last(b)) + end + end + + return # v ## Used to return v, but should be unnecessary, as the only user of this function + ## is timsort(), and the return value is ignored there... +end + + +# Version which permutes an auxilliary array mirroring the sort +function ($merge_collapse)($(args...), v::AbstractVector, p::AbstractVector{Int}, state::MergeState, force::Bool) + + while length(state.runs) > 2 + (a,b,c) = state.runs[end-2:end] + + if length(a) > length(b)+length(c) && length(b) > length(c) && !force + break # invariants are satisfied, leave loop + end + + if length(a) < length(c) + ($merge)($(args...), v,p,a,b,state) + pop(state.runs) + pop(state.runs) + pop(state.runs) + push(state.runs, first(a):last(b)) + push(state.runs, c) + else + ($merge)($(args...), v,p,b,c,state) + pop(state.runs) + pop(state.runs) + push(state.runs, first(b):last(c)) + end + end + + if length(state.runs) == 2 + (a,b) = state.runs[end-1:end] + + if length(a) <= length(b) || force + ($merge)($(args...), v,p,a,b,state) + pop(state.runs) + pop(state.runs) + push(state.runs, first(a):last(b)) + end + end + + return # v ## Used to return v, but should be unnecessary, as the only user of this function + ## is timsort(), and the return value is ignored there... +end + + +# Merge runs a and b in vector v +function ($merge)($(args...), v::AbstractVector, a::Run, b::Run, state::MergeState) + + # First elements in a <= b[1] are already in place + a = ($gallop_last)($(args...), v, v[first(b)], first(a), last(a)) : last(a) + + if length(a) == 0 return end + + # Last elements in b >= a[end] are already in place + b = first(b) : ($rgallop_first)($(args...), v, v[last(a)], first(b), last(b))-1 + + # Choose merge_lo or merge_hi based on the amount + # of temporary memory needed (smaller of a and b) + if length(a) < length(b) + ($merge_lo)($(args...), v, a, b, state) + else + ($merge_hi)($(args...), v, a, b, state) + end +end + + +# Merge runs a and b in vector v (version which permutes an auxilliary array mirroring the sort) +function ($merge)($(args...), v::AbstractVector, p::AbstractVector{Int}, a::Run, b::Run, state::MergeState) + + # First elements in a <= b[1] are already in place + a = ($gallop_last)($(args...), v, v[first(b)], first(a), last(a)) : last(a) + + if length(a) == 0 return end + + # Last elements in b >= a[end] are already in place + b = first(b) : ($rgallop_first)($(args...), v, v[last(a)], first(b), last(b))-1 + + # Choose merge_lo or merge_hi based on the amount + # of temporary memory needed (smaller of a and b) + if length(a) < length(b) + ($merge_lo)($(args...), v, p, a, b, state) + else + ($merge_hi)($(args...), v, p, a, b, state) + end +end + +# Merge runs a and b in vector v (a is smaller) +function ($merge_lo)($(args...), v::AbstractVector, a::Run, b::Run, state::MergeState) + + # Copy a + v_a = v[a] + + # Pointer into (sub)arrays + i = first(a) + from_a = 1 + from_b = first(b) + + mode = :normal + while true + if mode == :normal + # Compare and copy element by element + count_a = count_b = 0 + while from_a <= length(a) && from_b <= last(b) + if $(lt(:(v[from_b]), :(v_a[from_a]))) + v[i] = v[from_b] + from_b += 1 + count_a = 0 + count_b += 1 + else + v[i] = v_a[from_a] + from_a += 1 + count_a += 1 + count_b = 0 + end + i += 1 + + # Switch to galloping mode if a string of elements + # has come from the same set + if count_b >= state.min_gallop || count_a >= state.min_gallop + mode = :galloping + break + end + end + # Finalize if we've exited the loop normally + if mode == :normal + mode = :finalize + end + end + + if mode == :galloping + # Use binary search to find range to copy + while from_a <= length(a) && from_b <= last(b) + # Copy the next run from b + b_run = from_b : ($gallop_first)($(args...), v, v_a[from_a], from_b, last(b)) - 1 + i_end = i + length(b_run) - 1 + v[i:i_end] = v[b_run] + i = i_end + 1 + from_b = last(b_run) + 1 + + # ... then copy the first element from a + v[i] = v_a[from_a] + i += 1 + from_a += 1 + + if from_a > length(a) || from_b > last(b) break end + + # Copy the next run from a + a_run = from_a : ($gallop_last)($(args...), v_a, v[from_b], from_a, length(a)) - 1 + i_end = i + length(a_run) - 1 + v[i:i_end] = v_a[a_run] + i = i_end + 1 + from_a = last(a_run) + 1 + + # ... then copy the first element from b + v[i] = v[from_b] + i += 1 + from_b += 1 + + # Return to normal mode if we haven't galloped... + if length(a_run) < MIN_GALLOP && length(b_run) < MIN_GALLOP + mode = :normal + break + end + # Reduce min_gallop if this gallop was successful + state.min_gallop -= 1 + end + if mode == :galloping + mode = :finalize + end + state.min_gallop = max(state.min_gallop,0) + 2 # penalty for leaving gallop mode + end + + if mode == :finalize + # copy end of a + i_end = i + (length(a) - from_a) + v[i:i_end] = v_a[from_a:end] + break + end + end +end + +# Merge runs a and b in vector v (a is smaller) +function ($merge_lo)($(args...), v::AbstractVector, p::AbstractVector{Int}, a::Run, b::Run, state::MergeState) + + # Copy a + v_a = v[a] + p_a = p[a] + + # Pointer into (sub)arrays + i = first(a) + from_a = 1 + from_b = first(b) + + mode = :normal + while true + if mode == :normal + # Compare and copy element by element + count_a = count_b = 0 + while from_a <= length(a) && from_b <= last(b) + if $(lt(:(v[from_b]), :(v_a[from_a]))) + v[i] = v[from_b] + p[i] = p[from_b] + from_b += 1 + count_a = 0 + count_b += 1 + else + v[i] = v_a[from_a] + p[i] = p_a[from_a] + from_a += 1 + count_a += 1 + count_b = 0 + end + i += 1 + + # Switch to galloping mode if a string of elements + # has come from the same set + if count_b >= state.min_gallop || count_a >= state.min_gallop + mode = :galloping + break + end + end + # Finalize if we've exited the loop normally + if mode == :normal + mode = :finalize + end + end + + if mode == :galloping + # Use binary search to find range to copy + while from_a <= length(a) && from_b <= last(b) + # Copy the next run from b + b_run = from_b : ($gallop_first)($(args...), v, v_a[from_a], from_b, last(b)) - 1 + i_end = i + length(b_run) - 1 + v[i:i_end] = v[b_run] + p[i:i_end] = p[b_run] + i = i_end + 1 + from_b = last(b_run) + 1 + + # ... then copy the first element from a + v[i] = v_a[from_a] + p[i] = p_a[from_a] + i += 1 + from_a += 1 + + if from_a > length(a) || from_b > last(b) break end + + # Copy the next run from a + a_run = from_a : ($gallop_last)($(args...), v_a, v[from_b], from_a, length(a)) - 1 + i_end = i + length(a_run) - 1 + v[i:i_end] = v_a[a_run] + p[i:i_end] = p_a[a_run] + i = i_end + 1 + from_a = last(a_run) + 1 + + # ... then copy the first element from b + v[i] = v[from_b] + p[i] = p[from_b] + i += 1 + from_b += 1 + + # Return to normal mode if we haven't galloped... + if length(a_run) < MIN_GALLOP && length(b_run) < MIN_GALLOP + mode = :normal + break + end + # Reduce min_gallop if this gallop was successful + state.min_gallop -= 1 + end + if mode == :galloping + mode = :finalize + end + state.min_gallop = max(state.min_gallop,0) + 2 # penalty for leaving gallop mode + end + + if mode == :finalize + # copy end of a + i_end = i + (length(a) - from_a) + v[i:i_end] = v_a[from_a:end] + p[i:i_end] = p_a[from_a:end] + break + end + end +end + + +# Merge runs a and b in vector v (b is smaller) +function ($merge_hi)($(args...), v::AbstractVector, a::Run, b::Run, state::MergeState) + + # Copy b + v_b = v[b] + + # Pointer into (sub)arrays + i = last(b) + from_a = last(a) + from_b = length(b) + + mode = :normal + while true + if mode == :normal + # Compare and copy element by element + count_a = count_b = 0 + while from_a >= first(a) && from_b >= 1 + if $(lt(:(v[from_a]), :(v_b[from_b]))) + v[i] = v_b[from_b] + from_b -= 1 + count_a = 0 + count_b += 1 + else + v[i] = v[from_a] + from_a -= 1 + count_a += 1 + count_b = 0 + end + i -= 1 + + # Switch to galloping mode if a string of elements + # has come from the same set + if count_b >= state.min_gallop || count_a >= state.min_gallop + mode = :galloping + break + end + end + # Finalize if we've exited the loop normally + if mode == :normal + mode = :finalize + end + end + + if mode == :galloping + # Use binary search to find range to copy + while from_a >= first(a) && from_b >= 1 + # Copy the next run from b + b_run = ($rgallop_first)($(args...), v_b, v[from_a], 1, from_b) : from_b + i_start = i - length(b_run) + 1 + v[i_start:i] = v_b[b_run] + i = i_start - 1 + from_b = first(b_run) - 1 + + # ... then copy the first element from a + v[i] = v[from_a] + i -= 1 + from_a -= 1 + + if from_a < first(a) || from_b < 1 break end + + # Copy the next run from a + a_run = ($rgallop_last)($(args...), v, v_b[from_b], first(a), from_a) : from_a + i_start = i - length(a_run) + 1 + v[i_start:i] = v[a_run] + i = i_start - 1 + from_a = first(a_run) - 1 + + # ... then copy the first element from b + v[i] = v_b[from_b] + i -= 1 + from_b -= 1 + + # Return to normal mode if we haven't galloped... + if length(a_run) < MIN_GALLOP && length(b_run) < MIN_GALLOP + mode = :normal + break + end + # Reduce min_gallop if this gallop was successful + state.min_gallop -= 1 + end + if mode == :galloping + mode = :finalize + end + state.min_gallop = max(state.min_gallop, 0) + 2 # penalty for leaving gallop mode + end + + if mode == :finalize + # copy start of b + i_start = i - from_b + 1 + v[i_start:i] = v_b[1:from_b] + break + end + end +end + +# Merge runs a and b in vector v (b is smaller) +function ($merge_hi)($(args...), v::AbstractVector, p::AbstractVector{Int}, a::Run, b::Run, state::MergeState) + + # Copy b + v_b = v[b] + p_b = p[b] + + # Pointer into (sub)arrays + i = last(b) + from_a = last(a) + from_b = length(b) + + mode = :normal + while true + if mode == :normal + # Compare and copy element by element + count_a = count_b = 0 + while from_a >= first(a) && from_b >= 1 + if $(lt(:(v[from_a]), :(v_b[from_b]))) + v[i] = v_b[from_b] + p[i] = p_b[from_b] + from_b -= 1 + count_a = 0 + count_b += 1 + else + v[i] = v[from_a] + p[i] = p[from_a] + from_a -= 1 + count_a += 1 + count_b = 0 + end + i -= 1 + + # Switch to galloping mode if a string of elements + # has come from the same set + if count_b >= state.min_gallop || count_a >= state.min_gallop + mode = :galloping + break + end + end + # Finalize if we've exited the loop normally + if mode == :normal + mode = :finalize + end + end + + if mode == :galloping + # Use binary search to find range to copy + while from_a >= first(a) && from_b >= 1 + # Copy the next run from b + b_run = ($rgallop_first)($(args...), v_b, v[from_a], 1, from_b) : from_b + i_start = i - length(b_run) + 1 + v[i_start:i] = v_b[b_run] + p[i_start:i] = p_b[b_run] + i = i_start - 1 + from_b = first(b_run) - 1 + + # ... then copy the first element from a + v[i] = v[from_a] + p[i] = p[from_a] + i -= 1 + from_a -= 1 + + if from_a < first(a) || from_b < 1 break end + + # Copy the next run from a + a_run = ($rgallop_last)($(args...), v, v_b[from_b], first(a), from_a) : from_a + i_start = i - length(a_run) + 1 + v[i_start:i] = v[a_run] + p[i_start:i] = p[a_run] + i = i_start - 1 + from_a = first(a_run) - 1 + + # ... then copy the first element from b + v[i] = v_b[from_b] + p[i] = p_b[from_b] + i -= 1 + from_b -= 1 + + # Return to normal mode if we haven't galloped... + if length(a_run) < MIN_GALLOP && length(b_run) < MIN_GALLOP + mode = :normal + break + end + # Reduce min_gallop if this gallop was successful + state.min_gallop -= 1 + end + if mode == :galloping + mode = :finalize + end + state.min_gallop = max(state.min_gallop, 0) + 2 # penalty for leaving gallop mode + end + + if mode == :finalize + # copy start of b + i_start = i - from_b + 1 + v[i_start:i] = v_b[1:from_b] + p[i_start:i] = p_b[1:from_b] + break + end + end +end + + +# Timsort function +function ($timsort!)($(args...), v::AbstractVector, lo::Int, hi::Int) + # Initialization + minrun = merge_compute_minrun(hi-lo+1) + state = MergeState() + + i = lo + while i <= hi + run_range = $(next_run)($(args...), v, i, hi) + count = length(run_range) + if count < minrun + # Make a run of length minrun + count = min(minrun, hi-i+1) + run_range = i:i+count-1 + ($insertionsort!)($(args...), v, i, i+count-1) + else + if !issorted(run_range) + run_range = last(run_range):first(run_range) + reverse!(sub(v, run_range)) + end + end + + # Push this run onto the queue and merge if needed + push(state.runs, run_range) + i = i+count + ($merge_collapse)($(args...), v, state, false) + end + + # Force merge at the end + if length(state.runs) > 1 + ($merge_collapse)($(args...), v, state, true) + end + + v +end + +($timsort!)($(args...), v::AbstractVector) = ($timsort!)($(args...), v, 1, length(v)) +($timsort)($(args...), v::AbstractVector, args2...) = ($timsort!)($(args...), copy(v), args2...) + + +# Timsort function which permutes an auxilliary array mirroring the sort +function ($timsort_perm!)($(args...), v::AbstractVector, p::AbstractVector{Int}, lo::Int, hi::Int) + # Initialization + minrun = merge_compute_minrun(hi-lo+1) + state = MergeState() + + i = lo + while i <= hi + run_range = $(next_run)($(args...), v, i, hi) + count = length(run_range) + if count < minrun + # Make a run of length minrun + count = min(minrun, hi-i+1) + run_range = i:i+count-1 + ($insertionsort_perm!)($(args...), v, p, i, i+count-1) + else + if !issorted(run_range) + run_range = last(run_range):first(run_range) + reverse!(sub(v, run_range)) + reverse!(sub(p, run_range)) + end + end + + # Push this run onto the queue and merge if needed + push(state.runs, run_range) + i = i+count + ($merge_collapse)($(args...), v, p, state, false) + end + + # Force merge at the end + if length(state.runs) > 1 + ($merge_collapse)($(args...), v, p, state, true) + end + + v, p +end + +($timsort_perm!)($(args...), v::AbstractVector, p::AbstractVector{Int}) = + ($timsort_perm!)($(args...), v, p, 1, length(v)) +($timsort_perm!)($(args...), v::AbstractVector) = + ($timsort_perm!)($(args...), v, [1:length(v)]) +($timsort_perm)($(args...), v::AbstractVector, args2...) = + ($timsort_perm!)($(args...), copy(v), args2...) + +end; end # quote; macro diff --git a/base/tuple.jl b/base/tuple.jl index 5ccb6299a3e90..ddf676c734c2c 100644 --- a/base/tuple.jl +++ b/base/tuple.jl @@ -3,8 +3,9 @@ length(t::Tuple) = tuplelen(t) size(t::Tuple, d) = d==1 ? tuplelen(t) : error("invalid tuple dimension") ref(t::Tuple, i::Int) = tupleref(t, i) -ref(t::Tuple, i::Integer) = tupleref(t, int(i)) -ref(t::Tuple, r::Ranges) = tuple([t[ri] for ri in r]...) +ref(t::Tuple, i::Real) = tupleref(t, convert(Int, i)) +ref(t::Tuple, r::AbstractArray) = tuple([t[ri] for ri in r]...) +ref(t::Tuple, b::AbstractArray{Bool}) = ref(t,find(b)) ## iterating ## diff --git a/base/utf8.jl b/base/utf8.jl index e5c95ee0f186b..8da6d963f6f82 100644 --- a/base/utf8.jl +++ b/base/utf8.jl @@ -7,13 +7,13 @@ ## basic UTF-8 decoding & iteration ## -const _jl_utf8_offset = [ +const utf8_offset = [ 0x00000000, 0x00003080, 0x000e2080, 0x03c82080, 0xfa082080, 0x82082080, ] -const _jl_utf8_trailing = [ +const utf8_trailing = [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, @@ -35,11 +35,19 @@ function ref(s::UTF8String, i::Int) d = s.data b = d[i] if !is_utf8_start(b) - error("invalid UTF-8 character index") + j = i-1 + while 0 < j && !is_utf8_start(d[j]) + j -= 1 + end + if 0 < j && i <= j+utf8_trailing[d[j]+1] <= length(d) + # b is a continuation byte of a valid UTF-8 character + error("invalid UTF-8 character index") + end + return '\ufffd' end - trailing = _jl_utf8_trailing[b+1] + trailing = utf8_trailing[b+1] if length(d) < i + trailing - error("premature end of UTF-8 data") + return '\ufffd' end c::Uint32 = 0 for j = 1:trailing+1 @@ -47,12 +55,12 @@ function ref(s::UTF8String, i::Int) c += d[i] i += 1 end - c -= _jl_utf8_offset[trailing+1] + c -= utf8_offset[trailing+1] char(c) end # this is a trick to allow inlining and tuple elision -next(s::UTF8String, i::Int) = (s[i], i+1+_jl_utf8_trailing[s.data[i]+1]) +next(s::UTF8String, i::Int) = (s[i], i+1+utf8_trailing[s.data[i]+1]) function first_utf8_byte(c::Char) c < 0x80 ? uint8(c) : diff --git a/base/util.jl b/base/util.jl index 94df97c1484cd..9c1b4f782fbaa 100644 --- a/base/util.jl +++ b/base/util.jl @@ -64,7 +64,7 @@ function peakflops(n) a = rand(n,n) t = @elapsed a*a t = @elapsed a*a - floprate = (2.0*n^3/t) + floprate = (2.0*float64(n)^3/t) println("The peak flop rate is ", floprate*1e-9, " gigaflops") floprate end @@ -173,29 +173,7 @@ end methods(t::CompositeKind) = (methods(t,Tuple); # force constructor creation t.env) - # require -# Store list of files and their load time -_jl_package_list = (ByteString=>Float64)[] -require(fname::String) = require(bytestring(fname)) -require(f::String, fs::String...) = (require(f); for x in fs require(x); end) -function require(name::ByteString) - path = find_in_path(name) - if !has(_jl_package_list,path) - load_now(name) - else - # Determine whether the file has been modified since it was last loaded - if mtime(path) > _jl_package_list[path] - load_now(name) - end - end -end - -const load = require - -# remote/parallel load - -include_string(txt::ByteString) = ccall(:jl_load_file_string, Void, (Ptr{Uint8},), txt) function is_file_readable(path) s = stat(bytestring(path)) @@ -203,8 +181,8 @@ function is_file_readable(path) end function find_in_path(name::String) - name[1] == '/' && return realpath(name) - isfile(name) && return realpath(name) + name[1] == '/' && return abspath(name) + isfile(name) && return abspath(name) base = name if ends_with(name,".jl") base = match(r"^(.*)\.jl$",name).captures[1] @@ -213,74 +191,89 @@ function find_in_path(name::String) end for prefix in LOAD_PATH path = strcat(prefix,"/",base,"/src/",name) - is_file_readable(path) && return realpath(path) + is_file_readable(path) && return abspath(path) path = strcat(prefix,"/",name) - is_file_readable(path) && return realpath(path) + is_file_readable(path) && return abspath(path) + end + return abspath(name) +end + +function find_in_node1_path(name) + if myid()==1 + return find_in_path(name) + else + return remote_call_fetch(1, find_in_path, name) end - return realpath(name) end -begin -local in_load = false -local in_remote_load = false -local load_dict = {} -global load_now, remote_load - -load_now(fname::String) = load_now(bytestring(fname)) -function load_now(fname::ByteString) - if in_load - path = find_in_path(fname) - push(load_dict, fname) - f = open(path) - push(load_dict, readall(f)) - close(f) - include(path) - _jl_package_list[path] = time() - return - elseif in_remote_load - for i=1:2:length(load_dict) - if load_dict[i] == fname - return include_string(load_dict[i+1]) +# Store list of files and their load time +package_list = (ByteString=>Float64)[] +require(fname::String) = require(bytestring(fname)) +require(f::String, fs::String...) = (require(f); for x in fs require(x); end) +function require(name::ByteString) + if myid() == 1 + @sync begin + for p = 2:nprocs() + @spawnat p require(name) end end - else - in_load = true - try - load_now(fname) - for p = 1:nprocs() - if p != myid() - remote_do(p, remote_load, load_dict) - end + end + path = find_in_node1_path(name) + if !has(package_list,path) + reload_path(path) + end +end + +function reload(name::String) + if myid() == 1 + @sync begin + for p = 2:nprocs() + @spawnat p reload(name) end - finally - load_dict = {} - in_load = false end end + reload_path(find_in_node1_path(name)) +end + +# remote/parallel load + +include_string(txt::ByteString) = ccall(:jl_load_file_string, Void, (Ptr{Uint8},), txt) + +function include_from_node1(path) + if myid()==1 + Core.include(path) + else + include_string(remote_call_fetch(1, readall, path)) + end end -function remote_load(dict) - load_dict = dict - in_remote_load = true +function reload_path(path) + had = has(package_list, path) + package_list[path] = time() try - load_now(dict[1]) - finally - in_remote_load = false + eval(Main, :(Base.include_from_node1($path))) + catch e + if !had + del(package_list, path) + end + rethrow(e) end nothing end -end -evalfile(fname::String) = eval(Main,parse(readall(fname))[1]) +# deprecated +const load = require + +evalfile(fname::String) = eval(Main, parse(readall(fname))[1]) # help -_jl_help_category_list = nothing -_jl_help_category_dict = nothing -_jl_help_module_dict = nothing -_jl_help_function_dict = nothing +help_category_list = nothing +help_category_dict = nothing +help_module_dict = nothing +help_function_dict = nothing -function _jl_decor_help_desc(func::String, mfunc::String, desc::String) +function decor_help_desc(func::String, mfunc::String, desc::String) sd = split(desc, '\n') for i = 1:length(sd) if begins_with(sd[i], func) @@ -292,20 +285,20 @@ function _jl_decor_help_desc(func::String, mfunc::String, desc::String) return join(sd, '\n') end -function _jl_init_help() - global _jl_help_category_list, _jl_help_category_dict, - _jl_help_module_dict, _jl_help_function_dict - if _jl_help_category_dict == nothing +function init_help() + global help_category_list, help_category_dict, + help_module_dict, help_function_dict + if help_category_dict == nothing println("Loading help data...") helpdb = evalfile("$JULIA_HOME/../share/julia/helpdb.jl") - _jl_help_category_list = {} - _jl_help_category_dict = Dict() - _jl_help_module_dict = Dict() - _jl_help_function_dict = Dict() + help_category_list = {} + help_category_dict = Dict() + help_module_dict = Dict() + help_function_dict = Dict() for (cat,mod,func,desc) in helpdb - if !has(_jl_help_category_dict, cat) - push(_jl_help_category_list, cat) - _jl_help_category_dict[cat] = {} + if !has(help_category_dict, cat) + push(help_category_list, cat) + help_category_dict[cat] = {} end if !isempty(mod) if begins_with(func, '@') @@ -313,20 +306,20 @@ function _jl_init_help() else mfunc = mod * "." * func end - desc = _jl_decor_help_desc(func, mfunc, desc) + desc = decor_help_desc(func, mfunc, desc) else mfunc = func end - push(_jl_help_category_dict[cat], mfunc) - if !has(_jl_help_function_dict, mfunc) - _jl_help_function_dict[mfunc] = {} + push(help_category_dict[cat], mfunc) + if !has(help_function_dict, mfunc) + help_function_dict[mfunc] = {} end - push(_jl_help_function_dict[mfunc], desc) - if !has(_jl_help_module_dict, func) - _jl_help_module_dict[func] = {} + push(help_function_dict[mfunc], desc) + if !has(help_module_dict, func) + help_module_dict[func] = {} end - if !contains(_jl_help_module_dict[func], mod) - push(_jl_help_module_dict[func], mod) + if !contains(help_module_dict[func], mod) + push(help_module_dict[func], mod) end end end @@ -334,7 +327,7 @@ end function help() - _jl_init_help() + init_help() print( " Welcome to Julia. The full manual is available at @@ -345,8 +338,8 @@ function help() for one of the following categories: ") - for cat = _jl_help_category_list - if !isempty(_jl_help_category_dict[cat]) + for cat = help_category_list + if !isempty(help_category_dict[cat]) print(" ") show(cat); println() end @@ -354,19 +347,19 @@ function help() end function help(cat::String) - _jl_init_help() - if !has(_jl_help_category_dict, cat) + init_help() + if !has(help_category_dict, cat) # if it's not a category, try another named thing return help_for(cat) end println("Help is available for the following items:") - for func = _jl_help_category_dict[cat] + for func = help_category_dict[cat] print(func, " ") end println() end -function _jl_print_help_entries(entries) +function print_help_entries(entries) first = true for desc in entries if !first @@ -379,11 +372,11 @@ end help_for(s::String) = help_for(s, 0) function help_for(fname::String, obj) - _jl_init_help() + init_help() found = false if contains(fname, '.') - if has(_jl_help_function_dict, fname) - _jl_print_help_entries(_jl_help_function_dict[fname]) + if has(help_function_dict, fname) + print_help_entries(help_function_dict[fname]) found = true end else @@ -394,14 +387,14 @@ function help_for(fname::String, obj) else sfname = fname end - if has(_jl_help_module_dict, fname) - allmods = _jl_help_module_dict[fname] + if has(help_module_dict, fname) + allmods = help_module_dict[fname] alldesc = {} for mod in allmods mod_prefix = isempty(mod) ? "" : mod * "." - append!(alldesc, _jl_help_function_dict[macrocall * mod_prefix * sfname]) + append!(alldesc, help_function_dict[macrocall * mod_prefix * sfname]) end - _jl_print_help_entries(alldesc) + print_help_entries(alldesc) found = true end end @@ -415,15 +408,15 @@ function help_for(fname::String, obj) end function apropos(txt::String) - _jl_init_help() + init_help() n = 0 r = Regex("\\Q$txt", PCRE.CASELESS) - for (cat, _) in _jl_help_category_dict + for (cat, _) in help_category_dict if ismatch(r, cat) println("Category: \"$cat\"") end end - for (func, entries) in _jl_help_function_dict + for (func, entries) in help_function_dict if ismatch(r, func) || anyp(e->ismatch(r,e), entries) for desc in entries nl = search(desc,'\n') diff --git a/base/version.jl b/base/version.jl index 2652c6527bb56..9e21b28b4b1df 100644 --- a/base/version.jl +++ b/base/version.jl @@ -88,19 +88,19 @@ end macro v_str(v); convert(VersionNumber, v); end -_jl_ident_cmp(a::Int, b::Int) = cmp(a,b) -_jl_ident_cmp(a::Int, b::ASCIIString) = isempty(b) ? +1 : -1 -_jl_ident_cmp(a::ASCIIString, b::Int) = isempty(a) ? -1 : +1 -_jl_ident_cmp(a::ASCIIString, b::ASCIIString) = cmp(a,b) +ident_cmp(a::Int, b::Int) = cmp(a,b) +ident_cmp(a::Int, b::ASCIIString) = isempty(b) ? +1 : -1 +ident_cmp(a::ASCIIString, b::Int) = isempty(a) ? -1 : +1 +ident_cmp(a::ASCIIString, b::ASCIIString) = cmp(a,b) -function _jl_ident_cmp(A::Vector{Union(Int,ASCIIString)}, +function ident_cmp(A::Vector{Union(Int,ASCIIString)}, B::Vector{Union(Int,ASCIIString)}) i = start(A) j = start(B) while !done(A,i) && !done(B,i) a,i = next(A,i) b,j = next(B,j) - c = _jl_ident_cmp(a,b) + c = ident_cmp(a,b) (c != 0) && return c end done(A,i) && !done(B,j) ? -1 : @@ -111,8 +111,8 @@ function isequal(a::VersionNumber, b::VersionNumber) (a.major != b.major) && return false (a.minor != b.minor) && return false (a.patch != b.patch) && return false - (_jl_ident_cmp(a.prerelease,b.prerelease) != 0) && return false - (_jl_ident_cmp(a.build,b.build) != 0) && return false + (ident_cmp(a.prerelease,b.prerelease) != 0) && return false + (ident_cmp(a.build,b.build) != 0) && return false return true end @@ -125,10 +125,10 @@ function isless(a::VersionNumber, b::VersionNumber) (a.patch > b.patch) && return false (!isempty(a.prerelease) && isempty(b.prerelease)) && return true (isempty(a.prerelease) && !isempty(b.prerelease)) && return false - c = _jl_ident_cmp(a.prerelease,b.prerelease) + c = ident_cmp(a.prerelease,b.prerelease) (c < 0) && return true (c > 0) && return false - c = _jl_ident_cmp(a.build,b.build) + c = ident_cmp(a.build,b.build) (c < 0) && return true return false end @@ -136,7 +136,7 @@ end ## julia version info if(isfile("$JULIA_HOME/../../VERSION")) - const VERSION = convert(VersionNumber,readchomp("$JULIA_HOME/../../VERSION")) +const VERSION = convert(VersionNumber,readchomp("$JULIA_HOME/../../VERSION")) elseif(isfile("$JULIA_HOME/../VERSION")) const VERSION = convert(VersionNumber,readchomp("$JULIA_HOME/../VERSION")) else @@ -190,7 +190,7 @@ let error(acceptable) end isotime = strftime("%Y-%m-%d %H:%M:%S", ctim) - global const _jl_commit_string = "Commit $(commit[1:10]) ($isotime)$clean" + global const commit_string = "Commit $(commit[1:10]) ($isotime)$clean" global const VERSION_COMMIT = commit[1:10] error(expected) end @@ -203,27 +203,27 @@ let # so we do what we must, but don't do this in user-land code or you'll regret it catch err if err != expected - global const _jl_commit_string = "" + global const commit_string = "" global const VERSION_COMMIT = "" if err == acceptable println("Warning: git failed in version.jl") #println(err) # not a useful error msg currently else error(err) - end +end end end end begin -const _jl_version_string = "Version $VERSION" -const _jl_banner_plain = +const version_string = "Version $VERSION" +const banner_plain = I" _ _ _ _(_)_ | A fresh approach to technical computing (_) | (_) (_) | Documentation: http://docs.julialang.org _ _ _| |_ __ _ | Type \"help()\" to list help topics | | | | | | |/ _` | | - | | |_| | | | (_| | | $_jl_version_string - _/ |\__'_|_|_|\__'_| | $_jl_commit_string + | | |_| | | | (_| | | $version_string + _/ |\__'_|_|_|\__'_| | $commit_string |__/ | " @@ -233,14 +233,14 @@ local d1 = "\033[34m" # first dot local d2 = "\033[31m" # second dot local d3 = "\033[32m" # third dot local d4 = "\033[35m" # fourth dot -const _jl_banner_color = +const banner_color = "\033[1m $(d3)_ $(d1)_ $(jl)_$(tx) $(d2)_$(d3)(_)$(d4)_$(tx) | A fresh approach to technical computing $(d1)(_)$(jl) | $(d2)(_)$(tx) $(d4)(_)$(tx) | Documentation: http://docs.julialang.org $(jl)_ _ _| |_ __ _$(tx) | Type \"help()\" to list help topics $(jl)| | | | | | |/ _` |$(tx) | - $(jl)| | |_| | | | (_| |$(tx) | $_jl_version_string - $(jl)_/ |\\__'_|_|_|\\__'_|$(tx) | $_jl_commit_string + $(jl)| | |_| | | | (_| |$(tx) | $version_string + $(jl)_/ |\\__'_|_|_|\\__'_|$(tx) | $commit_string $(jl)|__/$(tx) | \033[0m" diff --git a/contrib/julia-mode.el b/contrib/julia-mode.el index e4d7789402804..269ec94482ee5 100644 --- a/contrib/julia-mode.el +++ b/contrib/julia-mode.el @@ -60,7 +60,7 @@ "for +.*[^ ].* \\(in\\)\\(\\s-\\|$\\)+") (defconst julia-font-lock-keywords - (list '("\\<\\(\\|Uint\\(8\\|16\\|32\\|64\\|128\\)\\|Int\\(8\\|16\\|32\\|64\\|128\\)\\|Integer\\|Float\\|Float32\\|Float64\\|Complex128\\|Complex64\\|ComplexPair\\|Bool\\|Char\\|Number\\|Real\\|Int\\|Uint\\|Array\\|DArray\\|AbstractArray\\|AbstractVector\\|AbstractMatrix\\|AbstractSparseMatrix\\|SubArray\\|StridedArray\\|StridedVector\\|StridedMatrix\\|VecOrMat\\|StridedVecOrMat\\|Range\\|Range1\\|SparseMatrixCSC\\|Tuple\\|NTuple\\|Symbol\\|Function\\|Vector\\|Matrix\\|Union\\|Type\\|Any\\|Complex\\|None\\|String\\|Ptr\\|Void\\|Exception\\|Task\\|Signed\\|Unsigned\\|Associative\\|Dict\\|IO\\|IOStream\\|Ranges\\|Rational\\|Regex\\|RegexMatch\\|Set\\|IntSet\\|ASCIIString\\|UTF8String\\|ByteString\\|Expr\\|WeakRef\\|Nothing\\|ObjectIdDict\\|SubString\\)\\>" . + (list '("\\<\\(\\|Uint\\(8\\|16\\|32\\|64\\|128\\)\\|Int\\(8\\|16\\|32\\|64\\|128\\)\\|Integer\\|FloatingPoint\\|Float32\\|Float64\\|Complex128\\|Complex64\\|ComplexPair\\|Bool\\|Char\\|Number\\|Real\\|Int\\|Uint\\|Array\\|DArray\\|AbstractArray\\|AbstractVector\\|AbstractMatrix\\|AbstractSparseMatrix\\|SubArray\\|StridedArray\\|StridedVector\\|StridedMatrix\\|VecOrMat\\|StridedVecOrMat\\|Range\\|Range1\\|SparseMatrixCSC\\|Tuple\\|NTuple\\|Symbol\\|Function\\|Vector\\|Matrix\\|Union\\|Type\\|Any\\|Complex\\|None\\|String\\|Ptr\\|Void\\|Exception\\|Task\\|Signed\\|Unsigned\\|Associative\\|Dict\\|IO\\|IOStream\\|Ranges\\|Rational\\|Regex\\|RegexMatch\\|Set\\|IntSet\\|ASCIIString\\|UTF8String\\|ByteString\\|Expr\\|WeakRef\\|Nothing\\|ObjectIdDict\\|SubString\\)\\>" . font-lock-type-face) (cons (concat "\\<\\(" diff --git a/contrib/julia.xml b/contrib/julia.xml index 311d4df57d8b0..9a689ccd0dd30 100644 --- a/contrib/julia.xml +++ b/contrib/julia.xml @@ -71,6 +71,7 @@ baremodule return typealias + using AbstractArray diff --git a/contrib/repackage_system_suitesparse3.make b/contrib/repackage_system_suitesparse3.make index 1b1cb16cb1518..155fd01eb574b 100755 --- a/contrib/repackage_system_suitesparse3.make +++ b/contrib/repackage_system_suitesparse3.make @@ -6,18 +6,18 @@ include $(JULIAHOME)/Make.inc all: default default: - mkdir -p $(USR)/$(JL_LIBDIR) + mkdir -p $(BUILD)/$(JL_LIBDIR) mkdir -p $(JULIAHOME)/deps/SuiteSparse-SYSTEM/lib cd $(JULIAHOME)/deps/SuiteSparse-SYSTEM/lib && \ rm -f *.a && \ cp -f $(shell find /lib /usr/lib /usr/local/lib $(shell eval $(JULIAHOME)/contrib/filterArgs.sh $(LDFLAGS)) -name libamd.a -o -name libcolamd.a -o -name libcholmod.a -o -name libumfpack.a -o -name libspqr.a 2>/dev/null) . && \ - $(CC) -shared $(WHOLE_ARCHIVE) libamd.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libamd.$(SHLIB_EXT) && \ - $(INSTALL_NAME_CMD)libamd.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libamd.$(SHLIB_EXT) && \ - $(CC) -shared $(WHOLE_ARCHIVE) libcolamd.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libcolamd.$(SHLIB_EXT) && \ - $(INSTALL_NAME_CMD)libcolamd.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libcolamd.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libcholmod.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libcholmod.$(SHLIB_EXT) $(LDFLAGS) -L$(USR)/$(JL_LIBDIR) -lcolamd -lamd $(LIBBLAS) && \ - $(INSTALL_NAME_CMD)libcholmod.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libcholmod.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libumfpack.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libumfpack.$(SHLIB_EXT) $(LDFLAGS) -L$(USR)/$(JL_LIBDIR) -lcholmod -lcolamd -lamd $(LIBBLAS) && \ - $(INSTALL_NAME_CMD)libumfpack.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libumfpack.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libspqr.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libspqr.$(SHLIB_EXT) $(LDFLAGS) -L$(USR)/$(JL_LIBDIR) -lcholmod -lcolamd -lamd $(LIBBLAS) && \ - $(INSTALL_NAME_CMD)libspqr.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libspqr.$(SHLIB_EXT) + $(CC) -shared $(WHOLE_ARCHIVE) libamd.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libamd.$(SHLIB_EXT) && \ + $(INSTALL_NAME_CMD)libamd.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libamd.$(SHLIB_EXT) && \ + $(CC) -shared $(WHOLE_ARCHIVE) libcolamd.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libcolamd.$(SHLIB_EXT) && \ + $(INSTALL_NAME_CMD)libcolamd.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libcolamd.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libcholmod.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libcholmod.$(SHLIB_EXT) $(LDFLAGS) -L$(BUILD)/$(JL_LIBDIR) -lcolamd -lamd $(LIBBLAS) && \ + $(INSTALL_NAME_CMD)libcholmod.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libcholmod.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libumfpack.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libumfpack.$(SHLIB_EXT) $(LDFLAGS) -L$(BUILD)/$(JL_LIBDIR) -lcholmod -lcolamd -lamd $(LIBBLAS) && \ + $(INSTALL_NAME_CMD)libumfpack.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libumfpack.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libspqr.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libspqr.$(SHLIB_EXT) $(LDFLAGS) -L$(BUILD)/$(JL_LIBDIR) -lcholmod -lcolamd -lamd $(LIBBLAS) && \ + $(INSTALL_NAME_CMD)libspqr.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libspqr.$(SHLIB_EXT) diff --git a/contrib/repackage_system_suitesparse4.make b/contrib/repackage_system_suitesparse4.make index 4d386e86c3ac8..4c5141680efd1 100755 --- a/contrib/repackage_system_suitesparse4.make +++ b/contrib/repackage_system_suitesparse4.make @@ -6,19 +6,19 @@ include $(JULIAHOME)/Make.inc all: default default: - mkdir -p $(USR)/$(JL_LIBDIR) + mkdir -p $(BUILD)/$(JL_LIBDIR) mkdir -p $(JULIAHOME)/deps/SuiteSparse-SYSTEM/lib cd $(JULIAHOME)/deps/SuiteSparse-SYSTEM/lib && \ rm -f *.a && \ cp -f $(shell find /lib /usr/lib /usr/local/lib $(shell eval $(JULIAHOME)/contrib/filterArgs.sh $(LDFLAGS)) -name libamd.a -o -name libcolamd.a -o -name libcholmod.a -o -name libumfpack.a -o -name libspqr.a -o -name libsuitesparseconfig.a 2>/dev/null) . && \ - $(CC) -shared $(WHOLE_ARCHIVE) libamd.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libamd.$(SHLIB_EXT) && \ - $(INSTALL_NAME_CMD)libamd.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libamd.$(SHLIB_EXT) && \ - $(CC) -shared $(WHOLE_ARCHIVE) libcolamd.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libcolamd.$(SHLIB_EXT) && \ - $(INSTALL_NAME_CMD)libcolamd.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libcolamd.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libcholmod.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libcholmod.$(SHLIB_EXT) $(LDFLAGS) -L$(USR)/$(JL_LIBDIR) -L. -lcolamd -lccolamd -lcamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ - $(INSTALL_NAME_CMD)libcholmod.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libcholmod.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libumfpack.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libumfpack.$(SHLIB_EXT) $(LDFLAGS) -L$(USR)/$(JL_LIBDIR) -L. -lcholmod -lcolamd -lcamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ - $(INSTALL_NAME_CMD)libumfpack.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libumfpack.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libspqr.a $(NO_WHOLE_ARCHIVE) -o $(USR)/$(JL_LIBDIR)/libspqr.$(SHLIB_EXT) $(LDFLAGS) -L$(USR)/$(JL_LIBDIR) -lcholmod -lcolamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ - $(INSTALL_NAME_CMD)libspqr.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libspqr.$(SHLIB_EXT) + $(CC) -shared $(WHOLE_ARCHIVE) libamd.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libamd.$(SHLIB_EXT) && \ + $(INSTALL_NAME_CMD)libamd.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libamd.$(SHLIB_EXT) && \ + $(CC) -shared $(WHOLE_ARCHIVE) libcolamd.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libcolamd.$(SHLIB_EXT) && \ + $(INSTALL_NAME_CMD)libcolamd.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libcolamd.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libcholmod.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libcholmod.$(SHLIB_EXT) $(LDFLAGS) -L$(BUILD)/$(JL_LIBDIR) -L. -lcolamd -lccolamd -lcamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ + $(INSTALL_NAME_CMD)libcholmod.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libcholmod.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libumfpack.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libumfpack.$(SHLIB_EXT) $(LDFLAGS) -L$(BUILD)/$(JL_LIBDIR) -L. -lcholmod -lcolamd -lcamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ + $(INSTALL_NAME_CMD)libumfpack.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libumfpack.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libspqr.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/$(JL_LIBDIR)/libspqr.$(SHLIB_EXT) $(LDFLAGS) -L$(BUILD)/$(JL_LIBDIR) -lcholmod -lcolamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ + $(INSTALL_NAME_CMD)libspqr.$(SHLIB_EXT) $(BUILD)/$(JL_LIBDIR)/libspqr.$(SHLIB_EXT) \ No newline at end of file diff --git a/deps/.gitignore b/deps/.gitignore index 7b772dad021c9..353a78aa975f3 100644 --- a/deps/.gitignore +++ b/deps/.gitignore @@ -1,6 +1,7 @@ /arpack-* /clang-* /Clp-* +/clp-* /compiler-rt-* /double-conversion-* /dsfmt-* diff --git a/deps/Faddeeva_wrapper.c b/deps/Faddeeva_wrapper.c new file mode 100644 index 0000000000000..649577f72b504 --- /dev/null +++ b/deps/Faddeeva_wrapper.c @@ -0,0 +1,45 @@ +/* Copyright (c) 2012 Massachusetts Institute of Technology + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* C89-compatible wrappers for complex Faddeeva functions, that + pass and return complex values via a double* which points to + the real and imaginary parts consecutively. (Note that this + is binary-compatible with both C99 complex numbers and with + C++ std::complex.) */ + +#include "Faddeeva.h" + +#define WRAP(func) \ +void wrap ## Faddeeva_ ## func(double *func, const double *z, double relerr) \ +{ \ + const double complex *zc = (const double complex *) z; \ + double complex c = Faddeeva_ ## func(*zc, relerr); \ + func[0] = creal(c); \ + func[1] = cimag(c); \ +} + +WRAP(w) +WRAP(erfcx) +WRAP(erf) +WRAP(erfi) +WRAP(erfc) +WRAP(Dawson) diff --git a/deps/Makefile b/deps/Makefile index 992e54f1f72be..d3f0e8942e3a9 100644 --- a/deps/Makefile +++ b/deps/Makefile @@ -1,20 +1,32 @@ include Versions.make - -## optional packages ## +## optional packages and options # +LLVM_ASSERTIONS = 0 # set to 1 to get clang and compiler-rt BUILD_LLVM_CLANG = 0 +# set to 1 to get lldb (does not work with llvm3.1 and earlier) +# see http://lldb.llvm.org/build.html for dependancies +BUILD_LLDB = 0 ## high-level setup ## JULIAHOME = $(abspath ..) include $(JULIAHOME)/Make.inc +CONFIGURE_COMMON = --prefix=$(abspath $(BUILD)) F77="$(FC)" CC="$(CC)" CXX="$(CXX)" +ifneq ($(HOST),) +CONFIG_GUESS := $(shell ./config.guess) +CONFIGURE_COMMON += --host=$(HOST) --build=$(CONFIG_GUESS) +endif + +#autoconf configure-driven scripts: llvm readline pcre arpack fftw clp unwind lighttpd gmp glpk patchelf +#custom configure-driven script: zlib nginx +#custom Makefile rules: openlibm Faddeeva-wrapper rmath double-conversion random gmp-wrapper suitesparse-wrapper suitesparse lapack openblas uv tk-wrapper # prevent installing libs into usr/lib64 on opensuse unexport CONFIG_SITE STAGE1_DEPS = uv openlibm random rmath double-conversion glpk -STAGE2_DEPS = gmp-wrapper +STAGE2_DEPS = gmp-wrapper Faddeeva-wrapper STAGE3_DEPS = suitesparse-wrapper ifeq ($(OS), Linux) @@ -82,7 +94,7 @@ STAGE2_DEPS += suitesparse #Platform specific flags ifeq ($(OS), WINNT) -LIBTOOL_CCLD = CCLD="gcc -no-undefined -avoid-version" +LIBTOOL_CCLD = CCLD="$(CC) -no-undefined -avoid-version" AUTOTOOLS_PATH_CORRECT = -cp -f $(USRBIN)/$(@F) $(USR)/$(JL_LIBDIR)/$(@F) endif @@ -90,27 +102,36 @@ endif LIBS = $(STAGE1_DEPS) $(STAGE2_DEPS) $(STAGE3_DEPS) -default: $(USR) install +default: $(BUILD) install compile: $(addprefix compile-, $(LIBS)) install: $(addprefix install-, $(LIBS)) cleanall: $(addprefix clean-, $(LIBS)) distclean: $(addprefix distclean-, $(LIBS)) - rm -rf $(USR) + rm -rf $(BUILD) ## PATHS ## -DIRS = $(addprefix $(USR)/,lib include bin share etc) +DIRS = $(addprefix $(BUILD)/,lib include bin share etc) $(foreach dir,$(DIRS),$(eval $(call dir_target,$(dir)))) -$(USR): $(DIRS) +$(BUILD): $(DIRS) ## LLVM ## +ifeq ($(BUILD_LLDB), 1) +BUILD_LLVM_CLANG = 1 +# because it's a build requirement +endif +ifeq ($(LLVM_ASSERTIONS), 1) +LLVM_BUILDDIR = build/Release+Asserts +else +LLVM_BUILDDIR = build/Release +endif -LLVM_OBJ_TARGET = $(USR)/lib/libLLVM-$(LLVM_VER).$(SHLIB_EXT) +LLVM_OBJ_TARGET = $(BUILD)/lib/libLLVM-$(LLVM_VER).$(SHLIB_EXT) ifeq ($(OS),WINNT) - LLVM_OBJ_SOURCE = llvm-$(LLVM_VER)/Release/bin/LLVM-$(LLVM_VER).$(SHLIB_EXT) + LLVM_OBJ_SOURCE = llvm-$(LLVM_VER)/$(LLVM_BUILDDIR)/bin/LLVM-$(LLVM_VER).$(SHLIB_EXT) else - LLVM_OBJ_SOURCE = llvm-$(LLVM_VER)/Release/lib/libLLVM-$(LLVM_VER).$(SHLIB_EXT) + LLVM_OBJ_SOURCE = llvm-$(LLVM_VER)/$(LLVM_BUILDDIR)/lib/libLLVM-$(LLVM_VER).$(SHLIB_EXT) endif compile-llvm: $(LLVM_OBJ_SOURCE) @@ -163,6 +184,11 @@ endif $(LLVM_TAR): $(WGET) http://llvm.org/releases/$(LLVM_VER)/$@ +ifeq ($(BUILD_LLDB), 1) +llvm-$(LLVM_VER)/tools/lldb: +llvm-$(LLVM_VER)/configure: llvm-$(LLVM_VER)/tools/lldb +endif + llvm-$(LLVM_VER)/configure: $(LLVM_TAR) $(LLVM_CLANG_TAR) $(LLVM_COMPILER_RT_TAR) mkdir -p llvm-$(LLVM_VER) && \ tar -C llvm-$(LLVM_VER) --strip-components 1 -xf $(LLVM_TAR) @@ -173,6 +199,14 @@ endif ifneq ($(LLVM_COMPILER_RT_TAR),) mkdir -p llvm-$(LLVM_VER)/projects/compiler-rt && \ tar -C llvm-$(LLVM_VER)/projects/compiler-rt --strip-components 1 -xf $(LLVM_COMPILER_RT_TAR) +endif +ifeq ($(BUILD_LLDB), 1) + ([ ! -d llvm-$(LLVM_VER)/tools/lldb ] && \ + (cd llvm-$(LLVM_VER)/tools && \ + git clone http://llvm.org/git/lldb.git)) || \ + ([ -d llvm-$(LLVM_VER)/tools/lldb ] && \ + (cd llvm-$(LLVM_VER)/tools/lldb && \ + git pull)) endif touch $@ @@ -185,31 +219,45 @@ llvm_python_workaround: mkdir -p llvm-$(LLVM_VER)/python2_path && \ ln -s /usr/bin/python2 "llvm-$(LLVM_VER)/python2_path/python" -LLVM_CXX = $(CXX) +LLVM_FLAGS = --disable-threads --enable-optimized --disable-profiling --enable-shared --enable-targets=host --disable-bindings --disable-docs +LLVM_MFLAGS = +ifeq ($(LLVM_ASSERTIONS), 1) +LLVM_FLAGS += --enable-assertions +else +LLVM_FLAGS += --disable-assertions +endif +ifeq ($(BUILD_LLDB),1) +ifeq ($(USE_CLANG),1) +LLVM_FLAGS += --enable-cxx11 +else +LLVM_MFLAGS += CXXFLAGS=-std=c++0x +endif +endif ifeq ($(ARCH), ppc64) - LLVM_CXX += -mminimal-toc + LLVM_FLAGS += CXXFLAGS=-mminimal-toc endif $(LLVM_OBJ_SOURCE): llvm-$(LLVM_VER)/configure | llvm_python_workaround cd llvm-$(LLVM_VER) && \ + mkdir -p build && cd build && \ export PATH=$(abspath llvm-$(LLVM_VER)/python2_path):$$PATH && \ - ./configure --prefix=$(abspath $(USR)) --disable-threads --enable-optimized --disable-profiling --disable-assertions --enable-shared --enable-targets=host --disable-bindings --disable-docs CC="$(CC)" CXX="$(LLVM_CXX)" && \ - $(MAKE) + ../configure $(CONFIGURE_COMMON) $(LLVM_FLAGS) && \ + $(MAKE) $(LLVM_MFLAGS) $(LLVM_OBJ_TARGET): $(LLVM_OBJ_SOURCE) | llvm_python_workaround export PATH=$(abspath llvm-$(LLVM_VER)/python2_path):$$PATH && \ - $(MAKE) -C llvm-$(LLVM_VER) install - $(INSTALL_NAME_CMD)libLLVM-$(LLVM_VER).$(SHLIB_EXT) $(USR)/lib/libLLVM-$(LLVM_VER).$(SHLIB_EXT) + $(MAKE) -C llvm-$(LLVM_VER)/build install + $(INSTALL_NAME_CMD)libLLVM-$(LLVM_VER).$(SHLIB_EXT) $(BUILD)/lib/libLLVM-$(LLVM_VER).$(SHLIB_EXT) touch $@ clean-llvm: - -$(MAKE) -C llvm-$(LLVM_VER) clean - -rm -f $(USRBIN)/llvm-config + -$(MAKE) -C llvm-$(LLVM_VER)/build clean + -rm -f $(BUILD)/bin/llvm-config distclean-llvm: -rm -rf llvm-$(LLVM_VER).tar.gz llvm-$(LLVM_VER).src.tar.gz clang-$(LLVM_VER).src.tar.gz clang-$(LLVM_VER).tar.gz compiler-rt-$(LLVM_VER).src.tar.gz llvm-$(LLVM_VER) ## GNU readline ## -READLINE_OBJ_TARGET = $(USR)/lib/libreadline.$(SHLIB_EXT) +READLINE_OBJ_TARGET = $(BUILD)/lib/libreadline.$(SHLIB_EXT) READLINE_OBJ_SOURCE = readline-$(READLINE_VER)/shlib/libreadline.$(READLINE_VER).$(SHLIB_EXT) READLINE_OPTS = --disable-shared --enable-static @@ -235,7 +283,8 @@ readline-$(READLINE_VER)/configure: readline-$(READLINE_VER).tar.gz touch $@ $(READLINE_OBJ_SOURCE): readline-$(READLINE_VER)/configure cd readline-$(READLINE_VER) && \ - ./configure --prefix=$(abspath $(USR)) $(READLINE_OPTS) CC="$(CC)" CXX="$(CXX)" && \ + chmod a+x ./configure && \ + ./configure $(CONFIGURE_COMMON) $(READLINE_OPTS) && \ $(MAKE) $(READLINE_CFLAGS) touch $@ $(READLINE_OBJ_TARGET): $(READLINE_OBJ_SOURCE) @@ -265,18 +314,18 @@ readline-$(READLINE_VER)/configure: readline-$(READLINE_VER).tar.gz touch $@ $(READLINE_OBJ_SOURCE): readline-$(READLINE_VER)/configure cd readline-$(READLINE_VER) && \ - ./configure --prefix=$(abspath $(USR)) --enable-shared --enable-static --with-curses CC="$(CC)" CXX="$(CXX)" && \ + ./configure $(CONFIGURE_COMMON) --enable-shared --enable-static --with-curses && \ $(MAKE) touch $@ $(READLINE_OBJ_TARGET): $(READLINE_OBJ_SOURCE) $(MAKE) -C readline-$(READLINE_VER) install - chmod +w $(USR)/lib/libreadline.* $(USR)/lib/libhistory.* + chmod +w $(BUILD)/lib/libreadline.* $(BUILD)/lib/libhistory.* ifeq ($(OS), Darwin) - $(INSTALL_NAME_CMD)libreadline.$(SHLIB_EXT) $(USR)/lib/libreadline.$(SHLIB_EXT) - $(INSTALL_NAME_CMD)libhistory.dylib $(USR)/lib/libhistory.dylib + $(INSTALL_NAME_CMD)libreadline.$(SHLIB_EXT) $(BUILD)/lib/libreadline.$(SHLIB_EXT) + $(INSTALL_NAME_CMD)libhistory.dylib $(BUILD)/lib/libhistory.dylib else ifeq ($(OS), Linux) - for filename in $(USR)/lib/libhistory.so* $(USR)/lib/libreadline.so* ; do \ - $(USR)/bin/patchelf --set-rpath '$$ORIGIN' $$filename ;\ + for filename in $(BUILD)/lib/libhistory.so* $(BUILD)/lib/libreadline.so* ; do \ + $(BUILD)/bin/patchelf --set-rpath '$$ORIGIN' $$filename ;\ done endif touch $@ @@ -290,8 +339,12 @@ distclean-readline: endif ## LIBUV +uname_S=$(OS) +ifeq ($(uname_S),WINNT) +uname_S=MINGW +endif -UV_OBJ_TARGET = $(USR)/lib/libuv.a +UV_OBJ_TARGET = $(BUILD)/lib/libuv.a UV_OBJ_SOURCE = libuv/libuv.a libuv/Makefile: @@ -304,23 +357,23 @@ $(UV_OBJ_SOURCE): $(JULIAHOME)/.git/modules/deps/libuv/HEAD endif $(UV_OBJ_SOURCE): libuv/Makefile ifneq ($(OS), WINNT) - $(MAKE) libuv.${SHLIB_EXT} -C libuv CC="$(CC)" + $(MAKE) libuv.${SHLIB_EXT} -C libuv CC="$(CC)" AR="$(AR)" uname_S=$(uname_S) endif - $(MAKE) libuv.a -C libuv CC="$(CC)" + $(MAKE) libuv.a -C libuv CC="$(CC)" AR="$(AR)" uname_S=$(uname_S) $(UV_OBJ_TARGET): $(UV_OBJ_SOURCE) - mkdir -p $(USR)/include - cp $(UV_OBJ_SOURCE) $(USR)/lib/ - cp -r libuv/include/* $(USR)/include + mkdir -p $(BUILD)/include + cp $(UV_OBJ_SOURCE) $(BUILD)/lib/ + cp -r libuv/include/* $(BUILD)/include install-uv: $(UV_OBJ_TARGET) clean-uv: - -$(MAKE) -C libuv clean - -rm -rf $(USR)/lib/libuv.a $(USR)/include/uv.h $(USR)/include/uv-private + -$(MAKE) -C libuv clean uname_S=$(uname_S) + -rm -rf $(BUILD)/lib/libuv.a $(BUILD)/include/uv.h $(BUILD)/include/uv-private distclean-uv: clean-uv ## PCRE ## -PCRE_OBJ_TARGET = $(USR)/lib/libpcre.$(SHLIB_EXT) +PCRE_OBJ_TARGET = $(BUILD)/lib/libpcre.$(SHLIB_EXT) compile-pcre: install-pcre install-pcre: $(PCRE_OBJ_TARGET) @@ -332,13 +385,13 @@ pcre-$(PCRE_VER)/configure: pcre-$(PCRE_VER).tar.bz2 touch $@ pcre-$(PCRE_VER)/config.status: pcre-$(PCRE_VER)/configure cd pcre-$(PCRE_VER) && \ - ./configure --prefix=$(abspath $(USR)) --enable-utf --enable-unicode-properties --enable-jit CC="$(CC)" CXX="$(CXX)" + ./configure $(CONFIGURE_COMMON) --enable-utf --enable-unicode-properties --enable-jit $(PCRE_OBJ_TARGET): pcre-$(PCRE_VER)/config.status $(MAKE) -C pcre-$(PCRE_VER) $(LIBTOOL_CCLD) install $(INSTALL_NAME_CMD)libpcre.dylib $@ ifeq ($(OS),WINNT) - -rm $(USR)/lib/libpcre.dll - mv $(USRBIN)/libpcre.dll $(USR)/lib/libpcre.dll + -rm $(BUILD)/lib/libpcre.dll + mv $(BUILD)/bin/libpcre.dll $(BUILD)/lib/libpcre.dll endif touch $@ @@ -350,10 +403,10 @@ distclean-pcre: ## Grisu floating-point printing library ## -GRISU_OPTS = -O3 -fvisibility=hidden $(fPIC) +GRISU_OPTS = $(CXXFLAGS) -O3 -fvisibility=hidden $(fPIC) compile-double-conversion: double-conversion-$(GRISU_VER)/src/libgrisu_.$(SHLIB_EXT) -install-double-conversion: $(USR)/lib/libgrisu.$(SHLIB_EXT) +install-double-conversion: $(BUILD)/lib/libgrisu.$(SHLIB_EXT) double-conversion-$(GRISU_VER).tar.gz: $(WGET) http://double-conversion.googlecode.com/files/double-conversion-$(GRISU_VER).tar.gz @@ -372,8 +425,8 @@ double-conversion-$(GRISU_VER)/src/libgrisu.$(SHLIB_EXT): double-conversion-$(GR $(CXX) -c $(GRISU_OPTS) -o src/fixed-dtoa.o -Isrc src/fixed-dtoa.cc && \ $(CXX) -c $(GRISU_OPTS) -o src/strtod.o -Isrc src/strtod.cc && \ $(CXX) -c $(GRISU_OPTS) -o src/libdouble-conversion.o -I.. -Isrc ../double_conversion_wrapper.cpp && \ - $(CXX) $(GRISU_OPTS) src/*.o -shared -dead_strip -o src/libgrisu.$(SHLIB_EXT) -$(USR)/lib/libgrisu.$(SHLIB_EXT): double-conversion-$(GRISU_VER)/src/libgrisu.$(SHLIB_EXT) + $(CXX) $(GRISU_OPTS) src/*.o $(LDFLAGS) -shared -dead_strip -o src/libgrisu.$(SHLIB_EXT) +$(BUILD)/lib/libgrisu.$(SHLIB_EXT): double-conversion-$(GRISU_VER)/src/libgrisu.$(SHLIB_EXT) cp -f $< $@ $(INSTALL_NAME_CMD)libgrisu.dylib $@ @@ -387,9 +440,11 @@ distclean-double-conversion: ifeq ($(OS), WINNT) #needs more advanced detection once 64bit build is possible OPENLIBM_FLAGS = ARCH=i386 +else +OPENLIBM_FLAGS = ARCH="$(ARCH)" endif -OPENLIBM_OBJ_TARGET = $(USR)/lib/libopenlibm.$(SHLIB_EXT) +OPENLIBM_OBJ_TARGET = $(BUILD)/lib/libopenlibm.$(SHLIB_EXT) OPENLIBM_OBJ_SOURCE = openlibm/libopenlibm.$(SHLIB_EXT) openlibm/Makefile: @@ -401,19 +456,31 @@ ifeq (exists, $(shell [ -d $(JULIAHOME)/modules ] && echo exists )) $(OPENLIBM_OBJ_SOURCE): $(JULIAHOME)/.git/modules/deps/openlibm/HEAD endif $(OPENLIBM_OBJ_SOURCE): openlibm/Makefile - $(MAKE) -C openlibm $(OPENLIBM_FLAGS) CC="$(CC)" FC="$(FC)" USECLANG=$(USECLANG) USEGCC=$(USEGCC) -$(OPENLIBM_OBJ_TARGET): $(OPENLIBM_OBJ_SOURCE) | $(USR)/lib + $(MAKE) -C openlibm $(OPENLIBM_FLAGS) CC="$(CC)" FC="$(FC)" AR="$(AR)" OS="$(OS)" USECLANG=$(USECLANG) USEGCC=$(USEGCC) +$(OPENLIBM_OBJ_TARGET): $(OPENLIBM_OBJ_SOURCE) | $(BUILD)/lib cp $< $@ -install-openlibm: $(OPENLIBM_OBJ_TARGET) + $(INSTALL_NAME_CMD)libopenlibm.$(SHLIB_EXT) $@ +install-openlibm: $(OPENLIBM_OBJ_TARGET) $(BUILD)/lib/libFaddeeva_wrapper.$(SHLIB_EXT) clean-openlibm: -$(MAKE) -C openlibm distclean -rm $(OPENLIBM_OBJ_TARGET) distclean-openlibm: clean-openlibm +# Wrapper for openlibm/Faddeeva since ccall doesn't support C99 complex: +$(BUILD)/lib/libFaddeeva_wrapper.$(SHLIB_EXT): Faddeeva_wrapper.c $(OPENLIBM_OBJ_TARGET) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) -I openlibm/Faddeeva Faddeeva_wrapper.c -o $@ -L $(BUILD)/lib -lopenlibm + $(INSTALL_NAME_CMD)libFaddeeva_wrapper.$(SHLIB_EXT) $@ + touch $@ +install-Faddeeva-wrapper: $(BUILD)/lib/libFaddeeva_wrapper.$(SHLIB_EXT) + +clean-Faddeeva-wrapper: + -rm -f $(OPENLIBM_OBJ_TARGET) $(BUILD)/lib/libFaddeeva_wrapper.$(SHLIB_EXT) +distclean-Faddeeva-wrapper: clean-Faddeeva-wrapper + ## Rmath ## -RMATH_OBJ_TARGET = $(USR)/lib/libRmath.$(SHLIB_EXT) +RMATH_OBJ_TARGET = $(BUILD)/lib/libRmath.$(SHLIB_EXT) RMATH_OBJ_SOURCE = Rmath/src/libRmath.$(SHLIB_EXT) compile-rmath: $(RMATH_OBJ_SOURCE) @@ -433,10 +500,12 @@ distclean-rmath: clean-rmath ## LIBRANDOM ## -LIBRANDOM_OBJ_TARGET = $(USR)/lib/librandom.$(SHLIB_EXT) +LIBRANDOM_OBJ_TARGET = $(BUILD)/lib/librandom.$(SHLIB_EXT) LIBRANDOM_OBJ_SOURCE = random/librandom.$(SHLIB_EXT) -LIBRANDOM_CFLAGS = $(CFLAGS) -O3 -finline-functions -fomit-frame-pointer -DNDEBUG -fno-strict-aliasing --param max-inline-insns-single=1800 -Wmissing-prototypes -Wall -std=c99 -DDSFMT_MEXP=19937 $(fPIC) -shared -DDSFMT_DO_NOT_USE_OLD_NAMES +LIBRANDOM_CFLAGS = $(CFLAGS) -O3 -finline-functions -fomit-frame-pointer -DNDEBUG -fno-strict-aliasing \ + --param max-inline-insns-single=1800 -Wmissing-prototypes -Wall -std=c99 \ + -DDSFMT_MEXP=19937 $(fPIC) -shared -DDSFMT_DO_NOT_USE_OLD_NAMES ifeq ($(ARCH), x86_64) LIBRANDOM_CFLAGS += -msse2 -DHAVE_SSE2 endif @@ -451,11 +520,11 @@ random/jl_random.c: random/dsfmt-$(DSFMT_VER).tar.gz cd random && \ mkdir -p dsfmt-$(DSFMT_VER) && \ tar -C dsfmt-$(DSFMT_VER) --strip-components 1 -xf dsfmt-$(DSFMT_VER).tar.gz && \ - cd dsfmt-$(DSFMT_VER) && patch < ../dSFMT.h.patch + cd dsfmt-$(DSFMT_VER) && patch < ../dSFMT.h.patch && patch < ../dSFMT.c.patch touch $@ $(LIBRANDOM_OBJ_SOURCE): random/jl_random.c random/randmtzig.c cd random && \ - $(CC) $(LIBRANDOM_CFLAGS) jl_random.c -o librandom.$(SHLIB_EXT) && \ + $(CC) $(CPPFLAGS) $(LIBRANDOM_CFLAGS) $(LDFLAGS) jl_random.c -o librandom.$(SHLIB_EXT) && \ $(INSTALL_NAME_CMD)librandom.$(SHLIB_EXT) librandom.$(SHLIB_EXT) $(LIBRANDOM_OBJ_TARGET): $(LIBRANDOM_OBJ_SOURCE) @@ -474,17 +543,26 @@ else OPENBLAS_OBJ_SOURCE = endif -OPENBLAS_BUILD_OPTS = CC="$(CC)" FC="$(FC)" FFLAGS="$(FFLAGS) $(JFFLAGS)" USE_THREAD=$(OPENBLAS_USE_THREAD) TARGET=$(OPENBLAS_TARGET_ARCH) +OPENBLAS_BUILD_OPTS = CC="$(CC)" FC="$(FC)" RANLIB="$(RANLIB)" FFLAGS="$(FFLAGS) $(JFFLAGS)" USE_THREAD=$(OPENBLAS_USE_THREAD) TARGET=$(OPENBLAS_TARGET_ARCH) ifeq ($(OPENBLAS_DYNAMIC_ARCH), 1) OPENBLAS_BUILD_OPTS += DYNAMIC_ARCH=1 endif -#ifeq ($(ARCH), x86_64) -#OPENBLAS_BUILD_OPTS += -DINTERFACE64=1 -#endif +ifeq ($(USE_LIB64), 1) +OPENBLAS_BUILD_OPTS += INTERFACE64=1 +endif + +ifneq ($(BUILD_OS),$(OS)) +OPENBLAS_BUILD_OPTS += OSNAME=$(OS) CROSS=1 +ifeq ($(ARCH),i686) +OPENBLAS_BUILD_OPTS += BINARY=32 +else +$(error "unknown arch for openblas cross-compile") +endif +endif compile-openblas: $(OPENBLAS_OBJ_SOURCE) -install-openblas: $(USR)/lib/libopenblas.$(SHLIB_EXT) +install-openblas: $(BUILD)/lib/libopenblas.$(SHLIB_EXT) openblas-$(OPENBLAS_VER).tar.gz: $(WGET_DASH_O) $@ https://github.com/xianyi/OpenBLAS/tarball/$(OPENBLAS_VER) @@ -494,10 +572,10 @@ openblas-$(OPENBLAS_VER)/Makefile: openblas-$(OPENBLAS_VER).tar.gz perl -i -ple 's/^\s*(EXTRALIB\s*\+=\s*-lSystemStubs)\s*$$/# $$1/g' $@.system touch $@ $(OPENBLAS_OBJ_SOURCE): openblas-$(OPENBLAS_VER)/Makefile - $(MAKE) -C openblas-$(OPENBLAS_VER) CC="$(CC)" FC="$(FC)" FFLAGS="$(FFLAGS) $(JFFLAGS)" USE_THREAD=$(OPENBLAS_USE_THREAD) TARGET=$(OPENBLAS_TARGET_ARCH) $(OPENBLAS_BUILD_OPTS) -$(USR)/$(JL_LIBDIR)/libopenblas.$(SHLIB_EXT): $(OPENBLAS_OBJ_SOURCE) | $(USR)/$(JL_LIBDIR) - cp -f openblas-$(OPENBLAS_VER)/libopenblas.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR) - $(INSTALL_NAME_CMD)libopenblas.$(SHLIB_EXT) $(USR)/$(JL_LIBDIR)/libopenblas.$(SHLIB_EXT) + $(MAKE) -C openblas-$(OPENBLAS_VER) $(OPENBLAS_BUILD_OPTS) +$(BUILD)/lib/libopenblas.$(SHLIB_EXT): $(OPENBLAS_OBJ_SOURCE) | $(BUILD)/lib + cp -f openblas-$(OPENBLAS_VER)/libopenblas.$(SHLIB_EXT) $(BUILD)/lib + $(INSTALL_NAME_CMD)libopenblas.$(SHLIB_EXT) $(BUILD)/lib/libopenblas.$(SHLIB_EXT) clean-openblas: -$(MAKE) -C openblas-$(OPENBLAS_VER) clean @@ -550,7 +628,7 @@ distclean-atlas: clean-atlas ## LAPACK ## ifeq ($(USE_SYSTEM_LAPACK), 0) -LAPACK_OBJ_TARGET = $(USR)/lib/liblapack.$(SHLIB_EXT) +LAPACK_OBJ_TARGET = $(BUILD)/lib/liblapack.$(SHLIB_EXT) LAPACK_OBJ_SOURCE = lapack-$(LAPACK_VER)/liblapack.$(SHLIB_EXT) else LAPACK_OBJ_TARGET = @@ -584,7 +662,11 @@ distclean-lapack: ## ARPACK ## -ARPACK_OBJ_TARGET = $(USR)/lib/libarpack.$(SHLIB_EXT) +ifeq ($(USE_LIB64), 1) +ARPACK_FFLAGS = -fdefault-integer-8 +endif + +ARPACK_OBJ_TARGET = $(BUILD)/lib/libarpack.$(SHLIB_EXT) ARPACK_OBJ_SOURCE = arpack-ng_$(ARPACK_VER)/libarpack.$(SHLIB_EXT) ARPACK_OPTS = $(FFLAGS) $(JFFLAGS) @@ -598,20 +680,27 @@ arpack-ng_$(ARPACK_VER).tar.gz: arpack-ng_$(ARPACK_VER)/configure: arpack-ng_$(ARPACK_VER).tar.gz tar zxf $< touch $@ -$(ARPACK_OBJ_TARGET): arpack-ng_$(ARPACK_VER)/configure $(OPENBLAS_OBJ_SOURCE) | $(USR)/$(JL_LIBDIR) +$(ARPACK_OBJ_SOURCE): arpack-ng_$(ARPACK_VER)/configure $(OPENBLAS_OBJ_SOURCE) +ifeq ($(OS),WINNT) + cd arpack-ng_$(ARPACK_VER) && \ + rm -f UTIL/second_NONE.f +else + cd arpack-ng_$(ARPACK_VER) && \ + ./configure $(CONFIGURE_COMMON) --with-blas="$(LIBBLAS)" --with-lapack="$(LIBLAPACK)" --disable-mpi --enable-shared FFLAGS="$(ARPACK_FFLAGS)" +endif + touch $@ +$(ARPACK_OBJ_TARGET): $(ARPACK_OBJ_SOURCE) | $(BUILD)/lib ifeq ($(OS),WINNT) cd arpack-ng_$(ARPACK_VER) && \ - rm -f UTIL/second_NONE.f && \ - $(FC) -shared $(ARPACK_OPTS) SRC/*.f UTIL/*.f $(LIBLAPACK) $(LIBBLAS) -o libarpack.$(SHLIB_EXT) && \ - cp libarpack.$(SHLIB_EXT) $(USR)/lib/libarpack.$(SHLIB_EXT) + $(FC) -shared $(ARPACK_OPTS) SRC/*.f UTIL/*.f $(LIBLAPACK) $(LIBBLAS) -o $@ && + cp libarpack.$(SHLIB_EXT) $(BUILD)/lib/libarpack.$(SHLIB_EXT) else cd arpack-ng_$(ARPACK_VER) && \ - ./configure --prefix=$(abspath $(USR)) --with-blas="$(LIBBLAS)" --with-lapack="$(LIBLAPACK)" --disable-mpi --enable-shared F77="$(FC)" MPIF77="$(FC)" CC="$(CC)" CXX="$(CXX)" && \ - $(MAKE) install F77="$(FC)" MPIF77="$(FC)" && \ - $(INSTALL_NAME_CMD)libarpack.$(SHLIB_EXT) $(USR)/lib/libarpack.$(SHLIB_EXT) + $(MAKE) install F77="$(FC)" MPIF77="$(FC)" + $(INSTALL_NAME_CMD)libarpack.$(SHLIB_EXT) $(BUILD)/lib/libarpack.$(SHLIB_EXT) ifeq ($(OS), Linux) - for filename in $(USR)/lib/libarpack.so* ; do \ - $(USR)/bin/patchelf --set-rpath '$$ORIGIN' $$filename ;\ + for filename in $(BUILD)/lib/libarpack.so* ; do \ + $(BUILD)/bin/patchelf --set-rpath '$$ORIGIN' $$filename ;\ done endif endif @@ -625,8 +714,8 @@ distclean-arpack: ## FFTW ## -FFTW_SINGLE_OBJ_TARGET = $(USR)/lib/libfftw3f.3.$(SHLIB_EXT) -FFTW_DOUBLE_OBJ_TARGET = $(USR)/lib/libfftw3.3.$(SHLIB_EXT) +FFTW_SINGLE_OBJ_TARGET = $(BUILD)/lib/libfftw3f.3.$(SHLIB_EXT) +FFTW_DOUBLE_OBJ_TARGET = $(BUILD)/lib/libfftw3.3.$(SHLIB_EXT) compile-fftw: compile-fftw-single compile-fftw-double compile-fftw-single: install-fftw-single @@ -653,22 +742,22 @@ fftw-$(FFTW_VER)-single/configure: fftw-$(FFTW_VER).tar.gz touch $@ fftw-$(FFTW_VER)-single/config.status: fftw-$(FFTW_VER)-single/configure cd fftw-$(FFTW_VER)-single && \ - ./configure --prefix=$(abspath $(USR)) $(FFTW_CONFIG) --enable-avx --enable-single CC="$(CC)" CXX="$(CXX)" || \ - ./configure --prefix=$(abspath $(USR)) $(FFTW_CONFIG) --enable-single CC="$(CC)" CXX="$(CXX)" && \ + (./configure $(CONFIGURE_COMMON) $(FFTW_CONFIG) --enable-avx --enable-single || \ + ./configure $(CONFIGURE_COMMON) $(FFTW_CONFIG) --enable-single) && \ $(MAKE) clean touch $@ $(FFTW_SINGLE_OBJ_TARGET): fftw-$(FFTW_VER)-single/config.status $(MAKE) -C fftw-$(FFTW_VER)-single install ifeq ($(OS), Darwin) - $(INSTALL_NAME_CMD)libfftw3f.dylib $(USR)/lib/libfftw3f.dylib - $(INSTALL_NAME_CMD)libfftw3f_threads.$(SHLIB_EXT) $(USR)/lib/libfftw3f_threads.$(SHLIB_EXT) - $(INSTALL_NAME_CHANGE_CMD) $(USR)/lib/libfftw3f.3.dylib $(INSTALL_NAME_ID_DIR)libfftw3f.dylib $(USR)/lib/libfftw3f_threads.dylib + $(INSTALL_NAME_CMD)libfftw3f.dylib $(BUILD)/lib/libfftw3f.dylib + $(INSTALL_NAME_CMD)libfftw3f_threads.$(SHLIB_EXT) $(BUILD)/lib/libfftw3f_threads.$(SHLIB_EXT) + $(INSTALL_NAME_CHANGE_CMD) $(BUILD)/lib/libfftw3f.3.dylib $(INSTALL_NAME_ID_DIR)libfftw3f.dylib $(BUILD)/lib/libfftw3f_threads.dylib else ifeq ($(OS),WINNT) - -rm $(USR)/lib/libfftw3f.dll - mv $(USRBIN)/libfftw3f-3.dll $(USR)/lib/libfftw3f.dll + -rm $(BUILD)/lib/libfftw3f.dll + mv $(BUILD)/bin/libfftw3f-3.dll $(BUILD)/lib/libfftw3f.dll else ifeq ($(OS), Linux) - for filename in $(USR)/lib/libfftw3f_threads.so* ; do \ - $(USR)/bin/patchelf --set-rpath '$$ORIGIN' $$filename ;\ + for filename in $(BUILD)/lib/libfftw3f_threads.so* ; do \ + $(BUILD)/bin/patchelf --set-rpath '$$ORIGIN' $$filename ;\ done endif touch $@ @@ -679,22 +768,22 @@ fftw-$(FFTW_VER)-double/configure: fftw-$(FFTW_VER).tar.gz touch $@ fftw-$(FFTW_VER)-double/config.status: fftw-$(FFTW_VER)-double/configure cd fftw-$(FFTW_VER)-double && \ - ./configure --prefix=$(abspath $(USR)) $(FFTW_CONFIG) --enable-avx CC="$(CC)" CXX="$(CXX)" || \ - ./configure --prefix=$(abspath $(USR)) $(FFTW_CONFIG) CC="$(CC)" CXX="$(CXX)" && \ + (./configure $(CONFIGURE_COMMON) $(FFTW_CONFIG) --enable-avx || \ + ./configure $(CONFIGURE_COMMON) $(FFTW_CONFIG)) && \ $(MAKE) clean touch $@ $(FFTW_DOUBLE_OBJ_TARGET): fftw-$(FFTW_VER)-double/config.status $(MAKE) -C fftw-$(FFTW_VER)-double install ifeq ($(OS), Darwin) - $(INSTALL_NAME_CMD)libfftw3.$(SHLIB_EXT) $(USR)/lib/libfftw3.$(SHLIB_EXT) - $(INSTALL_NAME_CMD)libfftw3_threads.$(SHLIB_EXT) $(USR)/lib/libfftw3_threads.$(SHLIB_EXT) - $(INSTALL_NAME_CHANGE_CMD) $(USR)/lib/libfftw3.3.dylib $(INSTALL_NAME_ID_DIR)libfftw3.dylib $(USR)/lib/libfftw3_threads.dylib + $(INSTALL_NAME_CMD)libfftw3.$(SHLIB_EXT) $(BUILD)/lib/libfftw3.$(SHLIB_EXT) + $(INSTALL_NAME_CMD)libfftw3_threads.$(SHLIB_EXT) $(BUILD)/lib/libfftw3_threads.$(SHLIB_EXT) + $(INSTALL_NAME_CHANGE_CMD) $(BUILD)/lib/libfftw3.3.dylib $(INSTALL_NAME_ID_DIR)libfftw3.dylib $(BUILD)/lib/libfftw3_threads.dylib else ifeq ($(OS),WINNT) - -rm $(USR)/lib/libfftw3.dll - mv $(USRBIN)/libfftw3-3.dll $(USR)/lib/libfftw3.dll + -rm $(BUILD)/lib/libfftw3.dll + mv $(BUILD)/bin/libfftw3-3.dll $(BUILD)/lib/libfftw3.dll else ifeq ($(OS), Linux) - for filename in $(USR)/lib/libfftw3_threads.so* ; do \ - $(USR)/bin/patchelf --set-rpath '$$ORIGIN' $$filename ;\ + for filename in $(BUILD)/lib/libfftw3_threads.so* ; do \ + $(BUILD)/bin/patchelf --set-rpath '$$ORIGIN' $$filename ;\ done endif touch $@ @@ -714,16 +803,23 @@ distclean-fftw: ifeq ($(USE_SYSTEM_SUITESPARSE), 0) SUITESPARSE_OBJ_SOURCE = SuiteSparse-$(SUITESPARSE_VER)/UMFPACK/Lib/libumfpack.a -SUITESPARSE_OBJ_TARGET = $(USR)/lib/libumfpack.$(SHLIB_EXT) +SUITESPARSE_OBJ_TARGET = $(BUILD)/lib/libumfpack.$(SHLIB_EXT) +endif + +ifeq ($(USE_LIB64), 1) +UMFPACK_CONFIG = -DLONGBLAS='long long' +CHOLMOD_CONFIG = -DLONGBLAS='long long' endif SUITE_SPARSE_LIB = -lm ifneq ($(OS), Darwin) +ifneq ($(OS), WINNT) SUITE_SPARSE_LIB += -lrt endif +endif compile-suitesparse: $(SUITESPARSE_OBJ_SOURCE) -install-suitesparse: $(SUITESPARSE_OBJ_TARGET) $(USR)/lib/libsuitesparse_wrapper.$(SHLIB_EXT) +install-suitesparse: $(SUITESPARSE_OBJ_TARGET) $(BUILD)/lib/libsuitesparse_wrapper.$(SHLIB_EXT) SuiteSparse-$(SUITESPARSE_VER).tar.gz: $(WGET) http://www.cise.ufl.edu/research/sparse/SuiteSparse/SuiteSparse-$(SUITESPARSE_VER).tar.gz @@ -733,7 +829,9 @@ SuiteSparse-$(SUITESPARSE_VER)/Makefile: SuiteSparse-$(SUITESPARSE_VER).tar.gz touch $@ $(SUITESPARSE_OBJ_SOURCE): $(OPENBLAS_OBJ_SOURCE) SuiteSparse-$(SUITESPARSE_VER)/Makefile cd SuiteSparse-$(SUITESPARSE_VER) && \ - $(MAKE) CC="$(CC)" CXX="$(CXX)" BLAS="$(LIBBLAS)" LAPACK="$(LIBLAPACK)" INSTALL_LIB="$(USR)/lib" INSTALL_INCLUDE="$(USRINC)" LIB="$(SUITE_SPARSE_LIB)" + $(MAKE) CC="$(CC)" CXX="$(CXX)" F77="$(FC)" AR="$(AR)" RANLIB="$(RANLIB)" BLAS="$(LIBBLAS)" LAPACK="$(LIBLAPACK)" \ + INSTALL_LIB="$(BUILD)/lib" INSTALL_INCLUDE="$(BUILD)/include" LIB="$(SUITE_SPARSE_LIB)" \ + UMFPACK_CONFIG="$(UMFPACK_CONFIG)" CHOLMOD_CONFIG="$(CHOLMOD_CONFIG)" touch $@ ifeq ($(USE_SYSTEM_SUITESPARSE), 0) @@ -742,16 +840,16 @@ $(SUITESPARSE_OBJ_TARGET): $(SUITESPARSE_OBJ_SOURCE) cd SuiteSparse-$(SUITESPARSE_VER)/lib && \ rm -f *.a && \ cp -f `find .. -name libamd.a -o -name libcolamd.a -o -name libcholmod.a -o -name libumfpack.a -o -name libsuitesparseconfig.a -o -name libspqr.a 2>/dev/null` . && \ - $(CC) -shared $(WHOLE_ARCHIVE) libamd.a $(NO_WHOLE_ARCHIVE) -o $(USR)/lib/libamd.$(SHLIB_EXT) && \ - $(INSTALL_NAME_CMD)libamd.$(SHLIB_EXT) $(USR)/lib/libamd.$(SHLIB_EXT) && \ - $(CC) -shared $(WHOLE_ARCHIVE) libcolamd.a $(NO_WHOLE_ARCHIVE) -o $(USR)/lib/libcolamd.$(SHLIB_EXT) && \ - $(INSTALL_NAME_CMD)libcolamd.$(SHLIB_EXT) $(USR)/lib/libcolamd.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libcholmod.a $(NO_WHOLE_ARCHIVE) -o $(USR)/lib/libcholmod.$(SHLIB_EXT) -L$(USR)/lib -lcolamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ - $(INSTALL_NAME_CMD)libcholmod.$(SHLIB_EXT) $(USR)/lib/libcholmod.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libumfpack.a $(NO_WHOLE_ARCHIVE) -o $(USR)/lib/libumfpack.$(SHLIB_EXT) -L$(USR)/lib -lcholmod -lcolamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ - $(INSTALL_NAME_CMD)libumfpack.$(SHLIB_EXT) $(USR)/lib/libumfpack.$(SHLIB_EXT) && \ - $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libspqr.a $(NO_WHOLE_ARCHIVE) -o $(USR)/lib/libspqr.$(SHLIB_EXT) -L$(USR)/lib -lcholmod -lcolamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ - $(INSTALL_NAME_CMD)libspqr.$(SHLIB_EXT) $(USR)/lib/libspqr.$(SHLIB_EXT) + $(CC) -shared $(WHOLE_ARCHIVE) libamd.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/lib/libamd.$(SHLIB_EXT) && \ + $(INSTALL_NAME_CMD)libamd.$(SHLIB_EXT) $(BUILD)/lib/libamd.$(SHLIB_EXT) && \ + $(CC) -shared $(WHOLE_ARCHIVE) libcolamd.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/lib/libcolamd.$(SHLIB_EXT) && \ + $(INSTALL_NAME_CMD)libcolamd.$(SHLIB_EXT) $(BUILD)/lib/libcolamd.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libcholmod.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/lib/libcholmod.$(SHLIB_EXT) -L$(BUILD)/lib -lcolamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ + $(INSTALL_NAME_CMD)libcholmod.$(SHLIB_EXT) $(BUILD)/lib/libcholmod.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libumfpack.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/lib/libumfpack.$(SHLIB_EXT) -L$(BUILD)/lib -lcholmod -lcolamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ + $(INSTALL_NAME_CMD)libumfpack.$(SHLIB_EXT) $(BUILD)/lib/libumfpack.$(SHLIB_EXT) && \ + $(CXX) -shared $(WHOLE_ARCHIVE) libsuitesparseconfig.a libspqr.a $(NO_WHOLE_ARCHIVE) -o $(BUILD)/lib/libspqr.$(SHLIB_EXT) -L$(BUILD)/lib -lcholmod -lcolamd -lamd $(LIBBLAS) $(RPATH_ORIGIN) && \ + $(INSTALL_NAME_CMD)libspqr.$(SHLIB_EXT) $(BUILD)/lib/libspqr.$(SHLIB_EXT) endif clean-suitesparse: @@ -767,22 +865,22 @@ SUITESPARSE_INC = -I /usr/include/suitesparse SUITESPARSE_LIB = -lumfpack -lcholmod -lamd -lcamd -lcolamd -lspqr else SUITESPARSE_INC = -I SuiteSparse-$(SUITESPARSE_VER)/CHOLMOD/Include -I SuiteSparse-$(SUITESPARSE_VER)/SuiteSparse_config -I SuiteSparse-$(SUITESPARSE_VER)/SPQR/Include -SUITESPARSE_LIB = -L$(USR)/lib -lcholmod -lumfpack -lspqr $(RPATH_ORIGIN) +SUITESPARSE_LIB = -L$(BUILD)/lib -lcholmod -lumfpack -lspqr $(RPATH_ORIGIN) endif -$(USR)/lib/libsuitesparse_wrapper.$(SHLIB_EXT): SuiteSparse_wrapper.c $(SUITESPARSE_OBJ_TARGET) - $(CC) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) $(SUITESPARSE_INC) SuiteSparse_wrapper.c -o $(USR)/lib/libsuitesparse_wrapper.$(SHLIB_EXT) $(SUITESPARSE_LIB) +$(BUILD)/lib/libsuitesparse_wrapper.$(SHLIB_EXT): SuiteSparse_wrapper.c $(SUITESPARSE_OBJ_TARGET) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) $(SUITESPARSE_INC) SuiteSparse_wrapper.c -o $(BUILD)/lib/libsuitesparse_wrapper.$(SHLIB_EXT) $(SUITESPARSE_LIB) $(INSTALL_NAME_CMD)libsuitesparse_wrapper.$(SHLIB_EXT) $@ touch $@ -install-suitesparse-wrapper: $(USR)/lib/libsuitesparse_wrapper.$(SHLIB_EXT) +install-suitesparse-wrapper: $(BUILD)/lib/libsuitesparse_wrapper.$(SHLIB_EXT) clean-suitesparse-wrapper: - -rm -f $(SUITESPARSE_OBJ_TARGET) $(USR)/lib/libsuitesparse_wrapper.$(SHLIB_EXT) + -rm -f $(SUITESPARSE_OBJ_TARGET) $(BUILD)/lib/libsuitesparse_wrapper.$(SHLIB_EXT) distclean-suitesparse-wrapper: clean-suitesparse-wrapper ## CLP ## -CLP_OBJ_TARGET = $(USR)/lib/libClp.$(SHLIB_EXT) +CLP_OBJ_TARGET = $(BUILD)/lib/libClp.$(SHLIB_EXT) compile-clp: install-clp install-clp: $(CLP_OBJ_TARGET) @@ -795,7 +893,7 @@ clp-$(CLP_VER)/configure: clp-$(CLP_VER).tar.gz touch $@ clp-$(CLP_VER)/config.status: clp-$(CLP_VER)/configure cd clp-$(CLP_VER) && \ - ./configure --prefix="$(abspath $(USR))" CC="$(CC)" CXX="$(CXX)" + ./configure $(CONFIGURE_COMMON) MPIF77="$(FC)" MPICXX="$(CXX)" MPICC="$(CC)" $(CLP_OBJ_TARGET): clp-$(CLP_VER)/config.status $(MAKE) -C clp-$(CLP_VER) install touch $@ @@ -809,7 +907,7 @@ distclean-clp: ## UNWIND ## ifeq ($(USE_SYSTEM_LIBUNWIND), 0) -LIBUNWIND_TARGET_OBJ = $(USR)/lib/libunwind.a +LIBUNWIND_TARGET_OBJ = $(BUILD)/lib/libunwind.a LIBUNWIND_TARGET_SOURCE = libunwind-$(UNWIND_VER)/src/.libs/libunwind.a else LIBUNWIND_TARGET_OBJ = @@ -828,7 +926,7 @@ libunwind-$(UNWIND_VER).tar.gz: $(WGET) http://savannah.spinellicreations.com/libunwind/libunwind-$(UNWIND_VER).tar.gz libunwind-$(UNWIND_VER)/Makefile: libunwind-$(UNWIND_VER).tar.gz tar xfz $< - cd libunwind-$(UNWIND_VER) && ./configure CFLAGS="$(LIBUNWIND_CFLAGS)" --prefix="$(abspath $(USR))" CC="$(CC)" CXX="$(CXX)" + cd libunwind-$(UNWIND_VER) && ./configure $(CONFIGURE_COMMON) CFLAGS="$(LIBUNWIND_CFLAGS)" $(LIBUNWIND_TARGET_SOURCE): libunwind-$(UNWIND_VER)/Makefile cd libunwind-$(UNWIND_VER) && $(MAKE) @@ -846,15 +944,15 @@ distclean-unwind: ## GNU LIGHTTPD ## ifeq ($(USE_SYSTEM_LIGHTTPD), 0) -LIGHTTPD_OBJ_TARGET = $(USR)/sbin/lighttpd +LIGHTTPD_OBJ_TARGET = $(BUILD)/sbin/lighttpd else LIGHTTPD_OBJ_TARGET = endif compile-lighttpd: install-lighttpd install-lighttpd: $(LIGHTTPD_OBJ_TARGET) lighttpd.conf - mkdir -p $(USR)/etc - cp -f lighttpd.conf $(USR)/etc/lighttpd.conf + mkdir -p $(BUILD)/etc + cp -f lighttpd.conf $(BUILD)/etc/lighttpd.conf lighttpd-$(LIGHTTPD_VER).tar.gz: $(WGET) http://download.lighttpd.net/lighttpd/releases-1.4.x/lighttpd-$(LIGHTTPD_VER).tar.gz @@ -862,11 +960,13 @@ lighttpd-$(LIGHTTPD_VER)/configure: lighttpd-$(LIGHTTPD_VER).tar.gz tar zxf $< touch $@ lighttpd-$(LIGHTTPD_VER)/config.status: lighttpd-$(LIGHTTPD_VER)/configure - mkdir -p $(USR)/lib/lighttpd && \ + mkdir -p $(BUILD)/lib/lighttpd && \ cd lighttpd-$(LIGHTTPD_VER) && \ - ./configure --prefix=$(USR) --libdir=$(USR)/lib/lighttpd --without-pcre --without-zlib --without-bzip2 CC="$(CC)" CXX="$(CXX)" + ./configure $(CONFIGURE_COMMON) --libdir=$(BUILD)/lib/lighttpd --without-pcre --without-zlib --without-bzip2 $(LIGHTTPD_OBJ_TARGET): lighttpd-$(LIGHTTPD_VER)/config.status $(MAKE) -C lighttpd-$(LIGHTTPD_VER) install + $(INSTALL_NAME_CMD)lighttpd/liblightcomp.$(SHLIB_EXT) $(BUILD)/lib/lighttpd/liblightcomp.$(SHLIB_EXT) + $(INSTALL_NAME_CHANGE_CMD) $(BUILD)/lib/lighttpd/liblightcomp.dylib @executable_path/../lib/lighttpd/liblightcomp.dylib $(BUILD)/sbin/lighttpd touch $@ clean-lighttpd: @@ -917,7 +1017,7 @@ distclean-nginx: ## GMP ## ifeq ($(USE_SYSTEM_GMP), 0) -GMP_OBJ_TARGET = $(USR)/lib/libgmp.$(SHLIB_EXT) +GMP_OBJ_TARGET = $(BUILD)/lib/libgmp.$(SHLIB_EXT) else GMP_OBJ_TARGET = endif @@ -932,10 +1032,12 @@ gmp-$(GMP_VER)/configure: gmp-$(GMP_VER).tar.bz2 touch $@ gmp-$(GMP_VER)/config.status: gmp-$(GMP_VER)/configure cd gmp-$(GMP_VER) && \ - ./configure --prefix=$(abspath $(USR)) CC="$(CC)" CXX="$(CXX)" + ./configure $(CONFIGURE_COMMON) --enable-shared --disable-static $(GMP_OBJ_TARGET): gmp-$(GMP_VER)/config.status $(MAKE) -C gmp-$(GMP_VER) $(LIBTOOL_CCLD) +ifeq ($(OS),$(BUILD_OS)) $(MAKE) -C gmp-$(GMP_VER) $(LIBTOOL_CCLD) check +endif $(MAKE) -C gmp-$(GMP_VER) $(LIBTOOL_CCLD) install $(INSTALL_NAME_CMD)libgmp.dylib $@ $(AUTOTOOLS_PATH_CORRECT) @@ -953,18 +1055,18 @@ ifeq ($(USE_SYSTEM_GMP), 1) GMPW_INC = GMPW_LIB = -lgmp else -GMPW_INC = -I $(USRINC) -GMPW_LIB = -L$(USR)/lib/ -lgmp +GMPW_INC = -I $(BUILD)/include +GMPW_LIB = -L$(BUILD)/lib/ -lgmp endif -$(USR)/lib/libgmp_wrapper.$(SHLIB_EXT): gmp_wrapper.c $(GMP_OBJ_TARGET) | $(USR)/lib - $(CC) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) $(GMPW_INC) gmp_wrapper.c -o $(USR)/lib/libgmp_wrapper.$(SHLIB_EXT) $(RPATH_ORIGIN) $(GMPW_LIB) +$(BUILD)/lib/libgmp_wrapper.$(SHLIB_EXT): gmp_wrapper.c $(GMP_OBJ_TARGET) | $(BUILD)/lib + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) $(GMPW_INC) gmp_wrapper.c -o $(BUILD)/lib/libgmp_wrapper.$(SHLIB_EXT) $(RPATH_ORIGIN) $(GMPW_LIB) $(INSTALL_NAME_CMD)libgmp_wrapper.$(SHLIB_EXT) $@ touch $@ -install-gmp-wrapper: $(USR)/lib/libgmp_wrapper.$(SHLIB_EXT) +install-gmp-wrapper: $(BUILD)/lib/libgmp_wrapper.$(SHLIB_EXT) clean-gmp-wrapper: - -rm -f $(GMP_OBJ_TARGET) $(USR)/lib/libgmp_wrapper.$(SHLIB_EXT) + -rm -f $(GMP_OBJ_TARGET) $(BUILD)/lib/libgmp_wrapper.$(SHLIB_EXT) distclean-gmp-wrapper: clean-gmp-wrapper ## GLPK ## @@ -972,11 +1074,11 @@ distclean-gmp-wrapper: clean-gmp-wrapper ifeq ($(USE_SYSTEM_GLPK), 1) GLPK_OBJ_TARGET = else -GLPK_OBJ_TARGET = $(USR)/lib/libglpk.$(SHLIB_EXT) +GLPK_OBJ_TARGET = $(BUILD)/lib/libglpk.$(SHLIB_EXT) endif compile-glpk: install-glpk -install-glpk: $(GLPK_OBJ_TARGET) $(USR)/lib/libglpk_wrapper.$(SHLIB_EXT) +install-glpk: $(GLPK_OBJ_TARGET) $(BUILD)/lib/libglpk_wrapper.$(SHLIB_EXT) glpk-$(GLPK_VER).tar.gz: $(WGET) http://ftp.gnu.org/gnu/glpk/$@ @@ -986,10 +1088,10 @@ glpk-$(GLPK_VER)/configure: glpk-$(GLPK_VER).tar.gz touch $@ glpk-$(GLPK_VER)/config.status: glpk-$(GLPK_VER)/configure cd glpk-$(GLPK_VER) && \ - ./configure --prefix=$(abspath $(USR)) CC="$(CC)" CXX="$(CXX)" + ./configure $(CONFIGURE_COMMON) $(GLPK_OBJ_TARGET): glpk-$(GLPK_VER)/config.status - $(MAKE) -C glpk-$(GLPK_VER) $(LIBTOOL_CCLD) install - $(INSTALL_NAME_CMD)libglpk.$(SHLIB_EXT) $@ + $(MAKE) -C glpk-$(GLPK_VER) $(LIBTOOL_CCLD) install + $(INSTALL_NAME_CMD)libglpk.dylib $@ $(AUTOTOOLS_PATH_CORRECT) touch $@ @@ -1006,19 +1108,19 @@ ifeq ($(USE_SYSTEM_GLPK), 1) GLPKW_INC = -I /usr/include/ GLPKW_LIB = -lglpk else -GLPKW_INC = -I $(USRINC) -GLPKW_LIB = -L$(USR)/lib -lglpk +GLPKW_INC = -I $(BUILD)/include +GLPKW_LIB = -L$(BUILD)/lib -lglpk endif -$(USR)/lib/libglpk_wrapper.$(SHLIB_EXT): glpk_wrapper.c $(GLPK_OBJ_TARGET) - $(CC) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) $(GLPKW_INC) glpk_wrapper.c $(GLPKW_LIB) -o $(USR)/lib/libglpk_wrapper.$(SHLIB_EXT) $(RPATH_ORIGIN) +$(BUILD)/lib/libglpk_wrapper.$(SHLIB_EXT): glpk_wrapper.c $(GLPK_OBJ_TARGET) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) $(GLPKW_INC) glpk_wrapper.c $(GLPKW_LIB) -o $(BUILD)/lib/libglpk_wrapper.$(SHLIB_EXT) $(RPATH_ORIGIN) $(INSTALL_NAME_CMD)libglpk_wrapper.$(SHLIB_EXT) $@ touch $@ -install-glpk-wrapper: $(USR)/lib/libglpk_wrapper.$(SHLIB_EXT) glpk_wrapper.c +install-glpk-wrapper: $(BUILD)/lib/libglpk_wrapper.$(SHLIB_EXT) glpk_wrapper.c clean-glpk-wrapper: - -rm -f $(GLPK_OBJ_TARGET) $(USR)/lib/libglpk_wrapper.$(SHLIB_EXT) + -rm -f $(GLPK_OBJ_TARGET) $(BUILD)/lib/libglpk_wrapper.$(SHLIB_EXT) distclean-glpk-wrapper: clean-glpk-wrapper ## ZLIB ## @@ -1026,8 +1128,13 @@ distclean-glpk-wrapper: clean-glpk-wrapper ifeq ($(USE_SYSTEM_ZLIB), 1) ZLIB_OBJ_TARGET = else -ZLIB_OBJ_TARGET = $(USR)/lib/libz.$(SHLIB_EXT) -ZLIB_CFLAGS = CFLAGS="$(CFLAGS) -D_FILE_OFFSET_BITS=64" +ZLIB_OBJ_TARGET = $(BUILD)/lib/libz.$(SHLIB_EXT) +ZLIB_CONFIGFLAGS = CFLAGS="-O3 $(CFLAGS) -D_FILE_OFFSET_BITS=64" +ifneq ($(OS),$(BUILD_OS)) +ZLIB_CONFIGFLAGS += CHOST=$(HOST) +else +ZLIB_CONFIGFLAGS += CC="$(CC)" +endif endif compile-zlib: install-zlib @@ -1042,17 +1149,18 @@ zlib-$(ZLIB_VER)/config.status: zlib-$(ZLIB_VER)/configure ifeq ($(OS), WINNT) cd zlib-$(ZLIB_VER) && \ cp win32/Makefile.gcc Makefile -endif +else cd zlib-$(ZLIB_VER) && \ - CC="$(CC)" $(ZLIB_CFLAGS) ./configure --prefix=$(abspath $(USR)) + $(ZLIB_CONFIGFLAGS) ./configure --prefix=$(abspath $(BUILD)) #not an autoconf script +endif touch $@ $(ZLIB_OBJ_TARGET): zlib-$(ZLIB_VER)/config.status - $(MAKE) -C zlib-$(ZLIB_VER) CC="$(CC)" + $(MAKE) -C zlib-$(ZLIB_VER) PREFIX=$(CROSS_COMPILE) ifeq ($(OS), WINNT) cp zlib-$(ZLIB_VER)/zlib1.dll $@ else - $(MAKE) -C zlib-$(ZLIB_VER) check - PREFIX=$(USRLIB) $(MAKE) -C zlib-$(ZLIB_VER) install + $(MAKE) -C zlib-$(ZLIB_VER) check PREFIX=$(CROSS_COMPILE) + $(MAKE) -C zlib-$(ZLIB_VER) install PREFIX=$(CROSS_COMPILE) endif $(INSTALL_NAME_CMD)libz.dylib $@ touch $@ @@ -1065,7 +1173,7 @@ distclean-zlib: ## Tk wrapper ## -TKW_INC = -I $(USRINC) -I $(JULIAHOME)/src -I $(JULIAHOME)/src/support +TKW_INC = -I $(BUILD)/include -I $(JULIAHOME)/src -I $(JULIAHOME)/src/support TKW_LIB = ifeq ($(OS), Darwin) ifneq ($(wildcard /opt/local/bin/port),) @@ -1079,21 +1187,21 @@ ifeq ($(OS), Darwin) else TKW_INC += -I/usr/include/tcl endif -TKW_LIB += -ltcl8.5 -ltk8.5 -L$(USR)/lib/ -ljulia-release +TKW_LIB += -ltcl8.5 -ltk8.5 -L$(BUILD)/lib/ -ljulia-release -$(USR)/lib/libtk_wrapper.$(SHLIB_EXT): tk_wrapper.c - $(CC) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) $(TKW_INC) tk_wrapper.c $(TKW_LIB) -o $(USR)/lib/libtk_wrapper.$(SHLIB_EXT) +$(BUILD)/lib/libtk_wrapper.$(SHLIB_EXT): tk_wrapper.c + $(CC) $(CFLAGS) $(LDFLAGS) -O2 -shared $(fPIC) $(TKW_INC) tk_wrapper.c $(TKW_LIB) -o $(BUILD)/lib/libtk_wrapper.$(SHLIB_EXT) $(INSTALL_NAME_CMD)libtk_wrapper.$(SHLIB_EXT) $@ touch $@ -install-tk-wrapper: $(USR)/lib/libtk_wrapper.$(SHLIB_EXT) tk_wrapper.c +install-tk-wrapper: $(BUILD)/lib/libtk_wrapper.$(SHLIB_EXT) tk_wrapper.c clean-tk-wrapper: - -rm -f $(USR)/lib/libtk_wrapper.$(SHLIB_EXT) + -rm -f $(BUILD)/lib/libtk_wrapper.$(SHLIB_EXT) distclean-tk-wrapper: clean-tk-wrapper ## patchelf -PATCHELF_TARGET = $(USR)/bin/patchelf +PATCHELF_TARGET = $(BUILD)/bin/patchelf compile-patchelf: install-patchelf install-patchelf: $(PATCHELF_TARGET) @@ -1105,7 +1213,7 @@ patchelf-$(PATCHELF_VER)/configure: patchelf-$(PATCHELF_VER).tar.bz2 touch $@ patchelf-$(PATCHELF_VER)/config.status: patchelf-$(PATCHELF_VER)/configure cd patchelf-$(PATCHELF_VER) && \ - ./configure --prefix=$(abspath $(USR)) CC="$(CC)" CXX="$(CXX)" + ./configure $(CONFIGURE_COMMON) $(PATCHELF_TARGET): patchelf-$(PATCHELF_VER)/config.status $(MAKE) -C patchelf-$(PATCHELF_VER) install touch $@ diff --git a/deps/Rmath/src/Makefile b/deps/Rmath/src/Makefile index 3552b1887a732..01621af5ae9e0 100644 --- a/deps/Rmath/src/Makefile +++ b/deps/Rmath/src/Makefile @@ -34,15 +34,15 @@ endif default: release %.o: %.c - $(QUIET_CC) $(CC) $(fPIC) -std=gnu99 -I../include -DMATHLIB_STANDALONE -DNDEBUG -O3 -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(CFLAGS) $(fPIC) -std=gnu99 -I../include -DMATHLIB_STANDALONE -DNDEBUG -O3 -c $< -o $@ %.do: %.c - $(QUIET_CC) $(CC) $(fPIC) -std=gnu99 -I../include -DMATHLIB_STANDALONE -g -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(CFLAGS) $(fPIC) -std=gnu99 -I../include -DMATHLIB_STANDALONE -g -c $< -o $@ release debug: libRmath.$(SHLIB_EXT) libRmath.$(SHLIB_EXT): $(XOBJS) rm -rf $@ - $(QUIET_LINK) $(CC) -shared -o $@ $^ -L$(USR)/lib -lrandom $(RPATH_ORIGIN) + $(QUIET_LINK) $(CC) $(LDFLAGS) -shared -o $@ $^ -L$(BUILD)/lib -lrandom $(RPATH_ORIGIN) clean: rm -f *.o *.do *.a *.$(SHLIB_EXT) core* *~ *# diff --git a/deps/Versions.make b/deps/Versions.make index d95a54fb9f433..fd7cb9aca1b29 100644 --- a/deps/Versions.make +++ b/deps/Versions.make @@ -10,7 +10,7 @@ FFTW_VER = 3.3.3 SUITESPARSE_VER = 4.0.2 CLP_VER = 1.14.5 UNWIND_VER = 1.0.1 -LIGHTTPD_VER = 1.4.29 +LIGHTTPD_VER = 1.4.32 GMP_VER=5.0.5 GLPK_VER = 4.47 ZLIB_VER = 1.2.7 diff --git a/deps/config.guess b/deps/config.guess new file mode 100755 index 0000000000000..f7dd69ecc9c4c --- /dev/null +++ b/deps/config.guess @@ -0,0 +1,1516 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +# 2011 Free Software Foundation, Inc. + +timestamp='2011-08-20' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Originally written by Per Bothner. Please send patches (context +# diff format) to and include a ChangeLog +# entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# You can get the latest version of this script from: +# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, +2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free +Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ; set_cc_for_build= ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + sh5el) machine=sh5le-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ELF__ + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + exit ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit ;; + *:SolidBSD:*:*) + echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + exit ;; + macppc:MirBSD:*:*) + echo powerpc-unknown-mirbsd${UNAME_RELEASE} + exit ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Reset EXIT trap before exiting to avoid spurious non-zero exit code. + exitcode=$? + trap '' 0 + exit $exitcode ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit ;; + arm:riscos:*:*|arm:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7; exit ;; + esac ;; + s390x:SunOS:*:*) + echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) + echo i386-pc-auroraux${UNAME_RELEASE} + exit ;; + i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) + eval $set_cc_for_build + SUN_ARCH="i386" + # If there is a compiler, see if it is configured for 64-bit objects. + # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. + # This test works for both compilers. + if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then + if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + SUN_ARCH="x86_64" + fi + fi + echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && + dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`$dummy $dummyarg` && + { echo "$SYSTEM_NAME"; exit; } + echo mips-mips-riscos${UNAME_RELEASE} + exit ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit ;; + *:AIX:*:[4567]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + eval $set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + grep -q __LP64__ + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + echo unknown-hitachi-hiuxwe2 + exit ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:FreeBSD:*:*) + UNAME_PROCESSOR=`/usr/bin/uname -p` + case ${UNAME_PROCESSOR} in + amd64) + echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + *) + echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + esac + exit ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit ;; + *:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit ;; + i*:windows32*:*) + # uname -m includes "-pc" on this system. + echo ${UNAME_MACHINE}-mingw32 + exit ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit ;; + *:Interix*:*) + case ${UNAME_MACHINE} in + x86) + echo i586-pc-interix${UNAME_RELEASE} + exit ;; + authenticamd | genuineintel | EM64T) + echo x86_64-unknown-interix${UNAME_RELEASE} + exit ;; + IA64) + echo ia64-unknown-interix${UNAME_RELEASE} + exit ;; + esac ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit ;; + 8664:Windows_NT:*) + echo x86_64-pc-mks + exit ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu + exit ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep -q ld.so.1 + if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit ;; + arm*:Linux:*:*) + eval $set_cc_for_build + if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_EABI__ + then + echo ${UNAME_MACHINE}-unknown-linux-gnu + else + if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_PCS_VFP + then + echo ${UNAME_MACHINE}-unknown-linux-gnueabi + else + echo ${UNAME_MACHINE}-unknown-linux-gnueabihf + fi + fi + exit ;; + avr32*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + cris:Linux:*:*) + echo cris-axis-linux-gnu + exit ;; + crisv32:Linux:*:*) + echo crisv32-axis-linux-gnu + exit ;; + frv:Linux:*:*) + echo frv-unknown-linux-gnu + exit ;; + i*86:Linux:*:*) + LIBC=gnu + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #ifdef __dietlibc__ + LIBC=dietlibc + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` + echo "${UNAME_MACHINE}-pc-linux-${LIBC}" + exit ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + mips:Linux:*:* | mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef ${UNAME_MACHINE} + #undef ${UNAME_MACHINE}el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=${UNAME_MACHINE}el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=${UNAME_MACHINE} + #else + CPU= + #endif + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } + ;; + or32:Linux:*:*) + echo or32-unknown-linux-gnu + exit ;; + padre:Linux:*:*) + echo sparc-unknown-linux-gnu + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-gnu + exit ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-gnu + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + tile*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + vax:Linux:*:*) + echo ${UNAME_MACHINE}-dec-linux-gnu + exit ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-gnu + exit ;; + xtensa*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i586. + # Note: whatever this is, it MUST be the same as what config.sub + # prints for the "djgpp" host, or else GDB configury will decide that + # this is a cross-build. + echo i586-pc-msdosdjgpp + exit ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + NCR*:*:4.2:* | MPRAS*:*:4.2:*) + OS_REL='.3' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit ;; + BePC:Haiku:*:*) # Haiku running on Intel PC compatible. + echo i586-pc-haiku + exit ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit ;; + SX-7:SUPER-UX:*:*) + echo sx7-nec-superux${UNAME_RELEASE} + exit ;; + SX-8:SUPER-UX:*:*) + echo sx8-nec-superux${UNAME_RELEASE} + exit ;; + SX-8R:SUPER-UX:*:*) + echo sx8r-nec-superux${UNAME_RELEASE} + exit ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown + case $UNAME_PROCESSOR in + i386) + eval $set_cc_for_build + if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then + if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + UNAME_PROCESSOR="x86_64" + fi + fi ;; + unknown) UNAME_PROCESSOR=powerpc ;; + esac + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit ;; + NEO-?:NONSTOP_KERNEL:*:*) + echo neo-tandem-nsk${UNAME_RELEASE} + exit ;; + NSE-?:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "${UNAME_MACHINE}" in + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit ;; + i*86:skyos:*:*) + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + exit ;; + i*86:rdos:*:*) + echo ${UNAME_MACHINE}-pc-rdos + exit ;; + i*86:AROS:*:*) + echo ${UNAME_MACHINE}-pc-aros + exit ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix\n"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + c34*) + echo c34-convex-bsd + exit ;; + c38*) + echo c38-convex-bsd + exit ;; + c4*) + echo c4-convex-bsd + exit ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/deps/glpk_wrapper.c b/deps/glpk_wrapper.c index 5c4c7634782d0..1c1f134d517a2 100644 --- a/deps/glpk_wrapper.c +++ b/deps/glpk_wrapper.c @@ -3,26 +3,26 @@ #include #define generate_accessors(str, field, type) \ - extern void _jl_glpkw__ ## str ## _set_ ## field(void * v, type val) \ + extern void jl_glpkw__ ## str ## _set_ ## field(void * v, type val) \ { \ glp_ ## str * s = (glp_ ## str *) v; \ s->field = val; \ } \ \ - extern type _jl_glpkw__ ## str ## _get_ ## field(void * v) \ + extern type jl_glpkw__ ## str ## _get_ ## field(void * v) \ { \ glp_ ## str * s = (glp_ ## str *) v; \ return s->field; \ } -extern void* _jl_glpkw__smcp_init() +extern void* jl_glpkw__smcp_init() { glp_smcp * smcp = calloc(1, sizeof(glp_smcp)); glp_init_smcp(smcp); return (void*) smcp; } -extern void _jl_glpkw__smcp_delete(void* smcp) +extern void jl_glpkw__smcp_delete(void* smcp) { free((glp_smcp*) smcp); } @@ -44,14 +44,14 @@ generate_accessors(smcp, presolve, int); -extern void* _jl_glpkw__iptcp_init() +extern void* jl_glpkw__iptcp_init() { glp_iptcp * iptcp = calloc(1, sizeof(glp_iptcp)); glp_init_iptcp(iptcp); return (void*) iptcp; } -extern void _jl_glpkw__iptcp_delete(void* iptcp) +extern void jl_glpkw__iptcp_delete(void* iptcp) { free((glp_iptcp*) iptcp); } @@ -61,14 +61,14 @@ generate_accessors(iptcp, ord_alg, int); -extern void* _jl_glpkw__iocp_init() +extern void* jl_glpkw__iocp_init() { glp_iocp * iocp = calloc(1, sizeof(glp_iocp)); glp_init_iocp(iocp); return (void*) iocp; } -extern void _jl_glpkw__iocp_delete(void* iocp) +extern void jl_glpkw__iocp_delete(void* iocp) { free((glp_iocp*) iocp); } @@ -96,13 +96,13 @@ generate_accessors(iocp, binarize, int); -extern void* _jl_glpkw__bfcp_init() +extern void* jl_glpkw__bfcp_init() { glp_bfcp * bfcp = calloc(1, sizeof(glp_bfcp)); return (void*) bfcp; } -extern void _jl_glpkw__bfcp_delete(void* bfcp) +extern void jl_glpkw__bfcp_delete(void* bfcp) { free((glp_bfcp*) bfcp); } diff --git a/deps/gmp_wrapper.c b/deps/gmp_wrapper.c index 9935e53e3f23c..063bf3d53e220 100644 --- a/deps/gmp_wrapper.c +++ b/deps/gmp_wrapper.c @@ -2,113 +2,113 @@ #include #include -void _jl_gmp_free(void *p) +void jl_gmp_free(void *p) { void (*freefunc) (void *, size_t); mp_get_memory_functions (NULL, NULL, &freefunc); freefunc(p, 0); } -extern void* _jl_mpz_init() +extern void* jl_mpz_init() { mpz_t* integ = malloc(sizeof(mpz_t)); mpz_init(*integ); return integ; } -extern void _jl_mpz_clear(mpz_t* rop) { +extern void jl_mpz_clear(mpz_t* rop) { mpz_clear(*rop); } -extern void _jl_mpz_set_string(mpz_t* rop, char* s) { +extern void jl_mpz_set_string(mpz_t* rop, char* s) { mpz_set_str(*rop, s, 0); } -extern void _jl_mpz_set_ui(mpz_t* rop, unsigned long int op) { +extern void jl_mpz_set_ui(mpz_t* rop, unsigned long int op) { mpz_set_ui(*rop, op); } -extern unsigned long _jl_mpz_get_ui(mpz_t* rop) { +extern unsigned long jl_mpz_get_ui(mpz_t* rop) { return mpz_get_ui(*rop); } -extern void _jl_mpz_set_si(mpz_t* rop, long int op) { +extern void jl_mpz_set_si(mpz_t* rop, long int op) { mpz_set_si(*rop, op); } -extern long _jl_mpz_get_si(mpz_t* rop) { +extern long jl_mpz_get_si(mpz_t* rop) { return mpz_get_si(*rop); } -extern void _jl_mpz_add(mpz_t* rop, mpz_t* op1, mpz_t* op2) { +extern void jl_mpz_add(mpz_t* rop, mpz_t* op1, mpz_t* op2) { mpz_add(*rop, *op1, *op2); } -extern void _jl_mpz_sub(mpz_t* rop, mpz_t* op1, mpz_t* op2) { +extern void jl_mpz_sub(mpz_t* rop, mpz_t* op1, mpz_t* op2) { mpz_sub(*rop, *op1, *op2); } -extern void _jl_mpz_mul(mpz_t* rop, mpz_t* op1, mpz_t* op2) { +extern void jl_mpz_mul(mpz_t* rop, mpz_t* op1, mpz_t* op2) { mpz_mul(*rop, *op1, *op2); } -extern void _jl_mpz_div(mpz_t* rop, mpz_t* op1, mpz_t* op2) { +extern void jl_mpz_div(mpz_t* rop, mpz_t* op1, mpz_t* op2) { mpz_fdiv_q(*rop, *op1, *op2); } -extern void _jl_mpz_divmod(mpz_t* rop1, mpz_t* rop2, mpz_t* op1, mpz_t* op2) { +extern void jl_mpz_divmod(mpz_t* rop1, mpz_t* rop2, mpz_t* op1, mpz_t* op2) { mpz_divmod(*rop1, *rop2, *op1, *op2); } -extern void _jl_mpz_gcd(mpz_t* rop, mpz_t* op1, mpz_t* op2) { +extern void jl_mpz_gcd(mpz_t* rop, mpz_t* op1, mpz_t* op2) { mpz_gcd(*rop, *op1, *op2); } -extern void _jl_mpz_gcdext(mpz_t *g, mpz_t *s, mpz_t *t, mpz_t *a, mpz_t *b) { +extern void jl_mpz_gcdext(mpz_t *g, mpz_t *s, mpz_t *t, mpz_t *a, mpz_t *b) { mpz_gcdext(*g, *s, *t, *a, *b); } -extern void _jl_mpz_rem(mpz_t* rop, mpz_t* op1, mpz_t* op2) { +extern void jl_mpz_rem(mpz_t* rop, mpz_t* op1, mpz_t* op2) { mpz_fdiv_r(*rop, *op1, *op2); } -extern void _jl_mpz_neg(mpz_t* rop, mpz_t* op1) { +extern void jl_mpz_neg(mpz_t* rop, mpz_t* op1) { mpz_neg(*rop, *op1); } -extern void _jl_mpz_abs(mpz_t* rop, mpz_t* op1) { +extern void jl_mpz_abs(mpz_t* rop, mpz_t* op1) { mpz_abs(*rop, *op1); } -extern int _jl_mpz_cmp(mpz_t* op1, mpz_t* op2) { +extern int jl_mpz_cmp(mpz_t* op1, mpz_t* op2) { return mpz_cmp(*op1, *op2); } -extern void _jl_mpz_lshift(mpz_t* rop, mpz_t* base, unsigned long int count) { +extern void jl_mpz_lshift(mpz_t* rop, mpz_t* base, unsigned long int count) { mpz_mul_2exp(*rop, *base, count); } -extern void _jl_mpz_pow_ui(mpz_t* rop, mpz_t* base, unsigned long int exp) { +extern void jl_mpz_pow_ui(mpz_t* rop, mpz_t* base, unsigned long int exp) { mpz_pow_ui(*rop, *base, exp); } -extern void _jl_mpz_sqrt(mpz_t* rop, mpz_t* op) { +extern void jl_mpz_sqrt(mpz_t* rop, mpz_t* op) { mpz_sqrt(*rop, *op); } -extern void _jl_mpz_fac_ui(mpz_t* rop, unsigned long int op) { +extern void jl_mpz_fac_ui(mpz_t* rop, unsigned long int op) { mpz_fac_ui(*rop, op); } -extern void _jl_mpz_bin_ui(mpz_t* rop, mpz_t* n, unsigned long int k) { +extern void jl_mpz_bin_ui(mpz_t* rop, mpz_t* n, unsigned long int k) { mpz_bin_ui(*rop, *n, k); } -extern void _jl_mpz_bin_uiui(mpz_t* rop, unsigned long int n, unsigned long int k) { +extern void jl_mpz_bin_uiui(mpz_t* rop, unsigned long int n, unsigned long int k) { mpz_bin_uiui(*rop, n, k); } -extern char* _jl_mpz_printf(mpz_t* rop) { +extern char* jl_mpz_printf(mpz_t* rop) { char* pp; int s = gmp_asprintf(&pp, "%Zd", *rop); return pp; @@ -116,74 +116,74 @@ extern char* _jl_mpz_printf(mpz_t* rop) { //// MPF -extern void* _jl_mpf_init() +extern void* jl_mpf_init() { mpf_t* flt = malloc(sizeof(mpf_t)); mpf_init(*flt); return flt; } -extern void _jl_mpf_clear(mpf_t* rop) { +extern void jl_mpf_clear(mpf_t* rop) { mpf_clear(*rop); } -extern void _jl_mpf_set_string(mpf_t* rop, char* s) { +extern void jl_mpf_set_string(mpf_t* rop, char* s) { mpf_set_str(*rop, s, 0); } -extern void _jl_mpf_set_ui(mpf_t* rop, unsigned long int op) { +extern void jl_mpf_set_ui(mpf_t* rop, unsigned long int op) { mpf_set_ui(*rop, op); } -extern void _jl_mpf_set_si(mpf_t* rop, signed long int op) { +extern void jl_mpf_set_si(mpf_t* rop, signed long int op) { mpf_set_si(*rop, op); } -extern void _jl_mpf_set_d(mpf_t* rop, double op) { +extern void jl_mpf_set_d(mpf_t* rop, double op) { mpf_set_d(*rop, op); } -extern void _jl_mpf_set_z(mpf_t* rop, mpz_t* op) { +extern void jl_mpf_set_z(mpf_t* rop, mpz_t* op) { mpf_set_z(*rop, *op); } -extern void _jl_mpf_add(mpf_t* rop, mpf_t* op1, mpf_t* op2) { +extern void jl_mpf_add(mpf_t* rop, mpf_t* op1, mpf_t* op2) { mpf_add(*rop, *op1, *op2); } -extern void _jl_mpf_sub(mpf_t* rop, mpf_t* op1, mpf_t* op2) { +extern void jl_mpf_sub(mpf_t* rop, mpf_t* op1, mpf_t* op2) { mpf_sub(*rop, *op1, *op2); } -extern void _jl_mpf_mul(mpf_t* rop, mpf_t* op1, mpf_t* op2) { +extern void jl_mpf_mul(mpf_t* rop, mpf_t* op1, mpf_t* op2) { mpf_mul(*rop, *op1, *op2); } -extern void _jl_mpf_div(mpf_t* rop, mpf_t* op1, mpf_t* op2) { +extern void jl_mpf_div(mpf_t* rop, mpf_t* op1, mpf_t* op2) { mpf_div(*rop, *op1, *op2); } -extern void _jl_mpf_neg(mpf_t* rop, mpf_t* op1) { +extern void jl_mpf_neg(mpf_t* rop, mpf_t* op1) { mpf_neg(*rop, *op1); } -extern void _jl_mpf_abs(mpf_t* rop, mpf_t* op1) { +extern void jl_mpf_abs(mpf_t* rop, mpf_t* op1) { mpf_abs(*rop, *op1); } -extern int _jl_mpf_cmp(mpf_t* op1, mpf_t* op2) { +extern int jl_mpf_cmp(mpf_t* op1, mpf_t* op2) { return mpf_cmp(*op1, *op2); } -extern void _jl_mpf_pow_ui(mpf_t* rop, mpf_t* base, unsigned long int exp) { +extern void jl_mpf_pow_ui(mpf_t* rop, mpf_t* base, unsigned long int exp) { mpf_pow_ui(*rop, *base, exp); } -extern void _jl_mpf_sqrt(mpf_t* rop, mpf_t* op) { +extern void jl_mpf_sqrt(mpf_t* rop, mpf_t* op) { mpf_sqrt(*rop, *op); } -extern char* _jl_mpf_printf(mpf_t* rop) { +extern char* jl_mpf_printf(mpf_t* rop) { char* pp; gmp_asprintf(&pp, "%.Ff", *rop); return pp; @@ -193,19 +193,19 @@ extern char* _jl_mpf_printf(mpf_t* rop) { //Quick and dirty test of the gmp wrapper code int main( int argc, const char* argv[] ) { - void* rop = _jl_mpf_init(); - void* op1 = _jl_mpf_init(); + void* rop = jl_mpf_init(); + void* op1 = jl_mpf_init(); - _jl_mpf_set_string(op1, "123456789123456789123456789123456789"); + jl_mpf_set_string(op1, "123456789123456789123456789123456789"); - void* op2 = _jl_mpf_init(); - _jl_mpf_set_string(op2, "12345"); + void* op2 = jl_mpf_init(); + jl_mpf_set_string(op2, "12345"); - _jl_mpf_add(rop, op1, op2); + jl_mpf_add(rop, op1, op2); - printf("The sum is %s\n", _jl_mpf_printf(rop)); + printf("The sum is %s\n", jl_mpf_printf(rop)); - _jl_mpf_clear(rop); + jl_mpf_clear(rop); } diff --git a/deps/openlibm b/deps/openlibm index 00e0e7e5ee49b..07085279a1e8b 160000 --- a/deps/openlibm +++ b/deps/openlibm @@ -1 +1 @@ -Subproject commit 00e0e7e5ee49b7bf85f235b7020c19339469eb13 +Subproject commit 07085279a1e8be73fa7d6a2111a5a0ba10480518 diff --git a/deps/random/dSFMT.c.patch b/deps/random/dSFMT.c.patch new file mode 100644 index 0000000000000..055483135a789 --- /dev/null +++ b/deps/random/dSFMT.c.patch @@ -0,0 +1,100 @@ +--- dsfmt-2.2/dSFMT.c 2012-06-29 03:24:27.000000000 -0400 ++++ dSFMT-patched.c 2012-12-20 12:45:45.000000000 -0500 +@@ -32,13 +32,13 @@ + inline static uint32_t ini_func1(uint32_t x); + inline static uint32_t ini_func2(uint32_t x); + inline static void gen_rand_array_c1o2(dsfmt_t *dsfmt, w128_t *array, +- int size); ++ ptrdiff_t size); + inline static void gen_rand_array_c0o1(dsfmt_t *dsfmt, w128_t *array, +- int size); ++ ptrdiff_t size); + inline static void gen_rand_array_o0c1(dsfmt_t *dsfmt, w128_t *array, +- int size); ++ ptrdiff_t size); + inline static void gen_rand_array_o0o1(dsfmt_t *dsfmt, w128_t *array, +- int size); ++ ptrdiff_t size); + inline static int idxof(int i); + static void initial_mask(dsfmt_t *dsfmt); + static void period_certification(dsfmt_t *dsfmt); +@@ -142,8 +142,8 @@ + * @param size number of 128-bit pseudorandom numbers to be generated. + */ + inline static void gen_rand_array_c1o2(dsfmt_t *dsfmt, w128_t *array, +- int size) { +- int i, j; ++ ptrdiff_t size) { ++ ptrdiff_t i, j; + w128_t lung; + + lung = dsfmt->status[DSFMT_N]; +@@ -180,8 +180,8 @@ + * @param size number of 128-bit pseudorandom numbers to be generated. + */ + inline static void gen_rand_array_c0o1(dsfmt_t *dsfmt, w128_t *array, +- int size) { +- int i, j; ++ ptrdiff_t size) { ++ ptrdiff_t i, j; + w128_t lung; + + lung = dsfmt->status[DSFMT_N]; +@@ -223,8 +223,8 @@ + * @param size number of 128-bit pseudorandom numbers to be generated. + */ + inline static void gen_rand_array_o0o1(dsfmt_t *dsfmt, w128_t *array, +- int size) { +- int i, j; ++ ptrdiff_t size) { ++ ptrdiff_t i, j; + w128_t lung; + + lung = dsfmt->status[DSFMT_N]; +@@ -266,8 +266,8 @@ + * @param size number of 128-bit pseudorandom numbers to be generated. + */ + inline static void gen_rand_array_o0c1(dsfmt_t *dsfmt, w128_t *array, +- int size) { +- int i, j; ++ ptrdiff_t size) { ++ ptrdiff_t i, j; + w128_t lung; + + lung = dsfmt->status[DSFMT_N]; +@@ -453,7 +453,7 @@ + * memory. Mac OSX doesn't have these functions, but \b malloc of OSX + * returns the pointer to the aligned memory block. + */ +-void dsfmt_fill_array_close1_open2(dsfmt_t *dsfmt, double array[], int size) { ++void dsfmt_fill_array_close1_open2(dsfmt_t *dsfmt, double array[], ptrdiff_t size) { + assert(size % 2 == 0); + assert(size >= DSFMT_N64); + gen_rand_array_c1o2(dsfmt, (w128_t *)array, size / 2); +@@ -471,7 +471,7 @@ + * @param size the number of pseudorandom numbers to be generated. + * see also \sa fill_array_close1_open2() + */ +-void dsfmt_fill_array_open_close(dsfmt_t *dsfmt, double array[], int size) { ++void dsfmt_fill_array_open_close(dsfmt_t *dsfmt, double array[], ptrdiff_t size) { + assert(size % 2 == 0); + assert(size >= DSFMT_N64); + gen_rand_array_o0c1(dsfmt, (w128_t *)array, size / 2); +@@ -489,7 +489,7 @@ + * @param size the number of pseudorandom numbers to be generated. + * see also \sa fill_array_close1_open2() + */ +-void dsfmt_fill_array_close_open(dsfmt_t *dsfmt, double array[], int size) { ++void dsfmt_fill_array_close_open(dsfmt_t *dsfmt, double array[], ptrdiff_t size) { + assert(size % 2 == 0); + assert(size >= DSFMT_N64); + gen_rand_array_c0o1(dsfmt, (w128_t *)array, size / 2); +@@ -507,7 +507,7 @@ + * @param size the number of pseudorandom numbers to be generated. + * see also \sa fill_array_close1_open2() + */ +-void dsfmt_fill_array_open_open(dsfmt_t *dsfmt, double array[], int size) { ++void dsfmt_fill_array_open_open(dsfmt_t *dsfmt, double array[], ptrdiff_t size) { + assert(size % 2 == 0); + assert(size >= DSFMT_N64); + gen_rand_array_o0o1(dsfmt, (w128_t *)array, size / 2); diff --git a/deps/random/dSFMT.h.patch b/deps/random/dSFMT.h.patch index 7a4bfd423113a..72d41d411d055 100644 --- a/deps/random/dSFMT.h.patch +++ b/deps/random/dSFMT.h.patch @@ -1,6 +1,28 @@ ---- dSFMT.h 2012-06-29 12:54:27.000000000 +0530 -+++ dSFMT-julia.h 2012-09-22 23:02:26.000000000 +0530 -@@ -188,6 +188,7 @@ +--- dsfmt-2.2/dSFMT.h 2012-06-29 03:24:27.000000000 -0400 ++++ dSFMT-patched.h 2012-12-20 12:35:44.000000000 -0500 +@@ -40,6 +40,7 @@ + + #include + #include ++#include + + #if !defined(DSFMT_MEXP) + #ifdef __GNUC__ +@@ -178,16 +179,17 @@ + extern const int dsfmt_global_mexp; + + void dsfmt_gen_rand_all(dsfmt_t *dsfmt); +-void dsfmt_fill_array_open_close(dsfmt_t *dsfmt, double array[], int size); +-void dsfmt_fill_array_close_open(dsfmt_t *dsfmt, double array[], int size); +-void dsfmt_fill_array_open_open(dsfmt_t *dsfmt, double array[], int size); +-void dsfmt_fill_array_close1_open2(dsfmt_t *dsfmt, double array[], int size); ++void dsfmt_fill_array_open_close(dsfmt_t *dsfmt, double array[], ptrdiff_t size); ++void dsfmt_fill_array_close_open(dsfmt_t *dsfmt, double array[], ptrdiff_t size); ++void dsfmt_fill_array_open_open(dsfmt_t *dsfmt, double array[], ptrdiff_t size); ++void dsfmt_fill_array_close1_open2(dsfmt_t *dsfmt, double array[], ptrdiff_t size); + void dsfmt_chk_init_gen_rand(dsfmt_t *dsfmt, uint32_t seed, int mexp); + void dsfmt_chk_init_by_array(dsfmt_t *dsfmt, uint32_t init_key[], + int key_length, int mexp); const char *dsfmt_get_idstring(void); int dsfmt_get_min_array_size(void); @@ -8,7 +30,7 @@ #if defined(__GNUC__) # define DSFMT_PRE_INLINE inline static # define DSFMT_PST_INLINE __attribute__((always_inline)) -@@ -198,6 +199,10 @@ +@@ -198,6 +200,10 @@ # define DSFMT_PRE_INLINE inline static # define DSFMT_PST_INLINE #endif @@ -19,7 +41,25 @@ DSFMT_PRE_INLINE uint32_t dsfmt_genrand_uint32(dsfmt_t *dsfmt) DSFMT_PST_INLINE; DSFMT_PRE_INLINE double dsfmt_genrand_close1_open2(dsfmt_t *dsfmt) DSFMT_PST_INLINE; -@@ -236,7 +241,7 @@ +@@ -212,13 +218,13 @@ + DSFMT_PRE_INLINE double dsfmt_gv_genrand_close_open(void) DSFMT_PST_INLINE; + DSFMT_PRE_INLINE double dsfmt_gv_genrand_open_close(void) DSFMT_PST_INLINE; + DSFMT_PRE_INLINE double dsfmt_gv_genrand_open_open(void) DSFMT_PST_INLINE; +-DSFMT_PRE_INLINE void dsfmt_gv_fill_array_open_close(double array[], int size) ++DSFMT_PRE_INLINE void dsfmt_gv_fill_array_open_close(double array[], ptrdiff_t size) + DSFMT_PST_INLINE; +-DSFMT_PRE_INLINE void dsfmt_gv_fill_array_close_open(double array[], int size) ++DSFMT_PRE_INLINE void dsfmt_gv_fill_array_close_open(double array[], ptrdiff_t size) + DSFMT_PST_INLINE; +-DSFMT_PRE_INLINE void dsfmt_gv_fill_array_open_open(double array[], int size) ++DSFMT_PRE_INLINE void dsfmt_gv_fill_array_open_open(double array[], ptrdiff_t size) + DSFMT_PST_INLINE; +-DSFMT_PRE_INLINE void dsfmt_gv_fill_array_close1_open2(double array[], int size) ++DSFMT_PRE_INLINE void dsfmt_gv_fill_array_close1_open2(double array[], ptrdiff_t size) + DSFMT_PST_INLINE; + DSFMT_PRE_INLINE void dsfmt_gv_init_gen_rand(uint32_t seed) DSFMT_PST_INLINE; + DSFMT_PRE_INLINE void dsfmt_gv_init_by_array(uint32_t init_key[], +@@ -236,7 +242,7 @@ * @param dsfmt dsfmt internal state date * @return double precision floating point pseudorandom number */ @@ -28,7 +68,7 @@ uint32_t r; uint64_t *psfmt64 = &dsfmt->status[0].u[0]; -@@ -257,7 +262,7 @@ +@@ -257,7 +263,7 @@ * @param dsfmt dsfmt internal state date * @return double precision floating point pseudorandom number */ @@ -37,7 +77,7 @@ double r; double *psfmt64 = &dsfmt->status[0].d[0]; -@@ -276,7 +281,7 @@ +@@ -276,7 +282,7 @@ * before this function. This function uses \b global variables. * @return double precision floating point pseudorandom number */ @@ -46,7 +86,7 @@ return dsfmt_genrand_uint32(&dsfmt_global_data); } -@@ -287,7 +292,7 @@ +@@ -287,7 +293,7 @@ * before this function. This function uses \b global variables. * @return double precision floating point pseudorandom number */ @@ -55,7 +95,7 @@ return dsfmt_genrand_close1_open2(&dsfmt_global_data); } -@@ -299,7 +304,7 @@ +@@ -299,7 +305,7 @@ * @param dsfmt dsfmt internal state date * @return double precision floating point pseudorandom number */ @@ -64,7 +104,7 @@ return dsfmt_genrand_close1_open2(dsfmt) - 1.0; } -@@ -310,7 +315,7 @@ +@@ -310,7 +316,7 @@ * before this function. This function uses \b global variables. * @return double precision floating point pseudorandom number */ @@ -73,7 +113,7 @@ return dsfmt_gv_genrand_close1_open2() - 1.0; } -@@ -322,7 +327,7 @@ +@@ -322,7 +328,7 @@ * @param dsfmt dsfmt internal state date * @return double precision floating point pseudorandom number */ @@ -82,7 +122,7 @@ return 2.0 - dsfmt_genrand_close1_open2(dsfmt); } -@@ -333,7 +338,7 @@ +@@ -333,7 +339,7 @@ * before this function. This function uses \b global variables. * @return double precision floating point pseudorandom number */ @@ -91,7 +131,7 @@ return 2.0 - dsfmt_gv_genrand_close1_open2(); } -@@ -345,7 +350,7 @@ +@@ -345,7 +351,7 @@ * @param dsfmt dsfmt internal state date * @return double precision floating point pseudorandom number */ @@ -100,7 +140,7 @@ double *dsfmt64 = &dsfmt->status[0].d[0]; union { double d; -@@ -368,7 +373,7 @@ +@@ -368,7 +374,7 @@ * before this function. This function uses \b global variables. * @return double precision floating point pseudorandom number */ @@ -109,43 +149,43 @@ return dsfmt_genrand_open_open(&dsfmt_global_data); } -@@ -383,7 +388,7 @@ +@@ -383,7 +389,7 @@ * @param size the number of pseudorandom numbers to be generated. * see also \sa dsfmt_fill_array_close1_open2() */ -inline static void dsfmt_gv_fill_array_close1_open2(double array[], int size) { -+void dsfmt_gv_fill_array_close1_open2(double array[], int size) { ++void dsfmt_gv_fill_array_close1_open2(double array[], ptrdiff_t size) { dsfmt_fill_array_close1_open2(&dsfmt_global_data, array, size); } -@@ -399,7 +404,7 @@ +@@ -399,7 +405,7 @@ * see also \sa dsfmt_fill_array_close1_open2() and \sa * dsfmt_gv_fill_array_close1_open2() */ -inline static void dsfmt_gv_fill_array_open_close(double array[], int size) { -+void dsfmt_gv_fill_array_open_close(double array[], int size) { ++void dsfmt_gv_fill_array_open_close(double array[], ptrdiff_t size) { dsfmt_fill_array_open_close(&dsfmt_global_data, array, size); } -@@ -415,7 +420,7 @@ +@@ -415,7 +421,7 @@ * see also \sa dsfmt_fill_array_close1_open2() \sa * dsfmt_gv_fill_array_close1_open2() */ -inline static void dsfmt_gv_fill_array_close_open(double array[], int size) { -+void dsfmt_gv_fill_array_close_open(double array[], int size) { ++void dsfmt_gv_fill_array_close_open(double array[], ptrdiff_t size) { dsfmt_fill_array_close_open(&dsfmt_global_data, array, size); } -@@ -431,7 +436,7 @@ +@@ -431,7 +437,7 @@ * see also \sa dsfmt_fill_array_close1_open2() \sa * dsfmt_gv_fill_array_close1_open2() */ -inline static void dsfmt_gv_fill_array_open_open(double array[], int size) { -+void dsfmt_gv_fill_array_open_open(double array[], int size) { ++void dsfmt_gv_fill_array_open_open(double array[], ptrdiff_t size) { dsfmt_fill_array_open_open(&dsfmt_global_data, array, size); } -@@ -441,7 +446,7 @@ +@@ -441,7 +447,7 @@ * @param dsfmt dsfmt state vector. * @param seed a 32-bit integer used as the seed. */ @@ -154,7 +194,7 @@ dsfmt_chk_init_gen_rand(dsfmt, seed, DSFMT_MEXP); } -@@ -451,7 +456,7 @@ +@@ -451,7 +457,7 @@ * @param seed a 32-bit integer used as the seed. * see also \sa dsfmt_init_gen_rand() */ @@ -163,7 +203,7 @@ dsfmt_init_gen_rand(&dsfmt_global_data, seed); } -@@ -462,7 +467,7 @@ +@@ -462,7 +468,7 @@ * @param init_key the array of 32-bit integers, used as a seed. * @param key_length the length of init_key. */ @@ -172,7 +212,7 @@ int key_length) { dsfmt_chk_init_by_array(dsfmt, init_key, key_length, DSFMT_MEXP); } -@@ -475,7 +480,7 @@ +@@ -475,7 +481,7 @@ * @param key_length the length of init_key. * see also \sa dsfmt_init_by_array() */ @@ -181,7 +221,25 @@ dsfmt_init_by_array(&dsfmt_global_data, init_key, key_length); } -@@ -503,7 +508,7 @@ +@@ -489,13 +495,13 @@ + DSFMT_PRE_INLINE double genrand_close_open(void) DSFMT_PST_INLINE; + DSFMT_PRE_INLINE double genrand_open_close(void) DSFMT_PST_INLINE; + DSFMT_PRE_INLINE double genrand_open_open(void) DSFMT_PST_INLINE; +-DSFMT_PRE_INLINE void fill_array_open_close(double array[], int size) ++DSFMT_PRE_INLINE void fill_array_open_close(double array[], ptrdiff_t size) + DSFMT_PST_INLINE; +-DSFMT_PRE_INLINE void fill_array_close_open(double array[], int size) ++DSFMT_PRE_INLINE void fill_array_close_open(double array[], ptrdiff_t size) + DSFMT_PST_INLINE; +-DSFMT_PRE_INLINE void fill_array_open_open(double array[], int size) ++DSFMT_PRE_INLINE void fill_array_open_open(double array[], ptrdiff_t size) + DSFMT_PST_INLINE; +-DSFMT_PRE_INLINE void fill_array_close1_open2(double array[], int size) ++DSFMT_PRE_INLINE void fill_array_close1_open2(double array[], ptrdiff_t size) + DSFMT_PST_INLINE; + + /** +@@ -503,7 +509,7 @@ * @return id string. * see also \sa dsfmt_get_idstring() */ @@ -190,7 +248,7 @@ return dsfmt_get_idstring(); } -@@ -512,7 +517,7 @@ +@@ -512,7 +518,7 @@ * @return minimum size of array used for fill_array functions. * see also \sa dsfmt_get_min_array_size() */ @@ -199,7 +257,7 @@ return dsfmt_get_min_array_size(); } -@@ -521,7 +526,7 @@ +@@ -521,7 +527,7 @@ * @param seed a 32-bit integer used as the seed. * see also \sa dsfmt_gv_init_gen_rand(), \sa dsfmt_init_gen_rand(). */ @@ -208,7 +266,7 @@ dsfmt_gv_init_gen_rand(seed); } -@@ -531,7 +536,7 @@ +@@ -531,7 +537,7 @@ * @param key_length the length of init_key. * see also \sa dsfmt_gv_init_by_array(), \sa dsfmt_init_by_array(). */ @@ -217,7 +275,7 @@ dsfmt_gv_init_by_array(init_key, key_length); } -@@ -541,7 +546,7 @@ +@@ -541,7 +547,7 @@ * see also \sa dsfmt_genrand_close1_open2() \sa * dsfmt_gv_genrand_close1_open2() */ @@ -226,7 +284,7 @@ return dsfmt_gv_genrand_close1_open2(); } -@@ -551,7 +556,7 @@ +@@ -551,7 +557,7 @@ * see also \sa dsfmt_genrand_close_open() \sa * dsfmt_gv_genrand_close_open() */ @@ -235,7 +293,7 @@ return dsfmt_gv_genrand_close_open(); } -@@ -561,7 +566,7 @@ +@@ -561,7 +567,7 @@ * see also \sa dsfmt_genrand_open_close() \sa * dsfmt_gv_genrand_open_close() */ @@ -244,7 +302,7 @@ return dsfmt_gv_genrand_open_close(); } -@@ -571,7 +576,7 @@ +@@ -571,7 +577,7 @@ * see also \sa dsfmt_genrand_open_open() \sa * dsfmt_gv_genrand_open_open() */ @@ -253,39 +311,39 @@ return dsfmt_gv_genrand_open_open(); } -@@ -584,7 +589,7 @@ +@@ -584,7 +590,7 @@ * dsfmt_fill_array_close1_open2(), \sa * dsfmt_gv_fill_array_close1_open2() */ -inline static void fill_array_open_close(double array[], int size) { -+void fill_array_open_close(double array[], int size) { ++void fill_array_open_close(double array[], ptrdiff_t size) { dsfmt_gv_fill_array_open_close(array, size); } -@@ -597,7 +602,7 @@ +@@ -597,7 +603,7 @@ * dsfmt_fill_array_close1_open2(), \sa * dsfmt_gv_fill_array_close1_open2() */ -inline static void fill_array_close_open(double array[], int size) { -+void fill_array_close_open(double array[], int size) { ++void fill_array_close_open(double array[], ptrdiff_t size) { dsfmt_gv_fill_array_close_open(array, size); } -@@ -610,7 +615,7 @@ +@@ -610,7 +616,7 @@ * dsfmt_fill_array_close1_open2(), \sa * dsfmt_gv_fill_array_close1_open2() */ -inline static void fill_array_open_open(double array[], int size) { -+void fill_array_open_open(double array[], int size) { ++void fill_array_open_open(double array[], ptrdiff_t size) { dsfmt_gv_fill_array_open_open(array, size); } -@@ -622,7 +627,7 @@ +@@ -622,7 +628,7 @@ * see also \sa dsfmt_fill_array_close1_open2(), \sa * dsfmt_gv_fill_array_close1_open2() */ -inline static void fill_array_close1_open2(double array[], int size) { -+void fill_array_close1_open2(double array[], int size) { ++void fill_array_close1_open2(double array[], ptrdiff_t size) { dsfmt_gv_fill_array_close1_open2(array, size); } #endif /* DSFMT_DO_NOT_USE_OLD_NAMES */ diff --git a/deps/random/randmtzig.c b/deps/random/randmtzig.c index 226531c689223..adef147fa7186 100644 --- a/deps/random/randmtzig.c +++ b/deps/random/randmtzig.c @@ -55,6 +55,7 @@ #include #include +#include #include #include @@ -66,7 +67,7 @@ #include "dsfmt-2.2/dSFMT.c" #endif -typedef long randmtzig_idx_type; +typedef ptrdiff_t randmtzig_idx_type; typedef signed char randmtzig_int8_t; typedef unsigned char randmtzig_uint8_t; typedef short randmtzig_int16_t; diff --git a/doc/Makefile b/doc/Makefile index f4aba11a81206..263bc0a3ffa79 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -46,6 +46,7 @@ help: clean: -rm -rf $(BUILDDIR)/* + -rm -f sphinx/*.pyc clean-jquery: -rm -f $(JQUERYDEST) diff --git a/doc/helpdb.jl b/doc/helpdb.jl index 712106bc8b989..a5000efe12021 100644 --- a/doc/helpdb.jl +++ b/doc/helpdb.jl @@ -223,7 +223,7 @@ "), -(E"Getting Around",E"Base",E"whos",E"whos([Module][, pattern::Regex]) +(E"Getting Around",E"Base",E"whos",E"whos([Module,] [pattern::Regex]) Print information about global variables in a module, optionally restricted to those matching \"pattern\". @@ -917,14 +917,36 @@ collection[key...] = value "), -(E"Strings",E"Base",E"split",E"split(string, chars[, limit][, include_empty]) +(E"Strings",E"Base",E"replace",E"replace(string, pat, r[, n]) + + Search for the given pattern \"pat\", and replace each occurance + with \"r\". If \"n\" is provided, replace at most \"n\" occurances. + As with search, the second argument may be a single character, a + vector or a set of characters, a string, or a regular expression. + +"), + +(E"Strings",E"Base",E"replace",E"replace(string, pat, f[, n]) + + Search for the given pattern \"pat\", and replace each occurance + with \"f(pat)\". If \"n\" is provided, replace at most \"n\" + occurances. As with search, the second argument may be a single + character, a vector or a set of characters, a string, or a regular + expression. + +"), + +(E"Strings",E"Base",E"split",E"split(string, [chars, [limit,] [include_empty]]) Return an array of strings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by \"search\"'s second - argument. The last two arguments are optional; they are are a - maximum size for the result and a flag determining whether empty - fields should be included in the result. + argument (i.e. a single character, collection of characters, + string, or regular expression). If \"chars\" is omitted, it + defaults to the set of all space characters, and \"include_empty\" + is taken to be false. The last two arguments are also optional: + they are are a maximum size for the result and a flag determining + whether empty fields should be included in the result. "), @@ -1431,7 +1453,7 @@ collection[key...] = value "), -(E"Mathematical Functions",E"Base",E"atan2",E"atan2(x, y) +(E"Mathematical Functions",E"Base",E"atan2",E"atan2(y, x) Compute the inverse tangent of \"y/x\", using the signs of both \"x\" and \"y\" to determine the quadrant of the return value. @@ -1745,13 +1767,39 @@ collection[key...] = value (E"Mathematical Functions",E"Base",E"erf",E"erf(x) - Compute the error function of \"x\" + Compute the error function of \"x\", defined by + \\frac{2}{\\sqrt{\\pi}} \\int_0^x e^{-t^2} dt for arbitrary complex + \"x\". "), (E"Mathematical Functions",E"Base",E"erfc",E"erfc(x) - Compute the complementary error function of \"x\" + Compute the complementary error function of \"x\", defined by 1 - + \\operatorname{erf}(x). + +"), + +(E"Mathematical Functions",E"Base",E"erfcx",E"erfcx(x) + + Compute the scaled complementary error function of \"x\", defined + by e^{x^2} \\operatorname{erfc}(x). Note also that + \\operatorname{erfcx}(-ix) computes the Faddeeva function w(x). + +"), + +(E"Mathematical Functions",E"Base",E"erfi",E"erfi(x) + + Compute the imaginary error function of \"x\", defined by -i + \\operatorname{erf}(ix). + +"), + +(E"Mathematical Functions",E"Base",E"dawson",E"dawson(x) + + Compute the Dawson function (scaled imaginary error function) of + \"x\", defined by \\frac{\\sqrt{\\pi}}{2} e^{-x^2} + \\operatorname{erfi}(x). "), @@ -2486,6 +2534,13 @@ airyaiprime(x) "), +(E"Arrays",E"Base",E"bsxfun",E"bsxfun(fn, A, B[, C...]) + + Apply binary function \"fn\" to two or more arrays, with singleton + dimensions expanded. + +"), + (E"Arrays",E"Base",E"ref",E"ref(A, ind) Returns a subset of \"A\" as specified by \"ind\", which may be an @@ -2607,6 +2662,88 @@ airyaiprime(x) "), +(E"Sparse Matrices",E"Base",E"sparse",E"sparse(I, J, V[, m, n, combine]) + + Create a sparse matrix \"S\" of dimensions \"m x n\" such that + \"S[I[k], J[k]] = V[k]\". The \"combine\" function is used to + combine duplicates. If \"m\" and \"n\" are not specified, they are + set to \"max(I)\" and \"max(J)\" respectively. If the \"combine\" + function is not supplied, duplicates are added by default. + +"), + +(E"Sparse Matrices",E"Base",E"issparse",E"issparse(S) + + Returns \"true\" if \"S\" is sparse, and \"false\" otherwise. + +"), + +(E"Sparse Matrices",E"Base",E"nnz",E"nnz(S) + + Return the number of nonzeros in \"S\". + +"), + +(E"Sparse Matrices",E"Base",E"sparse",E"sparse(A) + + Convert a dense matrix \"A\" into a sparse matrix. + +"), + +(E"Sparse Matrices",E"Base",E"dense",E"dense(S) + + Convert a sparse matrix \"S\" into a dense matrix. + +"), + +(E"Sparse Matrices",E"Base",E"full",E"full(S) + + Convert a sparse matrix \"S\" into a dense matrix. + +"), + +(E"Sparse Matrices",E"Base",E"spzeros",E"spzeros(m, n) + + Create an empty sparse matrix of size \"m x n\". + +"), + +(E"Sparse Matrices",E"Base",E"speye",E"speye(type, m[, n]) + + Create a sparse identity matrix of specified type of size \"m x + m\". In case \"n\" is supplied, create a sparse identity matrix of + size \"m x n\". + +"), + +(E"Sparse Matrices",E"Base",E"spones",E"spones(S) + + Create a sparse matrix with the same structure as that of \"S\", + but with every nonzero element having the value \"1.0\". + +"), + +(E"Sparse Matrices",E"Base",E"sprand",E"sprand(m, n, density[, rng]) + + Create a random sparse matrix with the specified density. Nonzeros + are sampled from the distribution specified by \"rng\". The uniform + distribution is used in case \"rng\" is not specified. + +"), + +(E"Sparse Matrices",E"Base",E"sprandn",E"sprandn(m, n, density) + + Create a random sparse matrix of specified density with nonzeros + sampled from the normal distribution. + +"), + +(E"Sparse Matrices",E"Base",E"sprandbool",E"sprandbool(m, n, density) + + Create a random sparse boolean matrix with the specified density. + +"), + (E"Linear Algebra",E"Base",E"*",E"*() Matrix multiplication @@ -2713,15 +2850,16 @@ airyaiprime(x) "), -(E"Linear Algebra",E"Base",E"diag",E"diag(M) +(E"Linear Algebra",E"Base",E"diag",E"diag(M[, k]) - The diagonal of a matrix, as a vector + The \"k\"-th diagonal of a matrix, as a vector "), -(E"Linear Algebra",E"Base",E"diagm",E"diagm(v) +(E"Linear Algebra",E"Base",E"diagm",E"diagm(v[, k]) - Construct a diagonal matrix from a vector + Construct a diagonal matrix and place \"v\" on the \"k\"-th + diagonal "), @@ -2807,145 +2945,340 @@ airyaiprime(x) "), -(E"Combinatorics",E"Base",E"sort",E"sort(v) +(E"Combinatorics",E"Base",E"nthperm",E"nthperm(v, k) - Sort a vector in ascending order, according to \"isless\". + Compute the kth lexicographic permutation of a vector "), -(E"Combinatorics",E"Base",E"sort!",E"sort!(v) +(E"Combinatorics",E"Base",E"nthperm!",E"nthperm!(v, k) - In-place sort + In-place version of \"nthperm\" "), -(E"Combinatorics",E"Base",E"sortr",E"sortr(v) +(E"Combinatorics",E"Base",E"randperm",E"randperm(n) - Sort a vector in descending order + Construct a random permutation of the given length "), -(E"Combinatorics",E"Base",E"sortr!",E"sortr!(v) +(E"Combinatorics",E"Base",E"invperm",E"invperm(v) - In-place descending-order sort + Return the inverse permtation of v "), -(E"Combinatorics",E"Base",E"sort",E"sort(a, dim) +(E"Combinatorics",E"Base",E"isperm",E"isperm(v) - Sort an array along the given dimension + Returns true if v is a valid permutation "), -(E"Combinatorics",E"Base",E"sort",E"sort(lessthan, a[, dim]) +(E"Combinatorics",E"Base",E"randcycle",E"randcycle(n) - Sort with a custom comparison function + Construct a random cyclic permutation of the given length "), -(E"Combinatorics",E"Base",E"sortperm",E"sortperm(v) -> s,p +(E"Combinatorics",E"Base",E"shuffle",E"shuffle(v) - Sort a vector in ascending order, also constructing the permutation - that sorts the vector + Randomly rearrange the elements of a vector "), -(E"Combinatorics",E"Base",E"issorted",E"issorted(v) +(E"Combinatorics",E"Base",E"shuffle!",E"shuffle!(v) - Test whether a vector is in ascending sorted order + In-place version of \"shuffle\" "), -(E"Combinatorics",E"Base",E"nthperm",E"nthperm(v, k) +(E"Combinatorics",E"Base",E"reverse",E"reverse(v) - Compute the kth lexicographic permutation of a vector + Reverse vector \"v\" "), -(E"Combinatorics",E"Base",E"nthperm!",E"nthperm!(v, k) +(E"Combinatorics",E"Base",E"reverse!",E"reverse!(v) - In-place version of \"nthperm\" + Reverse vector \"v\" in-place "), -(E"Combinatorics",E"Base",E"randperm",E"randperm(n) +(E"Statistics",E"Base",E"mean",E"mean(v[, dim]) - Construct a random permutation of the given length + Compute the mean of whole array \"v\", or optionally along + dimension \"dim\" "), -(E"Combinatorics",E"Base",E"randcycle",E"randcycle(n) +(E"Statistics",E"Base",E"std",E"std(v[, corrected]) - Construct a random cyclic permutation of the given length + Compute the sample standard deviation of a vector \"v\". If the + optional argument \"corrected\" is either left unspecified or is + explicitly set to the default value of \"true\", then the algorithm + will return an estimator of the generative distribution's standard + deviation under the assumption that each entry of \"v\" is an IID + draw from that generative distribution. This computation is + equivalent to calculating \"sqrt(sum((v .- mean(v)).^2) / + (length(v) - 1))\" and involves an implicit correction term + sometimes called the Bessel correction which insures that the + estimator of the variance is unbiased. If, instead, the optional + argument \"corrected\" is set to \"false\", then the algorithm will + produce the equivalent of \"sqrt(sum((v .- mean(v)).^2) / + length(v))\", which is the empirical standard deviation of the + sample. "), -(E"Combinatorics",E"Base",E"shuffle",E"shuffle(v) +(E"Statistics",E"Base",E"std",E"std(v, m[, corrected]) - Randomly rearrange the elements of a vector + Compute the sample standard deviation of a vector \"v\" with known + mean \"m\". If the optional argument \"corrected\" is either left + unspecified or is explicitly set to the default value of \"true\", + then the algorithm will return an estimator of the generative + distribution's standard deviation under the assumption that each + entry of \"v\" is an IID draw from that generative distribution. + This computation is equivalent to calculating \"sqrt(sum((v .- + m).^2) / (length(v) - 1))\" and involves an implicit correction + term sometimes called the Bessel correction which insures that the + estimator of the variance is unbiased. If, instead, the optional + argument \"corrected\" is set to \"false\", then the algorithm will + produce the equivalent of \"sqrt(sum((v .- m).^2) / length(v))\", + which is the empirical standard deviation of the sample. "), -(E"Combinatorics",E"Base",E"shuffle!",E"shuffle!(v) +(E"Statistics",E"Base",E"var",E"var(v[, corrected]) - In-place version of \"shuffle\" + Compute the sample variance of a vector \"v\". If the optional + argument \"corrected\" is either left unspecified or is explicitly + set to the default value of \"true\", then the algorithm will + return an unbiased estimator of the generative distribution's + variance under the assumption that each entry of \"v\" is an IID + draw from that generative distribution. This computation is + equivalent to calculating \"sum((v .- mean(v)).^2) / (length(v) - + 1)\" and involves an implicit correction term sometimes called the + Bessel correction. If, instead, the optional argument \"corrected\" + is set to \"false\", then the algorithm will produce the equivalent + of \"sum((v .- mean(v)).^2) / length(v)\", which is the empirical + variance of the sample. "), -(E"Combinatorics",E"Base",E"reverse",E"reverse(v) +(E"Statistics",E"Base",E"var",E"var(v, m[, corrected]) - Reverse vector \"v\" + Compute the sample variance of a vector \"v\" with known mean + \"m\". If the optional argument \"corrected\" is either left + unspecified or is explicitly set to the default value of \"true\", + then the algorithm will return an unbiased estimator of the + generative distribution's variance under the assumption that each + entry of \"v\" is an IID draw from that generative distribution. + This computation is equivalent to calculating \"sum((v .- m)).^2) / + (length(v) - 1)\" and involves an implicit correction term + sometimes called the Bessel correction. If, instead, the optional + argument \"corrected\" is set to \"false\", then the algorithm will + produce the equivalent of \"sum((v .- m)).^2) / length(v)\", which + is the empirical variance of the sample. "), -(E"Combinatorics",E"Base",E"reverse!",E"reverse!(v) +(E"Statistics",E"Base",E"median",E"median(v) - Reverse vector \"v\" in-place + Compute the median of a vector \"v\" "), -(E"Combinatorics",E"Base",E"select",E"select(v, k) +(E"Statistics",E"Base",E"hist",E"hist(v[, n]) - Find the element in position \"k\" in the sorted vector \"v\" - without sorting + Compute the histogram of \"v\", optionally using \"n\" bins "), -(E"Combinatorics",E"Base",E"select!",E"select!(v, k) +(E"Statistics",E"Base",E"histc",E"histc(v, e) - In-place version of \"select\" + Compute the histogram of \"v\" using a vector \"e\" as the edges + for the bins "), -(E"Statistics",E"Base",E"mean",E"mean(v[, dim]) +(E"Statistics",E"Base",E"weighted_mean",E"weighted_mean(v, w) - Compute the mean of whole array \"v\", or optionally along - dimension \"dim\" + Compute the weighted mean of \"v\" using a vector of weights \"w\" "), -(E"Statistics",E"Base",E"std",E"std(v) +(E"Statistics",E"Base",E"mad",E"mad(v, m) - Compute the standard deviation of a vector \"v\" + Compute the median absolute deviation from the entries of a vector + \"v\" relative to a known median \"m\". The calculation involves an + adjustment factor of 1.4826 required to insure that the estimator + is consistent for normally distributed data. "), -(E"Statistics",E"Base",E"median",E"median(v) +(E"Statistics",E"Base",E"mad",E"mad(v) - Compute the median of a vector \"v\" + Compute the median absolute deviation from the entries of a vector + \"v\" relative to the median of \"v\". The calculation involves an + adjustment factor of 1.4826 required to insure that the estimator + is consistent for normally distributed data. "), -(E"Statistics",E"Base",E"hist",E"hist(v[, n]) +(E"Statistics",E"Base",E"skewness",E"skewness(v, m) - Compute the histogram of \"v\", optionally using \"n\" bins + Compute the sample skewness of a vector \"v\" relative to a known + mean \"m\". Uses a maximum likelihood estimator which can be + biased. "), -(E"Statistics",E"Base",E"histc",E"histc(v, e) +(E"Statistics",E"Base",E"skewness",E"skewness(v) - Compute the histogram of \"v\" using a vector \"e\" as the edges - for the bins + Compute the sample skewness of a vector \"v\" relative to the + sample mean. Uses a maximum likelihood estimator which can be + biased. + +"), + +(E"Statistics",E"Base",E"kurtosis",E"kurtosis(v, m) + + Compute the sample kurtosis of a vector \"v\" relative to a known + mean \"m\". Uses a maximum likelihood estimator which can be + biased. + +"), + +(E"Statistics",E"Base",E"kurtosis",E"kurtosis(v) + + Compute the sample kurtosis of a vector \"v\" relative to the + sample mean. Uses a maximum likelihood estimator which can be + biased. + +"), + +(E"Statistics",E"Base",E"quantile",E"quantile(v, p) + + Compute the quantiles of a vector \"v\" at a specified set of + probability values \"p\". + +"), + +(E"Statistics",E"Base",E"quantile",E"quantile(v) + + Compute the quantiles of a vector \"v\" at the probability values + \"[.0, .2, .4, .6, .8, 1.0]\". + +"), + +(E"Statistics",E"Base",E"quartile",E"quartile(v) + + Compute the quartiles of a vector \"v\" at the probability values + \"[.0, .25, .5, .75, 1.0]\". + +"), + +(E"Statistics",E"Base",E"quintile",E"quintile(v) + + Compute the quintiles of a vector \"v\" at the probability values + \"[.0, .2, .4, .6, .8, 1.0]\". + +"), + +(E"Statistics",E"Base",E"decile",E"decile(v) + + Compute the deciles of a vector \"v\" at the probability values + \"[.0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1.0]\". + +"), + +(E"Statistics",E"Base",E"iqr",E"iqr(v) + + Compute the interquantile range of a vector \"v\" at the + probability values \"[.25, .75]\". + +"), + +(E"Statistics",E"Base",E"tiedrank",E"tiedrank(v) + + Compute the ranks of the entries of vector \"v\". Ties are resolved + by taking the average rank over all tied values. + +"), + +(E"Statistics",E"Base",E"cov_pearson",E"cov_pearson(v1, v2) + + Compute the Pearson covariance between two vectors \"v1\" and + \"v2\". + +"), + +(E"Statistics",E"Base",E"cov_spearman",E"cov_spearman(v) + + Compute the Spearman covariance between two vectors \"v1\" and + \"v2\". + +"), + +(E"Statistics",E"Base",E"cov",E"cov(v) + + Compute the Pearson covariance between two vectors \"v1\" and + \"v2\". + +"), + +(E"Statistics",E"Base",E"cor_pearson",E"cor_pearson(v) + + Compute the Pearson correlation between two vectors \"v1\" and + \"v2\". + +"), + +(E"Statistics",E"Base",E"cor_spearman",E"cor_spearman(v) + + Compute the Spearman correlation between two vectors \"v1\" and + \"v2\". + +"), + +(E"Statistics",E"Base",E"cor",E"cor(v) + + Compute the Pearson correlation between two vectors \"v1\" and + \"v2\". + +"), + +(E"Statistics",E"Base",E"autocor",E"autocor(v, l) + + Compute the Pearson autocorrelation of a vector \"v\" with itself + at lag \"l\". + +"), + +(E"Statistics",E"Base",E"autocor",E"autocor(v) + + Compute the Pearson autocorrelation of a vector \"v\" with itself + at lag \"1\". + +"), + +(E"Statistics",E"Base",E"dist",E"dist(m) + + Compute the distance matrix between all of the rows of \"m\". + +"), + +(E"Statistics",E"Base",E"rle",E"rle(v) + + Compute a run-length encoding representation of a vector \"v\". + +"), + +(E"Statistics",E"Base",E"inverse_rle",E"inverse_rle(vals, lens) + + Compute a vector from its run-length vector representation as + values \"vals\" and run lengths \"lens\". "), @@ -2999,11 +3332,12 @@ airyaiprime(x) "), -(E"Signal Processing",E"Base",E"rfft",E"rfft(A[, dim=1]) +(E"Signal Processing",E"Base",E"rfft",E"rfft(A[, dim]) One-dimensional FFT of real array A along dimension dim. If A has size \"(..., n_dim, ...)\", the result has size \"(..., - floor(n_dim/2)+1, ...)\". + floor(n_dim/2)+1, ...)\". The \"dim\" argument is optional and + defaults to 1. "), @@ -5234,59 +5568,728 @@ eval_tab_col(glp_prob, k) "), -(E"Sound",E"Sound",E"wavread",E"wavread(io[, options]) +(E"Base.Sort",E"Base.Sort",E"sort",E"sort(v) - Reads and returns the samples from a RIFF/WAVE file. The samples - are converted to floating point values in the range from -1.0 to - 1.0 by default. The \"io\" argument accepts either an \"IO\" object - or a filename (\"String\"). The options are passed via an - \"Options\" object (see the \"OptionsMod\" module). + Sort a vector in ascending order, according to \"isless\". - The available options, and the default values, are: +"), - * \"format\" (default = \"double\"): changes the format of the - returned samples. The string \"double\" returns double precision - floating point values in the range -1.0 to 1.0. The string - \"native\" returns the values as encoded in the file. The string - \"size\" returns the number of samples in the file, rather than - the actual samples. +(E"Base.Sort",E"Base.Sort",E"sort!",E"sort!(v) - * \"subrange\" (default = \"Any\"): controls which samples are - returned. The default, \"Any\" returns all of the samples. - Passing a number (\"Real\"), \"N\", will return the first \"N\" - samples of each channel. Passing a range (\"Range1{Real}\"), - \"R\", will return the samples in that range of each channel. + In-place sort. - The returned values are: +"), - * \"y\": The acoustic samples; A matrix is returned for files that - contain multiple channels. +(E"Base.Sort",E"Base.Sort",E"sortr",E"sortr(v) - * \"Fs\": The sampling frequency + Sort a vector in descending order. - * \"nbits\": The number of bits used to encode each sample +"), - * \"extra\": Any additional bytes used to encode the samples (is - always \"None\") +(E"Base.Sort",E"Base.Sort",E"sortr!",E"sortr!(v) - The following functions are also defined to make this function - compatible with MATLAB: + In-place sort in descending-order. - wavread(filename::String) = wavread(filename, @options) - wavread(filename::String, fmt::String) = wavread(filename, @options format=fmt) - wavread(filename::String, N::Int) = wavread(filename, @options subrange=N) - wavread(filename::String, N::Range1{Int}) = wavread(filename, @options subrange=N) - wavread(filename::String, N::Int, fmt::String) = wavread(filename, @options subrange=N format=fmt) - wavread(filename::String, N::Range1{Int}, fmt::String) = wavread(filename, @options subrange=N format=fmt) +"), + +(E"Base.Sort",E"Base.Sort",E"sort_by",E"sort_by(by, v) + + Sort a vector by the result of applying function \"by\" to every + element. "), -(E"Sound",E"Sound",E"wavwrite",E"wavwrite(samples, io[, options]) +(E"Base.Sort",E"Base.Sort",E"sort_by!",E"sort_by!(by, v) - Writes samples to a RIFF/WAVE file io object. The \"io\" - argument accepts either an \"IO\" object or a filename - (\"String\"). The function assumes that the sample rate is 8 kHz - and uses 16 bits to encode each sample. Both of these values can + Sort a vector in place by the result of applying function \"by\" to + every element. + +"), + +(E"Base.Sort",E"Base.Sort",E"sort",E"sort(a, dim) + + Sort an array along the given dimension. + +"), + +(E"Base.Sort",E"Base.Sort",E"sort",E"sort(lessthan, a[, dim]) + + Sort with a custom comparison function. + +"), + +(E"Base.Sort",E"Base.Sort",E"sortperm",E"sortperm(v) -> s,p + + Sort a vector in ascending order, also constructing the permutation + that sorts the vector + +"), + +(E"Base.Sort",E"Base.Sort",E"sortperm!",E"sortperm!(v) -> s,p + + Sort a vector in ascending order in-place, also constructing the + permutation that sorts the vector + +"), + +(E"Base.Sort",E"Base.Sort",E"sortperm_r",E"sortperm_r(v) -> s,p + + Sort a vector in descending order, also constructing the + permutation that sorts the vector + +"), + +(E"Base.Sort",E"Base.Sort",E"sortperm_r!",E"sortperm_r!(v) -> s,p + + Sort a vector in descending order in-place, also constructing the + permutation that sorts the vector + +"), + +(E"Base.Sort",E"Base.Sort",E"sortperm_by",E"sortperm_by(by, v) -> s,p + + Sort a vector according to the result of function \"by\" applied to + all values, also constructing the permutation that sorts the + vector. + +"), + +(E"Base.Sort",E"Base.Sort",E"sortperm_by!",E"sortperm_by!(by, v) -> s,p + + Sort a vector in-place according to the result of function \"by\" + applied to all values of \"v\", also constructing the permutation + that sorts the vector + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort",E"insertionsort(v[, dim]) + + Sort a vector in ascending order with insertion sort, according to + \"isless\". + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort",E"insertionsort(lessthan, v[, dim]) + + Sort a vector in ascending order with insertion sort, using a + custom comparison function. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort!",E"insertionsort!(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort!",E"insertionsort!(v[, lo, hi]) + + In-place insertion sort, accoring to \"isless\". + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort!",E"insertionsort!(lessthan, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort!",E"insertionsort!(lessthan, v[, lo, hi]) + + In-place insertion sort with a custom comparison function. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_r",E"insertionsort_r(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_r",E"insertionsort_r(v[, lo, hi]) + + Sort a vector in descending order using insertion sort. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_r!",E"insertionsort_r!(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_r!",E"insertionsort_r!(v[, lo, hi]) + + In-place insertion sort in descending order. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_by",E"insertionsort_by(by, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_by",E"insertionsort_by(by, v[, lo, hi]) + + Sort a vector with insertion sort according to the result of + function \"by\" applied to all values. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_by!",E"insertionsort_by!(by, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_by!",E"insertionsort_by!(by, v[, lo, hi]) + + Sort a vector with insertion sort in place according to the result + of function \"by\" applied to all values. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_perm",E"insertionsort_perm(v[, p[, lo, hi]]) -> s,p + + Sort a vector in ascending order, also constructing the permutation + that sorts the vector + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_perm",E"insertionsort_perm(lessthan, v[, p[, lo, hi]]) -> s,p + + Sort a vector, using a custom comparison function, also + constructing the permutation that sorts the vector . + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_perm!",E"insertionsort_perm!(v[, p[, lo, hi]]) + + Sort a vector in ascending order in-place, also constructing the + permutation that sorts the vector + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_perm!",E"insertionsort_perm!(lessthan, v[, p[, lo, hi]]) + + Sort a vector in place, using a custom comparison function, also + constructing the permutation that sorts the vector . + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_perm_r",E"insertionsort_perm_r(v[, p[, lo, hi]]) + + Sort a vector in descending order, also constructing the + permutation that sorts the vector + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_perm_r!",E"insertionsort_perm_r!(v[, p[, lo, hi]]) + + Sort a vector in descending order in place, also constructing the + permutation that sorts the vector + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_perm_by",E"insertionsort_perm_by(by, v[, p[, lo, hi]]) + + Sort a vector with insertion sort according to the result of + function \"by\" applied to all values. + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"insertionsort_perm_by!",E"insertionsort_perm_by!(by, v[, p[, lo, hi]]) + + Sort a vector with insertion sort in place according to the result + of function \"by\" applied to all values. + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort",E"mergesort(v[, dim]) + + Sort a vector in ascending order with mergesort, according to + \"isless\". + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort",E"mergesort(lessthan, v[, dim]) + + Sort a vector in ascending order with mergesort, using a custom + comparison function. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort!",E"mergesort!(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort!",E"mergesort!(v[, lo, hi]) + + In-place mergesort, accoring to \"isless\". + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort!",E"mergesort!(lessthan, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort!",E"mergesort!(lessthan, v[, lo, hi]) + + In-place mergesort with a custom comparison function. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_r",E"mergesort_r(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_r",E"mergesort_r(v[, lo, hi]) + + Sort a vector in descending order using mergesort. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_r!",E"mergesort_r!(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_r!",E"mergesort_r!(v[, lo, hi]) + + In-place mergesort in descending order. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_by",E"mergesort_by(by, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_by",E"mergesort_by(by, v[, lo, hi]) + + Sort a vector with mergesort according to the result of function + \"by\" applied to all values. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_by!",E"mergesort_by!(by, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_by!",E"mergesort_by!(by, v[, lo, hi]) + + Sort a vector with mergesort in place according to the result of + function \"by\" applied to all values. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_perm",E"mergesort_perm(v[, p[, lo, hi]]) -> s,p + + Sort a vector in ascending order, also constructing the permutation + that sorts the vector + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_perm",E"mergesort_perm(lessthan, v[, p[, lo, hi]]) -> s,p + + Sort a vector, using a custom comparison function, also + constructing the permutation that sorts the vector . + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_perm!",E"mergesort_perm!(v[, p[, lo, hi]]) + + Sort a vector in ascending order in-place, also constructing the + permutation that sorts the vector + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_perm!",E"mergesort_perm!(lessthan, v[, p[, lo, hi]]) + + Sort a vector in place, using a custom comparison function, also + constructing the permutation that sorts the vector . + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_perm_r",E"mergesort_perm_r(v[, p[, lo, hi]]) + + Sort a vector in descending order, also constructing the + permutation that sorts the vector + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_perm_r!",E"mergesort_perm_r!(v[, p[, lo, hi]]) + + Sort a vector in descending order in place, also constructing the + permutation that sorts the vector + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_perm_by",E"mergesort_perm_by(by, v[, p[, lo, hi]]) + + Sort a vector with mergesort according to the result of function + \"by\" applied to all values. + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"mergesort_perm_by!",E"mergesort_perm_by!(by, v[, p[, lo, hi]]) + + Sort a vector with mergesort in place according to the result of + function \"by\" applied to all values. + + If provided, \"p\" is an initial permutation. + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort",E"quicksort(v[, dim]) + + Sort a vector in ascending order with quicksort, according to + \"isless\". + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort",E"quicksort(lessthan, v[, dim]) + + Sort a vector in ascending order with quicksort, using a custom + comparison function. + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort!",E"quicksort!(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort!",E"quicksort!(v[, lo, hi]) + + In-place quicksort, accoring to \"isless\". + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort!",E"quicksort!(lessthan, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort!",E"quicksort!(lessthan, v[, lo, hi]) + + In-place quicksort with a custom comparison function. + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort_r",E"quicksort_r(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort_r",E"quicksort_r(v[, lo, hi]) + + Sort a vector in descending order using quicksort. + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort_r!",E"quicksort_r!(v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort_r!",E"quicksort_r!(v[, lo, hi]) + + In-place quicksort in descending order. + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort_by",E"quicksort_by(by, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort_by",E"quicksort_by(by, v[, lo, hi]) + + Sort a vector with quicksort according to the result of function + \"by\" applied to all values. + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort_by!",E"quicksort_by!(by, v[, dim]) + +"), + +(E"Base.Sort",E"Base.Sort",E"quicksort_by!",E"quicksort_by!(by, v[, lo, hi]) + + Sort a vector with quicksort in place according to the result of + function \"by\" applied to all values. + +"), + +(E"Base.Sort",E"Base.Sort",E"issorted",E"issorted(v) + + Test whether a vector is in ascending sorted order + +"), + +(E"Base.Sort",E"Base.Sort",E"issorted_r",E"issorted_r(v) + + Test whether a vector is in descending sorted order + +"), + +(E"Base.Sort",E"Base.Sort",E"issorted_by",E"issorted_by(by, v) + + Test whether a vector is sorted by the result of function \"by\" + applied to all values of \"v\" + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted",E"search_sorted(a, x[, lo, hi]) + + For \"a\" sorted low to high, returns the index of the first value + \">=x\". + + \"lo\" and \"hi\" optionally limit the search range. + + Alias for \"search_sorted_first()\" + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted",E"search_sorted(lt, a, x[, lo, hi]) + + For \"a\" sorted using ordering function \"lt(x,y)\", returns the + index of the first value equal to \"x\" or following \"x\" in the + induced order + + \"lo\" and \"hi\" optionally limit the search range. + + Alias for \"search_sorted_first()\" + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_r",E"search_sorted_r(a, x[, lo, hi]) + + For \"a\" sorted high to low, returns the index of the first value + \"<=x\". + + \"lo\" and \"hi\" optionally limit the search range. + + Alias for \"search_sorted_first_r()\" + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_by",E"search_sorted_by(by, a, x[, lo, hi]) + + For \"a\" sorted according to the natural order of \"by(x)\" for + \"x\" in \"a\", returns the index of the first value equal to or + following \"x\" in the induced order. + + \"lo\" and \"hi\" optionally limit the search range. + + Alias for \"search_sorted_first_by()\" + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_first",E"search_sorted_first(a, x[, lo, hi]) + + For \"a\" sorted low to high, returns the index of the first + occurance of \"x\", or if \"x\" is not in \"a\", the index of the + first value following \"x\" in natural order. + + \"lo\" and \"hi\" optionally limit the search range. + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_first",E"search_sorted_first(lt, a, x[, lo, hi]) + + For \"a\" sorted using ordering function \"lt(x,y)\", returns the + index of the first occurance of \"x\", or if \"x\" is not in \"a\", + the index of the first value following \"x\" in the induced order. + + \"lo\" and \"hi\" optionally limit the search range. + + Alias for \"search_sorted_first()\" + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_first_r",E"search_sorted_first_r(a, x[, lo, hi]) + + For \"a\" sorted high to low, returns the index of the first + occurance of \"x\", or if \"x\" is not in \"a\", the index of the + first value following \"x\" in reverse natural order. + + \"lo\" and \"hi\" optionally limit the search range. + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_first_by",E"search_sorted_first_by(by, a, x[, lo, hi]) + + For \"a\" sorted according to the natural order of \"by(x)\" for + \"x\" in \"a\", returns the index of the first occurance of \"x\", + or if \"x\" is not in \"a\", the index of the first value following + \"x\" in the induced order. + + \"lo\" and \"hi\" optionally limit the search range. + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_last",E"search_sorted_last(a, x[, lo, hi]) + + For \"a\" sorted low to high, returns the index of the last + occurance of \"x\", or if \"x\" is not in \"a\", the index of the + last value preceding \"x\" in natural order. + + \"lo\" and \"hi\" optionally limit the search range. + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_last",E"search_sorted_last(lt, a, x[, lo, hi]) + + For \"a\" sorted using ordering function \"lt(x,y)\", returns the + index of the last occurance of``x``, or if \"x\" is not in \"a\", + the index of the last value preceding \"x\" in the induced order. + + \"lo\" and \"hi\" optionally limit the search range. + + Alias for \"search_sorted_last()\" + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_last_r",E"search_sorted_last_r(a, x[, lo, hi]) + + For \"a\" sorted high to low, returns the index of the last + occurance of \"x\", or if \"x\" is not in \"a\", the index of the + last value preceding \"x\" in reverse natural order. + + \"lo\" and \"hi\" optionally limit the search range. + +"), + +(E"Base.Sort",E"Base.Sort",E"search_sorted_last_by",E"search_sorted_last_by(by, a, x[, lo, hi]) + + For \"a\" sorted according to the natural order of \"by(x)\" for + \"x\" in \"a\", returns the index of the last occurance of \"x\", + or if \"x\" is not in \"a\", the index of the last value preceding + \"x\" in the induced order. + + \"lo\" and \"hi\" optionally limit the search range. + +"), + +(E"Base.Sort",E"Base.Sort",E"select",E"select(v, k) + + Find the element in position \"k\" in the sorted vector \"v\" + without sorting + +"), + +(E"Base.Sort",E"Base.Sort",E"select!",E"select!(v, k) + + Version of \"select\" which permutes the input vector in place. + +"), + +(E"Base.Sort",E"Base.Sort",E"select",E"select(lt, v, k) + + Find the element in position \"k\" in the vector \"v\" ordered by + \"lt\", without sorting. + +"), + +(E"Base.Sort",E"Base.Sort",E"select!",E"select!(lt, v, k) + + Version of \"select\" which permutes the input vector in place. + +"), + +(E"Base.Sort",E"Base.Sort",E"select_r",E"select_r(v, k) + + Find the element in position \"k\" in the reverse sorted vector + \"v\", without sorting. + +"), + +(E"Base.Sort",E"Base.Sort",E"select_r!",E"select_r!(v, k) + + Version of \"select_r\" which permutes the input vector in place. + +"), + +(E"Base.Sort",E"Base.Sort",E"select_by",E"select_by(by, v, k) + + Find the element in position \"k\" in the vector \"v\" as if sorted + by sort_by, without sorting. + +"), + +(E"Base.Sort",E"Base.Sort",E"select_by!",E"select_by!(by, v, k) + + Version of \"select_by\" which permutes the input vector in place. + +"), + +(E"Sound",E"Sound",E"wavread",E"wavread(io[, options]) + + Reads and returns the samples from a RIFF/WAVE file. The samples + are converted to floating point values in the range from -1.0 to + 1.0 by default. The \"io\" argument accepts either an \"IO\" object + or a filename (\"String\"). The options are passed via an + \"Options\" object (see the \"OptionsMod\" module). + + The available options, and the default values, are: + + * \"format\" (default = \"double\"): changes the format of the + returned samples. The string \"double\" returns double precision + floating point values in the range -1.0 to 1.0. The string + \"native\" returns the values as encoded in the file. The string + \"size\" returns the number of samples in the file, rather than + the actual samples. + + * \"subrange\" (default = \"Any\"): controls which samples are + returned. The default, \"Any\" returns all of the samples. + Passing a number (\"Real\"), \"N\", will return the first \"N\" + samples of each channel. Passing a range (\"Range1{Real}\"), + \"R\", will return the samples in that range of each channel. + + The returned values are: + + * \"y\": The acoustic samples; A matrix is returned for files that + contain multiple channels. + + * \"Fs\": The sampling frequency + + * \"nbits\": The number of bits used to encode each sample + + * \"extra\": Any additional bytes used to encode the samples (is + always \"None\") + + The following functions are also defined to make this function + compatible with MATLAB: + + wavread(filename::String) = wavread(filename, @options) + wavread(filename::String, fmt::String) = wavread(filename, @options format=fmt) + wavread(filename::String, N::Int) = wavread(filename, @options subrange=N) + wavread(filename::String, N::Range1{Int}) = wavread(filename, @options subrange=N) + wavread(filename::String, N::Int, fmt::String) = wavread(filename, @options subrange=N format=fmt) + wavread(filename::String, N::Range1{Int}, fmt::String) = wavread(filename, @options subrange=N format=fmt) + +"), + +(E"Sound",E"Sound",E"wavwrite",E"wavwrite(samples, io[, options]) + + Writes samples to a RIFF/WAVE file io object. The \"io\" + argument accepts either an \"IO\" object or a filename + (\"String\"). The function assumes that the sample rate is 8 kHz + and uses 16 bits to encode each sample. Both of these values can be changed with the options parameter. Each column of the data represents a different channel. Stereo files should contain two columns. The options are passed via an \"Options\" object (see @@ -5342,7 +6345,6 @@ eval_tab_col(glp_prob, k) "), - (E"strpack.jl",E"",E"pack",E"pack(io, composite[, strategy]) Create a packed buffer representation of \"composite\" in stream diff --git a/doc/manual/arrays.rst b/doc/manual/arrays.rst index da9b5bdd19cc3..596720cbe7ee3 100644 --- a/doc/manual/arrays.rst +++ b/doc/manual/arrays.rst @@ -271,6 +271,41 @@ one of the inputs is a scalar. ``sqrt``, ``cbrt``, ``erf``, ``erfc``, ``gamma``, ``lgamma``, ``real``, ``conj``, ``clamp`` +Broadcasting +------------ + +It is sometimes useful to perform element-by-element binary operations +on arrays of different sizes, such as adding a vector to each column +of a matrix. An inefficient way to do this would be to replicate the +vector to the size of the matrix:: + + julia> a = rand(2,1); A = rand(2,3); + + julia> repmat(a,1,3)+A + 2x3 Float64 Array: + 0.848333 1.66714 1.3262 + 1.26743 1.77988 1.13859 + +This is wasteful when dimensions get large, so Julia offers the +Matlab-inspired ``bsxfun``, which expands singleton dimensions in +array arguments to match the corresponding dimension in the other +array without using extra memory, and applies the given binary +function:: + + julia> bsxfun(+, a, A) + 2x3 Float64 Array: + 0.848333 1.66714 1.3262 + 1.26743 1.77988 1.13859 + + julia> b = rand(1,2) + 1x2 Float64 Array: + 0.629799 0.754948 + + julia> bsxfun(+, a, b) + 2x2 Float64 Array: + 1.31849 1.44364 + 1.56107 1.68622 + Implementation -------------- diff --git a/doc/manual/calling-c-and-fortran-code.rst b/doc/manual/calling-c-and-fortran-code.rst index d8b6de750b109..295f7162ccfd8 100644 --- a/doc/manual/calling-c-and-fortran-code.rst +++ b/doc/manual/calling-c-and-fortran-code.rst @@ -41,7 +41,7 @@ Julia. Finally, you can use ``ccall`` to actually generate a call to the library function. Arguments to ``ccall`` are as follows: -1. (:function, "library") pair. +1. (:function, "library") pair (must be a constant, but see below). 2. Return type, which may be any bits type, including ``Int32``, ``Int64``, ``Float64``, or ``Ptr{T}`` for any type parameter ``T``, indicating a pointer to values of type ``T``, or just ``Ptr`` for @@ -245,6 +245,23 @@ can be called via the following Julia code:: argv = [ "a.out", "arg1", "arg2" ] ccall(:main, Int32, (Int32, Ptr{Ptr{Uint8}}), length(argv), argv) +Non-constant Function Specifications +------------------------------------ + +A ``(name, library)`` function specification must be a constant expression. +However, it is possible to use computed values as function names by staging +through ``eval`` as follows: + + @eval ccall(($(strcat("a","b")), :lib), ... + +This expression constructs a name using ``strcat``, then substitutes this +name into a new ``ccall`` expression, which is then evaluated. Keep in mind that +``eval`` only operates at the top level, so within this expression local +variables will not be available (unless their values are substituted with +``$``). For this reason, ``eval`` is typically only used to form top-level +definitions, for example when wrapping libraries that contain many +similar functions. + Indirect calls -------------- diff --git a/doc/manual/performance-tips.rst b/doc/manual/performance-tips.rst index c9979f4acba32..cd2cf6dc6afba 100644 --- a/doc/manual/performance-tips.rst +++ b/doc/manual/performance-tips.rst @@ -177,7 +177,7 @@ The second form is also often better style and can lead to more code reuse. This pattern is used in several places in the standard library. For -example, see ``_jl_hvcat_fill`` in +example, see ``hvcat_fill`` in `abstractarray.jl `_, or the ``fill!`` function, which we could have used instead of writing our own ``fill_twos!``. diff --git a/doc/stdlib/base.rst b/doc/stdlib/base.rst index d8b5eb9b80772..c84fd2108300b 100644 --- a/doc/stdlib/base.rst +++ b/doc/stdlib/base.rst @@ -490,6 +490,14 @@ Strings Search for the given characters within the given string. The second argument may be a single character, a vector or a set of characters, a string, or a regular expression (but regular expressions are only allowed on contiguous strings, such as ASCII or UTF-8 strings). The third argument optionally specifies a starting index. The return value is a tuple with 2 integers: the index of the match and the first valid index past the match (or an index beyond the end of the string if the match is at the end); it returns ``(0,0)`` if no match was found, and ``(start,start)`` if ``chars`` is empty. +.. function:: replace(string, pat, r[, n]) + + Search for the given pattern ``pat``, and replace each occurance with ``r``. If ``n`` is provided, replace at most ``n`` occurances. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. + +.. function:: replace(string, pat, f[, n]) + + Search for the given pattern ``pat``, and replace each occurance with ``f(pat)``. If ``n`` is provided, replace at most ``n`` occurances. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. + .. function:: split(string, [chars, [limit,] [include_empty]]) Return an array of strings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by ``search``'s second argument (i.e. a single character, collection of characters, string, or regular expression). If ``chars`` is omitted, it defaults to the set of all space characters, and ``include_empty`` is taken to be false. The last two arguments are also optional: they are are a maximum size for the result and a flag determining whether empty fields should be included in the result. @@ -1016,11 +1024,31 @@ Mathematical Functions .. function:: erf(x) - Compute the error function of ``x`` + Compute the error function of ``x``, defined by + :math:`\frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} dt` + for arbitrary complex ``x``. .. function:: erfc(x) - Compute the complementary error function of ``x`` + Compute the complementary error function of ``x``, + defined by :math:`1 - \operatorname{erf}(x)`. + +.. function:: erfcx(x) + + Compute the scaled complementary error function of ``x``, + defined by :math:`e^{x^2} \operatorname{erfc}(x)`. Note + also that :math:`\operatorname{erfcx}(-ix)` computes the + Faddeeva function :math:`w(x)`. + +.. function:: erfi(x) + + Compute the imaginary error function of ``x``, + defined by :math:`-i \operatorname{erf}(ix)`. + +.. function:: dawson(x) + + Compute the Dawson function (scaled imaginary error function) of ``x``, + defined by :math:`\frac{\sqrt{\pi}}{2} e^{-x^2} \operatorname{erfi}(x)`. .. function:: real(z) @@ -1505,6 +1533,10 @@ Mathematical operators and functions All mathematical operations and functions are supported for arrays +.. function:: bsxfun(fn, A, B[, C...]) + + Apply binary function ``fn`` to two or more arrays, with singleton dimensions expanded. + Indexing, Assignment, and Concatenation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1703,13 +1735,13 @@ Linear algebra functions in Julia are largely implemented by calling functions f Lower triangle of a matrix -.. function:: diag(M) +.. function:: diag(M, [k]) - The diagonal of a matrix, as a vector + The ``k``-th diagonal of a matrix, as a vector -.. function:: diagm(v) +.. function:: diagm(v, [k]) - Construct a diagonal matrix from a vector + Construct a diagonal matrix and place ``v`` on the ``k``-th diagonal .. function:: Tridiagonal(dl, d, du) @@ -1723,9 +1755,13 @@ Linear algebra functions in Julia are largely implemented by calling functions f Compute the rank of a matrix -.. function:: cond(M) +.. function:: norm(A, [p]) - Matrix condition number + Compute the p-norm of a vector or a matrix. ``p`` is 2 by default, if not provided. The Frobenius norm of a matrix can be computed with ``norm(A, :fro)``. + +.. function:: cond(M, [p]) + + Matrix condition number, computed using the p-norm. ``p`` is 2 by default, if not provided. .. function:: trace(M) @@ -1766,38 +1802,6 @@ Linear algebra functions in Julia are largely implemented by calling functions f Combinatorics ------------- -.. function:: sort(v) - - Sort a vector in ascending order, according to ``isless``. - -.. function:: sort!(v) - - In-place sort - -.. function:: sortr(v) - - Sort a vector in descending order - -.. function:: sortr!(v) - - In-place descending-order sort - -.. function:: sort(a, dim) - - Sort an array along the given dimension - -.. function:: sort(lessthan, a, [dim]) - - Sort with a custom comparison function - -.. function:: sortperm(v) -> s,p - - Sort a vector in ascending order, also constructing the permutation that sorts the vector - -.. function:: issorted(v) - - Test whether a vector is in ascending sorted order - .. function:: nthperm(v, k) Compute the kth lexicographic permutation of a vector @@ -1810,6 +1814,14 @@ Combinatorics Construct a random permutation of the given length +.. function:: invperm(v) + + Return the inverse permtation of v + +.. function:: isperm(v) + + Returns true if v is a valid permutation + .. function:: randcycle(n) Construct a random cyclic permutation of the given length @@ -1830,14 +1842,6 @@ Combinatorics Reverse vector ``v`` in-place -.. function:: select(v, k) - - Find the element in position ``k`` in the sorted vector ``v`` without sorting - -.. function:: select!(v, k) - - In-place version of ``select`` - Statistics ---------- @@ -1845,9 +1849,21 @@ Statistics Compute the mean of whole array ``v``, or optionally along dimension ``dim`` -.. function:: std(v) +.. function:: std(v, [corrected]) + + Compute the sample standard deviation of a vector ``v``. If the optional argument ``corrected`` is either left unspecified or is explicitly set to the default value of ``true``, then the algorithm will return an estimator of the generative distribution's standard deviation under the assumption that each entry of ``v`` is an IID draw from that generative distribution. This computation is equivalent to calculating ``sqrt(sum((v .- mean(v)).^2) / (length(v) - 1))`` and involves an implicit correction term sometimes called the Bessel correction which insures that the estimator of the variance is unbiased. If, instead, the optional argument ``corrected`` is set to ``false``, then the algorithm will produce the equivalent of ``sqrt(sum((v .- mean(v)).^2) / length(v))``, which is the empirical standard deviation of the sample. + +.. function:: std(v, m, [corrected]) + + Compute the sample standard deviation of a vector ``v`` with known mean ``m``. If the optional argument ``corrected`` is either left unspecified or is explicitly set to the default value of ``true``, then the algorithm will return an estimator of the generative distribution's standard deviation under the assumption that each entry of ``v`` is an IID draw from that generative distribution. This computation is equivalent to calculating ``sqrt(sum((v .- m).^2) / (length(v) - 1))`` and involves an implicit correction term sometimes called the Bessel correction which insures that the estimator of the variance is unbiased. If, instead, the optional argument ``corrected`` is set to ``false``, then the algorithm will produce the equivalent of ``sqrt(sum((v .- m).^2) / length(v))``, which is the empirical standard deviation of the sample. + +.. function:: var(v, [corrected]) - Compute the standard deviation of a vector ``v`` + Compute the sample variance of a vector ``v``. If the optional argument ``corrected`` is either left unspecified or is explicitly set to the default value of ``true``, then the algorithm will return an unbiased estimator of the generative distribution's variance under the assumption that each entry of ``v`` is an IID draw from that generative distribution. This computation is equivalent to calculating ``sum((v .- mean(v)).^2) / (length(v) - 1)`` and involves an implicit correction term sometimes called the Bessel correction. If, instead, the optional argument ``corrected`` is set to ``false``, then the algorithm will produce the equivalent of ``sum((v .- mean(v)).^2) / length(v)``, which is the empirical variance of the sample. + +.. function:: var(v, m, [corrected]) + + Compute the sample variance of a vector ``v`` with known mean ``m``. If the optional argument ``corrected`` is either left unspecified or is explicitly set to the default value of ``true``, then the algorithm will return an unbiased estimator of the generative distribution's variance under the assumption that each entry of ``v`` is an IID draw from that generative distribution. This computation is equivalent to calculating ``sum((v .- m)).^2) / (length(v) - 1)`` and involves an implicit correction term sometimes called the Bessel correction. If, instead, the optional argument ``corrected`` is set to ``false``, then the algorithm will produce the equivalent of ``sum((v .- m)).^2) / length(v)``, which is the empirical variance of the sample. .. function:: median(v) @@ -1861,6 +1877,106 @@ Statistics Compute the histogram of ``v`` using a vector ``e`` as the edges for the bins +.. function:: weighted_mean(v, w) + + Compute the weighted mean of ``v`` using a vector of weights ``w`` + +.. function:: mad(v, m) + + Compute the median absolute deviation from the entries of a vector ``v`` relative to a known median ``m``. The calculation involves an adjustment factor of 1.4826 required to insure that the estimator is consistent for normally distributed data. + +.. function:: mad(v) + + Compute the median absolute deviation from the entries of a vector ``v`` relative to the median of ``v``. The calculation involves an adjustment factor of 1.4826 required to insure that the estimator is consistent for normally distributed data. + +.. function:: skewness(v, m) + + Compute the sample skewness of a vector ``v`` relative to a known mean ``m``. Uses a maximum likelihood estimator which can be biased. + +.. function:: skewness(v) + + Compute the sample skewness of a vector ``v`` relative to the sample mean. Uses a maximum likelihood estimator which can be biased. + +.. function:: kurtosis(v, m) + + Compute the sample kurtosis of a vector ``v`` relative to a known mean ``m``. Uses a maximum likelihood estimator which can be biased. + +.. function:: kurtosis(v) + + Compute the sample kurtosis of a vector ``v`` relative to the sample mean. Uses a maximum likelihood estimator which can be biased. + +.. function:: quantile(v, p) + + Compute the quantiles of a vector ``v`` at a specified set of probability values ``p``. + +.. function:: quantile(v) + + Compute the quantiles of a vector ``v`` at the probability values ``[.0, .2, .4, .6, .8, 1.0]``. + +.. function:: quartile(v) + + Compute the quartiles of a vector ``v`` at the probability values ``[.0, .25, .5, .75, 1.0]``. + +.. function:: quintile(v) + + Compute the quintiles of a vector ``v`` at the probability values ``[.0, .2, .4, .6, .8, 1.0]``. + +.. function:: decile(v) + + Compute the deciles of a vector ``v`` at the probability values ``[.0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1.0]``. + +.. function:: iqr(v) + + Compute the interquantile range of a vector ``v`` at the probability values ``[.25, .75]``. + +.. function:: tiedrank(v) + + Compute the ranks of the entries of vector ``v``. Ties are resolved by taking the average rank over all tied values. + +.. function:: cov_pearson(v1, v2) + + Compute the Pearson covariance between two vectors ``v1`` and ``v2``. + +.. function:: cov_spearman(v) + + Compute the Spearman covariance between two vectors ``v1`` and ``v2``. + +.. function:: cov(v) + + Compute the Pearson covariance between two vectors ``v1`` and ``v2``. + +.. function:: cor_pearson(v) + + Compute the Pearson correlation between two vectors ``v1`` and ``v2``. + +.. function:: cor_spearman(v) + + Compute the Spearman correlation between two vectors ``v1`` and ``v2``. + +.. function:: cor(v) + + Compute the Pearson correlation between two vectors ``v1`` and ``v2``. + +.. function:: autocor(v, l) + + Compute the Pearson autocorrelation of a vector ``v`` with itself at lag ``l``. + +.. function:: autocor(v) + + Compute the Pearson autocorrelation of a vector ``v`` with itself at lag ``1``. + +.. function:: dist(m) + + Compute the distance matrix between all of the rows of ``m``. + +.. function:: rle(v) + + Compute a run-length encoding representation of a vector ``v``. + +.. function:: inverse_rle(vals, lens) + + Compute a vector from its run-length vector representation as values ``vals`` and run lengths ``lens``. + Signal Processing ----------------- @@ -2073,7 +2189,7 @@ System Get the IP address of the local machine, as a string of the form "x.x.x.x". -.. function:: cwd() +.. function:: pwd() Get the current working directory. diff --git a/doc/stdlib/index.rst b/doc/stdlib/index.rst index 9ae98fcc94c48..0c59bf6ca535f 100644 --- a/doc/stdlib/index.rst +++ b/doc/stdlib/index.rst @@ -17,6 +17,15 @@ Built-ins base +**************** +Built-in Modules +**************** + +.. toctree:: + :maxdepth: 1 + + sort + ****** Extras ****** @@ -24,15 +33,15 @@ Extras .. toctree:: :maxdepth: 1 - profile - options + argparse cpp + options + gzip + profile + sound + strpack textwrap zlib - strpack - sound - argparse - gzip **************** Math & Numerical diff --git a/doc/stdlib/sort.rst b/doc/stdlib/sort.rst new file mode 100644 index 0000000000000..b80c64645cf7b --- /dev/null +++ b/doc/stdlib/sort.rst @@ -0,0 +1,613 @@ +:mod:`Base.Sort` --- Routines related to sorting +================================================================= + +.. module:: Base.Sort + :synopsis: Sort and related routines + +The `Sort` module contains algorithms and other functions related to +sorting. Default sort functions and standard versions of the various +sort algorithm are available by default. +Specific versions of unexported routines can be used by importing +`Sort`, or for finer grain control, importing the fully qualified +function name, e.g.,:: + + # Julia code + import Sort.timsort_perm! + +will allow use of the in-place version of timsort which provides a +permutation, which is not exported by default. All of the sorting +routines can be made available directly with:: + + # Julia code + using Sort + + +Overview +-------- + +Many users will simply want to use the default sort algorithms, which +allow sorting in ascending or descending order,:: + + # Julia code + julia> sort([2,3,1]) == [1,2,3] + true + + julia> sortr([2,3,1]) == [3,2,1] + true + +return a permutation,:: + + julia> v = [20,30,10] + 3-element Int64 Array: + 20 + 30 + 10 + + julia> (v2,p) = sortperm(v) + ([10, 20, 30],[3, 1, 2]) + + julia> v[p] + 3-element Int64 Array: + 10 + 20 + 30 + +and use a custom extractor function to order inputs:: + + julia> canonicalize(s) = filter(c -> ('A'<=c<='Z' || 'a'<=c<='z'), s) | uppercase + + julia> sort_by(canonicalize, ["New York", "New Jersey", "Nevada", "Nebraska", "Newark"]) + 5-element ASCIIString Array: + "Nebraska" + "Nevada" + "Newark" + "New Jersey" + "New York" + +Note that none of the variants above modify the original arrays. To sort in-place (which is often more efficient), each sort function has a mutating version which ends with an exclamation point (``sort!``, ``sortr!``, and ``sort_by!``). + +There are also versions of these functions which, in addition to returning a sorted array, will return the permutation of original indices which create the sorted array. These are ``sortperm``, ``sortperm_r``, and ``sortperm_by``, along with mutating versions ``sortperm!``, ``sortperm_r!``, and ``sortperm_by!``. + +These sort functions use reasonable default algorithms, but if you +want more control or want to see if a different sort algorithm will +work better on your data, read on... + + +Sort Algorithms +--------------- + +There are currently four main sorting algorithms available in Julia:: + + insertionsort + quicksort + mergesort + timsort + +Insertion sort is an O(n^2) stable sorting algorithm. It is +efficient for very small ``n``, and is used internally by +``quicksort!`` and ``timsort!``. + +Quicksort is an O(n log n) sorting algorithm. For efficiency, it +is not stable. It is among the fastest sorting algorithms. + +Mergesort is an O(n log n) stable sorting algorithm. + +Timsort is an O(n log n) stable adaptive sorting algorithm. It +takes advantage of sorted runs which exist in many real world +datasets. + +The ``sort``, ``sortr``, ``sort_by``, and ``sortperm`` functions select a reasonable +default algorithm, depending on the type of the target array. + +Mutating and non-mutating versions of the sort functions and of each +of the algorithm functions are exported and available for use by +default. + ++-------------------+--------------------+---------+-------------------+ +| Non-mutating | Mutating | Stable | Time Complexity | ++===================+====================+=========+===================+ +| ``sort`` | ``sort!`` | (\*) | O(n log n) | ++-------------------+--------------------+---------+-------------------+ +| ``sortr`` | ``sortr!`` | (\*) | O(n log n) | ++-------------------+--------------------+---------+-------------------+ +| ``sort_by`` | ``sort_by!`` | (\*) | O(n log n) | ++-------------------+--------------------+---------+-------------------+ +| ``sortperm`` | ``sortperm!`` | (\*) | O(n log n) | ++-------------------+--------------------+---------+-------------------+ +| ``insertionsort`` | ``insertionsort!`` | yes | O(n^2) | ++-------------------+--------------------+---------+-------------------+ +| ``quicksort`` | ``quicksort!`` | no | O(n log n) | ++-------------------+--------------------+---------+-------------------+ +| ``mergesort`` | ``mergesort!`` | yes | O(n log n) | ++-------------------+--------------------+---------+-------------------+ +| ``timsort`` | ``timsort!`` | yes | <= O(n log n) | ++-------------------+--------------------+---------+-------------------+ + +(\*) Stability depends on the algorithm for the target array data type. + +In addition to the exported functions shown in the table, each of the +algorithms also has an additional set of unexported functions for +reverse sorting, sorting by a function of the data, and for the stable +sorts, function varieties which return a permutation in addition to +the sorted array. These are shown in the table below. + ++----------------------+---------------------------+----------------------------+--------------------------+ +| Sort | Non-mutating Variation | Mutating Variation | Function | ++======================+===========================+============================+==========================+ +| ``insertionsort`` | ``insertionsort_r`` | ``insertionsort_r!`` | Reverse sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``insertionsort_by`` | ``insertionsort_by!`` | Sort by function | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``insertionsort_perm`` | ``insertionsort_perm!`` | Permutation sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``insertionsort_perm_r`` | ``insertionsort_perm_r!`` | Reverse permutation sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``insertionsort_perm_by`` | ``insertionsort_perm_by!`` | Permutation sort by func | ++----------------------+---------------------------+----------------------------+--------------------------+ +| ``mergesort`` | ``mergesort_r`` | ``mergesort_r!`` | Reverse sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``mergesort_by`` | ``mergesort_by!`` | Sort by function | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``mergesort_perm`` | ``mergesort_perm!`` | Permutation sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``mergesort_perm_r`` | ``mergesort_perm_r!`` | Reverse permutation sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``mergesort_perm_by`` | ``mergesort_perm_by!`` | Permutation sort by func | ++----------------------+---------------------------+----------------------------+--------------------------+ +| ``timsort`` | ``timsort_r`` | ``timsort_r!`` | Reverse sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``timsort_by`` | ``timsort_by!`` | Sort by function | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``timsort_perm`` | ``timsort_perm!`` | Permutation sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``timsort_perm_r`` | ``timsort_perm_r!`` | Reverse permutation sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``timsort_perm_by`` | ``timsort_perm_by!`` | Permutation sort by func | ++----------------------+---------------------------+----------------------------+--------------------------+ +| ``quicksort`` | ``quicksort_r`` | ``quicksort_r!`` | Reverse sort | ++----------------------+---------------------------+----------------------------+--------------------------+ +| | ``quicksort_by`` | ``quicksort_by!`` | Sort by function | ++----------------------+---------------------------+----------------------------+--------------------------+ + +Functions +--------- + +---------------------- +General Sort Functions +---------------------- +.. function:: sort(v) + + Sort a vector in ascending order, according to ``isless``. + +.. function:: sort!(v) + + In-place sort. + +.. function:: sortr(v) + + Sort a vector in descending order. + +.. function:: sortr!(v) + + In-place sort in descending-order. + +.. function:: sort_by(by, v) + + Sort a vector by the result of applying function ``by`` + to every element. + +.. function:: sort_by!(by, v) + + Sort a vector in place by the result of applying function ``by`` + to every element. + +.. function:: sort(a, dim) + + Sort an array along the given dimension. + +.. function:: sort(lessthan, a, [dim]) + + Sort with a custom comparison function. + +.. function:: sortperm(v) -> s,p + + Sort a vector in ascending order, also constructing the permutation that sorts the vector + +.. function:: sortperm!(v) -> s,p + + Sort a vector in ascending order in-place, also constructing the permutation that sorts the vector + +.. function:: sortperm_r(v) -> s,p + + Sort a vector in descending order, also constructing the permutation that sorts the vector + +.. function:: sortperm_r!(v) -> s,p + + Sort a vector in descending order in-place, also constructing the permutation that sorts the vector + +.. function:: sortperm_by(by,v) -> s,p + + Sort a vector according to the result of function ``by`` applied to + all values, also constructing the permutation that sorts the vector. + +.. function:: sortperm_by!(by,v) -> s,p + + Sort a vector in-place according to the result of function ``by`` + applied to all values of ``v``, also constructing the permutation + that sorts the vector + + +--------------------------- +Specific Sort Functions +--------------------------- + +.. function:: insertionsort(v[,dim]) + + Sort a vector in ascending order with insertion sort, according to ``isless``. + +.. function:: insertionsort(lessthan,v[,dim]) + + Sort a vector in ascending order with insertion sort, using a + custom comparison function. + +.. function:: insertionsort!(v[,dim]) +.. function:: insertionsort!(v[,lo,hi]) + + In-place insertion sort, accoring to ``isless``. + +.. function:: insertionsort!(lessthan,v[,dim]) +.. function:: insertionsort!(lessthan,v[,lo,hi]) + + In-place insertion sort with a custom comparison function. + +.. function:: insertionsort_r(v[,dim]) +.. function:: insertionsort_r(v[,lo,hi]) + + Sort a vector in descending order using insertion sort. + +.. function:: insertionsort_r!(v[,dim]) +.. function:: insertionsort_r!(v[,lo,hi]) + + In-place insertion sort in descending order. + +.. function:: insertionsort_by(by,v[,dim]) +.. function:: insertionsort_by(by,v[,lo,hi]) + + Sort a vector with insertion sort according to the result of + function ``by`` applied to all values. + +.. function:: insertionsort_by!(by,v[,dim]) +.. function:: insertionsort_by!(by,v[,lo,hi]) + + Sort a vector with insertion sort in place according to the result + of function ``by`` applied to all values. + +.. function:: insertionsort_perm(v[,p[,lo,hi]]) -> s,p + + Sort a vector in ascending order, also constructing the + permutation that sorts the vector + + If provided, ``p`` is an initial permutation. + +.. function:: insertionsort_perm(lessthan,v[,p[,lo,hi]]) -> s,p + + Sort a vector, using a custom comparison function, also + constructing the permutation that sorts the vector . + + If provided, ``p`` is an initial permutation. + +.. function:: insertionsort_perm!(v[,p[,lo,hi]]) + + Sort a vector in ascending order in-place, also constructing the + permutation that sorts the vector + + If provided, ``p`` is an initial permutation. + +.. function:: insertionsort_perm!(lessthan,v[,p[,lo,hi]]) + + Sort a vector in place, using a custom comparison function, also + constructing the permutation that sorts the vector . + + If provided, ``p`` is an initial permutation. + +.. function:: insertionsort_perm_r(v[,p,[,lo,hi]]) + + Sort a vector in descending order, also constructing the + permutation that sorts the vector + + If provided, ``p`` is an initial permutation. + +.. function:: insertionsort_perm_r!(v[,p,[,lo,hi]]) + + Sort a vector in descending order in place, also constructing the + permutation that sorts the vector + + If provided, ``p`` is an initial permutation. + +.. function:: insertionsort_perm_by(by,v[,p[,lo,hi]]) + + Sort a vector with insertion sort according to the result + of function ``by`` applied to all values. + + If provided, ``p`` is an initial permutation. + +.. function:: insertionsort_perm_by!(by,v[,p[,lo,hi]]) + + Sort a vector with insertion sort in place according to the result + of function ``by`` applied to all values. + + If provided, ``p`` is an initial permutation. + + +.. function:: mergesort(v[,dim]) + + Sort a vector in ascending order with mergesort, according to ``isless``. + +.. function:: mergesort(lessthan,v[,dim]) + + Sort a vector in ascending order with mergesort, using a + custom comparison function. + +.. function:: mergesort!(v[,dim]) +.. function:: mergesort!(v[,lo,hi]) + + In-place mergesort, accoring to ``isless``. + +.. function:: mergesort!(lessthan,v[,dim]) +.. function:: mergesort!(lessthan,v[,lo,hi]) + + In-place mergesort with a custom comparison function. + +.. function:: mergesort_r(v[,dim]) +.. function:: mergesort_r(v[,lo,hi]) + + Sort a vector in descending order using mergesort. + +.. function:: mergesort_r!(v[,dim]) +.. function:: mergesort_r!(v[,lo,hi]) + + In-place mergesort in descending order. + +.. function:: mergesort_by(by,v[,dim]) +.. function:: mergesort_by(by,v[,lo,hi]) + + Sort a vector with mergesort according to the result of + function ``by`` applied to all values. + +.. function:: mergesort_by!(by,v[,dim]) +.. function:: mergesort_by!(by,v[,lo,hi]) + + Sort a vector with mergesort in place according to the result + of function ``by`` applied to all values. + +.. function:: mergesort_perm(v[,p[,lo,hi]]) -> s,p + + Sort a vector in ascending order, also constructing the + permutation that sorts the vector + + If provided, ``p`` is an initial permutation. + +.. function:: mergesort_perm(lessthan,v[,p[,lo,hi]]) -> s,p + + Sort a vector, using a custom comparison function, also + constructing the permutation that sorts the vector . + + If provided, ``p`` is an initial permutation. + +.. function:: mergesort_perm!(v[,p[,lo,hi]]) + + Sort a vector in ascending order in-place, also constructing the + permutation that sorts the vector + + If provided, ``p`` is an initial permutation. + +.. function:: mergesort_perm!(lessthan,v[,p[,lo,hi]]) + + Sort a vector in place, using a custom comparison function, also + constructing the permutation that sorts the vector . + + If provided, ``p`` is an initial permutation. + +.. function:: mergesort_perm_r(v[,p,[,lo,hi]]) + + Sort a vector in descending order, also constructing the + permutation that sorts the vector + + If provided, ``p`` is an initial permutation. + +.. function:: mergesort_perm_r!(v[,p,[,lo,hi]]) + + Sort a vector in descending order in place, also constructing the + permutation that sorts the vector + + If provided, ``p`` is an initial permutation. + +.. function:: mergesort_perm_by(by,v[,p[,lo,hi]]) + + Sort a vector with mergesort according to the result + of function ``by`` applied to all values. + + If provided, ``p`` is an initial permutation. + +.. function:: mergesort_perm_by!(by,v[,p[,lo,hi]]) + + Sort a vector with mergesort in place according to the result + of function ``by`` applied to all values. + + If provided, ``p`` is an initial permutation. + + +.. function:: quicksort(v[,dim]) + + Sort a vector in ascending order with quicksort, according to ``isless``. + +.. function:: quicksort(lessthan,v[,dim]) + + Sort a vector in ascending order with quicksort, using a + custom comparison function. + +.. function:: quicksort!(v[,dim]) +.. function:: quicksort!(v[,lo,hi]) + + In-place quicksort, accoring to ``isless``. + +.. function:: quicksort!(lessthan,v[,dim]) +.. function:: quicksort!(lessthan,v[,lo,hi]) + + In-place quicksort with a custom comparison function. + +.. function:: quicksort_r(v[,dim]) +.. function:: quicksort_r(v[,lo,hi]) + + Sort a vector in descending order using quicksort. + +.. function:: quicksort_r!(v[,dim]) +.. function:: quicksort_r!(v[,lo,hi]) + + In-place quicksort in descending order. + +.. function:: quicksort_by(by,v[,dim]) +.. function:: quicksort_by(by,v[,lo,hi]) + + Sort a vector with quicksort according to the result of + function ``by`` applied to all values. + +.. function:: quicksort_by!(by,v[,dim]) +.. function:: quicksort_by!(by,v[,lo,hi]) + + Sort a vector with quicksort in place according to the result + of function ``by`` applied to all values. + +------------------------- +Sorting-related Functions +------------------------- + +.. function:: issorted(v) + + Test whether a vector is in ascending sorted order + +.. function:: issorted_r(v) + + Test whether a vector is in descending sorted order + +.. function:: issorted_by(by,v) + + Test whether a vector is sorted by the result of function ``by`` + applied to all values of ``v`` + +.. function:: search_sorted(a, x[, lo, hi]) + + For ``a`` sorted low to high, returns the index of the first value ``>=x``. + + ``lo`` and ``hi`` optionally limit the search range. + + Alias for ``search_sorted_first()`` + +.. function:: search_sorted(lt, a, x[, lo, hi]) + + For ``a`` sorted using ordering function ``lt(x,y)``, returns the index of the first value equal to ``x`` or following ``x`` in the induced order + + ``lo`` and ``hi`` optionally limit the search range. + + Alias for ``search_sorted_first()`` + +.. function:: search_sorted_r(a, x[, lo, hi]) + + For ``a`` sorted high to low, returns the index of the first value ``<=x``. + + ``lo`` and ``hi`` optionally limit the search range. + + Alias for ``search_sorted_first_r()`` + +.. function:: search_sorted_by(by, a, x[, lo, hi]) + + For ``a`` sorted according to the natural order of ``by(x)`` for ``x`` in ``a``, returns the index of the first value equal to or following ``x`` in the induced order. + + ``lo`` and ``hi`` optionally limit the search range. + + Alias for ``search_sorted_first_by()`` + +.. function:: search_sorted_first(a, x[, lo, hi]) + + For ``a`` sorted low to high, returns the index of the first occurance of ``x``, or if ``x`` is not in ``a``, the index of the first value following ``x`` in natural order. + + ``lo`` and ``hi`` optionally limit the search range. + +.. function:: search_sorted_first(lt, a, x[, lo, hi]) + + For ``a`` sorted using ordering function ``lt(x,y)``, returns the index of the first occurance of ``x``, or if ``x`` is not in ``a``, the index of the first value following ``x`` in the induced order. + + ``lo`` and ``hi`` optionally limit the search range. + + Alias for ``search_sorted_first()`` + +.. function:: search_sorted_first_r(a, x[, lo, hi]) + + For ``a`` sorted high to low, returns the index of the first occurance of ``x``, or if ``x`` is not in ``a``, the index of the first value following ``x`` in reverse natural order. + + ``lo`` and ``hi`` optionally limit the search range. + +.. function:: search_sorted_first_by(by, a, x[, lo, hi]) + + For ``a`` sorted according to the natural order of ``by(x)`` for ``x`` in ``a``, returns the index of the first occurance of ``x``, or if ``x`` is not in ``a``, the index of the first value following ``x`` in the induced order. + + ``lo`` and ``hi`` optionally limit the search range. + +.. function:: search_sorted_last(a, x[, lo, hi]) + + For ``a`` sorted low to high, returns the index of the last occurance of ``x``, or if ``x`` is not in ``a``, the index of the last value preceding ``x`` in natural order. + + ``lo`` and ``hi`` optionally limit the search range. + +.. function:: search_sorted_last(lt, a, x[, lo, hi]) + + For ``a`` sorted using ordering function ``lt(x,y)``, returns the index of the last occurance of``x``, or if ``x`` is not in ``a``, the index of the last value preceding ``x`` in the induced order. + + ``lo`` and ``hi`` optionally limit the search range. + + Alias for ``search_sorted_last()`` + +.. function:: search_sorted_last_r(a, x[, lo, hi]) + + For ``a`` sorted high to low, returns the index of the last occurance of ``x``, or if ``x`` is not in ``a``, the index of the last value preceding ``x`` in reverse natural order. + + ``lo`` and ``hi`` optionally limit the search range. + +.. function:: search_sorted_last_by(by, a, x[, lo, hi]) + + For ``a`` sorted according to the natural order of ``by(x)`` for ``x`` in ``a``, returns the index of the last occurance of ``x``, or if ``x`` is not in ``a``, the index of the last value preceding ``x`` in the induced order. + + ``lo`` and ``hi`` optionally limit the search range. + +.. function:: select(v, k) + + Find the element in position ``k`` in the sorted vector ``v`` without sorting + +.. function:: select!(v, k) + + Version of ``select`` which permutes the input vector in place. + +.. function:: select(lt, v, k) + + Find the element in position ``k`` in the vector ``v`` ordered by ``lt``, without sorting. + +.. function:: select!(lt, v, k) + + Version of ``select`` which permutes the input vector in place. + +.. function:: select_r(v, k) + + Find the element in position ``k`` in the reverse sorted vector ``v``, without sorting. + +.. function:: select_r!(v, k) + + Version of ``select_r`` which permutes the input vector in place. + +.. function:: select_by(by, v, k) + + Find the element in position ``k`` in the vector ``v`` as if sorted by sort_by, without sorting. + +.. function:: select_by!(by, v, k) + + Version of ``select_by`` which permutes the input vector in place. + diff --git a/examples/blksvd.jl b/examples/blksvd.jl index f35a55ff22be4..61d051ad2e28b 100644 --- a/examples/blksvd.jl +++ b/examples/blksvd.jl @@ -20,7 +20,7 @@ function bidiag(A::Matrix{Float64}, nb, nargout) X = zeros(m-k+1, nb) Y = zeros(n-k+1, nb) - ccall(dlsym(_jl_libLAPACK, :dlabrd_), Void, + ccall(dlsym(libLAPACK, :dlabrd_), Void, (Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, @@ -50,7 +50,7 @@ function bidiag(A::Matrix{Float64}, nb, nargout) tauqblk = zeros(s-k+1) taupblk = zeros(s-k+1) - ccall(dlsym(_jl_libLAPACK,:dgebd2_), Void, + ccall(dlsym(libLAPACK,:dgebd2_), Void, (Ptr{Int32}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Int32}), @@ -77,13 +77,13 @@ function bidiag(A::Matrix{Float64}, nb, nargout) if m >= n Q = copy(A0) - ccall(dlsym(_jl_libLAPACK,:dorgbr_), Void, + ccall(dlsym(libLAPACK,:dorgbr_), Void, (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Float64}, Ptr{Int32}, Ptr{Int32}), "Q", m, n, n, Q, m, tauq, zeros(s), s, 0) PT = A0 - ccall(dlsym(_jl_libLAPACK,:dorgbr_), Void, + ccall(dlsym(libLAPACK,:dorgbr_), Void, (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Float64}, Ptr{Int32}, Ptr{Int32}), @@ -91,14 +91,14 @@ function bidiag(A::Matrix{Float64}, nb, nargout) PT = PT[1:n,:] else Q = copy(A0) - ccall(dlsym(_jl_libLAPACK,:dorgbr_), Void, + ccall(dlsym(libLAPACK,:dorgbr_), Void, (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Float64}, Ptr{Int32}, Ptr{Int32}), "Q", m, m, n, Q, m, tauq, zeros(s), s, 0) Q = Q[:,1:m] PT = A0 - ccall(dlsym(_jl_libLAPACK,:dorgbr_), Void, + ccall(dlsym(libLAPACK,:dorgbr_), Void, (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Float64}, Ptr{Int32}, Ptr{Int32}), @@ -117,7 +117,7 @@ function blksvd(A::Matrix{Float64}, nargout) (Q, D, E, PT) = bidiag(A, nb, 4) if m >= n - ccall(dlsym(_jl_libLAPACK, :dbdsqr_), Void, + ccall(dlsym(libLAPACK, :dbdsqr_), Void, (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, @@ -125,7 +125,7 @@ function blksvd(A::Matrix{Float64}, nargout) "U", n, n, m, 0, D, E, PT, n, Q, m, zeros(1,1), 1, zeros(4*n,1), 0) else - ccall(dlsym(_jl_libLAPACK, :dbdsqr_), Void, + ccall(dlsym(libLAPACK, :dbdsqr_), Void, (Ptr{Uint8}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, diff --git a/examples/hpl.jl b/examples/hpl.jl index 627b4d875db49..6458037a2c5f7 100644 --- a/examples/hpl.jl +++ b/examples/hpl.jl @@ -218,7 +218,7 @@ function trailing_update_par(L_II, A_IJ, A_KI, A_KJ, row_dep, col_dep) if !isempty(A_KJ) m, k = size(A_KI) n = size(A_IJ,2) - _jl_blas_gemm('N','N',m,n,k,-1.0,A_KI,m,A_IJ,k,1.0,A_KJ,m) + blas_gemm('N','N',m,n,k,-1.0,A_KI,m,A_IJ,k,1.0,A_KJ,m) #A_KJ = A_KJ - A_KI*A_IJ end @@ -361,7 +361,7 @@ function trailing_update_par2(C, L_II, C_KI, i, j, n, flag, dep) if !isempty(C_KJ) cm, ck = size(C_KI) cn = size(C_IJ,2) - _jl_blas_gemm('N','N',cm,cn,ck,-1.0,C_KI,cm,C_IJ,ck,1.0,C_KJ,cm) + blas_gemm('N','N',cm,cn,ck,-1.0,C_KI,cm,C_IJ,ck,1.0,C_KJ,cm) #C_KJ = C_KJ - C_KI*C_IJ C[K,J] = C_KJ end diff --git a/examples/ndgrid.jl b/examples/ndgrid.jl index f6cbca97a1085..35e533fc2326a 100644 --- a/examples/ndgrid.jl +++ b/examples/ndgrid.jl @@ -7,7 +7,7 @@ function ndgrid{T}(v1::AbstractVector{T}, v2::AbstractVector{T}) (repmat(v1, 1, n), repmat(v2, m, 1)) end -function _jl_ndgrid_fill(a, v, s, snext) +function ndgrid_fill(a, v, s, snext) for j = 1:numel(a) a[j] = v[div(rem(j-1, snext), s)+1] end @@ -22,7 +22,7 @@ function ndgrid{T}(vs::AbstractVector{T}...) a = out[i]::Array v = vs[i] snext = s*size(a,i) - _jl_ndgrid_fill(a, v, s, snext) + ndgrid_fill(a, v, s, snext) s = snext end out diff --git a/examples/staged.jl b/examples/staged.jl index b8a19d5d39246..4e27bad553aa4 100644 --- a/examples/staged.jl +++ b/examples/staged.jl @@ -1,4 +1,4 @@ -function _jl_add_method(gf, an, at, body) +function add_method(gf, an, at, body) argexs = { expr(symbol("::"), an[i], at[i]) for i=1:length(an) } def = quote let __F__=($gf) @@ -32,7 +32,7 @@ macro staged(fdef) ($argtypes) = typeof(tuple($(argnames...))) if !method_exists($gengf, $argtypes) ($genbody) = apply(($expander), ($argtypes)) - _jl_add_method($gengf, {$(qargnames...)}, + add_method($gengf, {$(qargnames...)}, $argtypes, $genbody) end return ($gengf)($(argnames...)) diff --git a/extras/Makefile b/extras/Makefile index 1ec88005c62a5..e3d8fbd885eb4 100644 --- a/extras/Makefile +++ b/extras/Makefile @@ -20,4 +20,4 @@ webrepl_msgtypes_h.jl: ../ui/webserver/message_types.h $(QUIET_PERL) $(CC) -E -Dnotdefined $^ > $@ clean: - rm -f glpk_h.jl julia_message_types_h.jl + rm -f glpk_h.jl webrepl_msgtypes_h.jl diff --git a/extras/Rmath.jl b/extras/Rmath.jl index bf73e4b0dd68d..7a582e0b7211a 100644 --- a/extras/Rmath.jl +++ b/extras/Rmath.jl @@ -1,7 +1,6 @@ ## Interface to the Rmath library ## -_jl_libRmath = dlopen("libRmath") -macro _jl_libRmath_vectorize_3arg(f) +macro libRmath_vectorize_3arg(f) quote global $f ($f){T1<:Number, T2<:Number, T3<:Number}(x::AbstractArray{T1}, y::T2, z::T3) = @@ -35,10 +34,10 @@ end ## Is this version still needed? set_seed(a1::Integer, a2::Integer) = - ccall(dlsym(_jl_libRmath,:set_seed), Void, (Int32,Int32), a1, a2) + ccall((:set_seed, :libRmath), Void, (Int32,Int32), a1, a2) ## Vectorize over four numeric arguments -macro _jl_libRmath_vectorize_4arg(f) +macro libRmath_vectorize_4arg(f) quote global $f ($f){T1<:Number, T2<:Number, T3<:Number, T4<:Number}(a1::AbstractArray{T1}, a2::T2, a3::T3, a4::T4) = @@ -97,7 +96,7 @@ macro _jl_libRmath_vectorize_4arg(f) end ## Macro for deferring freeing data until GC for wilcox and signrank -macro _jl_libRmath_deferred_free(base) +macro libRmath_deferred_free(base) libcall = symbol(strcat(string(base), "_free")) func = symbol(strcat(string(base), "_deferred_free")) quote @@ -105,7 +104,7 @@ macro _jl_libRmath_deferred_free(base) global $func function $libcall(x::Vector{None}) gc_tracking_obj = [] - ccall(dlsym(_jl_libRmath, $(string(libcall))), Void, ()) + ccall(($(string(libcall)), :libRmath), Void, ()) end function $func() if !isa(gc_tracking_obj, Bool) @@ -118,7 +117,7 @@ macro _jl_libRmath_deferred_free(base) end ## Non-ccall functions for distributions with 1 parameter and no defaults -macro _jl_libRmath_1par_0d_aliases(base) +macro libRmath_1par_0d_aliases(base) dd = symbol(strcat("d", string(base))) pp = symbol(strcat("p", string(base))) qq = symbol(strcat("q", string(base))) @@ -146,7 +145,7 @@ macro _jl_libRmath_1par_0d_aliases(base) end ## Distributions with 1 parameter and no default -macro _jl_libRmath_1par_0d(base) +macro libRmath_1par_0d(base) dd = symbol(strcat("d", string(base))) pp = symbol(strcat("p", string(base))) qq = symbol(strcat("q", string(base))) @@ -154,43 +153,43 @@ macro _jl_libRmath_1par_0d(base) quote global $dd, $pp, $qq, $rr ($dd)(x::Number, p1::Number, give_log::Bool) = - ccall(dlsym(_jl_libRmath,$(string(dd))), Float64, (Float64,Float64,Int32), x, p1, give_log) + ccall(($(string(dd)), :libRmath), Float64, (Float64,Float64,Int32), x, p1, give_log) ($pp)(q::Number, p1::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(pp))), Float64, (Float64,Float64,Int32,Int32), q, p1, lower_tail, log_p) + ccall(($(string(pp)), :libRmath), Float64, (Float64,Float64,Int32,Int32), q, p1, lower_tail, log_p) ($qq)(p::Number, p1::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(qq))), Float64, (Float64,Float64,Int32,Int32), p, p1, lower_tail, log_p) + ccall(($(string(qq)), :libRmath), Float64, (Float64,Float64,Int32,Int32), p, p1, lower_tail, log_p) ($rr)(nn::Integer, p1::Number) = - [ ccall(dlsym(_jl_libRmath,$(string(rr))), Float64, (Float64,), p1) for i=1:nn ] - @_jl_libRmath_1par_0d_aliases $base + [ ccall(($(string(rr)), :libRmath), Float64, (Float64,), p1) for i=1:nn ] + @libRmath_1par_0d_aliases $base end end -@_jl_libRmath_1par_0d t # Student's t distribution (df) -@_jl_libRmath_1par_0d chisq # Central Chi-squared distribution (df) -@_jl_libRmath_1par_0d pois # Poisson distribution (lambda) -@_jl_libRmath_1par_0d geom # Geometric distribution (prob) +@libRmath_1par_0d t # Student's t distribution (df) +@libRmath_1par_0d chisq # Central Chi-squared distribution (df) +@libRmath_1par_0d pois # Poisson distribution (lambda) +@libRmath_1par_0d geom # Geometric distribution (prob) ## The d-p-q functions in Rmath for signrank allocate storage that must be freed ## Signrank - Wilcoxon Signed Rank statistic -@_jl_libRmath_deferred_free signrank +@libRmath_deferred_free signrank function dsignrank(x::Number, p1::Number, give_log::Bool) signrank_deferred_free() - ccall(dlsym(_jl_libRmath, "dsignrank"), Float64, (Float64,Float64,Int32), x, p1, give_log) + ccall((:dsignrank, :libRmath), Float64, (Float64,Float64,Int32), x, p1, give_log) end function psignrank(q::Number, p1::Number, lower_tail::Bool, log_p::Bool) signrank_deferred_free() - ccall(dlsym(_jl_libRmath, "psignrank"), Float64, (Float64,Float64,Int32,Int32), q, p1, lower_tail, log_p) + ccall((:psignrank, :libRmath), Float64, (Float64,Float64,Int32,Int32), q, p1, lower_tail, log_p) end function qsignrank(p::Number, p1::Number, lower_tail::Bool, log_p::Bool) signrank_deferred_free() - ccall(dlsym(_jl_libRmath, "qsignrank"), Float64, (Float64,Float64,Int32,Int32), p, p1, lower_tail, log_p) + ccall((:qsignrank, :libRmath), Float64, (Float64,Float64,Int32,Int32), p, p1, lower_tail, log_p) end -@_jl_libRmath_1par_0d_aliases signrank +@libRmath_1par_0d_aliases signrank rsignrank(nn::Integer, p1::Number) = - [ ccall(dlsym(_jl_libRmath, "rsignrank"), Float64, (Float64,), p1) for i=1:nn ] + [ ccall((:rsignrank, :libRmath), Float64, (Float64,), p1) for i=1:nn ] ## Distributions with 1 parameter and a default -macro _jl_libRmath_1par_1d(base, d1) +macro libRmath_1par_1d(base, d1) dd = symbol(strcat("d", string(base))) pp = symbol(strcat("p", string(base))) qq = symbol(strcat("q", string(base))) @@ -198,7 +197,7 @@ macro _jl_libRmath_1par_1d(base, d1) quote global $dd, $pp, $qq, $rr ($dd)(x::Number, p1::Number, give_log::Bool) = - ccall(dlsym(_jl_libRmath,$(string(dd))), Float64, (Float64,Float64,Int32), x, p1, give_log) + ccall(($(string(dd)), :libRmath), Float64, (Float64,Float64,Int32), x, p1, give_log) ($dd){T<:Number}(x::AbstractArray{T}, p1::Number, give_log::Bool) = reshape([ ($dd)(x[i], p1, give_log) for i=1:numel(x) ], size(x)) ($dd)(x::Number, give_log::Bool) = ($dd)(x, $d1, give_log) @@ -209,7 +208,7 @@ macro _jl_libRmath_1par_1d(base, d1) ($dd){T<:Number}(x::AbstractArray{T}) = ($dd)(x, $d1, false) ($pp)(q::Number, p1::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(pp))), Float64, (Float64,Float64,Int32,Int32), q, p1, lower_tail, log_p) + ccall(($(string(pp)), :libRmath), Float64, (Float64,Float64,Int32,Int32), q, p1, lower_tail, log_p) ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($pp)(q[i], p1, lower_tail, log_p) for i=1:numel(q) ], size(q)) ($pp)(q::Number, lower_tail::Bool, log_p::Bool) = ($pp)(q, $d1, lower_tail, log_p) @@ -224,7 +223,7 @@ macro _jl_libRmath_1par_1d(base, d1) ($pp){T<:Number}(q::AbstractArray{T}) = ($pp)(q, $d1, true, false) ($qq)(p::Number, p1::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(qq))), Float64, (Float64,Float64,Int32,Int32), p, p1, lower_tail, log_p) + ccall(($(string(qq)), :libRmath), Float64, (Float64,Float64,Int32,Int32), p, p1, lower_tail, log_p) ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($qq)(p[i], p1, lower_tail, log_p) for i=1:numel(p) ], size(p)) ($qq)(p::Number, lower_tail::Bool, log_p::Bool) = ($qq)(p, $d1, lower_tail, log_p) @@ -239,16 +238,16 @@ macro _jl_libRmath_1par_1d(base, d1) ($qq){T<:Number}(p::AbstractArray{T}) = ($qq)(p, $d1, true, false) ($rr)(nn::Integer, p1::Number) = - [ ccall(dlsym(_jl_libRmath,$(string(rr))), Float64, (Float64,), p1) for i=1:nn ] + [ ccall(($(string(rr)), :libRmath), Float64, (Float64,), p1) for i=1:nn ] ($rr)(nn::Integer) = ($rr)(nn, $d1) end end ## May need to handle this as a special case. The Rmath library uses 1/rate, not rate -@_jl_libRmath_1par_1d exp 1 # Exponential distribution (rate) +@libRmath_1par_1d exp 1 # Exponential distribution (rate) ## Non-ccall functions for distributions with 2 parameters and no defaults -macro _jl_libRmath_2par_0d_aliases(base) +macro libRmath_2par_0d_aliases(base) dd = symbol(strcat("d", string(base))) pp = symbol(strcat("p", string(base))) qq = symbol(strcat("q", string(base))) @@ -257,7 +256,7 @@ macro _jl_libRmath_2par_0d_aliases(base) ($dd){T<:Number}(x::AbstractArray{T}, p1::Number, p2::Number, give_log::Bool) = reshape([ ($dd)(x[i], p1, p2, give_log) for i=1:numel(x) ], size(x)) ($dd)(x::Number, p1::Number, p2::Number) = ($dd)(x, p1, p2, false) - @_jl_libRmath_vectorize_3arg $dd + @libRmath_vectorize_3arg $dd ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($pp)(q[i], p1, p2, lower_tail, log_p) for i=1:numel(q) ], size(q)) @@ -265,7 +264,7 @@ macro _jl_libRmath_2par_0d_aliases(base) ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool) = reshape([ ($pp)(q[i], p1, p2, lower_tail, false) for i=1:numel(q) ], size(q)) ($pp)(q::Number, p1::Number, p2::Number) = ($pp)(q, p1, p2, true, false) - @_jl_libRmath_vectorize_3arg $pp + @libRmath_vectorize_3arg $pp ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($qq)(p[i], p1, p2, lower_tail, log_p) for i=1:numel(p) ], size(p)) @@ -273,12 +272,12 @@ macro _jl_libRmath_2par_0d_aliases(base) ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool) = reshape([ ($qq)(p[i], p1, p2, lower_tail, false) for i=1:numel(p) ], size(p)) ($qq)(p::Number, p1::Number, p2::Number) = ($qq)(p, p1, p2, true, false) - @_jl_libRmath_vectorize_3arg $qq + @libRmath_vectorize_3arg $qq end end ## Distributions with 2 parameters and no defaults -macro _jl_libRmath_2par_0d(base) +macro libRmath_2par_0d(base) dd = symbol(strcat("d", string(base))) pp = symbol(strcat("p", string(base))) qq = symbol(strcat("q", string(base))) @@ -286,45 +285,45 @@ macro _jl_libRmath_2par_0d(base) quote global $dd, $pp, $qq, $rr ($dd)(x::Number, p1::Number, p2::Number, give_log::Bool) = - ccall(dlsym(_jl_libRmath,$(string(dd))), Float64, (Float64,Float64,Float64,Int32), x, p1, p2, give_log) + ccall(($(string(dd)), :libRmath), Float64, (Float64,Float64,Float64,Int32), x, p1, p2, give_log) ($pp)(q::Number, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(pp))), Float64, (Float64,Float64,Float64,Int32,Int32), q, p1, p2, lower_tail, log_p) + ccall(($(string(pp)), :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32), q, p1, p2, lower_tail, log_p) ($qq)(p::Number, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(qq))), Float64, (Float64,Float64,Float64,Int32,Int32), p, p1, p2, lower_tail, log_p) + ccall(($(string(qq)), :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32), p, p1, p2, lower_tail, log_p) ($rr)(nn::Integer, p1::Number, p2::Number) = - [ ccall(dlsym(_jl_libRmath,$(string(rr))), Float64, (Float64,Float64), p1, p2) for i=1:nn ] - @_jl_libRmath_2par_0d_aliases $base + [ ccall(($(string(rr)), :libRmath), Float64, (Float64,Float64), p1, p2) for i=1:nn ] + @libRmath_2par_0d_aliases $base end end -@_jl_libRmath_2par_0d f # Central F distribution (df1, df2) -@_jl_libRmath_2par_0d binom # Binomial distribution (size, prob) -@_jl_libRmath_2par_0d nbinom # Negative binomial distribution (size, prob) -@_jl_libRmath_2par_0d nbinom_mu # Negative binomial distribution (size, mu) -@_jl_libRmath_2par_0d beta # Beta distribution (shape1, shape2) -@_jl_libRmath_2par_0d nchisq # Noncentral Chi-squared distribution (df, ncp) +@libRmath_2par_0d f # Central F distribution (df1, df2) +@libRmath_2par_0d binom # Binomial distribution (size, prob) +@libRmath_2par_0d nbinom # Negative binomial distribution (size, prob) +@libRmath_2par_0d nbinom_mu # Negative binomial distribution (size, mu) +@libRmath_2par_0d beta # Beta distribution (shape1, shape2) +@libRmath_2par_0d nchisq # Noncentral Chi-squared distribution (df, ncp) ## Need to handle the d-p-q for Wilcox separately because the Rmath functions allocate storage that must be freed. ## Wilcox - Wilcox's Rank Sum statistic (m, n) - probably only makes sense for positive integers -@_jl_libRmath_deferred_free wilcox +@libRmath_deferred_free wilcox function dwilcox(x::Number, p1::Number, p2::Number, give_log::Bool) wilcox_deferred_free() - ccall(dlsym(_jl_libRmath,"dwilcox"), Float64, (Float64,Float64,Float64,Int32), x, p1, p2, give_log) + ccall((:dwilcox, :libRmath), Float64, (Float64,Float64,Float64,Int32), x, p1, p2, give_log) end function pwilcox(q::Number, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) wilcox_deferred_free() - ccall(dlsym(_jl_libRmath, "pwilcox"), Float64, (Float64,Float64,Float64,Int32,Int32), q, p1, p2, lower_tail, log_p) + ccall((:pwilcox, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32), q, p1, p2, lower_tail, log_p) end function qwilcox(p::Number, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) wilcox_deferred_free() - ccall(dlsym(_jl_libRmath, "qwilcox"), Float64, (Float64,Float64,Float64,Int32,Int32), p, p1, p2, lower_tail, log_p) + ccall((:qwilcox, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32), p, p1, p2, lower_tail, log_p) end rwilcox(nn::Integer, p1::Number, p2::Number) = - [ ccall(dlsym(_jl_libRmath, "rwilcox"), Float64, (Float64,Float64), p1, p2) for i=1:nn ] -@_jl_libRmath_2par_0d_aliases wilcox + [ ccall((:rwilcox, :libRmath), Float64, (Float64,Float64), p1, p2) for i=1:nn ] +@libRmath_2par_0d_aliases wilcox ## Distributions with 2 parameters and 1 default -macro _jl_libRmath_2par_1d(base, d2) +macro libRmath_2par_1d(base, d2) dd = symbol(strcat("d", string(base))) pp = symbol(strcat("p", string(base))) qq = symbol(strcat("q", string(base))) @@ -332,18 +331,18 @@ macro _jl_libRmath_2par_1d(base, d2) quote global $dd, $pp, $qq, $rr ($dd)(x::Number, p1::Number, p2::Number, give_log::Bool) = - ccall(dlsym(_jl_libRmath,$(string(dd))), Float64, (Float64,Float64,Float64,Int32), x, p1, p2, give_log) + ccall(($(string(dd)), :libRmath), Float64, (Float64,Float64,Float64,Int32), x, p1, p2, give_log) ($dd){T<:Number}(x::AbstractArray{T}, p1::Number, p2::Number, give_log::Bool) = reshape([ ($dd)(x[i], p1, p2, give_log) for i=1:numel(x) ], size(x)) ($dd)(x::Number, p1::Number, give_log::Bool) = ($dd)(x, p1, $d2, give_log) ($dd){T<:Number}(x::AbstractArray{T}, p1::Number, give_log::Bool) = ($dd)(x, p1, $d2, give_log) ($dd)(x::Number, p1::Number, p2::Number) = ($dd)(x, p1, p2, false) - @_jl_libRmath_vectorize_3arg $dd + @libRmath_vectorize_3arg $dd ($dd)(x::Number, p1::Number) = ($dd)(x, p1, $d2, false) @vectorize_2arg Number $dd ($pp)(q::Number, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(pp))), Float64, (Float64,Float64,Float64,Int32,Int32), q, p1, p2, lower_tail, log_p) + ccall(($(string(pp)), :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32), q, p1, p2, lower_tail, log_p) ($pp)(q::Number, p1::Number, lower_tail::Bool, log_p::Bool) = ($pp)(q, p1, $d2, lower_tail, log_p) ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($pp)(q[i], p1, p2, lower_tail, log_p) for i=1:numel(q) ], size(q)) @@ -353,12 +352,12 @@ macro _jl_libRmath_2par_1d(base, d2) ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool) = ($pp)(q, p1, p2, lower_tail, false) ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, lower_tail::Bool) = ($pp)(q, p1, $d2, lower_tail, false) ($pp)(q::Number, p1::Number, p2::Number) = ($pp)(q, p1, p2, true, false) - @_jl_libRmath_vectorize_3arg $pp + @libRmath_vectorize_3arg $pp ($pp)(q::Number, p1::Number) = ($pp)(q, p1, $d2, true, false) @vectorize_2arg Number $pp ($qq)(p::Number, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(qq))), Float64, (Float64,Float64,Float64,Int32,Int32), p, p1, p2, lower_tail, log_p) + ccall(($(string(qq)), :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32), p, p1, p2, lower_tail, log_p) ($qq)(p::Number, p1::Number, lower_tail::Bool, log_p::Bool) = ($qq)(p, p1, $d2, lower_tail, log_p) ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($qq)(p[i], p1, p2, lower_tail, log_p) for i=1:numel(p) ], size(p)) @@ -368,21 +367,21 @@ macro _jl_libRmath_2par_1d(base, d2) ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool) = ($qq)(p, p1, p2, lower_tail, false) ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, lower_tail::Bool) = ($qq)(p, p1, $d2, lower_tail, false) ($qq)(p::Number, p1::Number, p2::Number) = ($qq)(p, p1, p2, true, false) - @_jl_libRmath_vectorize_3arg $qq + @libRmath_vectorize_3arg $qq ($qq)(p::Number, p1::Number) = ($qq)(p, p1, $d2, true, false) @vectorize_2arg Number $qq ($rr)(nn::Integer, p1::Number, p2::Number) = - [ ccall(dlsym(_jl_libRmath,$(string(rr))), Float64, (Float64,Float64), p1, p2) for i=1:nn ] + [ ccall(($(string(rr)), :libRmath), Float64, (Float64,Float64), p1, p2) for i=1:nn ] ($rr)(nn::Integer, p1::Number) = ($rr)(nn, p1, $d2) end end -@_jl_libRmath_2par_1d gamma 1 # Gamma distribution (shape, scale) -@_jl_libRmath_2par_1d weibull 1 # Weibull distribution (shape, scale) +@libRmath_2par_1d gamma 1 # Gamma distribution (shape, scale) +@libRmath_2par_1d weibull 1 # Weibull distribution (shape, scale) ## Distributions with 2 parameters and 2 defaults -macro _jl_libRmath_2par_2d(base, d1, d2) +macro libRmath_2par_2d(base, d1, d2) ddsym = dd = symbol(strcat("d", string(base))) ppsym = pp = symbol(strcat("p", string(base))) qqsym = qq = symbol(strcat("q", string(base))) @@ -395,7 +394,7 @@ macro _jl_libRmath_2par_2d(base, d1, d2) quote global $dd, $pp, $qq, $rr ($dd)(x::Number, p1::Number, p2::Number, give_log::Bool) = - ccall(dlsym(_jl_libRmath,$(string(ddsym))), Float64, (Float64,Float64,Float64,Int32), x, p1, p2, give_log) + ccall(($(string(ddsym)), :libRmath), Float64, (Float64,Float64,Float64,Int32), x, p1, p2, give_log) ($dd){T<:Number}(x::AbstractArray{T}, p1::Number, p2::Number, give_log::Bool) = reshape([ ($dd)(x[i], p1, p2, give_log) for i=1:numel(x) ], size(x)) ($dd)(x::Number, p1::Number, give_log::Bool) = ($dd)(x, p1, $d2, give_log) @@ -403,7 +402,7 @@ macro _jl_libRmath_2par_2d(base, d1, d2) ($dd)(x::Number, give_log::Bool) = ($dd)(x, $d1, $d2, give_log) ($dd){T<:Number}(x::AbstractArray{T}, give_log::Bool) = ($dd)(x, $d1, $d2, give_log) ($dd)(x::Number, p1::Number, p2::Number) = ($dd)(x, p1, p2, false) - @_jl_libRmath_vectorize_3arg $dd + @libRmath_vectorize_3arg $dd ($dd)(x::Number, p1::Number) = ($dd)(x, p1, $d2, false) @vectorize_2arg Number $dd ($dd)(x::Number) = ($dd)(x, $d1, $d2, false) @@ -411,7 +410,7 @@ macro _jl_libRmath_2par_2d(base, d1, d2) ($pp)(q::Number, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(ppsym))), Float64, (Float64,Float64,Float64,Int32,Int32), q, p1, p2, lower_tail, log_p) + ccall(($(string(ppsym)), :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32), q, p1, p2, lower_tail, log_p) ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($pp)(q[i], p1, p2, lower_tail, log_p) for i=1:numel(q) ], size(q)) ($pp)(q::Number, p1::Number, lower_tail::Bool, log_p::Bool) = ($pp)(q, p1, $d2, lower_tail, log_p) @@ -425,14 +424,14 @@ macro _jl_libRmath_2par_2d(base, d1, d2) ($pp)(q::Number, lower_tail::Bool) = ($pp)(q, $d1, $d2, lower_tail, false) ($pp){T<:Number}(q::AbstractArray{T}, lower_tail::Bool) = ($pp)(q, $d1, $d2, lower_tail, false) ($pp)(q::Number, p1::Number, p2::Number) = ($pp)(q, p1, p2, true, false) - @_jl_libRmath_vectorize_3arg $pp + @libRmath_vectorize_3arg $pp ($pp)(q::Number, p1::Number) = ($pp)(q, p1, $d2, true, false) @vectorize_2arg Number $pp ($pp)(q::Number) = ($pp)(q, $d1, $d2, true, false) ($pp){T<:Number}(q::AbstractArray{T}) = ($pp)(q, $d1, $d2, true, false) ($qq)(p::Number, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(qqsym))), Float64, (Float64,Float64,Float64,Int32,Int32), p, p1, p2, lower_tail, log_p) + ccall(($(string(qqsym)), :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32), p, p1, p2, lower_tail, log_p) ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, p2::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($qq)(p[i], p1, p2, lower_tail, log_p) for i=1:numel(p) ], size(p)) ($qq)(p::Number, p1::Number, lower_tail::Bool, log_p::Bool) = ($qq)(p, p1, $d2, lower_tail, log_p) @@ -446,27 +445,27 @@ macro _jl_libRmath_2par_2d(base, d1, d2) ($qq)(p::Number, lower_tail::Bool) = ($qq)(p, $d1, $d2, lower_tail, false) ($qq){T<:Number}(p::AbstractArray{T}, lower_tail::Bool) = ($qq)(p, $d1, $d2, lower_tail, false) ($qq)(p::Number, p1::Number, p2::Number) = ($qq)(p, p1, p2, true, false) - @_jl_libRmath_vectorize_3arg $qq + @libRmath_vectorize_3arg $qq ($qq)(p::Number, p1::Number) = ($qq)(p, p1, $d2, true, false) @vectorize_2arg Number $qq ($qq)(p::Number) = ($qq)(p, $d1, $d2, true, false) ($qq){T<:Number}(p::AbstractArray{T}) = ($qq)(p, $d1, $d2, true, false) ($rr)(nn::Integer, p1::Number, p2::Number) = - [ ccall(dlsym(_jl_libRmath,$(string(rr))), Float64, (Float64,Float64), p1, p2) for i=1:nn ] + [ ccall(($(string(rr)), :libRmath), Float64, (Float64,Float64), p1, p2) for i=1:nn ] ($rr)(nn::Integer, p1::Number) = ($rr)(nn, p1, $d2) ($rr)(nn::Integer) = ($rr)(nn, $d1, $d2) end end -@_jl_libRmath_2par_2d cauchy 0 1 # Cauchy distribution (location, scale) -@_jl_libRmath_2par_2d lnorm 0 1 # Log-normal distribution (meanlog, sdlog) -@_jl_libRmath_2par_2d logis 0 1 # Logistic distribution (location, scale) -@_jl_libRmath_2par_2d norm 0 1 # Normal (Gaussian) distribution (mu, sd) -@_jl_libRmath_2par_2d unif 0 1 # Uniform distribution (min, max) +@libRmath_2par_2d cauchy 0 1 # Cauchy distribution (location, scale) +@libRmath_2par_2d lnorm 0 1 # Log-normal distribution (meanlog, sdlog) +@libRmath_2par_2d logis 0 1 # Logistic distribution (location, scale) +@libRmath_2par_2d norm 0 1 # Normal (Gaussian) distribution (mu, sd) +@libRmath_2par_2d unif 0 1 # Uniform distribution (min, max) ## Distributions with 3 parameters and no defaults -macro _jl_libRmath_3par_0d(base) +macro libRmath_3par_0d(base) dd = symbol(strcat("d", string(base))) pp = symbol(strcat("p", string(base))) qq = symbol(strcat("q", string(base))) @@ -474,48 +473,48 @@ macro _jl_libRmath_3par_0d(base) quote global $dd, $pp, $qq, $rr ($dd)(x::Number, p1::Number, p2::Number, p3::Number, give_log::Bool) = - ccall(dlsym(_jl_libRmath,$(string(dd))), Float64, (Float64,Float64,Float64,Float64,Int32), x, p1, p2, p3, give_log) + ccall(($(string(dd)), :libRmath), Float64, (Float64,Float64,Float64,Float64,Int32), x, p1, p2, p3, give_log) ($dd){T<:Number}(x::AbstractArray{T}, p1::Number, p2::Number, p3::Number, give_log::Bool) = reshape([ ($dd)(x[i], p1, p2, p3, give_log) for i=1:numel(x) ], size(x)) ($dd)(x::Number, p1::Number, p2::Number, p3::Number) = ($dd)(x, p1, p2, p3, false) - @_jl_libRmath_vectorize_4arg $dd + @libRmath_vectorize_4arg $dd ($pp)(q::Number, p1::Number, p2::Number, p3::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(pp))), Float64, (Float64,Float64,Float64,Float64,Int32,Int32), q, p1, p2, p3, lower_tail, log_p) + ccall(($(string(pp)), :libRmath), Float64, (Float64,Float64,Float64,Float64,Int32,Int32), q, p1, p2, p3, lower_tail, log_p) ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, p2::Number, p3::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($pp)(q[i], p1, p2, p3, lower_tail, log_p) for i=1:numel(q) ], size(q)) ($pp)(q::Number, p1::Number, p2::Number, p3::Number, lower_tail::Bool) = ($pp)(q, p1, p2, p3, lower_tail, false) ($pp){T<:Number}(q::AbstractArray{T}, p1::Number, p2::Number, p3::Number, lower_tail::Bool) = reshape([ ($pp)(q[i], p1, p2, p3, lower_tail, false) for i=1:numel(q) ], size(q)) ($pp)(q::Number, p1::Number, p2::Number, p3::Number) = ($pp)(q, p1, p2, p3, true, false) - @_jl_libRmath_vectorize_4arg $pp + @libRmath_vectorize_4arg $pp ($qq)(p::Number, p1::Number, p2::Number, p3::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath,$(string(qq))), Float64, (Float64,Float64,Float64,Float64,Int32,Int32), p, p1, p2, p3, lower_tail, log_p) + ccall(($(string(qq)), :libRmath), Float64, (Float64,Float64,Float64,Float64,Int32,Int32), p, p1, p2, p3, lower_tail, log_p) ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, p2::Number, p3::Number, lower_tail::Bool, log_p::Bool) = reshape([ ($qq)(p[i], p1, p2, p3, lower_tail, log_p) for i=1:numel(p) ], size(p)) ($qq)(p::Number, p1::Number, p2::Number, p3::Number, lower_tail::Bool) = ($qq)(p, p1, p2, p3, lower_tail, false) ($qq){T<:Number}(p::AbstractArray{T}, p1::Number, p2::Number, p3::Number, lower_tail::Bool) = reshape([ ($qq)(p[i], p1, p2, p3, lower_tail, false) for i=1:numel(p) ], size(p)) ($qq)(p::Number, p1::Number, p2::Number, p3::Number) = ($qq)(p, p1, p2, p3, true, false) - @_jl_libRmath_vectorize_4arg $qq + @libRmath_vectorize_4arg $qq ($rr)(nn::Integer, p1::Number, p2::Number, p3::Number) = - [ ccall(dlsym(_jl_libRmath,$(string(rr))), Float64, (Float64,Float64,Float64), p1, p2, p3) for i=1:nn ] + [ ccall(($(string(rr)), :libRmath), Float64, (Float64,Float64,Float64), p1, p2, p3) for i=1:nn ] end end -@_jl_libRmath_3par_0d hyper # Hypergeometric (m, n, k) -@_jl_libRmath_3par_0d nbeta # Non-central beta (shape1, shape2, ncp) -@_jl_libRmath_3par_0d nf # Non-central F (df1, df2, ncp) +@libRmath_3par_0d hyper # Hypergeometric (m, n, k) +@libRmath_3par_0d nbeta # Non-central beta (shape1, shape2, ncp) +@libRmath_3par_0d nf # Non-central F (df1, df2, ncp) ## tukey (Studentized Range Distribution - p and q only - 3pars) ptukey(q::Number, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath, :ptukey), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,lower_tail,log_p) + ccall((:ptukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,lower_tail,log_p) ptukey(q::Number, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool) = - ccall(dlsym(_jl_libRmath, :ptukey), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,lower_tail,false) + ccall((:ptukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,lower_tail,false) ptukey(q::Number, nmeans::Number, df::Number, nranges::Number) = - ccall(dlsym(_jl_libRmath, :ptukey), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,true,false) + ccall((:ptukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,true,false) ptukey{T<:Number}(q::AbstractArray{T}, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool, log_p::Bool) = reshape([ptukey(q[i],nmeans,df,nranges,lower_tail,log_p) for i=1:numel(q)], size(q)) ptukey{T<:Number}(q::AbstractArray{T}, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool) = @@ -525,13 +524,13 @@ ptukey{T<:Number}(q::AbstractArray{T}, nmeans::Number, df::Number, nranges::Numb ## tukey (Studentized Range Distribution - p and q only - 3pars) ptukey(q::Number, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath, :ptukey), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,lower_tail,log_p) + ccall((:ptukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,lower_tail,log_p) ptukey(q::Number, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool) = - ccall(dlsym(_jl_libRmath, :ptukey), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,lower_tail,false) + ccall((:ptukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,lower_tail,false) ptukey(q::Number, nmeans::Number, df::Number, nranges::Number) = - ccall(dlsym(_jl_libRmath, :ptukey), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,true,false) + ccall((:ptukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,nmeans,df,true,false) ptukey(q::Number, nmeans::Number, df::Number, nranges::Number) = - ccall(dlsym(_jl_libRmath, :ptukey), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,1.,df,true,false) + ccall((:ptukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),q,nranges,1.,df,true,false) ptukey{T<:Number}(q::AbstractArray{T}, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool, log_p::Bool) = reshape([ptukey(q[i],nmeans,df,nranges,lower_tail,log_p) for i=1:numel(q)], size(q)) ptukey{T<:Number}(q::AbstractArray{T}, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool) = @@ -542,13 +541,13 @@ ptukey{T<:Number}(q::AbstractArray{T}, nmeans::Number, df::Number) = reshape([ptukey(q[i],nmeans,df,1.,true,false) for i=1:numel(q)], size(q)) qtukey(q::Number, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool, log_p::Bool) = - ccall(dlsym(_jl_libRmath, :qtukey), Float64, (Float64,Float64,Float64,Int32,Int32),p,nranges,nmeans,df,lower_tail,log_p) + ccall((:qtukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),p,nranges,nmeans,df,lower_tail,log_p) qtukey(p::Number, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool) = - ccall(dlsym(_jl_libRmath, :qtukey), Float64, (Float64,Float64,Float64,Int32,Int32),p,nranges,nmeans,df,lower_tail,false) + ccall((:qtukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),p,nranges,nmeans,df,lower_tail,false) qtukey(p::Number, nmeans::Number, df::Number, nranges::Number) = - ccall(dlsym(_jl_libRmath, :qtukey), Float64, (Float64,Float64,Float64,Int32,Int32),p,nranges,nmeans,df,true,false) + ccall((:qtukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),p,nranges,nmeans,df,true,false) qtukey(p::Number, nmeans::Number, df::Number) = - ccall(dlsym(_jl_libRmath, :qtukey), Float64, (Float64,Float64,Float64,Int32,Int32),p,nranges,1.,df,true,false) + ccall((:qtukey, :libRmath), Float64, (Float64,Float64,Float64,Int32,Int32),p,nranges,1.,df,true,false) qtukey{T<:Number}(p::AbstractArray{T}, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool, log_p::Bool) = reshape([qtukey(p[i],nmeans,df,nranges,lower_tail,log_p) for i=1:numel(p)], size(p)) qtukey{T<:Number}(p::AbstractArray{T}, nmeans::Number, df::Number, nranges::Number, lower_tail::Bool) = diff --git a/extras/arpack.jl b/extras/arpack.jl index 419c2826de380..a265c0419d3ec 100644 --- a/extras/arpack.jl +++ b/extras/arpack.jl @@ -4,6 +4,9 @@ export eigs, svds const libarpack = "libarpack" +import Base.BlasInt +import Base.blas_int + # For a dense matrix A is ignored and At is actually A'*A sarupdate{T}(A::StridedMatrix{T}, At::StridedMatrix{T}, X::StridedVector{T}) = BLAS.symv('U', one(T), At, X) sarupdate{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, At::SparseMatrixCSC{Tv,Ti}, X::StridedVector{Tv}) = At*(A*X) @@ -21,94 +24,95 @@ for (T, saupd, seupd, naupd, neupd) in ncv = min(max(nev*2, 20), n) # if ncv-nev < 2 || ncv > n error("Compute fewer eigenvalues using eigs(A, k)") end - bmat = "I" - lworkl = sym ? ncv * (ncv + 8) : ncv * (3*ncv + 6) - - v = Array($T, n, ncv) - workd = Array($T, 3*n) - workl = Array($T, lworkl) - resid = Array($T, n) - select = Array(Int32, ncv) - iparam = zeros(Int32, 11) - ipntr = zeros(Int32, 14) - - tol = zeros($T, 1) - ido = zeros(Int32, 1) - info = zeros(Int32, 1) - - iparam[1] = int32(1) # ishifts - iparam[3] = int32(1000) # maxitr - iparam[7] = int32(1) # mode 1 - - zernm1 = 0:(n-1) - - while true - if sym - ccall(($(string(saupd)), libarpack), Void, - (Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, Ptr{Int32}, - Ptr{Int32}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{Int32}), - ido, bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, - iparam, ipntr, workd, workl, &lworkl, info) - else - ccall(($(string(naupd)), libarpack), Void, - (Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, Ptr{Int32}, - Ptr{Int32}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{Int32}), - ido, bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, - iparam, ipntr, workd, workl, &lworkl, info) - end - if info[1] != 0 error("error code $(info[1]) from ARPACK aupd") end - if (ido[1] != -1 && ido[1] != 1) break end - workd[ipntr[2]+zernm1] = A*ref(workd, ipntr[1]+zernm1) - end - - howmny = "A" - - if sym - d = Array($T, nev) - sigma = zeros($T, 1) - ccall(($(string(seupd)), libarpack), Void, - (Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, - Ptr{$T}, Ptr{Uint8}, Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, Ptr{Int32}, Ptr{Int32}, - Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{Int32}), - &rvec, howmny, select, d, v, &n, sigma, - bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, - iparam, ipntr, workd, workl, &lworkl, info) - if info[1] != 0 error("error code $(info[1]) from ARPACK eupd") end - return rvec ? (d, v[1:n, 1:nev]) : d - end - dr = Array($T, nev+1) - di = Array($T, nev+1) - sigmar = zeros($T, 1) - sigmai = zeros($T, 1) - workev = Array($T, 3*ncv) + bmat = "I" + lworkl = sym ? ncv * (ncv + 8) : ncv * (3*ncv + 6) + + v = Array($T, n, ncv) + workd = Array($T, 3*n) + workl = Array($T, lworkl) + resid = Array($T, n) + select = Array(BlasInt, ncv) + iparam = zeros(BlasInt, 11) + ipntr = zeros(BlasInt, 14) + + tol = zeros($T, 1) + ido = zeros(BlasInt, 1) + info = zeros(BlasInt, 1) + + iparam[1] = blas_int(1) # ishifts + iparam[3] = blas_int(1000) # maxitr + iparam[7] = blas_int(1) # mode 1 + + zernm1 = 0:(n-1) + + while true + if sym + ccall(($(string(saupd)), libarpack), Void, + (Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}), + ido, bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, + iparam, ipntr, workd, workl, &lworkl, info) + else + ccall(($(string(naupd)), libarpack), Void, + (Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}), + ido, bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, + iparam, ipntr, workd, workl, &lworkl, info) + end + if info[1] != 0 error("error code $(info[1]) from ARPACK aupd") end + if (ido[1] != -1 && ido[1] != 1) break end + workd[ipntr[2]+zernm1] = A*ref(workd, ipntr[1]+zernm1) + end + + howmny = "A" + + if sym + d = Array($T, nev) + sigma = zeros($T, 1) + + ccall(($(string(seupd)), libarpack), Void, + (Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, + Ptr{$T}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}), + &rvec, howmny, select, d, v, &n, sigma, + bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, + iparam, ipntr, workd, workl, &lworkl, info) + if info[1] != 0 error("error code $(info[1]) from ARPACK eupd") end + return rvec ? (d, v[1:n, 1:nev]) : d + end + dr = Array($T, nev+1) + di = Array($T, nev+1) + sigmar = zeros($T, 1) + sigmai = zeros($T, 1) + workev = Array($T, 3*ncv) ccall(($(string(neupd)), libarpack), Void, - (Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{$T}, - Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{$T}, Ptr{Uint8}, Ptr{Int32}, - Ptr{Uint8}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, - Ptr{Int32}, Ptr{Int32}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, - Ptr{Int32}, Ptr{Int32}), - &rvec, howmny, select, dr, di, v, &n, sigmar, sigmai, - workev, bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, - iparam, ipntr, workd, workl, &lworkl, info) - if info[1] != 0 error("error code $(info[1]) from ARPACK eupd") end - evec = complex(zeros($T, n, nev+1), zeros($T, n, nev+1)) - j = 1 - while j <= nev - if di[j] == 0.0 - evec[:,j] = v[:,j] - else - evec[:,j] = v[:,j] + im*v[:,j+1] - evec[:,j+1] = v[:,j] - im*v[:,j+1] - j += 1 - end - j += 1 - end - complex(dr[1:nev],di[1:nev]), evec[1:n, 1:nev] - end - end + (Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{$T}, + Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{$T}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{Uint8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, + Ptr{BlasInt}, Ptr{BlasInt}), + &rvec, howmny, select, dr, di, v, &n, sigmar, sigmai, + workev, bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, + iparam, ipntr, workd, workl, &lworkl, info) + if info[1] != 0 error("error code $(info[1]) from ARPACK eupd") end + evec = complex(zeros($T, n, nev+1), zeros($T, n, nev+1)) + j = 1 + while j <= nev + if di[j] == 0.0 + evec[:,j] = v[:,j] + else + evec[:,j] = v[:,j] + im*v[:,j+1] + evec[:,j+1] = v[:,j] - im*v[:,j+1] + j += 1 + end + j += 1 + end + complex(dr[1:nev],di[1:nev]), evec[1:n, 1:nev] + end + end end for (T, TR, naupd, neupd) in @@ -131,26 +135,26 @@ for (T, TR, naupd, neupd) in workl = Array($T, lworkl) rwork = Array($TR, ncv) resid = Array($T, n) - select = Array(Int32, ncv) - iparam = zeros(Int32, 11) - ipntr = zeros(Int32, 14) + select = Array(BlasInt, ncv) + iparam = zeros(BlasInt, 11) + ipntr = zeros(BlasInt, 14) tol = zeros($TR, 1) - ido = zeros(Int32, 1) - info = zeros(Int32, 1) + ido = zeros(BlasInt, 1) + info = zeros(BlasInt, 1) - iparam[1] = int32(1) # ishifts - iparam[3] = int32(1000) # maxitr - iparam[7] = int32(1) # mode 1 + iparam[1] = blas_int(1) # ishifts + iparam[3] = blas_int(1000) # maxitr + iparam[7] = blas_int(1) # mode 1 zernm1 = 0:(n-1) while true ccall(($(string(naupd)), libarpack), Void, - (Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$TR}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, Ptr{Int32}, - Ptr{Int32}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, - Ptr{$TR}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$TR}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, + Ptr{$TR}, Ptr{BlasInt}), ido, bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, iparam, ipntr, workd, workl, &lworkl, rwork, info) if info[1] != 0 error("error code $(info[1]) from ARPACK aupd") end @@ -164,10 +168,10 @@ for (T, TR, naupd, neupd) in sigma = zeros($T, 1) workev = Array($T, 2ncv) ccall(($(string(neupd)), libarpack), Void, - (Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, - Ptr{$T}, Ptr{$T}, Ptr{Uint8}, Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$TR}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, Ptr{Int32}, Ptr{Int32}, - Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{$TR}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, + Ptr{$T}, Ptr{$T}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$TR}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$TR}, Ptr{BlasInt}), &rvec, howmny, select, d, v, &n, workev, sigma, bmat, &n, evtype, &nev, tol, resid, &ncv, v, &n, iparam, ipntr, workd, workl, &lworkl, rwork, info) @@ -204,25 +208,25 @@ for (T, saupd, seupd) in ((:Float64, :dsaupd_, :dseupd_), (:Float32, :ssaupd_, : workd = Array($T, 3n) workl = Array($T, lworkl) resid = Array($T, n) - select = Array(Int32, ncv) - iparam = zeros(Int32, 11) + select = Array(BlasInt, ncv) + iparam = zeros(BlasInt, 11) iparam[1] = 1 # ishifts iparam[3] = 1000 # maxitr iparam[7] = 1 # mode 1 - ipntr = zeros(Int32, 14) + ipntr = zeros(BlasInt, 14) tol = zeros($T, 1) sigma = zeros($T, 1) - ido = zeros(Int32, 1) - info = Array(Int32, 1) + ido = zeros(BlasInt, 1) + info = Array(BlasInt, 1) bmat = "I" zernm1 = 0:(n-1) while true ccall(($(string(saupd)), libarpack), Void, - (Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, Ptr{Int32}, - Ptr{Int32}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}), ido, bmat, &n, which, &nev, tol, resid, &ncv, v, &n, iparam, ipntr, workd, workl, &lworkl, info) if (info[1] < 0) error("error code $(info[1]) from ARPACK saupd") end @@ -234,10 +238,10 @@ for (T, saupd, seupd) in ((:Float64, :dsaupd_, :dseupd_), (:Float32, :ssaupd_, : howmny = "A" ccall(($(string(seupd)), libarpack), Void, - (Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, - Ptr{Uint8}, Ptr{Int32}, Ptr{Uint8}, Ptr{Int32}, - Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{$T}, Ptr{Int32}, Ptr{Int32}, - Ptr{Int32}, Ptr{$T}, Ptr{$T}, Ptr{Int32}, Ptr{Int32}), + (Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, + Ptr{Uint8}, Ptr{BlasInt}, Ptr{Uint8}, Ptr{BlasInt}, + Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}, + Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}), &rvec, howmny, select, d, v, &n, sigma, bmat, &n, which, &nev, tol, resid, &ncv, v, &n, iparam, ipntr, workd, workl, &lworkl, info) diff --git a/extras/bigfloat.jl b/extras/bigfloat.jl index 28554ad29f0bf..970bbe1f6b8bc 100644 --- a/extras/bigfloat.jl +++ b/extras/bigfloat.jl @@ -3,56 +3,54 @@ import Base.isnan, Base.isinf, Base.^, Base.cmp, Base.sqrt import Base.==, Base.<=, Base.>=, Base.<, Base.>, Base.string, Base.show import Base.showcompact -_jl_libgmp_wrapper = dlopen("libgmp_wrapper") - require("bigint") type BigFloat <: FloatingPoint mpf::Ptr{Void} function BigFloat(x::String) - z = _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_set_string), Void, (Ptr{Void}, Ptr{Uint8}), z, bytestring(x)) + z = BigFloat_init() + ccall((:jl_mpf_set_string, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Uint8}), z, bytestring(x)) b = new(z) - finalizer(b, _jl_BigFloat_clear) + finalizer(b, BigFloat_clear) b end function BigFloat(x::Float64) - z = _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_set_d), Void, (Ptr{Void}, Float64), z, x) + z = BigFloat_init() + ccall((:jl_mpf_set_d, :libgmp_wrapper), Void, (Ptr{Void}, Float64), z, x) b = new(z) - finalizer(b, _jl_BigFloat_clear) + finalizer(b, BigFloat_clear) b end function BigFloat(x::Uint) - z = _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_set_ui), Void, (Ptr{Void}, Uint), z, x) + z = BigFloat_init() + ccall((:jl_mpf_set_ui, :libgmp_wrapper), Void, (Ptr{Void}, Uint), z, x) b = new(z) - finalizer(b, _jl_BigFloat_clear) + finalizer(b, BigFloat_clear) b end function BigFloat(x::Int) - z = _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_set_si), Void, (Ptr{Void}, Int), z, x) + z = BigFloat_init() + ccall((:jl_mpf_set_si, :libgmp_wrapper), Void, (Ptr{Void}, Int), z, x) b = new(z) - finalizer(b, _jl_BigFloat_clear) + finalizer(b, BigFloat_clear) b end function BigFloat(x::BigInt) - z = _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_set_z), Void, (Ptr{Void}, Ptr{Void}), z, x.mpz) + z = BigFloat_init() + ccall((:jl_mpf_set_z, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}), z, x.mpz) b = new(z) - finalizer(b, _jl_BigFloat_clear) + finalizer(b, BigFloat_clear) b end function BigFloat(z::Ptr{Void}) b = new(z) - finalizer(b, _jl_BigFloat_clear) + finalizer(b, BigFloat_clear) b end end @@ -88,48 +86,48 @@ isnan(x::BigFloat) = false isinf(x::BigFloat) = false function +(x::BigFloat, y::BigFloat) - z= _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_add), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}), z, x.mpf, y.mpf) + z= BigFloat_init() + ccall((:jl_mpf_add, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}), z, x.mpf, y.mpf) BigFloat(z) end function -(x::BigFloat) - z= _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_neg), Void, (Ptr{Void}, Ptr{Void}), z, x.mpf) + z= BigFloat_init() + ccall((:jl_mpf_neg, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}), z, x.mpf) BigFloat(z) end function -(x::BigFloat, y::BigFloat) - z= _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_sub), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}), z, x.mpf, y.mpf) + z= BigFloat_init() + ccall((:jl_mpf_sub, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}), z, x.mpf, y.mpf) BigFloat(z) end function *(x::BigFloat, y::BigFloat) - z= _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_mul), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}), z, x.mpf, y.mpf) + z= BigFloat_init() + ccall((:jl_mpf_mul, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}), z, x.mpf, y.mpf) BigFloat(z) end function /(x::BigFloat, y::BigFloat) - z= _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_div), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}), z, x.mpf, y.mpf) + z= BigFloat_init() + ccall((:jl_mpf_div, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}), z, x.mpf, y.mpf) BigFloat(z) end function cmp(x::BigFloat, y::BigFloat) - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_cmp), Int32, (Ptr{Void}, Ptr{Void}), x.mpf, y.mpf) + ccall((:jl_mpf_cmp, :libgmp_wrapper), Int32, (Ptr{Void}, Ptr{Void}), x.mpf, y.mpf) end function sqrt(x::BigFloat) - z = _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_sqrt), Void, (Ptr{Void}, Ptr{Void}), z, x.mpf) + z = BigFloat_init() + ccall((:jl_mpf_sqrt, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}), z, x.mpf) BigFloat(z) end function ^(x::BigFloat, y::Uint) - z = _jl_BigFloat_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_pow_ui), Void, (Ptr{Void}, Ptr{Void}, Uint), z, x.mpf, y) + z = BigFloat_init() + ccall((:jl_mpf_pow_ui, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Uint), z, x.mpf, y) BigFloat(z) end @@ -140,19 +138,19 @@ end >(x::BigFloat, y::BigFloat) = cmp(x,y) > 0 function string(x::BigFloat) - s=ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_printf), Ptr{Uint8}, (Ptr{Void},), x.mpf) + s=ccall((:jl_mpf_printf, :libgmp_wrapper), Ptr{Uint8}, (Ptr{Void},), x.mpf) ret = bytestring(s) #This copies s. - ccall(dlsym(_jl_libgmp_wrapper,:_jl_gmp_free), Void, (Ptr{Void},), s) + ccall((:jl_gmp_free, :libgmp_wrapper), Void, (Ptr{Void},), s) ret end show(io, b::BigFloat) = print(io, string(b)) showcompact(io, b::BigFloat) = print(io, string(b)) -function _jl_BigFloat_clear(x::BigFloat) - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_clear), Void, (Ptr{Void},), x.mpf) +function BigFloat_clear(x::BigFloat) + ccall((:jl_mpf_clear, :libgmp_wrapper), Void, (Ptr{Void},), x.mpf) end -function _jl_BigFloat_init() - return ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpf_init), Ptr{Void}, ()) +function BigFloat_init() + return ccall((:jl_mpf_init, :libgmp_wrapper), Ptr{Void}, ()) end diff --git a/extras/bigint.jl b/extras/bigint.jl index 8d780571f7983..897922ee48230 100644 --- a/extras/bigint.jl +++ b/extras/bigint.jl @@ -3,35 +3,33 @@ import Base.^, Base.div, Base.rem, Base.cmp, Base.sqrt import Base.gcd, Base.gcdx, Base.factorial, Base.binomial import Base.==, Base.<=, Base.>=, Base.<, Base.>, Base.string, Base.show -_jl_libgmp_wrapper = dlopen("libgmp_wrapper") - type BigInt <: Integer mpz::Ptr{Void} function BigInt(x::String) - z = _jl_bigint_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_set_string), Void, (Ptr{Void}, Ptr{Uint8}),z,bytestring(x)) + z = BigInt_init() + ccall((:jl_mpz_set_string, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Uint8}),z,bytestring(x)) b = new(z) - finalizer(b, _jl_bigint_clear) + finalizer(b, BigInt_clear) b end function BigInt(x::Int) - z = _jl_bigint_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_set_si), Void, (Ptr{Void}, Int),z,x) + z = BigInt_init() + ccall((:jl_mpz_set_si, :libgmp_wrapper), Void, (Ptr{Void}, Int),z,x) b = new(z) - finalizer(b, _jl_bigint_clear) + finalizer(b, BigInt_clear) b end BigInt{T<:Signed}(x::T) = BigInt(int(x)) BigInt(x::Int128) = BigInt(string(x)) function BigInt(x::Uint) - z = _jl_bigint_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_set_ui), Void, + z = BigInt_init() + ccall((:jl_mpz_set_ui, :libgmp_wrapper), Void, (Ptr{Void}, Uint), z, x) b = new(z) - finalizer(b, _jl_bigint_clear) + finalizer(b, BigInt_clear) b end BigInt{T<:Unsigned}(x::T) = BigInt(uint(x)) @@ -39,7 +37,7 @@ type BigInt <: Integer function BigInt(z::Ptr{Void}) b = new(z) - finalizer(b, _jl_bigint_clear) + finalizer(b, BigInt_clear) b end end @@ -63,10 +61,10 @@ else end convert(::Type{Int}, n::BigInt) = - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_get_si), Int, (Ptr{Void},), n.mpz) + ccall((:jl_mpz_get_si, :libgmp_wrapper), Int, (Ptr{Void},), n.mpz) convert(::Type{Uint}, n::BigInt) = - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_get_ui), Uint, (Ptr{Void},), n.mpz) + ccall((:jl_mpz_get_ui, :libgmp_wrapper), Uint, (Ptr{Void},), n.mpz) promote_rule(::Type{BigInt}, ::Type{Int8}) = BigInt promote_rule(::Type{BigInt}, ::Type{Int16}) = BigInt @@ -81,85 +79,85 @@ promote_rule(::Type{BigInt}, ::Type{Uint64}) = BigInt promote_rule(::Type{BigInt}, ::Type{Uint128}) = BigInt function +(x::BigInt, y::BigInt) - z= _jl_bigint_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_add), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}),z,x.mpz,y.mpz) + z= BigInt_init() + ccall((:jl_mpz_add, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}),z,x.mpz,y.mpz) BigInt(z) end function -(x::BigInt) - z= _jl_bigint_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_neg), Void, (Ptr{Void}, Ptr{Void}),z,x.mpz) + z= BigInt_init() + ccall((:jl_mpz_neg, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}),z,x.mpz) BigInt(z) end function -(x::BigInt, y::BigInt) - z= _jl_bigint_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_sub), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}),z,x.mpz,y.mpz) + z= BigInt_init() + ccall((:jl_mpz_sub, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}),z,x.mpz,y.mpz) BigInt(z) end function *(x::BigInt, y::BigInt) - z= _jl_bigint_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_mul), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}),z,x.mpz,y.mpz) + z= BigInt_init() + ccall((:jl_mpz_mul, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Ptr{Void}),z,x.mpz,y.mpz) BigInt(z) end function <<(x::BigInt, c::Uint) - z= _jl_bigint_init() - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_lshift), Void, (Ptr{Void}, Ptr{Void}, Uint), z, x.mpz, c) + z= BigInt_init() + ccall((:jl_mpz_lshift, :libgmp_wrapper), Void, (Ptr{Void}, Ptr{Void}, Uint), z, x.mpz, c) BigInt(z) end <<(x::BigInt, c::Int32) = c<0 ? throw(DomainError()) : x<(x::BigInt, y::BigInt) = cmp(x,y) > 0 function string(x::BigInt) - s=ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_printf), Ptr{Uint8}, (Ptr{Void},),x.mpz) + s=ccall((:jl_mpz_printf, :libgmp_wrapper), Ptr{Uint8}, (Ptr{Void},),x.mpz) ret = bytestring(s) #This copies s. - ccall(dlsym(_jl_libgmp_wrapper,:_jl_gmp_free), Void, (Ptr{Void},), s) + ccall((:jl_gmp_free, :libgmp_wrapper), Void, (Ptr{Void},), s) ret end @@ -202,10 +200,10 @@ function show(io, x::BigInt) print(io, string(x)) end -function _jl_bigint_clear(x::BigInt) - ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_clear), Void, (Ptr{Void},),x.mpz) +function BigInt_clear(x::BigInt) + ccall((:jl_mpz_clear, :libgmp_wrapper), Void, (Ptr{Void},),x.mpz) end -function _jl_bigint_init() - return ccall(dlsym(_jl_libgmp_wrapper, :_jl_mpz_init), Ptr{Void}, ()) +function BigInt_init() + return ccall((:jl_mpz_init, :libgmp_wrapper), Ptr{Void}, ()) end diff --git a/extras/glpk.jl b/extras/glpk.jl index 2fa010897bfaf..a4347f31633b3 100644 --- a/extras/glpk.jl +++ b/extras/glpk.jl @@ -173,21 +173,12 @@ import Base.pointer, Base.assign, Base.ref #{{{ include("$JULIA_HOME/../share/julia/extras/glpk_h.jl") -_jl_libglpk = dlopen("libglpk") -_jl_libglpk_wrapper = dlopen("libglpk_wrapper") - -macro glpk_ccall(func, args...) - f = "glp_$(func)" - quote - ccall(dlsym(_jl_libglpk, $f), $(args...)) - end +macro glpk_ccall(f, args...) + :(ccall(($"glp_$(f)", :libglpk), $(args...))) end -macro glpkw_ccall(func, args...) - f = "_jl_glpkw__$(func)" - quote - ccall(dlsym(_jl_libglpk_wrapper, $f), $(args...)) - end +macro glpkw_ccall(f, args...) + :(ccall(($"jl_glpkw__$(f)", :libglpk_wrapper), $(args...))) end # We need to define GLPK.version as first thing @@ -257,8 +248,8 @@ function assign{T}(param::Param, val::T, field_name::String) throw(Error("invalid struct")) end t = param.desc.field_types[i] - csf = strcat("_jl_glpkw__", param.desc.struct_name, "_set_", field_name) - ccs = :(ccall(dlsym(GLPK._jl_libglpk_wrapper, $csf), Void, (Ptr{Void}, $t), pointer($param), $val)) + csf = strcat("jl_glpkw__", param.desc.struct_name, "_set_", field_name) + ccs = :(ccall(($csf, :libglpk_wrapper), Void, (Ptr{Void}, $t), pointer($param), $val)) eval(ccs) return end @@ -276,8 +267,8 @@ function ref(param::Param, field_name::String) throw(Error("invalid struct")) end t = param.desc.field_types[i] - cgf = strcat("_jl_glpkw__", param.desc.struct_name, "_get_", field_name) - ccg = :(ccall(dlsym(GLPK._jl_libglpk_wrapper, $cgf), $t, (Ptr{Void},), pointer($param))) + cgf = strcat("jl_glpkw__", param.desc.struct_name, "_get_", field_name) + ccg = :(ccall(($cgf, :libglpk_wrapper), $t, (Ptr{Void},), pointer($param))) return eval(ccg) end end @@ -293,7 +284,7 @@ end # as an empty vector [] or as the 'nothing' constant typealias VecOrNothing Union(Vector, Nothing) -function _jl_glpk__convert_vecornothing{T}(::Type{T}, a::VecOrNothing) +function convert_vecornothing{T}(::Type{T}, a::VecOrNothing) if isequal(a, nothing) || isa(a, Array{None}) return T[] elseif T <: Integer @@ -307,7 +298,7 @@ function _jl_glpk__convert_vecornothing{T}(::Type{T}, a::VecOrNothing) end convert(Array{T}, a) end -_jl_glpk__vecornothing_length(a::VecOrNothing) = is(a, nothing) ? 0 : length(a) +vecornothing_length(a::VecOrNothing) = is(a, nothing) ? 0 : length(a) # General exception: all GLP functions @@ -377,7 +368,7 @@ function delete_prob(prob::Prob) end -_jl_glpk__simplex_param_struct_desc = ParamDescriptor("smcp", +simplex_param_struct_desc = ParamDescriptor("smcp", [("msg_lev", Int32), ("meth", Int32), ("pricing", Int32), ("r_test", Int32), ("tol_bnd", Float64), ("tol_dj", Float64), ("tol_piv", Float64), ("obj_ll", Float64), ("obj_ul", Float64), @@ -389,19 +380,19 @@ type SimplexParam <: Param desc::ParamDescriptor function SimplexParam() struct = @glpkw_ccall smcp_init Ptr{Void} () - param = new(struct, _jl_glpk__simplex_param_struct_desc) - finalizer(param, _jl_glpkw__smcp_delete) + param = new(struct, simplex_param_struct_desc) + finalizer(param, smcp_delete) return param end end -function _jl_glpkw__smcp_delete(param::SimplexParam) +function smcp_delete(param::SimplexParam) @glpkw_ccall smcp_delete Void (Ptr{Void},) pointer(param) param.struct = C_NULL end -_jl_glpk__interior_param_struct_desc = ParamDescriptor("iptcp", +interior_param_struct_desc = ParamDescriptor("iptcp", [("msg_lev", Int32), ("ord_alg", Int32)]) type InteriorParam <: Param @@ -409,19 +400,19 @@ type InteriorParam <: Param desc::ParamDescriptor function InteriorParam() struct = @glpkw_ccall iptcp_init Ptr{Void} () - param = new(struct, _jl_glpk__interior_param_struct_desc) - finalizer(param, _jl_glpkw__iptcp_delete) + param = new(struct, interior_param_struct_desc) + finalizer(param, iptcp_delete) return param end end -function _jl_glpkw__iptcp_delete(param::InteriorParam) +function iptcp_delete(param::InteriorParam) @glpkw_ccall iptcp_delete Void (Ptr{Void},) pointer(param) param.struct = C_NULL end -_jl_glpk__intopt_param_struct_desc = ParamDescriptor("iocp", +intopt_param_struct_desc = ParamDescriptor("iocp", [("msg_lev", Int32), ("br_tech", Int32), ("bt_tech", Int32), ("pp_tech", Int32), ("fp_heur", Int32), ("gmi_cuts", Int32), ("mir_cuts", Int32), ("cov_cuts", Int32), ("clq_cuts", Int32), @@ -435,19 +426,19 @@ type IntoptParam <: Param desc::ParamDescriptor function IntoptParam() struct = @glpkw_ccall iocp_init Ptr{Void} () - param = new(struct, _jl_glpk__intopt_param_struct_desc) - finalizer(param, _jl_glpkw__iocp_delete) + param = new(struct, intopt_param_struct_desc) + finalizer(param, iocp_delete) return param end end -function _jl_glpkw__iocp_delete(param::IntoptParam) +function iocp_delete(param::IntoptParam) @glpkw_ccall iocp_delete Void (Ptr{Void},) pointer(param) param.struct = C_NULL end -_jl_glpk__basisfact_param_struct_desc = ParamDescriptor("bfcp", +basisfact_param_struct_desc = ParamDescriptor("bfcp", [("type", Int32), ("lu_size", Int32), ("piv_tol", Float64), ("piv_lim", Int32), ("suhl", Int32), ("eps_tol", Float64), ("max_gro", Float64), ("nfs_max", Int32), ("upd_tol", Float64), @@ -458,13 +449,13 @@ type BasisFactParam <: Param desc::ParamDescriptor function BasisFactParam() struct = @glpkw_ccall bfcp_init Ptr{Void} () - param = new(struct, _jl_glpk__basisfact_param_struct_desc) - finalizer(param, _jl_glpkw__bfcp_delete) + param = new(struct, basisfact_param_struct_desc) + finalizer(param, bfcp_delete) return param end end -function _jl_glpkw__bfcp_delete(param::BasisFactParam) +function bfcp_delete(param::BasisFactParam) @glpkw_ccall bfcp_delete Void (Ptr{Void},) pointer(param) param.struct = C_NULL end @@ -505,14 +496,14 @@ end # to pass an invalid parameter to the # underlying glp API. -function _jl_glpk__check_prob(prob::Prob) +function check_prob(prob::Prob) if prob.p == C_NULL throw(Error("Invalid GLPK.Prob")) end return true end -function _jl_glpk__check_string_length(s::String, minl::Integer, maxl::Integer) +function check_string_length(s::String, minl::Integer, maxl::Integer) l = length(s) if !(minl <= l <= maxl) throw(Error("Invalid string length $l (must be $minl <= length <= $maxl)")) @@ -520,7 +511,7 @@ function _jl_glpk__check_string_length(s::String, minl::Integer, maxl::Integer) return true end -function _jl_glpk__check_row_is_valid(prob::Prob, row::Integer) +function check_row_is_valid(prob::Prob, row::Integer) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p if (row < 1 || row > rows) throw(Error("Invalid row $row (must be 1 <= row <= $rows)")) @@ -528,7 +519,7 @@ function _jl_glpk__check_row_is_valid(prob::Prob, row::Integer) return true end -function _jl_glpk__check_col_is_valid(prob::Prob, col::Integer) +function check_col_is_valid(prob::Prob, col::Integer) cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p if (col < 1 || col > cols) throw(Error("Invalid col $col (must be 1 <= col <= $cols)")) @@ -536,7 +527,7 @@ function _jl_glpk__check_col_is_valid(prob::Prob, col::Integer) return true end -function _jl_glpk__check_col_is_valid_w0(prob::Prob, col::Integer) +function check_col_is_valid_w0(prob::Prob, col::Integer) cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p if (col < 0 || col > cols) throw(Error("Invalid col $col (must be 0 <= col <= $cols)")) @@ -544,14 +535,14 @@ function _jl_glpk__check_col_is_valid_w0(prob::Prob, col::Integer) return true end -function _jl_glpk__check_obj_dir_is_valid(dir::Integer) +function check_obj_dir_is_valid(dir::Integer) if !(dir == MIN || dir == MAX) throw(Error("Invalid obj_dir $dir (use MIN or MAX)")) end return true end -function _jl_glpk__check_bounds_type_is_valid(bounds_type::Integer) +function check_bounds_type_is_valid(bounds_type::Integer) if !(bounds_type == FR || bounds_type == LO || bounds_type == UP || @@ -562,7 +553,7 @@ function _jl_glpk__check_bounds_type_is_valid(bounds_type::Integer) return true end -function _jl_glpk__check_bounds_are_valid(bounds_type::Integer, lb::Real, ub::Real) +function check_bounds_are_valid(bounds_type::Integer, lb::Real, ub::Real) if bounds_type == DB && lb > ub throw(Error("Invalid bounds for double-bounded variable: $lb > $ub")) elseif bounds_type == FX && lb != ub @@ -571,7 +562,7 @@ function _jl_glpk__check_bounds_are_valid(bounds_type::Integer, lb::Real, ub::Re return true end -function _jl_glpk__check_vectors_size(numel::Integer, vecs...) +function check_vectors_size(numel::Integer, vecs...) if numel < 0 throw(Error("Invalid numer of elements: $numel")) end @@ -587,10 +578,10 @@ function _jl_glpk__check_vectors_size(numel::Integer, vecs...) return true end -function _jl_glpk__check_vectors_all_same_size(vec0::VecOrNothing, vecs::VecOrNothing...) - l0 = _jl_glpk__vecornothing_length(vec0) +function check_vectors_all_same_size(vec0::VecOrNothing, vecs::VecOrNothing...) + l0 = vecornothing_length(vec0) for v in vecs - l = _jl_glpk__vecornothing_length(v) + l = vecornothing_length(v) if l != l0 throw(Error("incosistent vector lengths: $l0 and $l")) end @@ -598,7 +589,7 @@ function _jl_glpk__check_vectors_all_same_size(vec0::VecOrNothing, vecs::VecOrNo return true end -function _jl_glpk__check_indices_vectors_dup(prob::Prob, numel::Integer, ia::Vector{Int32}, ja::Vector{Int32}) +function check_indices_vectors_dup(prob::Prob, numel::Integer, ia::Vector{Int32}, ja::Vector{Int32}) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p #numel = length(ia) @@ -616,7 +607,7 @@ function _jl_glpk__check_indices_vectors_dup(prob::Prob, numel::Integer, ia::Vec return true end -function _jl_glpk__check_rows_and_cols(rows::Integer, cols::Integer) +function check_rows_and_cols(rows::Integer, cols::Integer) if (rows < 0) throw(Error("rows < 0 : $rows")) end @@ -625,7 +616,7 @@ function _jl_glpk__check_rows_and_cols(rows::Integer, cols::Integer) end end -function _jl_glpk__check_rows_ids(prob::Prob, min_size::Integer, num_rows::Integer, rows_ids::Vector{Int32}) +function check_rows_ids(prob::Prob, min_size::Integer, num_rows::Integer, rows_ids::Vector{Int32}) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p if num_rows < min_size || num_rows > rows throw(Error("invalid vector size: $num_rows (min=$min_size max=$rows)")) @@ -646,7 +637,7 @@ function _jl_glpk__check_rows_ids(prob::Prob, min_size::Integer, num_rows::Integ return true end -function _jl_glpk__check_cols_ids(prob::Prob, min_size::Integer, num_cols::Integer, cols_ids::Vector{Int32}) +function check_cols_ids(prob::Prob, min_size::Integer, num_cols::Integer, cols_ids::Vector{Int32}) cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p if num_cols < min_size || num_cols > cols throw(Error("invalid vector size: $num_cols (min=$min_size max=$cols)")) @@ -667,7 +658,7 @@ function _jl_glpk__check_cols_ids(prob::Prob, min_size::Integer, num_cols::Integ return true end -function _jl_glpk__check_list_ids(prob::Prob, len::Integer, list_ids::Vector{Int32}) +function check_list_ids(prob::Prob, len::Integer, list_ids::Vector{Int32}) if len == 0 return true end @@ -689,7 +680,7 @@ function _jl_glpk__check_list_ids(prob::Prob, len::Integer, list_ids::Vector{Int return true end -function _jl_glpk__check_status_is_optimal(prob::Prob) +function check_status_is_optimal(prob::Prob) ret = @glpk_ccall get_status Int32 (Ptr{Void},) prob.p if ret == OPT throw(Error("current basic solution is not optimal")) @@ -697,7 +688,7 @@ function _jl_glpk__check_status_is_optimal(prob::Prob) return true end -function _jl_glpk__check_bf_exists(prob::Prob) +function check_bf_exists(prob::Prob) ret = @glpk_ccall bf_exists Int32 (Ptr{Void},) prob.p if ret == 0 throw(Error("no bf solution found (use GLPK.factorize)")) @@ -705,7 +696,7 @@ function _jl_glpk__check_bf_exists(prob::Prob) return true end -function _jl_glpk__check_var_is_basic(prob::Prob, ind::Integer) +function check_var_is_basic(prob::Prob, ind::Integer) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p if ind <= rows j = @glpk_ccall get_row_stat Int32 (Ptr{Void}, Int32) prob.p ind @@ -720,7 +711,7 @@ function _jl_glpk__check_var_is_basic(prob::Prob, ind::Integer) end end -function _jl_glpk__check_var_is_non_basic(prob::Prob, ind::Integer) +function check_var_is_non_basic(prob::Prob, ind::Integer) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p if ind <= rows j = @glpk_ccall get_row_stat Int32 (Ptr{Void}, Int32) prob.p ind @@ -735,28 +726,28 @@ function _jl_glpk__check_var_is_non_basic(prob::Prob, ind::Integer) end end -function _jl_glpk__check_is_prim_feasible(prob::Prob) +function check_is_prim_feasible(prob::Prob) if FEAS != @glpk_ccall get_prim_stat Int32 (Ptr{Void},) prob.p throw(Error("problem is not primal feasible")) end return true end -function _jl_glpk__check_is_dual_feasible(prob::Prob) +function check_is_dual_feasible(prob::Prob) if FEAS != @glpk_ccall get_dual_stat Int32 (Ptr{Void},) prob.p throw(Error("problem is not dual feasible")) end return true end -function _jl_glpk__check_copy_names_flag(names::Integer) +function check_copy_names_flag(names::Integer) if names != ON && names != OFF throw(Error("invalid copy_names flag $names (use GLPK.ON or GLPK.OFF)")) end return true end -function _jl_glpk__check_scale_flags(flags::Integer) +function check_scale_flags(flags::Integer) all = (SF_GM | SF_EQ | SF_2N | SF_SKIP) if (flags | all) != all && flags != SF_AUTO throw(Error("invalid scale flags $flags")) @@ -764,7 +755,7 @@ function _jl_glpk__check_scale_flags(flags::Integer) return true end -function _jl_glpk__check_stat_is_valid(stat::Integer) +function check_stat_is_valid(stat::Integer) if (stat != BS && stat != NL && stat != NU && @@ -774,28 +765,28 @@ function _jl_glpk__check_stat_is_valid(stat::Integer) end end -function _jl_glpk__check_adv_basis_flags(flags::Integer) +function check_adv_basis_flags(flags::Integer) if flags != 0 throw(Error("adv_basis flags must be set to 0 (found $flags instead)")) end return true end -function _jl_glpk__check_simplex_param(param::SimplexParam) +function check_simplex_param(param::SimplexParam) if pointer(param) == C_NULL throw(Error("param = NULL")) end return true end -function _jl_glpk__check_interior_param(param::InteriorParam) +function check_interior_param(param::InteriorParam) if pointer(param) == C_NULL throw(Error("param = NULL")) end return true end -function _jl_glpk__check_kind_is_valid(kind::Integer) +function check_kind_is_valid(kind::Integer) if (kind != CV && kind != IV && kind != BV) @@ -804,14 +795,14 @@ function _jl_glpk__check_kind_is_valid(kind::Integer) return true end -function _jl_glpk__check_intopt_param(param::IntoptParam) +function check_intopt_param(param::IntoptParam) if pointer(param) == C_NULL throw(Error("param = NULL")) end return true end -function _jl_glpk__check_file_is_readable(filename::String) +function check_file_is_readable(filename::String) try f = open(filename, "r") close(f) @@ -821,7 +812,7 @@ function _jl_glpk__check_file_is_readable(filename::String) return true end -function _jl_glpk__check_file_is_writable(filename::String) +function check_file_is_writable(filename::String) try f = open(filename, "w") close(f) @@ -831,7 +822,7 @@ function _jl_glpk__check_file_is_writable(filename::String) return true end -function _jl_glpk__check_mps_format(format::Integer) +function check_mps_format(format::Integer) if (format != MPS_DECK && format != MPS_FILE) throw(Error("invalid MPS format $format (use GLPK.MPS_DECK or GLPK.MPS_FILE)")) @@ -839,35 +830,35 @@ function _jl_glpk__check_mps_format(format::Integer) return true end -function _jl_glpk__check_mps_param(param) +function check_mps_param(param) if param != C_NULL throw(Error("MPS param must be C_NULL")) end return true end -function _jl_glpk__check_lp_param(param) +function check_lp_param(param) if param != C_NULL throw(Error("LP param must be C_NULL")) end return true end -function _jl_glpk__check_read_prob_flags(flags::Integer) +function check_read_prob_flags(flags::Integer) if flags != 0 throw(Error("read_prob flags must be 0")) end return true end -function _jl_glpk__check_write_prob_flags(flags::Integer) +function check_write_prob_flags(flags::Integer) if flags != 0 throw(Error("write_prob flags must be 0")) end return true end -function _jl_glpk__check_print_ranges_flags(flags::Integer) +function check_print_ranges_flags(flags::Integer) if flags != 0 throw(Error("print_ranges flags must be set to 0 (found $flags instead)")) end @@ -875,28 +866,28 @@ function _jl_glpk__check_print_ranges_flags(flags::Integer) end -function _jl_glpk__check_bfcp(param::BasisFactParam) +function check_bfcp(param::BasisFactParam) if pointer(param) == C_NULL throw(Error("Invalid GLPK.BasisFactParam")) end return true end -function _jl_glpk__check_data(data::Data) +function check_data(data::Data) if pointer(data) == C_NULL throw(Error("Invalid GLPK.Data")) end return true end -function _jl_glpk__check_mpl_workspace(tran::MathProgWorkspace) +function check_mpl_workspace(tran::MathProgWorkspace) if tran.p == C_NULL throw(Error("Invalid GLPK.MathProgWorkspace")) end return true end -function _jl_glpk__check_rowcol_is_valid(prob::Prob, k::Integer) +function check_rowcol_is_valid(prob::Prob, k::Integer) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p @@ -908,56 +899,56 @@ function _jl_glpk__check_rowcol_is_valid(prob::Prob, k::Integer) return true end -function _jl_glpk__check_dir_is_valid(dir::Integer) +function check_dir_is_valid(dir::Integer) if !(dir == 1 || dir == -1) throw(Error("invalid direction $dir (must be 1 or -1)")) end return true end -function _jl_glpk__check_eps_is_valid(eps::Real) +function check_eps_is_valid(eps::Real) if (eps < 0) throw(Error("invalid eps $eps (must be >= 0)")) end return true end -function _jl_glpk__check_init_env_succeeded(ret::Integer) +function check_init_env_succeeded(ret::Integer) if !(0 <= ret <= 1) throw(Error("initialization failed")) end return true end -function _jl_glpk__check_term_out_flag(flag::Integer) +function check_term_out_flag(flag::Integer) if !(flag == ON || flag == OFF) throw(Error("invalid flag $flag (use GLPK.ON or GLPK.OFF)")) end return true end -function _jl_glpk__check_open_tee_succeeded(ret::Integer) +function check_open_tee_succeeded(ret::Integer) if !(0 <= ret <= 1) throw(Error("GLPK.open_tee failed")) end return true end -function _jl_glpk__check_alloc_size(n::Integer) +function check_alloc_size(n::Integer) if n <= 0 throw(Error("invalid alloc size $n")) end return true end -function _jl_glpk__check_pointer_is_valid(ptr::Ptr) +function check_pointer_is_valid(ptr::Ptr) if ptr == C_NULL throw(Error("invalid pointer")) end return true end -function _jl_glpk__check_sdf_file_opened(data_p::Ptr) +function check_sdf_file_opened(data_p::Ptr) if data_p == C_NULL throw(Error("GLPK.sdf_open_file failed")) end @@ -991,85 +982,85 @@ end # rather than a string. function set_prob_name(prob::Prob, name::Union(String,Nothing)) - _jl_glpk__check_prob(prob) + check_prob(prob) if is(name, nothing) name = "" end - _jl_glpk__check_string_length(name, 0, 255) + check_string_length(name, 0, 255) @glpk_ccall set_prob_name Void (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(name) end function set_obj_name(prob::Prob, name::Union(String,Nothing)) - _jl_glpk__check_prob(prob) + check_prob(prob) if is(name, nothing) name = "" end - _jl_glpk__check_string_length(name, 0, 255) + check_string_length(name, 0, 255) @glpk_ccall set_obj_name Void (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(name) end function set_row_name(prob::Prob, row::Integer, name::Union(String,Nothing)) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) if is(name, nothing) name = "" end - _jl_glpk__check_string_length(name, 0, 255) + check_string_length(name, 0, 255) @glpk_ccall set_row_name Void (Ptr{Void}, Int32, Ptr{Uint8}) prob.p row bytestring(name) end function set_col_name(prob::Prob, col::Integer, name::Union(String,Nothing)) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) if is(name, nothing) name = "" end - _jl_glpk__check_string_length(name, 0, 255) + check_string_length(name, 0, 255) @glpk_ccall set_col_name Void (Ptr{Void}, Int32, Ptr{Uint8}) prob.p col bytestring(name) end function set_obj_dir(prob::Prob, dir::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_obj_dir_is_valid(dir) + check_prob(prob) + check_obj_dir_is_valid(dir) @glpk_ccall set_obj_dir Void (Ptr{Void}, Int32) prob.p dir end function add_rows(prob::Prob, rows::Integer) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall add_rows Int32 (Ptr{Void}, Int32) prob.p rows end function add_cols(prob::Prob, cols::Integer) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall add_cols Int32 (Ptr{Void}, Int32) prob.p cols end function set_row_bnds(prob::Prob, row::Integer, bounds_type::Integer, lb::Real, ub::Real) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) - _jl_glpk__check_bounds_type_is_valid(bounds_type) - _jl_glpk__check_bounds_are_valid(bounds_type, lb, ub) + check_prob(prob) + check_row_is_valid(prob, row) + check_bounds_type_is_valid(bounds_type) + check_bounds_are_valid(bounds_type, lb, ub) @glpk_ccall set_row_bnds Void (Ptr{Void}, Int32, Int32, Float64, Float64) prob.p row bounds_type lb ub end function set_col_bnds(prob::Prob, col::Integer, bounds_type::Integer, lb::Real, ub::Real) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) - _jl_glpk__check_bounds_type_is_valid(bounds_type) - _jl_glpk__check_bounds_are_valid(bounds_type, lb, ub) + check_prob(prob) + check_col_is_valid(prob, col) + check_bounds_type_is_valid(bounds_type) + check_bounds_are_valid(bounds_type, lb, ub) @glpk_ccall set_col_bnds Void (Ptr{Void}, Int32, Int32, Float64, Float64) prob.p col bounds_type lb ub end function set_obj_coef(prob::Prob, col::Integer, coef::Real) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid_w0(prob, col) + check_prob(prob) + check_col_is_valid_w0(prob, col) @glpk_ccall set_obj_coef Void (Ptr{Void}, Int32, Float64) prob.p col coef end function set_mat_row{Ti<:Integer, Tv<:Real}(prob::Prob, row::Integer, len::Integer, ind::Vector{Ti}, val::Vector{Tv}) - _jl_glpk__check_prob(prob) - _jl_glpk__check_vectors_size(len, ind, val) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_vectors_size(len, ind, val) + check_row_is_valid(prob, row) if len > 0 ind32 = int32(ind) val64 = float64(val) @@ -1077,7 +1068,7 @@ function set_mat_row{Ti<:Integer, Tv<:Real}(prob::Prob, row::Integer, len::Integ off64 = sizeof(Float64) ind32p = pointer(ind32) - off32 val64p = pointer(val64) - off64 - _jl_glpk__check_cols_ids(prob, 0, len, ind32) + check_cols_ids(prob, 0, len, ind32) else ind32p = C_NULL val64p = C_NULL @@ -1086,21 +1077,21 @@ function set_mat_row{Ti<:Integer, Tv<:Real}(prob::Prob, row::Integer, len::Integ @glpk_ccall set_mat_row Void (Ptr{Void}, Int32, Int32, Ptr{Int32}, Ptr{Float64}) prob.p row len ind32p val64p end function set_mat_row(prob::Prob, row::Integer, len::Integer, ind::VecOrNothing, val::VecOrNothing) - ind = _jl_glpk__convert_vecornothing(Int32, ind) - val = _jl_glpk__convert_vecornothing(Float64, ar) + ind = convert_vecornothing(Int32, ind) + val = convert_vecornothing(Float64, ar) set_mat_row(prob, row, len, ind, val) end function set_mat_row(prob::Prob, row::Integer, ind::VecOrNothing, val::VecOrNothing) - _jl_glpk__check_vectors_all_same_size(ind, val) - l = _jl_glpk__vecornothing_length(ind) + check_vectors_all_same_size(ind, val) + l = vecornothing_length(ind) set_mat_row(prob, row, l, ind, val) end function set_mat_col{Ti<:Integer, Tv<:Real}(prob::Prob, col::Integer, len::Integer, ind::Vector{Ti}, val::Vector{Tv}) - _jl_glpk__check_prob(prob) - _jl_glpk__check_vectors_size(len, ind, val) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_vectors_size(len, ind, val) + check_col_is_valid(prob, col) if len > 0 ind32 = int32(ind) val64 = float64(val) @@ -1108,7 +1099,7 @@ function set_mat_col{Ti<:Integer, Tv<:Real}(prob::Prob, col::Integer, len::Integ off64 = sizeof(Float64) ind32p = pointer(ind32) - off32 val64p = pointer(val64) - off64 - _jl_glpk__check_rows_ids(prob, 0, len, ind32) + check_rows_ids(prob, 0, len, ind32) else ind32p = C_NULL val64p = C_NULL @@ -1117,26 +1108,26 @@ function set_mat_col{Ti<:Integer, Tv<:Real}(prob::Prob, col::Integer, len::Integ @glpk_ccall set_mat_col Void (Ptr{Void}, Int32, Int32, Ptr{Int32}, Ptr{Float64}) prob.p col len ind32p val64p end function set_mat_col(prob::Prob, col::Integer, len::Integer, ind::VecOrNothing, val::VecOrNothing) - ind = _jl_glpk__convert_vecornothing(Int32, ind) - val = _jl_glpk__convert_vecornothing(Float64, ar) + ind = convert_vecornothing(Int32, ind) + val = convert_vecornothing(Float64, ar) set_mat_col(prob, col, len, ind, val) end function set_mat_col(prob::Prob, col::Integer, ind::VecOrNothing, val::VecOrNothing) - _jl_glpk__check_vectors_all_same_size(ind, val) - l = _jl_glpk__vecornothing_length(ind) + check_vectors_all_same_size(ind, val) + l = vecornothing_length(ind) set_mat_col(prob, col, l, ind, val) end function load_matrix{Ti<:Integer, Tv<:Real}(prob::Prob, numel::Integer, ia::Vector{Ti}, ja::Vector{Ti}, ar::Vector{Tv}) - _jl_glpk__check_prob(prob) - _jl_glpk__check_vectors_size(numel, ia, ja, ar) + check_prob(prob) + check_vectors_size(numel, ia, ja, ar) if numel == 0 return end ia32 = int32(ia) ja32 = int32(ja) ar64 = float64(ar) - _jl_glpk__check_indices_vectors_dup(prob, numel, ia32, ja32) + check_indices_vectors_dup(prob, numel, ia32, ja32) off32 = sizeof(Int32) off64 = sizeof(Float64) @@ -1148,15 +1139,15 @@ function load_matrix{Ti<:Integer, Tv<:Real}(prob::Prob, numel::Integer, ia::Vect end function load_matrix(prob::Prob, numel::Integer, ia::VecOrNothing, ja::VecOrNothing, ar::VecOrNothing) - ia = _jl_glpk__convert_vecornothing(Int32, ia) - ja = _jl_glpk__convert_vecornothing(Int32, ja) - ar = _jl_glpk__convert_vecornothing(Float64, ar) + ia = convert_vecornothing(Int32, ia) + ja = convert_vecornothing(Int32, ja) + ar = convert_vecornothing(Float64, ar) load_matrix(prob, numel, ia, ja, ar) end function load_matrix(prob::Prob, ia::VecOrNothing, ja::VecOrNothing, ar::VecOrNothing) - _jl_glpk__check_vectors_all_same_size(ia, ja, ar) - l = _jl_glpk__vecornothing_length(ar) + check_vectors_all_same_size(ia, ja, ar) + l = vecornothing_length(ar) load_matrix(prob, l, ia, ja, ar) end @@ -1166,8 +1157,8 @@ function load_matrix{Ti<:Integer, Tv<:Real}(prob::Prob, a::SparseMatrixCSC{Tv, T end function check_dup{Ti<:Integer}(rows::Integer, cols::Integer, numel::Integer, ia::Vector{Ti}, ja::Vector{Ti}) - _jl_glpk__check_rows_and_cols(rows, cols) - _jl_glpk__check_vectors_size(numel, ia, ja) + check_rows_and_cols(rows, cols) + check_vectors_size(numel, ia, ja) ia32 = int32(ia) ja32 = int32(ja) @@ -1179,26 +1170,26 @@ function check_dup{Ti<:Integer}(rows::Integer, cols::Integer, numel::Integer, ia end function check_dup(rows::Integer, cols::Integer, numel::Integer, ia::VecOrNothing, ja::VecOrNothing) - ia = _jl_glpk__convert_vecornothing(Int32, ia) - ja = _jl_glpk__convert_vecornothing(Int32, ja) + ia = convert_vecornothing(Int32, ia) + ja = convert_vecornothing(Int32, ja) check_dup(rows, cols, numel, ia, ja) end function check_dup(rows::Integer, cols::Integer, ia::VecOrNothing, ja::VecOrNothing) - _jl_glpk__check_vectors_all_same_size(ia, ja) - l = _jl_glpk__vecornothing_length(ia) + check_vectors_all_same_size(ia, ja) + l = vecornothing_length(ia) check_dup(rows, cols, l, ia, ja) end function sort_matrix(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall sort_matrix Void (Ptr{Void},) prob.p end function del_rows{Ti<:Integer}(prob::Prob, num_rows::Integer, rows_ids::AbstractVector{Ti}) - _jl_glpk__check_prob(prob) + check_prob(prob) rows_ids32 = int32(rows_ids) - _jl_glpk__check_rows_ids(prob, 1, num_rows, rows_ids32) + check_rows_ids(prob, 1, num_rows, rows_ids32) off32 = sizeof(Int32) rows_ids32p = pointer(rows_ids32) - off32 @@ -1208,9 +1199,9 @@ del_rows{Ti<:Integer}(prob::Prob, rows_ids::AbstractVector{Ti}) = del_rows(prob, length(rows_ids), rows_ids) function del_cols{Ti<:Integer}(prob::Prob, num_cols::Integer, cols_ids::AbstractVector{Ti}) - _jl_glpk__check_prob(prob) + check_prob(prob) cols_ids32 = int32(cols_ids) - _jl_glpk__check_cols_ids(prob, 1, num_cols, cols_ids32) + check_cols_ids(prob, 1, num_cols, cols_ids32) off32 = sizeof(Int32) cols_ids32p = pointer(cols_ids32) - off32 @@ -1220,18 +1211,18 @@ del_cols{Ti<:Integer}(prob::Prob, cols_ids::AbstractVector{Ti}) = del_cols(prob, length(cols_ids), cols_ids) function copy_prob(prob_dest::Prob, prob::Prob, copy_names::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_copy_names_flag(copy_names) + check_prob(prob) + check_copy_names_flag(copy_names) @glpk_ccall copy_prob Void (Ptr{Void}, Ptr{Void}, Int32) prob_dest.p prob.p copy_names end function erase_prob(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall erase_prob Void (Ptr{Void},) prob.p end function get_prob_name(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) name_cstr = @glpk_ccall get_prob_name Ptr{Uint8} (Ptr{Void},) prob.p if name_cstr == C_NULL return "" @@ -1241,7 +1232,7 @@ function get_prob_name(prob::Prob) end function get_obj_name(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) name_cstr = @glpk_ccall get_obj_name Ptr{Uint8} (Ptr{Void},) prob.p if name_cstr == C_NULL return "" @@ -1251,23 +1242,23 @@ function get_obj_name(prob::Prob) end function get_obj_dir(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_obj_dir Int32 (Ptr{Void},) prob.p end function get_num_rows(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p end function get_num_cols(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p end function get_row_name(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) name_cstr = @glpk_ccall get_row_name Ptr{Uint8} (Ptr{Void}, Int32) prob.p row if name_cstr == C_NULL return "" @@ -1277,8 +1268,8 @@ function get_row_name(prob::Prob, row::Integer) end function get_col_name(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) name_cstr = @glpk_ccall get_col_name Ptr{Uint8} (Ptr{Void}, Int32) prob.p col if name_cstr == C_NULL return "" @@ -1288,68 +1279,68 @@ function get_col_name(prob::Prob, col::Integer) end function get_row_type(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall get_row_type Int32 (Ptr{Void}, Int32) prob.p row end function get_row_lb(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall get_row_lb Float64 (Ptr{Void}, Int32) prob.p row end function get_row_ub(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall get_row_ub Float64 (Ptr{Void}, Int32) prob.p row end function get_col_type(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall get_col_type Int32 (Ptr{Void}, Int32) prob.p col end function get_col_lb(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall get_col_lb Float64 (Ptr{Void}, Int32) prob.p col end function get_col_ub(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall get_col_ub Float64 (Ptr{Void}, Int32) prob.p col end function get_obj_coef(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid_w0(prob, col) + check_prob(prob) + check_col_is_valid_w0(prob, col) @glpk_ccall get_obj_coef Float64 (Ptr{Void}, Int32) prob.p col end function get_num_nz(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_num_nz Int32 (Ptr{Void},) prob.p end function get_mat_row(prob::Prob, row::Integer, ind::Union(Vector{Int32},Nothing), val::Union(Vector{Float64},Nothing)) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) numel = @glpk_ccall get_mat_row Int32 (Ptr{Void}, Int32, Ptr{Int32}, Ptr{Float64}) prob.p row C_NULL C_NULL if numel == 0 return 0 end if !isequal(ind, nothing) - _jl_glpk__check_vectors_size(numel, ind) + check_vectors_size(numel, ind) off32 = sizeof(Int32) ind32p = pointer(ind) - off32 else ind32p = C_NULL end if !isequal(val, nothing) - _jl_glpk__check_vectors_size(numel, val) + check_vectors_size(numel, val) off64 = sizeof(Float64) val64p = pointer(val) - off64 else @@ -1359,8 +1350,8 @@ function get_mat_row(prob::Prob, row::Integer, ind::Union(Vector{Int32},Nothing) end function get_mat_row(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) numel = @glpk_ccall get_mat_row Int32 (Ptr{Void}, Int32, Ptr{Int32}, Ptr{Float64}) prob.p row C_NULL C_NULL if numel == 0 return (Int32[], Float64[]) @@ -1377,21 +1368,21 @@ function get_mat_row(prob::Prob, row::Integer) end function get_mat_col(prob::Prob, col::Integer, ind::Union(Vector{Int32},Nothing), val::Union(Vector{Float64},Nothing)) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) numel = @glpk_ccall get_mat_col Int32 (Ptr{Void}, Int32, Ptr{Int32}, Ptr{Float64}) prob.p col C_NULL C_NULL if numel == 0 return 0 end if !isequal(ind, nothing) - _jl_glpk__check_vectors_size(numel, ind) + check_vectors_size(numel, ind) off32 = sizeof(Int32) ind32p = pointer(ind) - off32 else ind32p = C_NULL end if !isequal(val, nothing) - _jl_glpk__check_vectors_size(numel, val) + check_vectors_size(numel, val) off64 = sizeof(Float64) val64p = pointer(val) - off64 else @@ -1401,8 +1392,8 @@ function get_mat_col(prob::Prob, col::Integer, ind::Union(Vector{Int32},Nothing) end function get_mat_col(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) numel = @glpk_ccall get_mat_col Int32 (Ptr{Void}, Int32, Ptr{Int32}, Ptr{Float64}) prob.p col C_NULL C_NULL if numel == 0 return (Int32[], Float64[]) @@ -1419,93 +1410,93 @@ function get_mat_col(prob::Prob, col::Integer) end function create_index(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall create_index Void (Ptr{Void},) prob.p end function find_row(prob::Prob, name::String) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall find_row Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(name) end function find_col(prob::Prob, name::String) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall find_col Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(name) end function delete_index(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall delete_index Void (Ptr{Void},) prob.p end function set_rii(prob::Prob, row::Integer, rii::Real) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall set_rii Void (Ptr{Void}, Int32, Float64) prob.p row rii end function set_sjj(prob::Prob, col::Integer, sjj::Real) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall set_sjj Void (Ptr{Void}, Int32, Float64) prob.p col sjj end function get_rii(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall get_rii Float64 (Ptr{Void}, Int32) prob.p row end function get_sjj(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall get_sjj Float64 (Ptr{Void}, Int32) prob.p col end function scale_prob(prob::Prob, flags::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_scale_flags(flags) + check_prob(prob) + check_scale_flags(flags) @glpk_ccall scale_prob Void (Ptr{Void}, Int32) prob.p flags end function unscale_prob(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall unscale_prob Void (Ptr{Void},) prob.p end function set_row_stat(prob::Prob, row::Integer, stat::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) - _jl_glpk__check_stat_is_valid(stat) + check_prob(prob) + check_row_is_valid(prob, row) + check_stat_is_valid(stat) @glpk_ccall set_row_stat Void (Ptr{Void}, Int32, Int32) prob.p row stat end function set_col_stat(prob::Prob, col::Integer, stat::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) - _jl_glpk__check_stat_is_valid(stat) + check_prob(prob) + check_col_is_valid(prob, col) + check_stat_is_valid(stat) @glpk_ccall set_col_stat Void (Ptr{Void}, Int32, Int32) prob.p col stat end function std_basis(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall std_basis Void (Ptr{Void},) prob.p end function adv_basis(prob::Prob, flags::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_adv_basis_flags(flags) + check_prob(prob) + check_adv_basis_flags(flags) @glpk_ccall adv_basis Void (Ptr{Void}, Int32) prob.p flags end adv_basis(prob::Prob) = adv_basis(prob, 0) function cpx_basis(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall cpx_basis Void (Ptr{Void},) prob.p end function simplex{Tp<:Union(SimplexParam, Nothing)}(prob::Prob, param::Tp) - _jl_glpk__check_prob(prob) + check_prob(prob) if param == nothing param_ptr = C_NULL else @@ -1518,7 +1509,7 @@ simplex(prob::Prob) = simplex(prob, nothing) function exact{Tp<:Union(SimplexParam, Nothing)}(prob::Prob, param::Tp) - _jl_glpk__check_prob(prob) + check_prob(prob) if param == nothing param_ptr = C_NULL else @@ -1531,73 +1522,73 @@ exact(prob::Prob) = exact(prob, nothing) function init_smcp(param::SimplexParam) - _jl_glpk__check_simplex_param(param) + check_simplex_param(param) @glpk_ccall init_smcp Int32 (Ptr{Void},) pointer(param) end function get_status(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_status Int32 (Ptr{Void},) prob.p end function get_prim_stat(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_prim_stat Int32 (Ptr{Void},) prob.p end function get_dual_stat(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_dual_stat Int32 (Ptr{Void},) prob.p end function get_obj_val(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_obj_val Float64 (Ptr{Void},) prob.p end function get_row_stat(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall get_row_stat Int32 (Ptr{Void}, Int32) prob.p row end function get_row_prim(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall get_row_prim Float64 (Ptr{Void}, Int32) prob.p row end function get_row_dual(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall get_row_dual Float64 (Ptr{Void}, Int32) prob.p row end function get_col_stat(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall get_col_stat Int32 (Ptr{Void}, Int32) prob.p col end function get_col_prim(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall get_col_prim Float64 (Ptr{Void}, Int32) prob.p col end function get_col_dual(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall get_col_dual Float64 (Ptr{Void}, Int32) prob.p col end function get_unbnd_ray(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_unbnd_ray Int32 (Ptr{Void},) prob.p end function interior{Tp<:Union(InteriorParam, Nothing)}(prob::Prob, param::Tp) - _jl_glpk__check_prob(prob) + check_prob(prob) if param == nothing param_ptr::Ptr{Void} = C_NULL else @@ -1609,69 +1600,69 @@ end interior(prob::Prob) = interior(prob, nothing) function init_iptcp(param::InteriorParam) - _jl_glpk__check_interior_param(param) + check_interior_param(param) @glpk_ccall init_iptcp Int32 (Ptr{Void},) pointer(param) end function ipt_status(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall ipt_status Int32 (Ptr{Void},) prob.p end function ipt_obj_val(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall ipt_obj_val Float64 (Ptr{Void},) prob.p end function ipt_row_prim(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall ipt_row_prim Float64 (Ptr{Void}, Int32) prob.p row end function ipt_row_dual(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall ipt_row_dual Float64 (Ptr{Void}, Int32) prob.p row end function ipt_col_prim(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall ipt_col_prim Float64 (Ptr{Void}, Int32) prob.p col end function ipt_col_dual(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall ipt_col_dual Float64 (Ptr{Void}, Int32) prob.p col end function set_col_kind(prob::Prob, col::Integer, kind::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) - _jl_glpk__check_kind_is_valid(kind) + check_prob(prob) + check_col_is_valid(prob, col) + check_kind_is_valid(kind) @glpk_ccall set_col_kind Void (Ptr{Void}, Int32, Int32) prob.p col kind end function get_col_kind(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall get_col_kind Int32 (Ptr{Void}, Int32) prob.p col end function get_num_int(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_num_int Int32 (Ptr{Void},) prob.p end function get_num_bin(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall get_num_bin Int32 (Ptr{Void},) prob.p end function intopt{Tp<:Union(IntoptParam, Nothing)}(prob::Prob, param::Tp) - _jl_glpk__check_prob(prob) + check_prob(prob) if param == nothing param_ptr::Ptr{Void} = C_NULL else @@ -1683,29 +1674,29 @@ end intopt(prob::Prob) = intopt(prob, nothing) function init_iocp(param::IntoptParam) - _jl_glpk__check_intopt_param(param) + check_intopt_param(param) @glpk_ccall init_iocp Int32 (Ptr{Void},) pointer(param) end function mip_status(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall mip_status Int32 (Ptr{Void},) prob.p end function mip_obj_val(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall mip_obj_val Float64 (Ptr{Void},) prob.p end function mip_row_val(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_row_is_valid(prob, row) @glpk_ccall mip_row_val Float64 (Ptr{Void}, Int32) prob.p row end function mip_col_val(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_col_is_valid(prob, col) @glpk_ccall mip_col_val Float64 (Ptr{Void}, Int32) prob.p col end @@ -1713,15 +1704,15 @@ end #function lpx_check_kkt(prob::Prob, scaled::Integer, kkt) function read_mps(prob::Prob, format::Integer, param, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_mps_format(format) + check_prob(prob) + check_mps_format(format) if is(param, nothing) param = C_NULL else - _jl_glpk__check_mps_param(param) + check_mps_param(param) end - _jl_glpk__check_file_is_readable(filename) + check_file_is_readable(filename) ret = @glpk_ccall read_mps Int32 (Ptr{Void}, Int32, Ptr{Void}, Ptr{Uint8}) prob.p format param bytestring(filename) if ret != 0 throw(Error("Error reading MPS file")) @@ -1733,14 +1724,14 @@ read_mps(prob::Prob, format::Integer, filename::String) = read_mps(prob, format, C_NULL, filename) function write_mps(prob::Prob, format::Integer, param, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_mps_format(format) + check_prob(prob) + check_mps_format(format) if is(param, nothing) param = C_NULL else - _jl_glpk__check_mps_param(param) + check_mps_param(param) end - _jl_glpk__check_file_is_writable(filename) + check_file_is_writable(filename) ret = @glpk_ccall write_mps Int32 (Ptr{Void}, Int32, Ptr{Void}, Ptr{Uint8}) prob.p format param bytestring(filename) if ret != 0 throw(Error("Error writing MPS file")) @@ -1752,9 +1743,9 @@ write_mps(prob::Prob, format::Integer, filename::String) = write_mps(prob, format, C_NULL, filename) function read_lp(prob::Prob, param, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_lp_param(param) - _jl_glpk__check_file_is_readable(filename) + check_prob(prob) + check_lp_param(param) + check_file_is_readable(filename) ret = @glpk_ccall read_lp Int32 (Ptr{Void}, Ptr{Void}, Ptr{Uint8}) prob.p param bytestring(filename) if ret != 0 throw(Error("Error reading LP file")) @@ -1766,9 +1757,9 @@ read_lp(prob::Prob, filename::String) = read_lp(prob, C_NULL, filename) function write_lp(prob::Prob, param, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_lp_param(param) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_lp_param(param) + check_file_is_writable(filename) ret = @glpk_ccall write_lp Int32 (Ptr{Void}, Ptr{Void}, Ptr{Uint8}) prob.p param bytestring(filename) if ret != 0 throw(Error("Error writing LP file")) @@ -1780,9 +1771,9 @@ write_lp(prob::Prob, filename::String) = write_lp(prob, C_NULL, filename) function read_prob(prob::Prob, flags::Integer, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_read_prob_flags(flags) - _jl_glpk__check_file_is_readable(filename) + check_prob(prob) + check_read_prob_flags(flags) + check_file_is_readable(filename) @glpk_ccall read_prob Int32 (Ptr{Void}, Int32, Ptr{Uint8}) prob.p flags bytestring(filename) end @@ -1790,9 +1781,9 @@ read_prob(prob::Prob, filename::String) = read_prob(prob, 0, filename) function write_prob(prob::Prob, flags::Integer, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_write_prob_flags(flags) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_write_prob_flags(flags) + check_file_is_writable(filename) @glpk_ccall write_prob Int32 (Ptr{Void}, Int32, Ptr{Uint8}) prob.p flags bytestring(filename) end @@ -1800,8 +1791,8 @@ write_prob(prob::Prob, filename::String) = write_prob(prob, 0, filename) function mpl_read_model(tran::MathProgWorkspace, filename::String, skip::Integer) - _jl_glpk__check_mpl_workspace(tran) - _jl_glpk__check_file_is_readable(filename) + check_mpl_workspace(tran) + check_file_is_readable(filename) ret = @glpk_ccall mpl_read_model Int32 (Ptr{Void}, Ptr{Uint8}, Int32) tran.p bytestring(filename) skip if ret != 0 throw(Error("Error reading MathProg file")) @@ -1810,8 +1801,8 @@ function mpl_read_model(tran::MathProgWorkspace, filename::String, skip::Integer end function mpl_read_data(tran::MathProgWorkspace, filename::String) - _jl_glpk__check_mpl_workspace(tran) - _jl_glpk__check_file_is_readable(filename) + check_mpl_workspace(tran) + check_file_is_readable(filename) ret = @glpk_ccall mpl_read_data Int32 (Ptr{Void}, Ptr{Uint8}) tran.p bytestring(filename) if ret != 0 throw(Error("Error reading MathProg data file")) @@ -1820,11 +1811,11 @@ function mpl_read_data(tran::MathProgWorkspace, filename::String) end function mpl_generate(tran::MathProgWorkspace, filename::Union(String, Nothing)) - _jl_glpk__check_mpl_workspace(tran) + check_mpl_workspace(tran) if is(filename, nothing) cfilename = C_NULL else - _jl_glpk__check_file_is_writable(filename) + check_file_is_writable(filename) cfilename = bytestring(filename) end ret = @glpk_ccall mpl_generate Int32 (Ptr{Void}, Ptr{Uint8}) tran.p cfilename @@ -1837,14 +1828,14 @@ end mpl_generate(tran::MathProgWorkspace) = mpl_generate(tran, nothing) function mpl_build_prob(tran::MathProgWorkspace, prob::Prob) - _jl_glpk__check_mpl_workspace(tran) - _jl_glpk__check_prob(prob) + check_mpl_workspace(tran) + check_prob(prob) @glpk_ccall mpl_build_prob Void (Ptr{Void}, Ptr{Void}) tran.p prob.p end function mpl_postsolve(tran::MathProgWorkspace, prob::Prob, sol::Integer) - _jl_glpk__check_mpl_workspace(tran) - _jl_glpk__check_prob(prob) + check_mpl_workspace(tran) + check_prob(prob) if !(sol == SOL || sol == IPT || sol == MIP) throw(Error("Invalid parameter sol $sol (use GLPK.SOL, GLPK.IPT or GLPK.MIP)")) end @@ -1856,8 +1847,8 @@ function mpl_postsolve(tran::MathProgWorkspace, prob::Prob, sol::Integer) end function print_sol(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_file_is_writable(filename) ret = @glpk_ccall print_sol Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error printing solution")) @@ -1866,8 +1857,8 @@ function print_sol(prob::Prob, filename::String) end function read_sol(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_readable(filename) + check_prob(prob) + check_file_is_readable(filename) ret = @glpk_ccall read_sol Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error reading solution")) @@ -1876,8 +1867,8 @@ function read_sol(prob::Prob, filename::String) end function write_sol(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_file_is_writable(filename) ret = @glpk_ccall write_sol Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error writing solution")) @@ -1886,8 +1877,8 @@ function write_sol(prob::Prob, filename::String) end function print_ipt(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_file_is_writable(filename) ret = @glpk_ccall print_ipt Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error printing interior point solution")) @@ -1896,8 +1887,8 @@ function print_ipt(prob::Prob, filename::String) end function read_ipt(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_readable(filename) + check_prob(prob) + check_file_is_readable(filename) ret = @glpk_ccall read_ipt Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error reading interior point solution")) @@ -1906,8 +1897,8 @@ function read_ipt(prob::Prob, filename::String) end function write_ipt(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_file_is_writable(filename) ret = @glpk_ccall write_ipt Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error writing interior point solution")) @@ -1916,8 +1907,8 @@ function write_ipt(prob::Prob, filename::String) end function print_mip(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_file_is_writable(filename) ret = @glpk_ccall print_mip Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error printing mixed integer programming solution")) @@ -1926,8 +1917,8 @@ function print_mip(prob::Prob, filename::String) end function read_mip(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_readable(filename) + check_prob(prob) + check_file_is_readable(filename) ret = @glpk_ccall read_mip Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error reading mixed integer programming solution")) @@ -1936,8 +1927,8 @@ function read_mip(prob::Prob, filename::String) end function write_mip(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_file_is_writable(filename) ret = @glpk_ccall write_mip Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error writing mixed integer programming solution")) @@ -1946,16 +1937,16 @@ function write_mip(prob::Prob, filename::String) end function print_ranges{Ti<:Integer}(prob::Prob, len::Integer, list::Vector{Ti}, flags::Integer, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_vectors_size(len, list) - _jl_glpk__check_status_is_optimal(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_print_ranges_flags(flags) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_vectors_size(len, list) + check_status_is_optimal(prob) + check_bf_exists(prob) + check_print_ranges_flags(flags) + check_file_is_writable(filename) if len > 0 list32 = int32(list) - _jl_glpk__check_list_ids(prob, len, list32) + check_list_ids(prob, len, list32) off32 = sizeof(Int32) list32p = pointer(list32) - off32 @@ -1976,49 +1967,49 @@ print_ranges{Ti<:Integer}(prob::Prob, list::Vector{Ti}, filename::String) = print_ranges(prob, length(list), list, 0, filename) function print_ranges(prob::Prob, len::Integer, list::VecOrNothing, flags::Integer, filename::String) - list = _jl_glpk__convert_vecornothing(Int32, list) + list = convert_vecornothing(Int32, list) print_ranges(prob, len, list, flags, filename) end print_ranges(prob::Prob, list::VecOrNothing, flags::Integer, filename::String) = - print_ranges(prob, _jl_glpk__vecornothing_length(list), list, flags, filename) + print_ranges(prob, vecornothing_length(list), list, flags, filename) print_ranges(prob::Prob, len::Integer, list::VecOrNothing, filename::String) = print_ranges(prob, len, list, 0, filename) print_ranges(prob::Prob, list::VecOrNothing, filename::String) = - print_ranges(prob, _jl_glpk__vecornothing_length(list), list, 0, filename) + print_ranges(prob, vecornothing_length(list), list, 0, filename) print_ranges(prob::Prob, filename::String) = print_ranges(prob, 0, nothing, 0, filename) function bf_exists(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall bf_exists Int32 (Ptr{Void},) prob.p end function factorize(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall factorize Int32 (Ptr{Void},) prob.p end function bf_updated(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall bf_updated Int32 (Ptr{Void},) prob.p end function get_bfcp(prob::Prob, param::BasisFactParam) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bfcp(param) + check_prob(prob) + check_bfcp(param) @glpk_ccall get_bfcp Void (Ptr{Void}, Ptr{Void}) prob.p pointer(param) end function set_bfcp(prob::Prob, param::Union(BasisFactParam,Nothing)) - _jl_glpk__check_prob(prob) + check_prob(prob) if is(param, nothing) param_p = C_NULL else - _jl_glpk__check_bfcp(param) + check_bfcp(param) param_p = pointer(param) end @glpk_ccall set_bfcp Void (Ptr{Void}, Ptr{Void}) prob.p param_p @@ -2026,51 +2017,51 @@ end set_bfcp(prob::Prob) = set_bfcp(prob, nothing) function get_bhead(prob::Prob, k::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_row_is_valid(prob, k) + check_prob(prob) + check_row_is_valid(prob, k) @glpk_ccall get_bhead Int32 (Ptr{Void}, Int32) prob.p k end function get_row_bind(prob::Prob, row::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_row_is_valid(prob, row) + check_prob(prob) + check_bf_exists(prob) + check_row_is_valid(prob, row) @glpk_ccall get_row_bind Int32 (Ptr{Void}, Int32) prob.p row end function get_col_bind(prob::Prob, col::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_col_is_valid(prob, col) + check_prob(prob) + check_bf_exists(prob) + check_col_is_valid(prob, col) @glpk_ccall get_col_bind Int32 (Ptr{Void}, Int32) prob.p col end function ftran(prob::Prob, x::Vector{Float64}) - _jl_glpk__check_prob(prob) + check_prob(prob) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p - _jl_glpk__check_vectors_size(rows, x) + check_vectors_size(rows, x) off64 = sizeof(Float64) x64p = pointer(x) - off64 @glpk_ccall ftran Void (Ptr{Void}, Ptr{Float64}) prob.p x64p end function btran(prob::Prob, x::Vector{Float64}) - _jl_glpk__check_prob(prob) + check_prob(prob) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p - _jl_glpk__check_vectors_size(rows, x) + check_vectors_size(rows, x) off64 = sizeof(Float64) x64p = pointer(x) - off64 @glpk_ccall btran Void (Ptr{Void}, Ptr{Float64}) prob.p x64p end function warm_up(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall warm_up Int32 (Ptr{Void},) prob.p end function eval_tab_row(prob::Prob, k::Integer, ind::Vector{Int32}, val::Vector{Float64}) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) + check_prob(prob) + check_bf_exists(prob) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p @@ -2080,7 +2071,7 @@ function eval_tab_row(prob::Prob, k::Integer, ind::Vector{Int32}, val::Vector{Fl throw(Error("index out of bounds: $k (bounds are 1 <= k <= $k_max")) end - _jl_glpk__check_var_is_basic(prob, k) + check_var_is_basic(prob, k) grow(ind, k_max - length(ind)) grow(val, k_max - length(val)) @@ -2099,8 +2090,8 @@ function eval_tab_row(prob::Prob, k::Integer, ind::Vector{Int32}, val::Vector{Fl end function eval_tab_row(prob::Prob, k::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) + check_prob(prob) + check_bf_exists(prob) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p @@ -2110,7 +2101,7 @@ function eval_tab_row(prob::Prob, k::Integer) throw(Error("index out of bounds: $k (bounds are 1 <= k <= $k_max")) end - _jl_glpk__check_var_is_basic(prob, k) + check_var_is_basic(prob, k) ind = Array(Int32, k_max) val = Array(Float64, k_max) @@ -2129,8 +2120,8 @@ function eval_tab_row(prob::Prob, k::Integer) end function eval_tab_col(prob::Prob, k::Integer, ind::Vector{Int32}, val::Vector{Float64}) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) + check_prob(prob) + check_bf_exists(prob) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p @@ -2141,7 +2132,7 @@ function eval_tab_col(prob::Prob, k::Integer, ind::Vector{Int32}, val::Vector{Fl throw(Error("index out of bounds: $k (bounds are 1 <= k <= $k_max")) end - _jl_glpk__check_var_is_non_basic(prob, k) + check_var_is_non_basic(prob, k) grow(ind, k_max - length(ind)) grow(val, k_max - length(val)) @@ -2160,8 +2151,8 @@ function eval_tab_col(prob::Prob, k::Integer, ind::Vector{Int32}, val::Vector{Fl end function eval_tab_col(prob::Prob, k::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) + check_prob(prob) + check_bf_exists(prob) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p @@ -2172,7 +2163,7 @@ function eval_tab_col(prob::Prob, k::Integer) throw(Error("index out of bounds: $k (bounds are 1 <= k <= $k_max")) end - _jl_glpk__check_var_is_non_basic(prob, k) + check_var_is_non_basic(prob, k) ind = Array(Int32, k_max) val = Array(Float64, k_max) @@ -2191,10 +2182,10 @@ function eval_tab_col(prob::Prob, k::Integer) end function transform_row(prob::Prob, len::Integer, ind::Vector{Int32}, val::Vector{Float64}) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_col_is_valid(prob, len) - _jl_glpk__check_vectors_size(len, ind, val) + check_prob(prob) + check_bf_exists(prob) + check_col_is_valid(prob, len) + check_vectors_size(len, ind, val) cols = @glpk_ccall get_num_cols Int32 (Ptr{Void},) prob.p @@ -2215,15 +2206,15 @@ function transform_row(prob::Prob, len::Integer, ind::Vector{Int32}, val::Vector end function transform_row(prob::Prob, ind::Vector{Int32}, val::Vector{Float64}) - _jl_glpk__check_vectors_all_same_size(ind, val) + check_vectors_all_same_size(ind, val) transform_row(prob, length(ind), ind, val) end function transform_col(prob::Prob, len::Integer, ind::Vector{Int32}, val::Vector{Float64}) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_row_is_valid(prob, len) - _jl_glpk__check_vectors_size(len, ind, val) + check_prob(prob) + check_bf_exists(prob) + check_row_is_valid(prob, len) + check_vectors_size(len, ind, val) rows = @glpk_ccall get_num_rows Int32 (Ptr{Void},) prob.p @@ -2244,21 +2235,21 @@ function transform_col(prob::Prob, len::Integer, ind::Vector{Int32}, val::Vector end function transform_col(prob::Prob, ind::Vector{Int32}, val::Vector{Float64}) - _jl_glpk__check_vectors_all_same_size(ind, val) + check_vectors_all_same_size(ind, val) transform_col(prob, length(ind), ind, val) end function prim_rtest{Ti<:Integer, Tv<:Real}(prob::Prob, len::Integer, ind::Vector{Ti}, val::Vector{Tv}, dir::Integer, eps::Real) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_is_prim_feasible(prob) - _jl_glpk__check_row_is_valid(prob, len) - _jl_glpk__check_vectors_size(len, ind, val) - _jl_glpk__check_dir_is_valid(dir) - _jl_glpk__check_eps_is_valid(eps) + check_prob(prob) + check_bf_exists(prob) + check_is_prim_feasible(prob) + check_row_is_valid(prob, len) + check_vectors_size(len, ind, val) + check_dir_is_valid(dir) + check_eps_is_valid(eps) for i = 1:len - _jl_glpk__check_var_is_basic(prob, ind[i]) + check_var_is_basic(prob, ind[i]) end ind32 = int32(ind) @@ -2273,21 +2264,21 @@ function prim_rtest{Ti<:Integer, Tv<:Real}(prob::Prob, len::Integer, ind::Vector end function prim_rtest{Ti<:Integer, Tv<:Real}(prob::Prob, ind::Vector{Ti}, val::Vector{Tv}, dir::Integer, eps::Real) - _jl_glpk__check_vectors_all_same_size(ind, val) + check_vectors_all_same_size(ind, val) prim_rtest(prob, length(ind), ind, val, dir, eps) end function dual_rtest{Ti<:Integer, Tv<:Real}(prob::Prob, len::Integer, ind::Vector{Ti}, val::Vector{Tv}, dir::Integer, eps::Real) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_is_dual_feasible(prob) - _jl_glpk__check_col_is_valid(prob, len) - _jl_glpk__check_vectors_size(len, ind, val) - _jl_glpk__check_dir_is_valid(dir) - _jl_glpk__check_eps_is_valid(eps) + check_prob(prob) + check_bf_exists(prob) + check_is_dual_feasible(prob) + check_col_is_valid(prob, len) + check_vectors_size(len, ind, val) + check_dir_is_valid(dir) + check_eps_is_valid(eps) for i = 1:len - _jl_glpk__check_var_is_non_basic(prob, ind[i]) + check_var_is_non_basic(prob, ind[i]) end ind32 = int32(ind) @@ -2302,7 +2293,7 @@ function dual_rtest{Ti<:Integer, Tv<:Real}(prob::Prob, len::Integer, ind::Vector end function dual_rtest{Ti<:Integer, Tv<:Real}(prob::Prob, ind::Vector{Ti}, val::Vector{Tv}, dir::Integer, eps::Real) - _jl_glpk__check_vectors_all_same_size(ind, val) + check_vectors_all_same_size(ind, val) dual_rtest(prob, length(ind), ind, val, dir, eps) end @@ -2311,10 +2302,10 @@ function analyze_bound(prob::Prob, k, limit1, var1, limit2, var2) end function analyze_bound(prob::Prob, k::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_rowcol_is_valid(prob, k) - _jl_glpk__check_var_is_non_basic(prob, k) + check_prob(prob) + check_bf_exists(prob) + check_rowcol_is_valid(prob, k) + check_var_is_non_basic(prob, k) limit1 = Array(Float64, 1) var1 = Array(Int32, 1) @@ -2331,10 +2322,10 @@ function analyze_coef(prob::Prob, k, coef1, var1, value1, coef2, var2, value2) end function analyze_coef(prob::Prob, k::Integer) - _jl_glpk__check_prob(prob) - _jl_glpk__check_bf_exists(prob) - _jl_glpk__check_rowcol_is_valid(prob, k) - _jl_glpk__check_var_is_basic(prob, k) + check_prob(prob) + check_bf_exists(prob) + check_rowcol_is_valid(prob, k) + check_var_is_basic(prob, k) coef1 = Array(Float64, 1) var1 = Array(Int32, 1) @@ -2350,7 +2341,7 @@ end function init_env() ret = @glpk_ccall init_env Int32 () - _jl_glpk__check_init_env_succeeded(ret) + check_init_env_succeeded(ret) return ret end @@ -2359,13 +2350,13 @@ function free_env() end function term_out(flag::Integer) - _jl_glpk__check_term_out_flag(flag) + check_term_out_flag(flag) @glpk_ccall term_out Int32 (Int32,) flag end function open_tee(filename::String) ret = @glpk_ccall open_tee Int32 (Ptr{Uint8},) bytestring(filename) - _jl_glpk__check_open_tee_succeeded(ret) + check_open_tee_succeeded(ret) return ret end @@ -2374,18 +2365,18 @@ function close_tee() end function malloc(size::Integer) - _jl_glpk__check_alloc_size(size) + check_alloc_size(size) @glpk_ccall malloc Ptr{Void} (Int32,) size end function calloc(n::Integer, size::Integer) - _jl_glpk__check_alloc_size(n) - _jl_glpk__check_alloc_size(size) + check_alloc_size(n) + check_alloc_size(size) @glpk_ccall calloc Ptr{Void} (Int32, Int32) n size end function free(ptr::Ptr) - _jl_glpk__check_pointer_is_valid(ptr) + check_pointer_is_valid(ptr) @glpk_ccall free Void (Ptr{Void},) ptr end @@ -2430,47 +2421,47 @@ function difftime(t1::Integer, t0::Integer) end function sdf_open_file(filename::String) - _jl_glpk__check_file_is_readable(filename) + check_file_is_readable(filename) data_p = @glpk_ccall sdf_open_file Ptr{Void} (Ptr{Uint8},) bytestring(filename) - _jl_glpk__check_sdf_file_opened(data_p) + check_sdf_file_opened(data_p) return Data(data_p) end function sdf_read_int(data::Data) - _jl_glpk__check_data(data) + check_data(data) @glpk_ccall sdf_read_int Int32 (Ptr{Void},) pointer(data) end function sdf_read_num(data::Data) - _jl_glpk__check_data(data) + check_data(data) @glpk_ccall sdf_read_num Float64 (Ptr{Void},) pointer(data) end function sdf_read_item(data::Data) - _jl_glpk__check_data(data) + check_data(data) item_cstr = @glpk_ccall sdf_read_item Ptr{Uint8} (Ptr{Void},) pointer(data) return bytestring(item_cstr) end function sdf_read_text(data::Data) - _jl_glpk__check_data(data) + check_data(data) text_cstr = @glpk_ccall sdf_read_text Ptr{Uint8} (Ptr{Void},) pointer(data) return bytestring(text_cstr) end function sdf_line(data::Data) - _jl_glpk__check_data(data) + check_data(data) @glpk_ccall sdf_line Int32 (Ptr{Void},) pointer(data) end function sdf_close_file(data::Data) - _jl_glpk__check_data(data) + check_data(data) @glpk_ccall sdf_close_file Void (Ptr{Void},) pointer(data) end function read_cnfsat(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_readable(filename) + check_prob(prob) + check_file_is_readable(filename) ret = @glpk_ccall read_cnfsat Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error reading CNF file")) @@ -2479,13 +2470,13 @@ function read_cnfsat(prob::Prob, filename::String) end function check_cnfsat(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall check_cnfsat Int32 (Ptr{Void},) prob.p end function write_cnfsat(prob::Prob, filename::String) - _jl_glpk__check_prob(prob) - _jl_glpk__check_file_is_writable(filename) + check_prob(prob) + check_file_is_writable(filename) ret = @glpk_ccall write_cnfsat Int32 (Ptr{Void}, Ptr{Uint8}) prob.p bytestring(filename) if ret != 0 throw(Error("Error writing CNF file")) @@ -2494,12 +2485,12 @@ function write_cnfsat(prob::Prob, filename::String) end function minisat1(prob::Prob) - _jl_glpk__check_prob(prob) + check_prob(prob) @glpk_ccall minisat1 Int32 (Ptr{Void},) prob.p end function intfeas1(prob::Prob, use_bound::Integer, obj_bound::Integer) - _jl_glpk__check_prob(prob) + check_prob(prob) # TODO : more checks: # 1) columns must be GLPK.BV od GLPK.FX # 2) constraints and objj coeffs must be integer diff --git a/extras/gzip.jl b/extras/gzip.jl index 040226c8c318a..9ffb0ef0166d8 100644 --- a/extras/gzip.jl +++ b/extras/gzip.jl @@ -92,7 +92,7 @@ GZipStream(name::String, gz_file::Ptr{Void}) = GZipStream(name, gz_file, Z_DEFAU function gzerror(err::Integer, s::GZipStream) e = Int32[err] if !s._closed - msg_p = ccall(dlsym(_zlib, :gzerror), Ptr{Uint8}, (Ptr{Void}, Ptr{Int32}), + msg_p = ccall((:gzerror, _zlib), Ptr{Uint8}, (Ptr{Void}, Ptr{Int32}), s.gz_file, e) msg = (msg_p == C_NULL ? "" : bytestring(msg_p)) else @@ -162,53 +162,57 @@ end # Easy access to gz reading/writing functions (Internal) gzgetc(s::GZipStream) = - @test_eof_gzerr(s, ccall(dlsym(_zlib, :gzgetc), Int32, (Ptr{Void},), s.gz_file), -1) + @test_eof_gzerr(s, ccall((:gzgetc, _zlib), Int32, (Ptr{Void},), s.gz_file), -1) gzungetc(c::Integer, s::GZipStream) = - @test_eof_gzerr(s, ccall(dlsym(_zlib, :gzungetc), Int32, (Int32, Ptr{Void}), c, s.gz_file), -1) + @test_eof_gzerr(s, ccall((:gzungetc, _zlib), Int32, (Int32, Ptr{Void}), c, s.gz_file), -1) gzgets(s::GZipStream, a::Array{Uint8}) = - @test_eof_gzerr2(s, ccall(dlsym(_zlib, :gzgets), Ptr{Uint8}, (Ptr{Void}, Ptr{Uint8}, Int32), + @test_eof_gzerr2(s, ccall((:gzgets, _zlib), Ptr{Uint8}, (Ptr{Void}, Ptr{Uint8}, Int32), s.gz_file, a, int32(length(a))), C_NULL) gzgets(s::GZipStream, p::Ptr{Uint8}, len::Integer) = - @test_eof_gzerr2(s, ccall(dlsym(_zlib, :gzgets), Ptr{Uint8}, (Ptr{Void}, Ptr{Uint8}, Int32), + @test_eof_gzerr2(s, ccall((:gzgets, _zlib), Ptr{Uint8}, (Ptr{Void}, Ptr{Uint8}, Int32), s.gz_file, p, int32(len)), C_NULL) gzputc(s::GZipStream, c::Integer) = - @test_gzerror(s, ccall(dlsym(_zlib, :gzputc), Int32, (Ptr{Void}, Int32), + @test_gzerror(s, ccall((:gzputc, _zlib), Int32, (Ptr{Void}, Int32), s.gz_file, int32(c)), -1) gzwrite(s::GZipStream, p::Ptr, len::Integer) = - @test_gzerror0(s, ccall(dlsym(_zlib, :gzwrite), Int32, (Ptr{Void}, Ptr{Void}, Uint32), + @test_gzerror0(s, ccall((:gzwrite, _zlib), Int32, (Ptr{Void}, Ptr{Void}, Uint32), s.gz_file, p, len)) gzread(s::GZipStream, p::Ptr, len::Integer) = - @test_gzerror(s, ccall(dlsym(_zlib, :gzread), Int32, (Ptr{Void}, Ptr{Void}, Uint32), + @test_gzerror(s, ccall((:gzread, _zlib), Int32, (Ptr{Void}, Ptr{Void}, Uint32), s.gz_file, p, len), -1) -# Doesn't exist in zlib 1.2.3 or earlier -if dlsym_e(_zlib, :gzbuffer) != C_NULL - gzbuffer(gz_file::Ptr, gz_buf_size::Integer) = - ccall(dlsym(_zlib, :gzbuffer), Int32, (Ptr{Void}, Uint32), gz_file, gz_buf_size) -else - gzbuffer(gz_file::Ptr, gz_buf_size::Integer) = int32(-1) -end +let _zlib_h = dlopen("libz") + global gzbuffer, _gzopen, _gzseek, _gztell + + # Doesn't exist in zlib 1.2.3 or earlier + if dlsym_e(_zlib_h, :gzbuffer) != C_NULL + gzbuffer(gz_file::Ptr, gz_buf_size::Integer) = + ccall((:gzbuffer, _zlib), Int32, (Ptr{Void}, Uint32), gz_file, gz_buf_size) + else + gzbuffer(gz_file::Ptr, gz_buf_size::Integer) = int32(-1) + end -##### + ##### -# Use 64-bit functions if available + # Use 64-bit functions if available -if dlsym_e(_zlib, :gzopen64) != C_NULL - const _gzopen = :gzopen64 - const _gzseek = :gzseek64 - const _gztell = :gztell64 - #_gzoffset = :gzoffset64 ## not implemented -else - const _gzopen = :gzopen - const _gzseek = :gzseek - const _gztell = :gztell - #_gzoffset = :gzoffset ## not implemented + if dlsym_e(_zlib_h, :gzopen64) != C_NULL + const _gzopen = :gzopen64 + const _gzseek = :gzseek64 + const _gztell = :gztell64 + #_gzoffset = :gzoffset64 ## not implemented + else + const _gzopen = :gzopen + const _gzseek = :gzseek + const _gztell = :gztell + #_gzoffset = :gzoffset ## not implemented + end end function gzopen(fname::String, gzmode::String, gz_buf_size::Integer) @@ -224,7 +228,7 @@ function gzopen(fname::String, gzmode::String, gz_buf_size::Integer) gzmode *= "b" end - gz_file = ccall(dlsym(_zlib, _gzopen), Ptr{Void}, (Ptr{Uint8}, Ptr{Uint8}), fname, gzmode) + gz_file = ccall((_gzopen, _zlib), Ptr{Void}, (Ptr{Uint8}, Ptr{Uint8}), fname, gzmode) if gz_file == C_NULL throw(GZError(-1, "gzopen failed")) end @@ -258,7 +262,7 @@ function gzdopen(name::String, fd::Integer, gzmode::String, gz_buf_size::Integer # not to close the original fd dup_fd = ccall(:dup, Int32, (Int32,), fd) - gz_file = ccall(dlsym(_zlib, :gzdopen), Ptr{Void}, (Int32, Ptr{Uint8}), dup_fd, gzmode) + gz_file = ccall((:gzdopen, _zlib), Ptr{Void}, (Int32, Ptr{Uint8}), dup_fd, gzmode) if gz_file == C_NULL throw(GZError(-1, "gzdopen failed")) end @@ -294,20 +298,20 @@ function close(s::GZipStream) s.name *= " (closed)" - ret = (@test_z_ok ccall(dlsym(_zlib, :gzclose), Int32, (Ptr{Void},), s.gz_file)) + ret = (@test_z_ok ccall((:gzclose, _zlib), Int32, (Ptr{Void},), s.gz_file)) return ret end flush(s::GZipStream, fl::Integer) = - @test_z_ok ccall(dlsym(_zlib, :gzflush), Int32, (Ptr{Void}, Int32), s.gz_file, int32(fl)) + @test_z_ok ccall((:gzflush, _zlib), Int32, (Ptr{Void}, Int32), s.gz_file, int32(fl)) flush(s::GZipStream) = flush(s, Z_SYNC_FLUSH) truncate(s::GZipStream, n::Integer) = error("truncate is not supported for GZipStreams") # Note: seeks to byte position within uncompressed data stream seek(s::GZipStream, n::Integer) = - (ccall(dlsym(_zlib, _gzseek), ZFileOffset, (Ptr{Void}, ZFileOffset, Int32), + (ccall((_gzseek, _zlib), ZFileOffset, (Ptr{Void}, ZFileOffset, Int32), s.gz_file, n, SEEK_SET)!=-1 || # Mimick behavior of seek(s::IOStream, n) error("seek (gzseek) failed")) @@ -315,14 +319,14 @@ seek_end(s::GZipStream) = error("seek_end is not supported for GZipStreams") # Note: skips bytes within uncompressed data stream skip(s::GZipStream, n::Integer) = - (ccall(dlsym(_zlib, _gzseek), ZFileOffset, (Ptr{Void}, ZFileOffset, Int32), + (ccall((_gzseek, _zlib), ZFileOffset, (Ptr{Void}, ZFileOffset, Int32), s.gz_file, n, SEEK_CUR)!=-1 || error("skip (gzseek) failed")) # Mimick behavior of skip(s::IOStream, n) position(s::GZipStream) = - ccall(dlsym(_zlib, _gztell), ZFileOffset, (Ptr{Void},), s.gz_file) + ccall((_gztell, _zlib), ZFileOffset, (Ptr{Void},), s.gz_file) -eof(s::GZipStream) = bool(ccall(dlsym(_zlib, :gzeof), Int32, (Ptr{Void},), s.gz_file)) +eof(s::GZipStream) = bool(ccall((:gzeof, _zlib), Int32, (Ptr{Void},), s.gz_file)) function check_eof(s::GZipStream) # Force eof to be set... @@ -341,7 +345,7 @@ function read{T<:Union(Int8,Uint8,Int16,Uint16,Int32,Uint32,Int64,Uint64, Int128,Uint128,Float32,Float64,Complex64,Complex128)}(s::GZipStream, a::Array{T}) nb = numel(a)*sizeof(T) # Note: this will overflow and succeed without warning if nb > 4GB - ret = ccall(dlsym(_zlib, :gzread), Int32, + ret = ccall((:gzread, _zlib), Int32, (Ptr{Void}, Ptr{Void}, Uint32), s.gz_file, a, nb) if ret == -1 throw(GZError(s)) @@ -398,46 +402,23 @@ end readall(s::GZipStream) = readall(s, Z_BIG_BUFSIZE) # TODO: Create a c-wrapper based on gzreadline -function readuntil(s::GZipStream, delim) - if delim == '\n' - return readline(s) - else - buf = memio(GZ_LINE_BUFSIZE, false) - c = read(s, Char) - print(buf, c) - while c != delim && !eof(s) - try - c = read(s, Char) - print(buf, c) - catch e - if !isa(e, EOFError) - throw(e) - end - end - end - check_eof(s) - takebuf_string(buf) - end -end - - -function readline(s::GZipStream) +function readuntil(s::GZipStream, c::Uint8) buf = Array(Uint8, GZ_LINE_BUFSIZE) pos = 1 if gzgets(s, buf) == C_NULL # Throws an exception on error - return "" + return buf[1:0] end while(true) # since gzgets didn't return C_NULL, there must be a \0 in the buffer eos = memchr(buf, '\0', pos) - if eos == 1 || buf[eos-1] == '\n' - return bytestring(buf[1:eos-1]) + if eos == 1 || buf[eos-1] == c + return buf[1:eos-1] end # If we're at the end of the file, return the string - if eof(s) return bytestring(buf[1:eos-1]) end + if eof(s) return buf[1:eos-1] end # Otherwise, append to the end of the previous buffer @@ -450,7 +431,7 @@ function readline(s::GZipStream) if gzgets(s, pointer(buf)+pos-1, GZ_LINE_BUFSIZE) == C_NULL # eof(s); remove extra buffer space grow(buf, -GZ_LINE_BUFSIZE) - return bytestring(buf) + return buf end end end diff --git a/extras/julia_web_base.jl b/extras/julia_web_base.jl index 773b66579b512..0e70157a52862 100644 --- a/extras/julia_web_base.jl +++ b/extras/julia_web_base.jl @@ -16,7 +16,7 @@ # [message_type::number, arg0::string, arg1::string, ...] # import the message types -load("webrepl_msgtypes_h") +include(find_in_path("webrepl_msgtypes_h")) ########################################### # set up the socket connection @@ -83,7 +83,7 @@ end ########################################### # load the special functions available to the web repl -load("julia_web") +include(find_in_path("julia_web")) ########################################### # input event handler @@ -192,11 +192,11 @@ function __eval_exprs(__parsed_exprs) end # print version info -println("Julia ", Base._jl_version_string) -println(Base._jl_commit_string, "\n") +println("Julia ", Base.version_string) +println(Base.commit_string, "\n") # work around bug displaying "\n " -#print(" ",replace(Base._jl_banner_plain, "\n", "\n ")) +#print(" ",replace(Base.banner_plain, "\n", "\n ")) ########################################### # wait forever while asynchronous processing happens diff --git a/extras/libhdfs.jl b/extras/libhdfs.jl index 3ec3df3d51c72..9de17a52ad783 100644 --- a/extras/libhdfs.jl +++ b/extras/libhdfs.jl @@ -1,36 +1,35 @@ -libhdfs=dlopen("libhdfs") -_hdfsConnectAsUser= dlsym(libhdfs, :hdfsConnectAsUser) -_hdfsConnect= dlsym(libhdfs, :hdfsConnect) -_hdfsDisconnect= dlsym(libhdfs, :hdfsDisconnect) -_hdfsOpenFile= dlsym(libhdfs,:hdfsOpenFile) -_hdfsCloseFile= dlsym(libhdfs, :hdfsCloseFile) -_hdfsExists= dlsym(libhdfs, :hdfsExists) -_hdfsSeek= dlsym(libhdfs, :hdfsSeek) -_hdfsTell= dlsym(libhdfs, :hdfsTell) -_hdfsRead= dlsym(libhdfs, :hdfsRead) -_hdfsPread= dlsym(libhdfs, :hdfsPread) -_hdfsWrite= dlsym(libhdfs, :hdfsWrite) -_hdfsFlush= dlsym(libhdfs, :hdfsFlush) -_hdfsAvailable= dlsym(libhdfs, :hdfsAvailable) -_hdfsCopy= dlsym(libhdfs, :hdfsCopy) -_hdfsMove= dlsym(libhdfs, :hdfsMove) -_hdfsDelete= dlsym(libhdfs, :hdfsDelete) -_hdfsRename= dlsym(libhdfs, :hdfsRename) -_hdfsGetWorkingDirectory= dlsym(libhdfs, :hdfsGetWorkingDirectory) -_hdfsSetWorkingDirectory= dlsym(libhdfs, :hdfsSetWorkingDirectory) -_hdfsCreateDirectory= dlsym(libhdfs, :hdfsCreateDirectory) -_hdfsSetReplication= dlsym(libhdfs, :hdfsSetReplication) -_hdfsListDirectory=dlsym(libhdfs, :hdfsListDirectory) -_hdfsGetPathInfo=dlsym(libhdfs, :hdfsGetPathInfo) -_hdfsFreeFileInfo=dlsym(libhdfs, :hdfsFreeFileInfo) -_hdfsGetHosts=dlsym(libhdfs, :hdfsGetHosts) -_hdfsFreeHosts=dlsym(libhdfs, :hdfsFreeHosts) -_hdfsGetDefaultBlockSize= dlsym(libhdfs, :hdfsGetDefaultBlockSize) -_hdfsGetCapacity= dlsym(libhdfs, :hdfsGetCapacity) -_hdfsGetUsed= dlsym(libhdfs, :hdfsGetUsed) -_hdfsChown=dlsym(libhdfs, :hdfsChown) -_hdfsChmod=dlsym(libhdfs, :hdfsChmod) -_hdfsUtime=dlsym(libhdfs, :hdfsUtime) +_hdfsConnectAsUser= (:hdfsConnectAsUser, :libhdfs) +_hdfsConnect= (:hdfsConnect, :libhdfs) +_hdfsDisconnect= (:hdfsDisconnect, :libhdfs) +_hdfsOpenFile= (:hdfsOpenFile, :libhdfs) +_hdfsCloseFile= (:hdfsCloseFile, :libhdfs) +_hdfsExists= (:hdfsExists, :libhdfs) +_hdfsSeek= (:hdfsSeek, :libhdfs) +_hdfsTell= (:hdfsTell, :libhdfs) +_hdfsRead= (:hdfsRead, :libhdfs) +_hdfsPread= (:hdfsPread, :libhdfs) +_hdfsWrite= (:hdfsWrite, :libhdfs) +_hdfsFlush= (:hdfsFlush, :libhdfs) +_hdfsAvailable= (:hdfsAvailable, :libhdfs) +_hdfsCopy= (:hdfsCopy, :libhdfs) +_hdfsMove= (:hdfsMove, :libhdfs) +_hdfsDelete= (:hdfsDelete, :libhdfs) +_hdfsRename= (:hdfsRename, :libhdfs) +_hdfsGetWorkingDirectory= (:hdfsGetWorkingDirectory, :libhdfs) +_hdfsSetWorkingDirectory= (:hdfsSetWorkingDirectory, :libhdfs) +_hdfsCreateDirectory= (:hdfsCreateDirectory, :libhdfs) +_hdfsSetReplication= (:hdfsSetReplication, :libhdfs) +_hdfsListDirectory=(:hdfsListDirectory, :libhdfs) +_hdfsGetPathInfo=(:hdfsGetPathInfo, :libhdfs) +_hdfsFreeFileInfo=(:hdfsFreeFileInfo, :libhdfs) +_hdfsGetHosts=(:hdfsGetHosts, :libhdfs) +_hdfsFreeHosts=(:hdfsFreeHosts, :libhdfs) +_hdfsGetDefaultBlockSize= (:hdfsGetDefaultBlockSize, :libhdfs) +_hdfsGetCapacity= (:hdfsGetCapacity, :libhdfs) +_hdfsGetUsed= (:hdfsGetUsed, :libhdfs) +_hdfsChown=(:hdfsChown, :libhdfs) +_hdfsChmod=(:hdfsChmod, :libhdfs) +_hdfsUtime=(:hdfsUtime, :libhdfs) ## used to enforce typing ## diff --git a/extras/linprog.jl b/extras/linprog.jl index daa7cb23c432c..1e3e71bb941b4 100644 --- a/extras/linprog.jl +++ b/extras/linprog.jl @@ -67,7 +67,7 @@ typealias MatOrNothing Union(Matrix, SparseMatrixCSC, Vector{None}, Nothing) function linprog_interior{T<:Real,P<:Union(GLPK.InteriorParam,Nothing)}(f::Vector{T}, A::SparseOrFullMat{T}, b::Vector{T}, Aeq::SparseOrFullMat{T}, beq::Vector{T}, lb::Vector{T}, ub::Vector{T}, params::P) - lp, n = _jl_linprog__setup_prob(f, A, b, Aeq, beq, lb, ub, params) + lp, n = linprog__setup_prob(f, A, b, Aeq, beq, lb, ub, params) ret = GLPK.interior(lp, params) #println("ret=$ret") @@ -87,12 +87,12 @@ end function linprog_interior{T<:Real,P<:Union(GLPK.InteriorParam,Nothing)}(f::Vector{T}, A::MatOrNothing, b::VecOrNothing, Aeq::MatOrNothing, beq::VecOrNothing, lb::VecOrNothing, ub::VecOrNothing, params::P) - cA = _jl_linprog__convert_matornothing(T, A) - cb = _jl_linprog__convert_vecornothing(T, b) - cAeq = _jl_linprog__convert_matornothing(T, Aeq) - cbeq = _jl_linprog__convert_vecornothing(T, beq) - clb = _jl_linprog__convert_vecornothing(T, lb) - cub = _jl_linprog__convert_vecornothing(T, ub) + cA = linprog__convert_matornothing(T, A) + cb = linprog__convert_vecornothing(T, b) + cAeq = linprog__convert_matornothing(T, Aeq) + cbeq = linprog__convert_vecornothing(T, beq) + clb = linprog__convert_vecornothing(T, lb) + cub = linprog__convert_vecornothing(T, ub) return linprog_interior(f, cA, cb, cAeq, cbeq, clb, cub, params) end @@ -117,7 +117,7 @@ linprog = linprog_interior function linprog_simplex{T<:Real,P<:Union(GLPK.SimplexParam,Nothing)}(f::Vector{T}, A::SparseOrFullMat{T}, b::Vector{T}, Aeq::SparseOrFullMat{T}, beq::Vector{T}, lb::Vector{T}, ub::Vector{T}, params::P) - lp, n = _jl_linprog__setup_prob(f, A, b, Aeq, beq, lb, ub, params) + lp, n = linprog__setup_prob(f, A, b, Aeq, beq, lb, ub, params) ret = GLPK.simplex(lp, params) #println("ret=$ret") @@ -137,12 +137,12 @@ end function linprog_simplex{T<:Real,P<:Union(GLPK.SimplexParam,Nothing)}(f::Vector{T}, A::MatOrNothing, b::VecOrNothing, Aeq::MatOrNothing, beq::VecOrNothing, lb::VecOrNothing, ub::VecOrNothing, params::P) - cA = _jl_linprog__convert_matornothing(T, A) - cb = _jl_linprog__convert_vecornothing(T, b) - cAeq = _jl_linprog__convert_matornothing(T, Aeq) - cbeq = _jl_linprog__convert_vecornothing(T, beq) - clb = _jl_linprog__convert_vecornothing(T, lb) - cub = _jl_linprog__convert_vecornothing(T, ub) + cA = linprog__convert_matornothing(T, A) + cb = linprog__convert_vecornothing(T, b) + cAeq = linprog__convert_matornothing(T, Aeq) + cbeq = linprog__convert_vecornothing(T, beq) + clb = linprog__convert_vecornothing(T, lb) + cub = linprog__convert_vecornothing(T, ub) return linprog_simplex(f, cA, cb, cAeq, cbeq, clb, cub, params) end @@ -171,7 +171,7 @@ linprog_simplex{T<:Real}(f::Vector{T}, A::MatOrNothing, b::VecOrNothing, function linprog_exact{T<:Real,P<:Union(GLPK.SimplexParam,Nothing)}(f::Vector{T}, A::SparseOrFullMat{T}, b::Vector{T}, Aeq::SparseOrFullMat{T}, beq::Vector{T}, lb::Vector{T}, ub::Vector{T}, params::P) - lp, n = _jl_linprog__setup_prob(f, A, b, Aeq, beq, lb, ub, params) + lp, n = linprog__setup_prob(f, A, b, Aeq, beq, lb, ub, params) ret = GLPK.simplex(lp, params) if ret != 0 @@ -195,12 +195,12 @@ end function linprog_exact{T<:Real,P<:Union(GLPK.SimplexParam,Nothing)}(f::Vector{T}, A::MatOrNothing, b::VecOrNothing, Aeq::MatOrNothing, beq::VecOrNothing, lb::VecOrNothing, ub::VecOrNothing, params::P) - cA = _jl_linprog__convert_matornothing(T, A) - cb = _jl_linprog__convert_vecornothing(T, b) - cAeq = _jl_linprog__convert_matornothing(T, Aeq) - cbeq = _jl_linprog__convert_vecornothing(T, beq) - clb = _jl_linprog__convert_vecornothing(T, lb) - cub = _jl_linprog__convert_vecornothing(T, ub) + cA = linprog__convert_matornothing(T, A) + cb = linprog__convert_vecornothing(T, b) + cAeq = linprog__convert_matornothing(T, Aeq) + cbeq = linprog__convert_vecornothing(T, beq) + clb = linprog__convert_vecornothing(T, lb) + cub = linprog__convert_vecornothing(T, ub) return linprog_exact(f, cA, cb, cAeq, cbeq, clb, cub, params) end @@ -240,8 +240,8 @@ function mixintprog{T<:Real,Ti<:Integer,P<:Union(GLPK.IntoptParam,Nothing),Px<:U f::Vector{T}, A::SparseOrFullMat{T}, b::Vector{T}, Aeq::SparseOrFullMat{T}, beq::Vector{T}, lb::Vector{T}, ub::Vector{T}, col_kind::Vector{Ti}, params::P, params_presolve::Px) - lp, n = _jl_linprog__setup_prob(f, A, b, Aeq, beq, lb, ub, params) - _jl_mixintprog_set_col_kind(lp, n, col_kind) + lp, n = linprog__setup_prob(f, A, b, Aeq, beq, lb, ub, params) + mixintprog_set_col_kind(lp, n, col_kind) if params == nothing || pointer(params) == C_NULL || params["presolve"] != GLPK.ON ret_ps = GLPK.simplex(lp, params_presolve) @@ -271,13 +271,13 @@ function mixintprog{T<:Real,P<:Union(GLPK.IntoptParam,Nothing),Px<:Union(GLPK.Si f::Vector{T}, A::MatOrNothing, b::VecOrNothing, Aeq::MatOrNothing, beq::VecOrNothing, lb::VecOrNothing, ub::VecOrNothing, col_kind::VecOrNothing, params::P, params_presolve::Px) - cA = _jl_linprog__convert_matornothing(T, A) - cb = _jl_linprog__convert_vecornothing(T, b) - cAeq = _jl_linprog__convert_matornothing(T, Aeq) - cbeq = _jl_linprog__convert_vecornothing(T, beq) - clb = _jl_linprog__convert_vecornothing(T, lb) - cub = _jl_linprog__convert_vecornothing(T, ub) - ccol_kind = _jl_linprog__convert_vecornothing(Int32, col_kind) + cA = linprog__convert_matornothing(T, A) + cb = linprog__convert_vecornothing(T, b) + cAeq = linprog__convert_matornothing(T, Aeq) + cbeq = linprog__convert_vecornothing(T, beq) + clb = linprog__convert_vecornothing(T, lb) + cub = linprog__convert_vecornothing(T, ub) + ccol_kind = linprog__convert_vecornothing(Int32, col_kind) return mixintprog(f, cA, cb, cAeq, cbeq, clb, cub, ccol_kind, params, params_presolve) end @@ -342,7 +342,7 @@ end ## Common auxiliary functions #{{{ -function _jl_linprog__convert_vecornothing{T}(::Type{T}, a::VecOrNothing) +function linprog__convert_vecornothing{T}(::Type{T}, a::VecOrNothing) if isequal(a, nothing) || isa(a, Array{None}) return T[] elseif T <: Integer @@ -356,7 +356,7 @@ function _jl_linprog__convert_vecornothing{T}(::Type{T}, a::VecOrNothing) end return convert(Array{T}, a) end -function _jl_linprog__convert_matornothing{T}(::Type{T}, a::MatOrNothing) +function linprog__convert_matornothing{T}(::Type{T}, a::MatOrNothing) if isequal(a, nothing) || isa(a, Array{None}) return Array(T, 0, 0) elseif T <: Integer @@ -375,7 +375,7 @@ function _jl_linprog__convert_matornothing{T}(::Type{T}, a::MatOrNothing) end end -function _jl_linprog__setup_prob{T<:Real, P<:Union(GLPK.Param, Nothing)}(f::Vector{T}, A::SparseOrFullMat{T}, b::Vector{T}, +function linprog__setup_prob{T<:Real, P<:Union(GLPK.Param, Nothing)}(f::Vector{T}, A::SparseOrFullMat{T}, b::Vector{T}, Aeq::SparseOrFullMat{T}, beq::Vector{T}, lb::Vector{T}, ub::Vector{T}, params::P) lp = GLPK.Prob() @@ -383,10 +383,10 @@ function _jl_linprog__setup_prob{T<:Real, P<:Union(GLPK.Param, Nothing)}(f::Vect n = size(f, 1) - m = _jl_linprog__check_A_b(A, b, n) - meq = _jl_linprog__check_A_b(Aeq, beq, n) + m = linprog__check_A_b(A, b, n) + meq = linprog__check_A_b(Aeq, beq, n) - has_lb, has_ub = _jl_linprog__check_lb_ub(lb, ub, n) + has_lb, has_ub = linprog__check_lb_ub(lb, ub, n) #println("n=$n m=$m meq=$meq has_lb=$has_lb ub=$has_ub") @@ -416,18 +416,37 @@ function _jl_linprog__setup_prob{T<:Real, P<:Union(GLPK.Param, Nothing)}(f::Vect if has_lb && has_ub for c = 1 : n #println(" c=$c lb=$(lb[c]) ub=$(ub[c])") - bounds_type = (lb[c] != ub[c] ? GLPK.DB : GLPK.FX) + local bounds_type + if lb[c] == ub[c] + bounds_type = GLPK.FX + else + if isinf(lb[c]) + if isinf(ub[c]) + bounds_type = GLPK.FR + else + bounds_type = GLPK.UP + end + else + if isinf(ub[c]) + bounds_type = GLPK.LO + else + bounds_type = GLPK.DB + end + end + end GLPK.set_col_bnds(lp, c, bounds_type, lb[c], ub[c]) end elseif has_lb for c = 1 : n #println(" c=$c lb=$(lb[c])") - GLPK.set_col_bnds(lp, c, GLPK.LO, lb[c], 0.0) + bounds_type = isinf(lb[c]) ? GLPK.FR : GLPK.LO + GLPK.set_col_bnds(lp, c, bounds_type, lb[c], 0.0) end elseif has_ub for c = 1 : n #println(" c=$c ub=$(ub[c])") - GLPK.set_col_bnds(lp, c, GLPK.UP, 0.0, ub[c]) + bounds_type = isinf(ub[c]) ? GLPK.FR : GLPK.UP + GLPK.set_col_bnds(lp, c, bounds_type, 0.0, ub[c]) end end @@ -438,7 +457,7 @@ function _jl_linprog__setup_prob{T<:Real, P<:Union(GLPK.Param, Nothing)}(f::Vect elseif (m == 0) && (meq > 0 && issparse(Aeq)) (ia, ja, ar) = findn_nzs(Aeq) else - (ia, ja, ar) = _jl_linprog__dense_matrices_to_glpk_format(m, meq, n, A, Aeq) + (ia, ja, ar) = linprog__dense_matrices_to_glpk_format(m, meq, n, A, Aeq) end #println("ia=$ia") #println("ja=$ja") @@ -448,7 +467,7 @@ function _jl_linprog__setup_prob{T<:Real, P<:Union(GLPK.Param, Nothing)}(f::Vect return (lp, n) end -function _jl_linprog__check_A_b{T}(A::SparseOrFullMat{T}, b::Vector{T}, n::Int) +function linprog__check_A_b{T}(A::SparseOrFullMat{T}, b::Vector{T}, n::Int) m = 0 if !isempty(A) if size(A, 2) != n @@ -469,7 +488,7 @@ function _jl_linprog__check_A_b{T}(A::SparseOrFullMat{T}, b::Vector{T}, n::Int) return m end -function _jl_linprog__check_lb_ub{T}(lb::Vector{T}, ub::Vector{T}, n::Int) +function linprog__check_lb_ub{T}(lb::Vector{T}, ub::Vector{T}, n::Int) has_lb = false has_ub = false if !isempty(lb) @@ -487,7 +506,7 @@ function _jl_linprog__check_lb_ub{T}(lb::Vector{T}, ub::Vector{T}, n::Int) return (has_lb, has_ub) end -function _jl_linprog__dense_matrices_to_glpk_format(m, meq, n, A, Aeq) +function linprog__dense_matrices_to_glpk_format(m, meq, n, A, Aeq) l = (m + meq) * n ia = zeros(Int32, l) @@ -515,7 +534,7 @@ function _jl_linprog__dense_matrices_to_glpk_format(m, meq, n, A, Aeq) return (ia, ja, ar) end -function _jl_mixintprog_set_col_kind{Ti<:Integer}(lp::GLPK.Prob, n::Int, col_kind::Vector{Ti}) +function mixintprog_set_col_kind{Ti<:Integer}(lp::GLPK.Prob, n::Int, col_kind::Vector{Ti}) if isempty(col_kind) for i = 1 : n GLPK.set_col_kind(lp, i, GLPK.IV) diff --git a/extras/ode.jl b/extras/ode.jl index 21ebec57a6a15..85de99e97b39b 100644 --- a/extras/ode.jl +++ b/extras/ode.jl @@ -28,7 +28,7 @@ # Adapted from Cleve Moler's textbook # http://www.mathworks.com/moler/ncm/ode23tx.m -load("poly") +require("poly") function ode23(F::Function, tspan::AbstractVector, y_0::AbstractVector) diff --git a/extras/profile.jl b/extras/profile.jl index b67d1f46c2487..f0adad4591e97 100644 --- a/extras/profile.jl +++ b/extras/profile.jl @@ -232,7 +232,9 @@ function profile_parse(ex::Expr) # Put all this inside a let block excore = expr(:block,coreargs) exlet = expr(:let,{expr(:block,excore), :($timers = zeros(Uint64, $n_lines)), :($counters = zeros(Uint64, $n_lines))}) - return exlet, tags, funcreport, funcclear + # Export the reporting and clearing functions, in case we're inside a module + exret = expr(:toplevel, {esc(exlet), expr(:export, {esc(funcclear), esc(funcreport)})}) + return exret, tags, funcreport, funcclear else return ex ,{}, :funcnoop, :funcnoop end @@ -338,7 +340,7 @@ macro profile(ex) push(PROFILE_REPORTS, esc(funcreport)) push(PROFILE_CLEARS, esc(funcclear)) end - return esc(exret) + return exret end end diff --git a/extras/strpack.jl b/extras/strpack.jl index b035db0d0827d..dbc870fec0e42 100644 --- a/extras/strpack.jl +++ b/extras/strpack.jl @@ -1,4 +1,4 @@ -load("lru") +require("lru") bswap(c::Char) = identity(c) # white lie which won't work for multibyte characters diff --git a/extras/suitesparse.jl b/extras/suitesparse.jl index 5a04bce0f5f69..c9e483ad68a5d 100644 --- a/extras/suitesparse.jl +++ b/extras/suitesparse.jl @@ -1,6 +1,10 @@ module SuiteSparse -import Base.SparseMatrixCSC, Base.size, Base.nnz, Base.eltype, Base.show, Base.triu, Base.norm, Base.solve, Base.(\), Base.ctranspose, Base.transpose +import Base.SparseMatrixCSC, Base.size, Base.nnz, Base.eltype, Base.show +import Base.triu, Base.norm, Base.solve, Base.(\), Base.ctranspose, Base.transpose + +import Base.BlasInt +import Base.blas_int export # types CholmodPtr, @@ -25,7 +29,7 @@ export # types At_ldiv_B, Ac_ldiv_B -require("suitesparse_h") +include(find_in_path("suitesparse_h")) const libsuitesparse_wrapper = "libsuitesparse_wrapper" const libcholmod = "libcholmod" @@ -61,20 +65,20 @@ const _spqr_C_qmult = (:SuiteSparseQR_C_qmult, libspqr) type MatrixIllConditionedException <: Exception end -function _jl_convert_to_0_based_indexing!(S::SparseMatrixCSC) +function convert_to_0_based_indexing!(S::SparseMatrixCSC) for i=1:(S.colptr[end]-1); S.rowval[i] -= 1; end for i=1:length(S.colptr); S.colptr[i] -= 1; end return S end -function _jl_convert_to_1_based_indexing!(S::SparseMatrixCSC) +function convert_to_1_based_indexing!(S::SparseMatrixCSC) for i=1:length(S.colptr); S.colptr[i] += 1; end for i=1:(S.colptr[end]-1); S.rowval[i] += 1; end return S end -_jl_convert_to_0_based_indexing(S) = _jl_convert_to_0_based_indexing!(copy(S)) -_jl_convert_to_1_based_indexing(S) = _jl_convert_to_1_based_indexing!(copy(S)) +convert_to_0_based_indexing(S) = convert_to_0_based_indexing!(copy(S)) +convert_to_1_based_indexing(S) = convert_to_1_based_indexing!(copy(S)) ## CHOLMOD @@ -83,17 +87,17 @@ typealias CHMITypes Union(Int32, Int64) function chm_itype{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}) if !(Ti<:CHMITypes) error("chm_itype: indtype(S) must be in CHMITypes") end - Ti == Int32 ? _jl_CHOLMOD_INT : _jl_CHOLMOD_LONG + Ti == Int32 ? CHOLMOD_INT : CHOLMOD_LONG end function chm_xtype{T}(S::SparseMatrixCSC{T}) if !(T<:CHMVTypes) error("chm_xtype: eltype(S) must be in CHMVTypes") end - T <: Complex ? _JL_CHOLMOD_COMPLEX : _jl_CHOLMOD_REAL + T <: Complex ? CHOLMOD_COMPLEX : CHOLMOD_REAL end function chm_dtype{T}(S::SparseMatrixCSC{T}) if !(T<:CHMVTypes) error("chm_dtype: eltype(S) must be in CHMVTypes") end - T <: Union(Float32, Complex64) ? _jl_CHOLMOD_SINGLE : _jl_CHOLMOD_DOUBLE + T <: Union(Float32, Complex64) ? CHOLMOD_SINGLE : CHOLMOD_DOUBLE end # Wrapper for memory allocated by CHOLMOD. Carry along the value and index types. @@ -105,9 +109,9 @@ end eltype{Tv,Ti}(P::CholmodPtr{Tv,Ti}) = Tv indtype{Tv,Ti}(P::CholmodPtr{Tv,Ti}) = Ti -function _jl_cholmod_common_finalizer(x::Vector{Ptr{Void}}) - st = ccall((:cholmod_finish, libcholmod), Int32, (Ptr{Void},), x[1]) - if st != _jl_CHOLMOD_TRUE error("Error calling cholmod_finish") end +function cholmod_common_finalizer(x::Vector{Ptr{Void}}) + st = ccall((:cholmod_finish, libcholmod), BlasInt, (Ptr{Void},), x[1]) + if st != CHOLMOD_TRUE error("Error calling cholmod_finish") end c_free(x[1]) end @@ -117,17 +121,17 @@ type CholmodCommon pt = Array(Ptr{Void}, 1) ccall((:jl_cholmod_common, libsuitesparse_wrapper), Void, (Ptr{Void},), pt) - st = ccall((:cholmod_start, libcholmod), Int, (Ptr{Void}, ), pt[1]) - if st != _jl_CHOLMOD_TRUE error("Error calling cholmod_start") end - finalizer(pt, _jl_cholmod_common_finalizer) + st = ccall((:cholmod_start, libcholmod), BlasInt, (Ptr{Void}, ), pt[1]) + if st != CHOLMOD_TRUE error("Error calling cholmod_start") end + finalizer(pt, cholmod_common_finalizer) new(pt) end end function show(io, cm::CholmodCommon) - st = ccall((:cholmod_print_common, libcholmod), Int32, + st = ccall((:cholmod_print_common, libcholmod), BlasInt, (Ptr{Uint8},Ptr{Void}), "", cm.pt[1]) - if st != _jl_CHOLMOD_TRUE error("Error calling cholmod_print_common") end + if st != CHOLMOD_TRUE error("Error calling cholmod_print_common") end end type CholmodSparse{Tv<:CHMVTypes,Ti<:CHMITypes} @@ -136,18 +140,18 @@ type CholmodSparse{Tv<:CHMVTypes,Ti<:CHMITypes} cp::SparseMatrixCSC{Tv,Ti} stype::Int cm::CholmodCommon - function CholmodSparse(S::SparseMatrixCSC{Tv,Ti}, stype::Int, cm::CholmodCommon) + function CholmodSparse(S::SparseMatrixCSC{Tv,Ti}, stype::BlasInt, cm::CholmodCommon) pt = CholmodPtr{Tv,Ti}(Array(Ptr{Void}, 1)) - cp = _jl_convert_to_0_based_indexing(S) + cp = convert_to_0_based_indexing(S) ccall((:jl_cholmod_sparse, libsuitesparse_wrapper), Void, (Ptr{Void}, Uint, Uint, Uint, Ptr{Void}, Ptr{Void}, Ptr{Void}, - Ptr{Void}, Ptr{Void}, Int32, Int32, Int32, Int32, Int32, Int32), + Ptr{Void}, Ptr{Void}, BlasInt, BlasInt, BlasInt, BlasInt, BlasInt, Int), pt.val, S.m, S.n, nnz(S), cp.colptr, cp.rowval, C_NULL, cp.nzval, C_NULL, stype, chm_itype(S), chm_xtype(S), chm_dtype(S), - _jl_CHOLMOD_TRUE, _jl_CHOLMOD_TRUE) + CHOLMOD_TRUE, CHOLMOD_TRUE) finalizer(pt, x->c_free(x.val[1])) - new(pt, cp, int(stype), cm) + new(pt, cp, blas_int(stype), cm) end end @@ -155,14 +159,14 @@ CholmodSparse{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, stype::Int) = CholmodSparse{Tv,T function CholmodSparse{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, cm::CholmodCommon) stype = S.m == S.n && ishermitian(S) - CholmodSparse{Tv,Ti}(stype ? triu(S) : S, int(stype), cm) + CholmodSparse{Tv,Ti}(stype ? triu(S) : S, blas_int(stype), cm) end CholmodSparse(S::SparseMatrixCSC) = CholmodSparse(S, CholmodCommon()) function show(io, cs::CholmodSparse) ccall(_chm_print_sp, - Int32, (Ptr{Void}, Ptr{Uint8},Ptr{Void}), cs.pt.val[1], "", cs.cm.pt[1]) + BlasInt, (Ptr{Void}, Ptr{Uint8},Ptr{Void}), cs.pt.val[1], "", cs.cm.pt[1]) end size(cs::CholmodSparse) = size(cs.cp) @@ -170,26 +174,26 @@ nnz(cs::CholmodSparse) = cs.cp.colptr[end] eltype{T}(cs::CholmodSparse{T}) = T indtype{Tv,Ti}(cs::CholmodSparse{Tv,Ti}) = Ti -SparseMatrixCSC(cs::CholmodSparse) = _jl_convert_to_1_based_indexing(cs.cp) +SparseMatrixCSC(cs::CholmodSparse) = convert_to_1_based_indexing(cs.cp) ## For testing only. The infinity and 1 norms of a sparse matrix are simply ## the same norm applied to its nzval field. function norm(cs::CholmodSparse, p::Number) ccall((:cholmod_norm_sparse, libcholmod), Float64, - (Ptr{Void}, Int32, Ptr{Void}), cs.pt.val[1], p == Inf ? 0 : 1, cs.cm.pt[1]) + (Ptr{Void}, BlasInt, Ptr{Void}), cs.pt.val[1], p == Inf ? 0 : 1, cs.cm.pt[1]) end norm(cs::CholmodSparse) = norm(cs, Inf) ## Approximate minimal degree ordering function chm_amd(cs::CholmodSparse) - aa = Array(Int32, cs.cp.m) - st = cs.stype == 0 ? ccall(_chm_colamd, Int32, - (Ptr{Void}, Ptr{Void}, Uint, Int32, Ptr{Int32}, Ptr{Void}), + aa = Array(BlasInt, cs.cp.m) + st = cs.stype == 0 ? ccall(_chm_colamd, BlasInt, + (Ptr{Void}, Ptr{Void}, Uint, BlasInt, Ptr{BlasInt}, Ptr{Void}), cs.pt.val[1], C_NULL, 0, 1, aa, cs.cm.pt[1]) : - ccall(_chm_amd, Int32, (Ptr{Void}, Ptr{Void}, Uint, Ptr{Int32}, Ptr{Void}), + ccall(_chm_amd, BlasInt, (Ptr{Void}, Ptr{Void}, Uint, Ptr{BlasInt}, Ptr{Void}), cs.pt.val[1], C_NULL, 0, aa, cs.cm.pt[1]) - if st != _jl_CHOLMOD_TRUE error("Error in cholmod_amd") end + if st != CHOLMOD_TRUE error("Error in cholmod_amd") end aa end @@ -198,13 +202,13 @@ type CholmodFactor{Tv<:CHMVTypes,Ti<:CHMITypes} <: Factorization{Tv} cs::CholmodSparse{Tv,Ti} function CholmodFactor(pt::CholmodPtr{Tv,Ti}, cs::CholmodSparse{Tv,Ti}) ff = new(pt, cs) - finalizer(ff, _jl_cholmod_factor_finalizer) + finalizer(ff, cholmod_factor_finalizer) ff end end -function _jl_cholmod_factor_finalizer(x::CholmodFactor) - if ccall(_chm_free_fa, Int32, (Ptr{Void}, Ptr{Void}), x.pt.val, x.cs.cm[1]) != _jl_CHOLMOD_TRUE +function cholmod_factor_finalizer(x::CholmodFactor) + if ccall(_chm_free_fa, BlasInt, (Ptr{Void}, Ptr{Void}), x.pt.val, x.cs.cm[1]) != CHOLMOD_TRUE error("CHOLMOD error in cholmod_free_factor") end end @@ -221,15 +225,15 @@ function CholmodFactor{Tv,Ti}(cs::CholmodSparse{Tv,Ti}) pt = CholmodPtr{Tv,Ti}(Array(Ptr{Void}, 1)) pt.val[1] = ccall(_chm_analyze, Ptr{Void}, (Ptr{Void}, Ptr{Void}), cs.pt.val[1], cs.cm.pt[1]) - st = ccall(_chm_factorize, Int32, + st = ccall(_chm_factorize, BlasInt, (Ptr{Void}, Ptr{Void}, Ptr{Void}), cs.pt.val[1], pt.val[1], cs.cm.pt[1]) - if st != _jl_CHOLMOD_TRUE error("CHOLMOD failure in factorize") end + if st != CHOLMOD_TRUE error("CHOLMOD failure in factorize") end CholmodFactor{Tv,Ti}(pt, cs) end function show(io, cf::CholmodFactor) - st = ccall(_chm_print_fa, Int32, (Ptr{Void}, Ptr{Uint8}, Ptr{Void}), cf.pt.val[1], "", cf.cs.cm.pt[1]) - if st != _jl_CHOLMOD_TRUE error("Cholmod error in print_factor") end + st = ccall(_chm_print_fa, BlasInt, (Ptr{Void}, Ptr{Uint8}, Ptr{Void}), cf.pt.val[1], "", cf.cs.cm.pt[1]) + if st != CHOLMOD_TRUE error("Cholmod error in print_factor") end end type CholmodDense{T<:CHMVTypes} @@ -244,13 +248,13 @@ function CholmodDense{T<:CHMVTypes}(b::VecOrMat{T}, cm::CholmodCommon) m = size(b, 1) n = isa(b, Matrix) ? size(b, 2) : 1 - xtype = T <: Complex ? _jl_CHOLMOD_COMPLEX : _jl_CHOLMOD_REAL - dtype = T <: Float32 || T == Complex64 ? _jl_CHOLMOD_SINGLE : _jl_CHOLMOD_DOUBLE + xtype = T <: Complex ? CHOLMOD_COMPLEX : CHOLMOD_REAL + dtype = T <: Float32 || T == Complex64 ? CHOLMOD_SINGLE : CHOLMOD_DOUBLE pt = Array(Ptr{Void}, 1) ccall((:jl_cholmod_dense, libsuitesparse_wrapper), Void, - (Ptr{Void}, Uint, Uint, Uint, Uint, Ptr{Void}, Ptr{Void}, Int32, Int32), + (Ptr{Void}, Uint, Uint, Uint, Uint, Ptr{Void}, Ptr{Void}, BlasInt, Int), pt, m, n, length(b), m, b, C_NULL, xtype, dtype) finalizer(pt, x->c_free(pt[1])) CholmodDense{T}(pt, m, n, copy(b), cm) @@ -261,8 +265,8 @@ CholmodDense{T<:Integer}(B::VecOrMat{T}, cm::CholmodCommon) = CholmodDense(float size(cd::CholmodDense) = (cd.m, cd.n) function show(io, cd::CholmodDense) - st = ccall(_chm_print_dn, Int32, (Ptr{Void},Ptr{Uint8},Ptr{Void}), cd.pt[1], "", cd.cm.pt[1]) - if st != _jl_CHOLMOD_TRUE error("Cholmod error in print_dense") end + st = ccall(_chm_print_dn, BlasInt, (Ptr{Void},Ptr{Uint8},Ptr{Void}), cd.pt[1], "", cd.cm.pt[1]) + if st != CHOLMOD_TRUE error("Cholmod error in print_dense") end end type CholmodDenseOut{Tv<:CHMVTypes,Ti<:CHMITypes} @@ -270,16 +274,16 @@ type CholmodDenseOut{Tv<:CHMVTypes,Ti<:CHMITypes} m::Int n::Int cm::CholmodCommon - function CholmodDenseOut(pt::CholmodPtr{Tv,Ti}, m::Int, n::Int, cm::CholmodCommon) + function CholmodDenseOut(pt::CholmodPtr{Tv,Ti}, m::BlasInt, n::BlasInt, cm::CholmodCommon) dd = new(pt, m, n, cm) - finalizer(dd, _jl_cholmod_denseout_finalizer) + finalizer(dd, cholmod_denseout_finalizer) dd end end -function _jl_cholmod_denseout_finalizer(cd::CholmodDenseOut) - st = ccall(_chm_free_dn, Int32, (Ptr{Void}, Ptr{Void}), cd.pt.val, cd.cm.pt[1]) - if st != _jl_CHOLMOD_TRUE error("Error in cholmod_free_dense") end +function cholmod_denseout_finalizer(cd::CholmodDenseOut) + st = ccall(_chm_free_dn, BlasInt, (Ptr{Void}, Ptr{Void}), cd.pt.val, cd.cm.pt[1]) + if st != CHOLMOD_TRUE error("Error in cholmod_free_dense") end end eltype{T}(cdo::CholmodDenseOut{T}) = T @@ -297,36 +301,36 @@ function solve{Tv,Ti}(cf::CholmodFactor{Tv,Ti}, B::CholmodDense{Tv}, solv::Integ m, n = size(B) cdo = CholmodPtr{Tv,Ti}(Array(Ptr{Void},1)) cdo.val[1] = ccall(_chm_solve, Ptr{Void}, - (Int32, Ptr{Void}, Ptr{Void}, Ptr{Void}), + (BlasInt, Ptr{Void}, Ptr{Void}, Ptr{Void}), solv, cf.pt.val[1], B.pt[1], cf.cs.cm.pt[1]) return cdo, m, n, cf.cs.cm CholmodDenseOut(cdo, m, n, cf.cs.cm) end -solve(cf::CholmodFactor, B::CholmodDense) = solve(cf, B, _jl_CHOLMOD_A) +solve(cf::CholmodFactor, B::CholmodDense) = solve(cf, B, CHOLMOD_A) -(\){Tf,Tb}(cf::CholmodFactor{Tf}, b::VecOrMat{Tb}) = solve(cf, CholmodDense{Tf}(convert(Array{Tf},b), cf.cs.cm), _jl_CHOLMOD_A) +(\){Tf,Tb}(cf::CholmodFactor{Tf}, b::VecOrMat{Tb}) = solve(cf, CholmodDense{Tf}(convert(Array{Tf},b), cf.cs.cm), CHOLMOD_A) type CholmodSparseOut{Tv<:CHMVTypes,Ti<:CHMITypes} pt::CholmodPtr{Tv,Ti} m::Int n::Int cm::CholmodCommon - function CholmodSparseOut(pt::CholmodPtr{Tv,Ti}, m::Int, n::Int, cm::CholmodCommon) + function CholmodSparseOut(pt::CholmodPtr{Tv,Ti}, m::BlasInt, n::BlasInt, cm::CholmodCommon) cso = new(pt, m, n, cm) - finalizer(cso, _jl_cholmod_sparseout_finalizer) + finalizer(cso, cholmod_sparseout_finalizer) cso end end -function _jl_cholmod_sparseout_finalizer(cso::CholmodSparseOut) - st = ccall(_chm_free_sp, Int32, +function cholmod_sparseout_finalizer(cso::CholmodSparseOut) + st = ccall(_chm_free_sp, BlasInt, (Ptr{Void}, Ptr{Void}), cso.pt.val, cso.cm.pt[1]) - if st != _jl_CHOLMOD_TRUE error("Error in cholmod_free_sparse") end + if st != CHOLMOD_TRUE error("Error in cholmod_free_sparse") end end function nnz(cso::CholmodSparseOut) - ccall((:cholmod_nnz, libcholmod), Int32, + ccall((:cholmod_nnz, libcholmod), BlasInt, (Ptr{Void}, Ptr{Void}), cso.pt.val[1], cso.cm.pt[1]) end size(cso::CholmodSparseOut) = (cso.m, cso.n) @@ -337,7 +341,7 @@ function solve{Tv,Ti}(cf::CholmodFactor{Tv,Ti}, B::CholmodSparse{Tv,Ti}, solv::I m, n = size(B) cso = CholmodPtr{Tv,Ti}(Array(Ptr{Void},1)) cso.val[1] = ccall((:cholmod_spsolve, libcholmod), Ptr{Void}, - (Int32, Ptr{Void}, Ptr{Void}, Ptr{Void}), + (BlasInt, Ptr{Void}, Ptr{Void}, Ptr{Void}), solv, cf.pt.val[1], B.pt[1], B.cm.pt[1]) CholmodSparseOut{Tv,Ti}(cso, m, n, cf.cs.cm) end @@ -353,32 +357,32 @@ end function SparseMatrixCSC{Tv,Ti}(cso::CholmodSparseOut{Tv,Ti}) nz = nnz(cso) sp = SparseMatrixCSC{Tv,Ti}(cso.m, cso.n, Array(Ti, cso.n + 1), Array(Ti, nz), Array(Tv, nz)) - st = ccall((:jl_cholmod_sparse_copy_out, libsuitesparse_wrapper), Int32, + st = ccall((:jl_cholmod_sparse_copy_out, libsuitesparse_wrapper), BlasInt, (Ptr{Void}, Ptr{Ti}, Ptr{Ti}, Ptr{Tv}), cso.pt.val[1], sp.colptr, sp.rowval, sp.nzval) if st == 1 error("CholmodSparseOut object is not packed") end if st == 2 error("CholmodSparseOut object is not sorted") end # Should not occur if st == 3 error("CholmodSparseOut object has INTLONG itype") end - _jl_convert_to_1_based_indexing!(sp) + convert_to_1_based_indexing!(sp) end function show(io, cso::CholmodSparseOut) - sp = ccall(_chm_print_sp, Int32, (Ptr{Void}, Ptr{Uint8},Ptr{Void}), cso.pt.val[1], "", cso.cm.pt[1]) - if sp != _jl_CHOLMOD_TRUE error("Cholmod error in print_sparse") end + sp = ccall(_chm_print_sp, BlasInt, (Ptr{Void}, Ptr{Uint8},Ptr{Void}), cso.pt.val[1], "", cso.cm.pt[1]) + if sp != CHOLMOD_TRUE error("Cholmod error in print_sparse") end end function chm_aat{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, symm::Bool) cs = CholmodSparse(A, 0) aa = CholmodPtr{Tv,Ti}(Array(Ptr{Void},1)) - aa.val[1] = ccall(_chm_aat, Ptr{Void}, (Ptr{Void},Ptr{Int},Int32,Int32,Ptr{Void}), + aa.val[1] = ccall(_chm_aat, Ptr{Void}, (Ptr{Void},Ptr{BlasInt},BlasInt,BlasInt,Ptr{Void}), cs.pt.val[1], C_NULL, 0, 1, cs.cm.pt[1]) - if ccall(_chm_sort, Int32, (Ptr{Void}, Ptr{Void}), aa.val[1], cs.cm.pt[1]) != _jl_CHOLMOD_TRUE + if ccall(_chm_sort, BlasInt, (Ptr{Void}, Ptr{Void}), aa.val[1], cs.cm.pt[1]) != CHOLMOD_TRUE error("Cholmod error in sort") end if symm - pt = ccall(_chm_copy, Ptr{Void}, (Ptr{Void}, Int32, Int32, Ptr{Void}), + pt = ccall(_chm_copy, Ptr{Void}, (Ptr{Void}, BlasInt, BlasInt, Ptr{Void}), aa.val[1], 1, 1, cs.cm.pt[1]) - if ccall(_chm_free_sp, Int32, (Ptr{Void}, Ptr{Void}), aa.val, cs.cm.pt[1]) != _jl_CHOLMOD_TRUE + if ccall(_chm_free_sp, BlasInt, (Ptr{Void}, Ptr{Void}), aa.val, cs.cm.pt[1]) != CHOLMOD_TRUE error("Cholmod error in free_sparse") end aa.val[1] = pt @@ -390,54 +394,54 @@ end chm_aat{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}) = chm_aat(A, false) ## call wrapper function to create cholmod_sparse objects -_jl_cholmod_sparse(S) = _jl_cholmod_sparse(S, 0) +cholmod_sparse(S) = cholmod_sparse(S, 0) -function _jl_cholmod_sparse{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, stype::Int) +function cholmod_sparse{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, stype::Int) cs = Array(Ptr{Void}, 1) - if Ti == Int32; itype = _jl_CHOLMOD_INT; - elseif Ti == Int64; itype = _jl_CHOLMOD_LONG; end + if Ti == Int; itype = CHOLMOD_INT; + elseif Ti == Int64; itype = CHOLMOD_LONG; end - if Tv == Float64 || Tv == Float32; xtype = _jl_CHOLMOD_REAL; - elseif Tv == Complex128 || Tv == Complex64 ; xtype = _jl_CHOLMOD_COMPLEX; end + if Tv == Float64 || Tv == Float32; xtype = CHOLMOD_REAL; + elseif Tv == Complex128 || Tv == Complex64 ; xtype = CHOLMOD_COMPLEX; end - if Tv == Float64 || Tv == Complex128; dtype = _jl_CHOLMOD_DOUBLE; - elseif Tv == Float32 || Tv == Complex64 ; dtype = _jl_CHOLMOD_SINGLE; end + if Tv == Float64 || Tv == Complex128; dtype = CHOLMOD_DOUBLE; + elseif Tv == Float32 || Tv == Complex64 ; dtype = CHOLMOD_SINGLE; end ccall((:jl_cholmod_sparse, libsuitesparse_wrapper), Ptr{Void}, - (Ptr{Void}, Int, Int, Int, Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{Void}, - Int32, Int32, Int32, Int32, Int32, Int32), - cs, int(S.m), int(S.n), int(length(S.nzval)), S.colptr, S.rowval, C_NULL, S.nzval, C_NULL, - int32(stype), itype, xtype, dtype, _jl_CHOLMOD_TRUE, _jl_CHOLMOD_TRUE + (Ptr{Void}, BlasInt, BlasInt, BlasInt, Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{Void}, + BlasInt, BlasInt, BlasInt, BlasInt, BlasInt, Int), + cs, blas_int(S.m), blas_int(S.n), blas_int(length(S.nzval)), S.colptr, S.rowval, C_NULL, S.nzval, C_NULL, + int32(stype), itype, xtype, dtype, CHOLMOD_TRUE, CHOLMOD_TRUE ) return cs end ## Call wrapper function to create cholmod_dense objects -function _jl_cholmod_dense{T}(B::VecOrMat{T}) +function cholmod_dense{T}(B::VecOrMat{T}) m = size(B, 1) n = isa(B, Matrix) ? size(B, 2) : 1 cd = Array(Ptr{Void}, 1) - if T == Float64 || T == Float32; xtype = _jl_CHOLMOD_REAL; - elseif T == Complex128 || T == Complex64 ; xtype = _jl_CHOLMOD_COMPLEX; end + if T == Float64 || T == Float32; xtype = CHOLMOD_REAL; + elseif T == Complex128 || T == Complex64 ; xtype = CHOLMOD_COMPLEX; end - if T == Float64 || T == Complex128; dtype = _jl_CHOLMOD_DOUBLE; - elseif T == Float32 || T == Complex64 ; dtype = _jl_CHOLMOD_SINGLE; end + if T == Float64 || T == Complex128; dtype = CHOLMOD_DOUBLE; + elseif T == Float32 || T == Complex64 ; dtype = CHOLMOD_SINGLE; end ccall((:jl_cholmod_dense, libsuitesparse_wrapper), Ptr{Void}, - (Ptr{Void}, Int, Int, Int, Int, Ptr{T}, Ptr{Void}, Int32, Int32), + (Ptr{Void}, BlasInt, BlasInt, BlasInt, BlasInt, Ptr{T}, Ptr{Void}, BlasInt, Int), cd, m, n, numel(B), m, B, C_NULL, xtype, dtype ) return cd end -function _jl_cholmod_dense_copy_out{T}(x::Ptr{Void}, sol::VecOrMat{T}) +function cholmod_dense_copy_out{T}(x::Ptr{Void}, sol::VecOrMat{T}) ccall((:jl_cholmod_dense_copy_out, libsuitesparse_wrapper), Void, (Ptr{Void}, Ptr{T}), @@ -446,16 +450,16 @@ function _jl_cholmod_dense_copy_out{T}(x::Ptr{Void}, sol::VecOrMat{T}) return sol end -function _jl_cholmod_transpose_unsym{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, cm::Array{Ptr{Void}, 1}) +function cholmod_transpose_unsym{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, cm::Array{Ptr{Void}, 1}) S_t = SparseMatrixCSC(Tv, S.n, S.m, nnz(S)+1) # Allocate space for a cholmod_sparse object - cs = _jl_cholmod_sparse(S) - cs_t = _jl_cholmod_sparse(S_t) + cs = cholmod_sparse(S) + cs_t = cholmod_sparse(S_t) status = ccall((:cholmod_transpose_unsym), Int32, - (Ptr{Void}, Int32, Ptr{Int32}, Ptr{Int32}, Int32, Ptr{Void}, Ptr{Void}), + (Ptr{Void}, BlasInt, Ptr{BlasInt}, Ptr{BlasInt}, BlasInt, Ptr{Void}, Ptr{Void}), cs[1], int32(1), C_NULL, C_NULL, int32(-1), cs_t[1], cm[1]); # Deallocate space for cholmod_sparse objects @@ -465,18 +469,18 @@ function _jl_cholmod_transpose_unsym{Tv,Ti}(S::SparseMatrixCSC{Tv,Ti}, cm::Array return S_t end -function _jl_cholmod_analyze{Tv<:Union(Float64,Complex128), Ti<:CHMITypes}(cs::Array{Ptr{Void},1}, cm::Array{Ptr{Void},1}) +function cholmod_analyze{Tv<:Union(Float64,Complex128), Ti<:CHMITypes}(cs::Array{Ptr{Void},1}, cm::Array{Ptr{Void},1}) ccall(_chm_analyze, Ptr{Void}, (Ptr{Void}, Ptr{Void}), cs[1], cm[1]) end -function _jl_cholmod_factorize{Tv<:Union(Float64,Complex128), Ti<:CHMITypes}(cs::Array{Ptr{Void},1}, cs_factor::Ptr{Void}, cm::Array{Ptr{Void},1}) - st = ccall(_chm_factorize, Int32, (Ptr{Void}, Ptr{Void}, Ptr{Void}), cs[1], cs_factor, cm[1]) - if st != _jl_CHOLMOD_TRUE error("CHOLMOD could not factorize the matrix") end +function cholmod_factorize{Tv<:Union(Float64,Complex128), Ti<:CHMITypes}(cs::Array{Ptr{Void},1}, cs_factor::Ptr{Void}, cm::Array{Ptr{Void},1}) + st = ccall(_chm_factorize, BlasInt, (Ptr{Void}, Ptr{Void}, Ptr{Void}), cs[1], cs_factor, cm[1]) + if st != CHOLMOD_TRUE error("CHOLMOD could not factorize the matrix") end end -function _jl_cholmod_solve(cs_factor::Ptr{Void}, cd_rhs::Array{Ptr{Void},1}, cm::Array{Ptr{Void},1}) - ccall(_chm_solve, Ptr{Void}, (Int32, Ptr{Void}, Ptr{Void}, Ptr{Void}), - _jl_CHOLMOD_A, cs_factor, cd_rhs[1], cm[1]) +function cholmod_solve(cs_factor::Ptr{Void}, cd_rhs::Array{Ptr{Void},1}, cm::Array{Ptr{Void},1}) + ccall(_chm_solve, Ptr{Void}, (BlasInt, Ptr{Void}, Ptr{Void}, Ptr{Void}), + CHOLMOD_A, cs_factor, cd_rhs[1], cm[1]) end ## UMFPACK @@ -495,7 +499,7 @@ function show(io, f::UmfpackLU) @printf("UMFPACK LU Factorization of a %d-by-%d sparse matrix\n", size(f.mat,1), size(f.mat,2)) println(f.numeric) - _jl_umfpack_report(f) + umfpack_report(f) end type UmfpackLUTrans{Tv<:Union(Float64,Complex128),Ti<:CHMITypes} <: Factorization{Tv} @@ -507,17 +511,17 @@ function show(io, f::UmfpackLUTrans) @printf("UMFPACK LU Factorization of a transposed %d-by-%d sparse matrix\n", size(f.mat,1), size(f.mat,2)) println(f.numeric) - _jl_umfpack_report(f) + umfpack_report(f) end function UmfpackLU{Tv<:Union(Float64,Complex128),Ti<:CHMITypes}(S::SparseMatrixCSC{Tv,Ti}) Scopy = copy(S) - Scopy = _jl_convert_to_0_based_indexing!(Scopy) + Scopy = convert_to_0_based_indexing!(Scopy) numeric = [] try - symbolic = _jl_umfpack_symbolic(Scopy) - numeric = _jl_umfpack_numeric(Scopy, symbolic) + symbolic = umfpack_symbolic(Scopy) + numeric = umfpack_numeric(Scopy, symbolic) catch e if is(e,MatrixIllConditionedException) error("Input matrix is ill conditioned or singular"); @@ -531,14 +535,14 @@ end function UmfpackLU!{Tv<:Union(Float64,Complex128),Ti<:CHMITypes}(S::SparseMatrixCSC{Tv,Ti}) Sshallow = SparseMatrixCSC(S.m,S.n,S.colptr,S.rowval,S.nzval) - Sshallow = _jl_convert_to_0_based_indexing!(Sshallow) + Sshallow = convert_to_0_based_indexing!(Sshallow) numeric = [] try - symbolic = _jl_umfpack_symbolic(Sshallow) - numeric = _jl_umfpack_numeric(Sshallow, symbolic) + symbolic = umfpack_symbolic(Sshallow) + numeric = umfpack_numeric(Sshallow, symbolic) catch e - Sshallow = _jl_convert_to_1_based_indexing!(Sshallow) + Sshallow = convert_to_1_based_indexing!(Sshallow) if is(e,MatrixIllConditionedException) error("Input matrix is ill conditioned or singular"); else @@ -561,10 +565,10 @@ end # Solve with Factorization (\){T}(fact::UmfpackLU{T}, b::Vector) = fact \ convert(Array{T,1}, b) -(\){T}(fact::UmfpackLU{T}, b::Vector{T}) = _jl_umfpack_solve(fact.mat,b,fact.numeric) +(\){T}(fact::UmfpackLU{T}, b::Vector{T}) = umfpack_solve(fact.mat,b,fact.numeric) (\){T}(fact::UmfpackLUTrans{T}, b::Vector) = fact \ convert(Array{T,1}, b) -(\){T}(fact::UmfpackLUTrans{T}, b::Vector{T}) = _jl_umfpack_transpose_solve(fact.mat,b,fact.numeric) +(\){T}(fact::UmfpackLUTrans{T}, b::Vector{T}) = umfpack_transpose_solve(fact.mat,b,fact.numeric) ctranspose(fact::UmfpackLU) = UmfpackLUTrans(fact.numeric, fact.mat) @@ -581,7 +585,7 @@ for (f_sym_r, f_sym_c, inttype) in ("umfpack_dl_symbolic","umfpack_zl_symbolic",:Int64)) @eval begin - function _jl_umfpack_symbolic{Tv<:Float64,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}) + function umfpack_symbolic{Tv<:Float64,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}) # Pointer to store the symbolic factorization returned by UMFPACK Symbolic = UmfpackPtr{Tv,Ti}(Array(Ptr{Void},1)) status = ccall(($f_sym_r, libumfpack), @@ -590,12 +594,12 @@ for (f_sym_r, f_sym_c, inttype) in Ptr{Ti}, Ptr{Ti}, Ptr{Float64}, Ptr{Void}, Ptr{Float64}, Ptr{Float64}), S.m, S.n, S.colptr, S.rowval, S.nzval, Symbolic.val, C_NULL, C_NULL) - if status != _jl_UMFPACK_OK; error("Error in symbolic factorization"); end - finalizer(Symbolic,_jl_umfpack_free_symbolic) + if status != UMFPACK_OK; error("Error in symbolic factorization"); end + finalizer(Symbolic,umfpack_free_symbolic) return Symbolic end - function _jl_umfpack_symbolic{Tv<:Complex128,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}) + function umfpack_symbolic{Tv<:Complex128,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}) # Pointer to store the symbolic factorization returned by UMFPACK Symbolic = UmfpackPtr{Tv,Ti}(Array(Ptr{Void},1)) status = ccall(($f_sym_c, libumfpack), @@ -606,8 +610,8 @@ for (f_sym_r, f_sym_c, inttype) in S.m, S.n, S.colptr, S.rowval, real(S.nzval), imag(S.nzval), Symbolic.val, C_NULL, C_NULL) - if status != _jl_UMFPACK_OK; error("Error in symbolic factorization"); end - finalizer(Symbolic,_jl_umfpack_free_symbolic) # Check: do we need to free if there was an error? + if status != UMFPACK_OK; error("Error in symbolic factorization"); end + finalizer(Symbolic,umfpack_free_symbolic) # Check: do we need to free if there was an error? return Symbolic end @@ -619,7 +623,7 @@ for (f_num_r, f_num_c, inttype) in ("umfpack_dl_numeric","umfpack_zl_numeric",:Int64)) @eval begin - function _jl_umfpack_numeric{Tv<:Float64,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, Symbolic) + function umfpack_numeric{Tv<:Float64,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, Symbolic) # Pointer to store the numeric factorization returned by UMFPACK Numeric = UmfpackPtr{Tv,Ti}(Array(Ptr{Void},1)) status = ccall(($f_num_r, libumfpack), @@ -629,12 +633,12 @@ for (f_num_r, f_num_c, inttype) in S.colptr, S.rowval, S.nzval, Symbolic.val[1], Numeric.val, C_NULL, C_NULL) if status > 0; throw(MatrixIllConditionedException); end - if status != _jl_UMFPACK_OK; error("Error in numeric factorization"); end - finalizer(Numeric,_jl_umfpack_free_numeric) + if status != UMFPACK_OK; error("Error in numeric factorization"); end + finalizer(Numeric,umfpack_free_numeric) return Numeric end - function _jl_umfpack_numeric{Tv<:Complex128,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, Symbolic) + function umfpack_numeric{Tv<:Complex128,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, Symbolic) # Pointer to store the numeric factorization returned by UMFPACK Numeric = UmfpackPtr{Tv,Ti}(Array(Ptr{Void},1)) status = ccall(($f_num_c, libumfpack), @@ -644,8 +648,8 @@ for (f_num_r, f_num_c, inttype) in S.colptr, S.rowval, real(S.nzval), imag(S.nzval), Symbolic.val[1], Numeric.val, C_NULL, C_NULL) if status > 0; throw(MatrixIllConditionedException); end - if status != _jl_UMFPACK_OK; error("Error in numeric factorization"); end - finalizer(Numeric,_jl_umfpack_free_numeric) + if status != UMFPACK_OK; error("Error in numeric factorization"); end + finalizer(Numeric,umfpack_free_numeric) return Numeric end @@ -657,20 +661,20 @@ for (f_sol_r, f_sol_c, inttype) in ("umfpack_dl_solve","umfpack_zl_solve",:Int64)) @eval begin - function _jl_umfpack_solve{Tv<:Float64,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, + function umfpack_solve{Tv<:Float64,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, b::Vector{Tv}, Numeric::UmfpackPtr{Tv,Ti}) x = similar(b) status = ccall(($f_sol_r, libumfpack), Ti, (Ti, Ptr{Ti}, Ptr{Ti}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Void}, Ptr{Float64}, Ptr{Float64}), - _jl_UMFPACK_A, S.colptr, S.rowval, S.nzval, + UMFPACK_A, S.colptr, S.rowval, S.nzval, x, b, Numeric.val[1], C_NULL, C_NULL) - if status != _jl_UMFPACK_OK; error("Error in solve"); end + if status != UMFPACK_OK; error("Error in solve"); end return x end - function _jl_umfpack_solve{Tv<:Complex128,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, + function umfpack_solve{Tv<:Complex128,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, b::Vector{Tv}, Numeric::UmfpackPtr{Tv,Ti}) xr = similar(b, Float64) xi = similar(b, Float64) @@ -678,26 +682,26 @@ for (f_sol_r, f_sol_c, inttype) in Ti, (Ti, Ptr{Ti}, Ptr{Ti}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Void}, Ptr{Float64}, Ptr{Float64}), - _jl_UMFPACK_A, S.colptr, S.rowval, real(S.nzval), imag(S.nzval), + UMFPACK_A, S.colptr, S.rowval, real(S.nzval), imag(S.nzval), xr, xi, real(b), imag(b), Numeric.val[1], C_NULL, C_NULL) - if status != _jl_UMFPACK_OK; error("Error in solve"); end + if status != UMFPACK_OK; error("Error in solve"); end return complex(xr,xi) end - function _jl_umfpack_transpose_solve{Tv<:Float64,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, + function umfpack_transpose_solve{Tv<:Float64,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, b::Vector{Tv}, Numeric::UmfpackPtr{Tv,Ti}) x = similar(b) status = ccall(($f_sol_r, libumfpack), Ti, (Ti, Ptr{Ti}, Ptr{Ti}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Void}, Ptr{Float64}, Ptr{Float64}), - _jl_UMFPACK_At, S.colptr, S.rowval, S.nzval, + UMFPACK_At, S.colptr, S.rowval, S.nzval, x, b, Numeric.val[1], C_NULL, C_NULL) - if status != _jl_UMFPACK_OK; error("Error in solve"); end + if status != UMFPACK_OK; error("Error in solve"); end return x end - function _jl_umfpack_transpose_solve{Tv<:Complex128,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, + function umfpack_transpose_solve{Tv<:Complex128,Ti<:$inttype}(S::SparseMatrixCSC{Tv,Ti}, b::Vector{Tv}, Numeric::UmfpackPtr{Tv,Ti}) xr = similar(b, Float64) xi = similar(b, Float64) @@ -705,9 +709,9 @@ for (f_sol_r, f_sol_c, inttype) in Ti, (Ti, Ptr{Ti}, Ptr{Ti}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Void}, Ptr{Float64}, Ptr{Float64}), - _jl_UMFPACK_At, S.colptr, S.rowval, real(S.nzval), imag(S.nzval), + UMFPACK_At, S.colptr, S.rowval, real(S.nzval), imag(S.nzval), xr, xi, real(b), imag(b), Numeric.val[1], C_NULL, C_NULL) - if status != _jl_UMFPACK_OK; error("Error in solve"); end + if status != UMFPACK_OK; error("Error in solve"); end return complex(xr,xi) end @@ -715,16 +719,16 @@ for (f_sol_r, f_sol_c, inttype) in end for (f_report, elty, inttype) in - (("umfpack_di_report_numeric", :Float64, :Int32), - ("umfpack_zi_report_numeric", :Complex128, :Int32), + (("umfpack_di_report_numeric", :Float64, :Int), + ("umfpack_zi_report_numeric", :Complex128, :Int), ("umfpack_dl_report_numeric", :Float64, :Int64), ("umfpack_zl_report_numeric", :Complex128, :Int64)) @eval begin - function _jl_umfpack_report{Tv<:$elty,Ti<:$inttype}(slu::UmfpackLU{Tv,Ti}) + function umfpack_report{Tv<:$elty,Ti<:$inttype}(slu::UmfpackLU{Tv,Ti}) - control = zeros(Float64, _jl_UMFPACK_CONTROL) - control[_jl_UMFPACK_PRL] = 4 + control = zeros(Float64, UMFPACK_CONTROL) + control[UMFPACK_PRL] = 4 ccall(($f_report, libumfpack), Ti, @@ -743,10 +747,10 @@ for (f_symfree, f_numfree, elty, inttype) in ("umfpack_zl_free_symbolic","umfpack_zl_free_numeric",:Complex128,:Int64)) @eval begin - _jl_umfpack_free_symbolic{Tv<:$elty,Ti<:$inttype}(Symbolic::UmfpackPtr{Tv,Ti}) = + umfpack_free_symbolic{Tv<:$elty,Ti<:$inttype}(Symbolic::UmfpackPtr{Tv,Ti}) = ccall(($f_symfree, libumfpack), Void, (Ptr{Void},), Symbolic.val) - _jl_umfpack_free_numeric{Tv<:$elty,Ti<:$inttype}(Numeric::UmfpackPtr{Tv,Ti}) = + umfpack_free_numeric{Tv<:$elty,Ti<:$inttype}(Numeric::UmfpackPtr{Tv,Ti}) = ccall(($f_numfree, libumfpack), Void, (Ptr{Void},), Numeric.val) end diff --git a/extras/suitesparse_h.jl b/extras/suitesparse_h.jl index ce4f161d35e41..7e675d8bc855b 100644 --- a/extras/suitesparse_h.jl +++ b/extras/suitesparse_h.jl @@ -1,106 +1,106 @@ ## CHOLMOD -const _jl_CHOLMOD_TRUE = int32(1) -const _jl_CHOLMOD_FALSE = int32(0) +const CHOLMOD_TRUE = int32(1) +const CHOLMOD_FALSE = int32(0) # Types of systems to solve -const _jl_CHOLMOD_A = int32(0) # solve Ax=b -const _jl_CHOLMOD_LDLt = int32(1) # solve LDL'x=b -const _jl_CHOLMOD_LD = int32(2) # solve LDx=b -const _jl_CHOLMOD_DLt = int32(3) # solve DL'x=b -const _jl_CHOLMOD_L = int32(4) # solve Lx=b -const _jl_CHOLMOD_Lt = int32(5) # solve L'x=b -const _jl_CHOLMOD_D = int32(6) # solve Dx=b -const _jl_CHOLMOD_P = int32(7) # permute x=Px -const _jl_CHOLMOD_Pt = int32(8) # permute x=P'x +const CHOLMOD_A = int32(0) # solve Ax=b +const CHOLMOD_LDLt = int32(1) # solve LDL'x=b +const CHOLMOD_LD = int32(2) # solve LDx=b +const CHOLMOD_DLt = int32(3) # solve DL'x=b +const CHOLMOD_L = int32(4) # solve Lx=b +const CHOLMOD_Lt = int32(5) # solve L'x=b +const CHOLMOD_D = int32(6) # solve Dx=b +const CHOLMOD_P = int32(7) # permute x=Px +const CHOLMOD_Pt = int32(8) # permute x=P'x # itype defines the types of integer used: -const _jl_CHOLMOD_INT = int32(0) # all integer arrays are int -const _jl_CHOLMOD_LONG = int32(2) # all integer arrays are UF_long +const CHOLMOD_INT = int32(0) # all integer arrays are int +const CHOLMOD_LONG = int32(2) # all integer arrays are UF_long # dtype defines what the numerical type is (double or float): -const _jl_CHOLMOD_DOUBLE = int32(0) # all numerical values are double -const _jl_CHOLMOD_SINGLE = int32(1) # all numerical values are float +const CHOLMOD_DOUBLE = int32(0) # all numerical values are double +const CHOLMOD_SINGLE = int32(1) # all numerical values are float # xtype defines the kind of numerical values used: -const _jl_CHOLMOD_PATTERN = int32(0) # pattern only, no numerical values -const _jl_CHOLMOD_REAL = int32(1) # a real matrix -const _jl_CHOLMOD_COMPLEX = int32(2) # a complex matrix (ANSI C99 compatible) -const _jl_CHOLMOD_ZOMPLEX = int32(3) # a complex matrix (MATLAB compatible) +const CHOLMOD_PATTERN = int32(0) # pattern only, no numerical values +const CHOLMOD_REAL = int32(1) # a real matrix +const CHOLMOD_COMPLEX = int32(2) # a complex matrix (ANSI C99 compatible) +const CHOLMOD_ZOMPLEX = int32(3) # a complex matrix (MATLAB compatible) # Definitions for cholmod_common: -const _jl_CHOLMOD_MAXMETHODS = int32(9) # maximum number of different methods that +const CHOLMOD_MAXMETHODS = int32(9) # maximum number of different methods that # cholmod_analyze can try. Must be >= 9. # Common->status values. zero means success, negative means a fatal error, positive is a warning. -const _jl_CHOLMOD_OK = int32(0) # success -const _jl_CHOLMOD_NOT_INSTALLED = int32(-1) # failure: method not installed -const _jl_CHOLMOD_OUT_OF_MEMORY = int32(-2) # failure: out of memory -const _jl_CHOLMOD_TOO_LARGE = int32(-3) # failure: integer overflow occured -const _jl_CHOLMOD_INVALID = int32(-4) # failure: invalid input -const _jl_CHOLMOD_NOT_POSDEF = int32(1) # warning: matrix not pos. def. -const _jl_CHOLMOD_DSMALL = int32(2) # warning: D for LDL' or diag(L) or LL' has tiny absolute value +const CHOLMOD_OK = int32(0) # success +const CHOLMOD_NOT_INSTALLED = int32(-1) # failure: method not installed +const CHOLMOD_OUT_OF_MEMORY = int32(-2) # failure: out of memory +const CHOLMOD_TOO_LARGE = int32(-3) # failure: integer overflow occured +const CHOLMOD_INVALID = int32(-4) # failure: invalid input +const CHOLMOD_NOT_POSDEF = int32(1) # warning: matrix not pos. def. +const CHOLMOD_DSMALL = int32(2) # warning: D for LDL' or diag(L) or LL' has tiny absolute value # ordering method (also used for L->ordering) -const _jl_CHOLMOD_NATURAL = int32(0) # use natural ordering -const _jl_CHOLMOD_GIVEN = int32(1) # use given permutation -const _jl_CHOLMOD_AMD = int32(2) # use minimum degree (AMD) -const _jl_CHOLMOD_METIS = int32(3) # use METIS' nested dissection -const _jl_CHOLMOD_NESDIS = int32(4) # use _jl_CHOLMOD's version of nested dissection: +const CHOLMOD_NATURAL = int32(0) # use natural ordering +const CHOLMOD_GIVEN = int32(1) # use given permutation +const CHOLMOD_AMD = int32(2) # use minimum degree (AMD) +const CHOLMOD_METIS = int32(3) # use METIS' nested dissection +const CHOLMOD_NESDIS = int32(4) # use CHOLMOD's version of nested dissection: # node bisector applied recursively, followed # by constrained minimum degree (CSYMAMD or CCOLAMD) -const _jl_CHOLMOD_COLAMD = int32(5) # use AMD for A, COLAMD for A*A' +const CHOLMOD_COLAMD = int32(5) # use AMD for A, COLAMD for A*A' # POSTORDERED is not a method, but a result of natural ordering followed by a # weighted postorder. It is used for L->ordering, not method [ ].ordering. -const _jl_CHOLMOD_POSTORDERED = int32(6) # natural ordering, postordered. +const CHOLMOD_POSTORDERED = int32(6) # natural ordering, postordered. # supernodal strategy (for Common->supernodal) -const _jl_CHOLMOD_SIMPLICIAL = int32(0) # always do simplicial -const _jl_CHOLMOD_AUTO = int32(1) # select simpl/super depending on matrix -const _jl_CHOLMOD_SUPERNODAL = int32(2) # always do supernodal +const CHOLMOD_SIMPLICIAL = int32(0) # always do simplicial +const CHOLMOD_AUTO = int32(1) # select simpl/super depending on matrix +const CHOLMOD_SUPERNODAL = int32(2) # always do supernodal ## UMFPACK ## Type of solve -const _jl_UMFPACK_A = 0 # Ax=b -const _jl_UMFPACK_At = 1 # A'x=b -const _jl_UMFPACK_Aat = 2 # A.'x=b -const _jl_UMFPACK_Pt_L = 3 # P'Lx=b -const _jl_UMFPACK_L = 4 # Lx=b -const _jl_UMFPACK_Lt_P = 5 # L'Px=b -const _jl_UMFPACK_Lat_P = 6 # L.'Px=b -const _jl_UMFPACK_Lt = 7 # L'x=b -const _jl_UMFPACK_Lat = 8 # L.'x=b -const _jl_UMFPACK_U_Qt = 9 # UQ'x=b -const _jl_UMFPACK_U = 10 # Ux=b -const _jl_UMFPACK_Q_Ut = 11 # QU'x=b -const _jl_UMFPACK_Q_Uat = 12 # QU.'x=b -const _jl_UMFPACK_Ut = 13 # U'x=b -const _jl_UMFPACK_Uat = 14 # U.'x=b +const UMFPACK_A = 0 # Ax=b +const UMFPACK_At = 1 # A'x=b +const UMFPACK_Aat = 2 # A.'x=b +const UMFPACK_Pt_L = 3 # P'Lx=b +const UMFPACK_L = 4 # Lx=b +const UMFPACK_Lt_P = 5 # L'Px=b +const UMFPACK_Lat_P = 6 # L.'Px=b +const UMFPACK_Lt = 7 # L'x=b +const UMFPACK_Lat = 8 # L.'x=b +const UMFPACK_U_Qt = 9 # UQ'x=b +const UMFPACK_U = 10 # Ux=b +const UMFPACK_Q_Ut = 11 # QU'x=b +const UMFPACK_Q_Uat = 12 # QU.'x=b +const UMFPACK_Ut = 13 # U'x=b +const UMFPACK_Uat = 14 # U.'x=b ## Sizes of Control and Info arrays for returning information from solver -const _jl_UMFPACK_INFO = 90 -const _jl_UMFPACK_CONTROL = 20 -const _jl_UMFPACK_PRL = 1 +const UMFPACK_INFO = 90 +const UMFPACK_CONTROL = 20 +const UMFPACK_PRL = 1 ## Status codes -const _jl_UMFPACK_OK = 0 -const _jl_UMFPACK_WARNING_singular_matrix = 1 -const _jl_UMFPACK_WARNING_determinant_underflow = 2 -const _jl_UMFPACK_WARNING_determinant_overflow = 3 -const _jl_UMFPACK_ERROR_out_of_memory = -1 -const _jl_UMFPACK_ERROR_invalid_Numeric_object = -3 -const _jl_UMFPACK_ERROR_invalid_Symbolic_object = -4 -const _jl_UMFPACK_ERROR_argument_missing = -5 -const _jl_UMFPACK_ERROR_n_nonpositive = -6 -const _jl_UMFPACK_ERROR_invalid_matrix = -8 -const _jl_UMFPACK_ERROR_different_pattern = -11 -const _jl_UMFPACK_ERROR_invalid_system = -13 -const _jl_UMFPACK_ERROR_invalid_permutation = -15 -const _jl_UMFPACK_ERROR_internal_error = -911 -const _jl_UMFPACK_ERROR_file_IO = -17 -const _jl_UMFPACK_ERROR_ordering_failed = -18 +const UMFPACK_OK = 0 +const UMFPACK_WARNING_singular_matrix = 1 +const UMFPACK_WARNING_determinant_underflow = 2 +const UMFPACK_WARNING_determinant_overflow = 3 +const UMFPACK_ERROR_out_of_memory = -1 +const UMFPACK_ERROR_invalid_Numeric_object = -3 +const UMFPACK_ERROR_invalid_Symbolic_object = -4 +const UMFPACK_ERROR_argument_missing = -5 +const UMFPACK_ERROR_n_nonpositive = -6 +const UMFPACK_ERROR_invalid_matrix = -8 +const UMFPACK_ERROR_different_pattern = -11 +const UMFPACK_ERROR_invalid_system = -13 +const UMFPACK_ERROR_invalid_permutation = -15 +const UMFPACK_ERROR_internal_error = -911 +const UMFPACK_ERROR_file_IO = -17 +const UMFPACK_ERROR_ordering_failed = -18 ## SuiteSparseQR diff --git a/extras/test.jl b/extras/test.jl index bbe24334635d5..b925b164ae95a 100644 --- a/extras/test.jl +++ b/extras/test.jl @@ -59,7 +59,7 @@ tests(filenames) = tests(filenames, test_printer_raw) function _tests_task(filenames) for fn = filenames - load(fn) + require(fn) end end diff --git a/extras/zlib.jl b/extras/zlib.jl index aa90d343b816a..b05827e0ca1e8 100644 --- a/extras/zlib.jl +++ b/extras/zlib.jl @@ -43,12 +43,12 @@ export # Z_BIG_BUFSIZE, # ZFileOffset -load("zlib_h") +include(find_in_path("zlib_h")) # zlib functions # Returns the maximum size of the compressed output buffer for a given uncompressed input size -compress_bound(input_size::Uint) = ccall(dlsym(_zlib, :compressBound), Uint, (Uint, ), input_size) +compress_bound(input_size::Uint) = ccall((:compressBound, _zlib), Uint, (Uint, ), input_size) compress_bound(input_size::Integer) = compress_bound(convert(Uint, input_size)) # Compress @@ -72,7 +72,7 @@ function compress_to_buffer(source::Array{Uint8}, dest::Array{Uint8}, level::Int dest_buf_size = Uint[length(dest)] # Compress the input - ret = ccall(dlsym(_zlib, :compress2), Int32, (Ptr{Uint8}, Ptr{Uint}, Ptr{Uint}, Uint, Int32), + ret = ccall((:compress2, _zlib), Int32, (Ptr{Uint8}, Ptr{Uint}, Ptr{Uint}, Uint, Int32), dest, dest_buf_size, source, length(source), int32(level)) if ret != Z_OK @@ -127,7 +127,7 @@ function uncompress_to_buffer(source::Array{Uint8}, dest::Array{Uint8}) dest_buf_size = Uint[uncompressed_size] # Uncompress the input - ret = ccall(dlsym(_zlib, :uncompress), Int32, (Ptr{Uint}, Ptr{Uint}, Ptr{Uint}, Uint), + ret = ccall((:uncompress, _zlib), Int32, (Ptr{Uint}, Ptr{Uint}, Ptr{Uint}, Uint), dest, dest_buf_size, source, length(source)) if ret != Z_OK diff --git a/extras/zlib_h.jl b/extras/zlib_h.jl index a31efe5e981e5..557c374e1c17b 100644 --- a/extras/zlib_h.jl +++ b/extras/zlib_h.jl @@ -1,10 +1,10 @@ # general zlib constants, definitions -_zlib = dlopen("libz") +const _zlib = "libz" # Constants -zlib_version = bytestring(ccall(dlsym(_zlib, :zlibVersion), Ptr{Uint8}, ())) +zlib_version = bytestring(ccall((:zlibVersion, _zlib), Ptr{Uint8}, ())) ZLIB_VERSION = tuple([int(c) for c in split(zlib_version, '.')]...) # Flush values @@ -29,7 +29,7 @@ const Z_VERSION_ERROR = int32(-6) # Zlib errors as Exceptions -zerror(e::Integer) = bytestring(ccall(dlsym(_zlib, :zError), Ptr{Uint8}, (Int32,), e)) +zerror(e::Integer) = bytestring(ccall((:zError, _zlib), Ptr{Uint8}, (Int32,), e)) type ZError <: Exception err::Int32 err_str::String @@ -76,13 +76,17 @@ const SEEK_CUR = int32(1) # 64-bit functions are not available # Get compile-time option flags -zlib_compile_flags = ccall(dlsym(_zlib, :zlibCompileFlags), Uint, ()) - -z_off_t_sz = 2 << ((zlib_compile_flags >> 6) & uint(3)) -if z_off_t_sz == sizeof(FileOffset) || (sizeof(FileOffset) == 8 && dlsym_e(_zlib, :crc32_combine64) != C_NULL) - typealias ZFileOffset FileOffset -elseif z_off_t_sz == 4 # 64-bit functions not available - typealias ZFileOffset Int32 -else - error("Can't figure out what to do with ZFileOffset. sizeof(z_off_t) = ", z_off_t_sz) +zlib_compile_flags = ccall((:zlibCompileFlags, _zlib), Uint, ()) + +let _zlib_h = dlopen("libz") + global ZFileOffset + + z_off_t_sz = 2 << ((zlib_compile_flags >> 6) & uint(3)) + if z_off_t_sz == sizeof(FileOffset) || (sizeof(FileOffset) == 8 && dlsym_e(_zlib_h, :gzopen64) != C_NULL) + typealias ZFileOffset FileOffset + elseif z_off_t_sz == 4 # 64-bit functions not available + typealias ZFileOffset Int32 + else + error("Can't figure out what to do with ZFileOffset. sizeof(z_off_t) = ", z_off_t_sz) + end end diff --git a/src/Makefile b/src/Makefile index fa724ac02b629..08c6f1e34f327 100644 --- a/src/Makefile +++ b/src/Makefile @@ -15,7 +15,7 @@ FLAGS = \ -I$(shell $(LLVM_CONFIG) --includedir) \ -I$(JULIAHOME)/deps/libuv/include -I$(JULIAHOME)/usr/include -LIBS = $(shell $(LLVM_CONFIG) --libfiles) $(WHOLE_ARCHIVE) $(JULIAHOME)/src/flisp/libflisp.a $(WHOLE_ARCHIVE) $(JULIAHOME)/src/support/libsupport.a -L$(USR)/lib $(USR)/lib/libuv.a $(OSLIBS) -lpthread $(shell $(LLVM_CONFIG) --ldflags) +LIBS = $(shell $(LLVM_CONFIG) --libfiles) $(WHOLE_ARCHIVE) $(JULIAHOME)/src/flisp/libflisp.a $(WHOLE_ARCHIVE) $(JULIAHOME)/src/support/libsupport.a -L$(BUILD)/lib $(BUILD)/lib/libuv.a $(OSLIBS) -lpthread $(shell $(LLVM_CONFIG) --ldflags) ifneq ($(MAKECMDGOALS),debug) TARGET = @@ -43,13 +43,13 @@ release debug: %: libjulia-% HEADERS = julia.h $(wildcard support/*.h) $(JULIAHOME)/deps/libuv/include/uv.h %.o: %.c $(HEADERS) - $(QUIET_CC) $(CC) $(CFLAGS) $(SHIPFLAGS) -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(CFLAGS) $(SHIPFLAGS) -c $< -o $@ %.do: %.c $(HEADERS) - $(QUIET_CC) $(CC) $(CFLAGS) $(DEBUGFLAGS) -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(CFLAGS) $(DEBUGFLAGS) -c $< -o $@ %.o: %.cpp $(HEADERS) - $(QUIET_CC) $(CXX) $(CXXFLAGS) $(SHIPFLAGS) $(shell $(LLVM_CONFIG) --cppflags) -c $< -o $@ + $(QUIET_CC) $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(SHIPFLAGS) $(shell $(LLVM_CONFIG) --cppflags) -c $< -o $@ %.do: %.cpp $(HEADERS) - $(QUIET_CC) $(CXX) $(CXXFLAGS) $(DEBUGFLAGS) $(shell $(LLVM_CONFIG) --cppflags) -c $< -o $@ + $(QUIET_CC) $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DEBUGFLAGS) $(shell $(LLVM_CONFIG) --cppflags) -c $< -o $@ ast.o ast.do: julia_flisp.boot.inc flisp/*.h @@ -69,13 +69,13 @@ support/libsupport.a: support/*.h support/*.c flisp/libflisp.a: flisp/*.h flisp/*.c support/libsupport.a $(MAKE) -C flisp -$(USR)/$(JL_LIBDIR)/libjulia-debug.$(SHLIB_EXT): julia.expmap $(DOBJS) flisp/libflisp.a support/libsupport.a - $(QUIET_LINK) $(CXX) $(DEBUGFLAGS) $(DOBJS) -shared -o $@ $(LIBS) $(LDFLAGS) +$(BUILD)/$(JL_LIBDIR)/libjulia-debug.$(SHLIB_EXT): julia.expmap $(DOBJS) flisp/libflisp.a support/libsupport.a + $(QUIET_LINK) $(CXX) $(DEBUGFLAGS) $(DOBJS) $(RPATH_ORIGIN) -shared -o $@ $(LIBS) $(LDFLAGS) $(INSTALL_NAME_CMD)libjulia-debug.$(SHLIB_EXT) $@ libjulia-debug.a: julia.expmap $(DOBJS) flisp/libflisp.a support/libsupport.a rm -f $@ $(QUIET_LINK) ar -rcs $@ $(DOBJS) -libjulia-debug: $(USR)/$(JL_LIBDIR)/libjulia-debug.$(SHLIB_EXT) +libjulia-debug: $(BUILD)/$(JL_LIBDIR)/libjulia-debug.$(SHLIB_EXT) ifeq ($(SHLIB_EXT), so) SONAME = -Wl,-soname=libjulia-release.so @@ -83,25 +83,35 @@ else SONAME = endif -$(USR)/$(JL_LIBDIR)/libjulia-release.$(SHLIB_EXT): julia.expmap $(OBJS) flisp/libflisp.a support/libsupport.a - $(QUIET_LINK) $(CXX) $(SHIPFLAGS) $(OBJS) $(LIBS) -shared -o $@ $(LDFLAGS) $(SONAME) +$(BUILD)/$(JL_LIBDIR)/libjulia-release.$(SHLIB_EXT): julia.expmap $(OBJS) flisp/libflisp.a support/libsupport.a + $(QUIET_LINK) $(CXX) $(SHIPFLAGS) $(OBJS) $(LIBS) $(RPATH_ORIGIN) -shared -o $@ $(LDFLAGS) $(SONAME) $(INSTALL_NAME_CMD)libjulia-release.$(SHLIB_EXT) $@ libjulia-release.a: julia.expmap $(OBJS) flisp/libflisp.a support/libsupport.a rm -f $@ $(QUIET_LINK) ar -rcs $@ $(OBJS) -libjulia-release: $(USR)/$(JL_LIBDIR)/libjulia-release.$(SHLIB_EXT) +libjulia-release: $(BUILD)/$(JL_LIBDIR)/libjulia-release.$(SHLIB_EXT) clean: - rm -f $(USR)/$(JL_LIBDIR)/libjulia* - rm -f julia_flisp.boot julia_flisp.boot.inc - rm -f *.do *.o *~ *# *.$(SHLIB_EXT) *.a + -rm -f $(BUILD)/$(JL_LIBDIR)/libjulia* + -rm -f julia_flisp.boot julia_flisp.boot.inc + -rm -f *.do *.o *~ *# *.$(SHLIB_EXT) *.a h2j clean-flisp: - $(MAKE) -C flisp clean + -$(MAKE) -C flisp clean clean-support: - $(MAKE) -C support clean + -$(MAKE) -C support clean cleanall: clean clean-flisp clean-support .PHONY: debug release clean cleanall clean-* + + +h2j: h2j.cpp + $(QUIET_CC) $(CXX) $(CFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(DEBUGFLAGS) $(shell $(LLVM_CONFIG) --cppflags) $< -o $@ \ + -lclangFrontendTool -lclangBasic -lclangLex -lclangDriver -lclangFrontend -lclangParse \ + -lclangAST -lclangSema -lclangAnalysis -lclangEdit \ + -lclangRewrite -lclangSerialization -lclangStaticAnalyzerCheckers \ + -lclangStaticAnalyzerCore -lclangStaticAnalyzerFrontend -lclangTooling \ + -lclangCodeGen -lclangARCMigrate -lclang $(LIBS) $(LDFLAGS) + diff --git a/src/ast.c b/src/ast.c index 7a5b59226a47c..8ad10bc64a22a 100644 --- a/src/ast.c +++ b/src/ast.c @@ -45,10 +45,10 @@ value_t fl_invoke_julia_macro(value_t *args, uint32_t nargs) if (nargs < 1) argcount("invoke-julia-macro", nargs, 1); jl_function_t *f = NULL; - jl_value_t **margs = alloca(nargs * sizeof(jl_value_t*)); + jl_value_t **margs; + JL_GC_PUSHARGS(margs, nargs); int i; for(i=0; i < nargs; i++) margs[i] = NULL; - JL_GC_PUSHARGS(margs, nargs); for(i=1; i < nargs; i++) margs[i] = scm_to_julia(args[i]); jl_value_t *result; diff --git a/src/ccall.cpp b/src/ccall.cpp index 95f971e7785ab..21b26b2058f8b 100644 --- a/src/ccall.cpp +++ b/src/ccall.cpp @@ -387,7 +387,7 @@ static Value *emit_ccall(jl_value_t **args, size_t nargs, jl_codectx_t *ctx) else if (lhd == jl_symbol("thiscall")) { cc = CallingConv::X86_ThisCall; nargs--; - } + } } if ((!isVa && jl_tuple_len(tt) != (nargs-2)/2) || diff --git a/src/codegen.cpp b/src/codegen.cpp index 57f8886f3eec7..639803b647bb2 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -82,9 +82,6 @@ static Type *T_pfloat32; static Type *T_float64; static Type *T_pfloat64; static Type *T_void; -#ifdef JL_GC_MARKSWEEP -static Type *T_gcframe; -#endif // constants static Value *V_null; @@ -321,7 +318,7 @@ typedef struct { Value *envArg; Value *argArray; Value *argCount; - AllocaInst *argTemp; + Instruction *argTemp; int argDepth; int maxDepth; int argSpaceOffs; @@ -409,10 +406,10 @@ static jl_value_t *static_eval(jl_value_t *ex, jl_codectx_t *ctx, bool sparams) { size_t i; size_t n = jl_array_dim0(e->args); - jl_value_t **v = (jl_value_t**)alloca(n*sizeof(jl_value_t*)); + jl_value_t **v; + JL_GC_PUSHARGS(v, n); memset(v, 0, n*sizeof(jl_value_t*)); v[0] = f; - JL_GC_PUSHARGS(v, n); for (i = 1; i < n; i++) { v[i] = static_eval(jl_exprarg(e,i),ctx,sparams); if (v[i] == NULL) { @@ -436,9 +433,9 @@ static jl_value_t *static_eval(jl_value_t *ex, jl_codectx_t *ctx, bool sparams) size_t i; size_t n = jl_array_dim0(e->args)-1; if (n==0) return (jl_value_t*)jl_null; - jl_value_t **v = (jl_value_t**)alloca(n*sizeof(jl_value_t*)); - memset(v, 0, n*sizeof(jl_value_t*)); + jl_value_t **v; JL_GC_PUSHARGS(v, n); + memset(v, 0, n*sizeof(jl_value_t*)); for (i = 0; i < n; i++) { v[i] = static_eval(jl_exprarg(e,i+1),ctx,sparams); if (v[i] == NULL) { @@ -2047,26 +2044,22 @@ static Function *emit_function(jl_lambda_info_t *lam) ctx.argDepth = 0; ctx.maxDepth = 0; #ifdef JL_GC_MARKSWEEP - AllocaInst *gcframe = NULL; + Instruction *gcframe = NULL; Instruction *argSpaceInits = NULL; StoreInst *storeFrameSize = NULL; #endif if (n_roots > 0) { - ctx.argTemp = builder.CreateAlloca(jl_pvalue_llvmt, - ConstantInt::get(T_int32, n_roots)); #ifdef JL_GC_MARKSWEEP // allocate gc frame - gcframe = builder.CreateAlloca(T_gcframe, 0); - builder.CreateStore(builder.CreateBitCast(ctx.argTemp, - PointerType::get(jl_ppvalue_llvmt,0)), - builder.CreateConstGEP2_32(gcframe, 0, 0)); + ctx.argTemp = builder.CreateAlloca(jl_pvalue_llvmt, + ConstantInt::get(T_int32,n_roots+2)); + gcframe = (Instruction*)ctx.argTemp; + ctx.argTemp = (Instruction*)builder.CreateConstGEP1_32(ctx.argTemp, 2); storeFrameSize = - builder.CreateStore(ConstantInt::get(T_size, n_roots), - builder.CreateConstGEP2_32(gcframe, 0, 1)); - builder.CreateStore(ConstantInt::get(T_int32, 0), - builder.CreateConstGEP2_32(gcframe, 0, 2)); + builder.CreateStore(ConstantInt::get(T_size, n_roots<<1), + builder.CreateBitCast(builder.CreateConstGEP1_32(gcframe, 0), T_psize)); builder.CreateStore(builder.CreateLoad(jlpgcstack_var, false), - builder.CreateConstGEP2_32(gcframe, 0, 3)); + builder.CreateBitCast(builder.CreateConstGEP1_32(gcframe, 1), PointerType::get(jl_ppvalue_llvmt,0))); builder.CreateStore(gcframe, jlpgcstack_var, false); // initialize local variable stack roots to null for(i=0; i < (size_t)ctx.argSpaceOffs; i++) { @@ -2074,6 +2067,9 @@ static Function *emit_function(jl_lambda_info_t *lam) builder.CreateStore(V_null, varSlot); } argSpaceInits = &b0->back(); +#else + ctx.argTemp = builder.CreateAlloca(jl_pvalue_llvmt, + ConstantInt::get(T_int32, n_roots)); #endif } else { @@ -2291,7 +2287,7 @@ static Function *emit_function(jl_lambda_info_t *lam) #ifdef JL_GC_MARKSWEEP // JL_GC_POP(); if (n_roots > 0) { - builder.CreateStore(builder.CreateLoad(builder.CreateConstGEP2_32(gcframe, 0, 3), false), + builder.CreateStore(builder.CreateBitCast(builder.CreateLoad(builder.CreateConstGEP1_32(gcframe, 1), false), jl_ppvalue_llvmt), jlpgcstack_var); } #endif @@ -2316,18 +2312,18 @@ static Function *emit_function(jl_lambda_info_t *lam) // step 16. fix up size of stack root list (just a code simplification) if (n_roots > 0) { - BasicBlock::iterator bbi(ctx.argTemp); - AllocaInst *newArgTemp = + BasicBlock::iterator bbi(gcframe); + AllocaInst *newgcframe = new AllocaInst(jl_pvalue_llvmt, ConstantInt::get(T_int32, ctx.argSpaceOffs + - ctx.maxDepth)); + ctx.maxDepth + 2)); ReplaceInstWithInst(ctx.argTemp->getParent()->getInstList(), bbi, - newArgTemp); + newgcframe); BasicBlock::iterator bbi2(storeFrameSize); StoreInst *newFrameSize = - new StoreInst(ConstantInt::get(T_size, ctx.argSpaceOffs + - ctx.maxDepth), + new StoreInst(ConstantInt::get(T_size, (ctx.argSpaceOffs + + ctx.maxDepth)<<1), storeFrameSize->getPointerOperand()); ReplaceInstWithInst(storeFrameSize->getParent()->getInstList(), bbi2, newFrameSize); @@ -2337,8 +2333,8 @@ static Function *emit_function(jl_lambda_info_t *lam) for(i=0; i < (size_t)ctx.maxDepth; i++) { Instruction *argTempi = - GetElementPtrInst::Create(newArgTemp, - ConstantInt::get(T_int32, i+ctx.argSpaceOffs)); + GetElementPtrInst::Create(newgcframe, + ConstantInt::get(T_int32, i+ctx.argSpaceOffs+2)); instList.insertAfter(after, argTempi); after = new StoreInst(V_null, argTempi); instList.insertAfter(argTempi, after); @@ -2423,17 +2419,8 @@ static void init_julia_llvm_env(Module *m) jl_fptr_llvmt = PointerType::get(jl_func_sig, 0); #ifdef JL_GC_MARKSWEEP - StructType *gcfst = StructType::create(getGlobalContext(), "jl_gcframe_t"); - Type *gcframeStructElts[4] = { - PointerType::get(jl_ppvalue_llvmt,0), - T_size, - T_int32, - PointerType::getUnqual(gcfst) }; - gcfst->setBody(ArrayRef(gcframeStructElts, 4)); - T_gcframe = gcfst; - jlpgcstack_var = - new GlobalVariable(*jl_Module, PointerType::get(T_gcframe,0), + new GlobalVariable(*jl_Module, jl_ppvalue_llvmt, true, GlobalVariable::ExternalLinkage, NULL, "jl_pgcstack"); jl_ExecutionEngine->addGlobalMapping(jlpgcstack_var, (void*)&jl_pgcstack); diff --git a/src/flisp/Makefile b/src/flisp/Makefile index e947080b11a03..8ed2b87f04b23 100644 --- a/src/flisp/Makefile +++ b/src/flisp/Makefile @@ -14,7 +14,7 @@ SRCS = flisp.c builtins.c string.c equalhash.c table.c iostream.c \ OBJS = $(SRCS:%.c=%.o) DOBJS = $(SRCS:%.c=%.do) LLTDIR = ../support -LLT = $(LLTDIR)/libsupport.a $(USR)/lib/libuv.a +LLT = $(LLTDIR)/libsupport.a $(BUILD)/lib/libuv.a FLAGS = -Wall -Wno-strict-aliasing -I$(LLTDIR) $(CFLAGS) \ -DUSE_COMPUTED_GOTO $(HFILEDIRS:%=-I%) $(LIBDIRS:%=-L%) -fvisibility=hidden @@ -33,9 +33,9 @@ debug: $(EXENAME)-debug HEADERS = $(wildcard *.h) $(JULIAHOME)/deps/libuv/include/uv.h %.o: %.c $(HEADERS) - $(QUIET_CC) $(CC) $(SHIPFLAGS) -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(SHIPFLAGS) -c $< -o $@ %.do: %.c $(HEADERS) - $(QUIET_CC) $(CC) $(DEBUGFLAGS) -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(DEBUGFLAGS) -c $< -o $@ flisp.o: flisp.c cvalues.c types.c flisp.h print.c read.c equal.c flisp.do: flisp.c cvalues.c types.c flisp.h print.c read.c equal.c @@ -59,7 +59,7 @@ $(EXENAME)-debug: $(DOBJS) $(LIBFILES) $(LIBTARGET)-debug.a flmain.do ./$(EXENAME)-debug unittest.lsp $(EXENAME): $(OBJS) $(LIBFILES) $(LIBTARGET).a flmain.o - $(QUIET_CC) $(CC) $(SHIPFLAGS) $(OBJS) flmain.o -o $(EXENAME) $(LIBS) $(LIBTARGET).a $(OSLIBS) + $(QUIET_CC) $(CC) $(SHIPFLAGS) $(OBJS) flmain.o $(LDFLAGS) -o $(EXENAME) $(LIBS) $(LIBTARGET).a $(OSLIBS) ./$(EXENAME) unittest.lsp clean: diff --git a/src/gc.c b/src/gc.c index f6642a5d97c65..b82440966b247 100644 --- a/src/gc.c +++ b/src/gc.c @@ -219,6 +219,27 @@ static int szclass(size_t sz) return 41; } +#ifdef __LP64__ +#define malloc_a16(sz) malloc(sz) +#else +#if defined(WIN32) +// TODO - use _aligned_malloc, which requires _aligned_free +#define malloc_a16(sz) malloc(sz) + +#elif defined(__APPLE__) +#define malloc_a16(sz) malloc(sz) + +#else +static inline void *malloc_a16(size_t sz) +{ + void *ptr; + if (posix_memalign(&ptr, 16, sz)) + return NULL; + return ptr; +} +#endif +#endif + static void *alloc_big(size_t sz) { if (allocd_bytes > collect_interval) { @@ -228,7 +249,7 @@ static void *alloc_big(size_t sz) size_t offs = BVOFFS*sizeof(void*); if (sz + offs < offs) // overflow in adding offs, size was "negative" jl_throw(jl_memory_exception); - bigval_t *v = (bigval_t*)malloc(sz + offs); + bigval_t *v = (bigval_t*)malloc_a16(sz + offs); allocd_bytes += (sz+offs); if (v == NULL) jl_throw(jl_memory_exception); @@ -284,7 +305,7 @@ jl_mallocptr_t *jl_gc_managed_malloc(size_t sz) jl_gc_collect(); } sz = (sz+3) & -4; - void *b = malloc(sz); + void *b = malloc_a16(sz); if (b == NULL) jl_throw(jl_memory_exception); allocd_bytes += sz; @@ -316,7 +337,7 @@ static void sweep_malloc_ptrs(void) static void add_page(pool_t *p) { - gcpage_t *pg = malloc(sizeof(gcpage_t)); + gcpage_t *pg = malloc_a16(sizeof(gcpage_t)); if (pg == NULL) jl_throw(jl_memory_exception); gcval_t *v = (gcval_t*)&pg->data[0]; @@ -469,19 +490,17 @@ static void gc_mark_stack(jl_gcframe_t *s, ptrint_t offset) { while (s != NULL) { s = (jl_gcframe_t*)((char*)s + offset); - size_t i; - jl_value_t ***rts = (jl_value_t***)((char*)s->roots + offset); - if (s->indirect) { - size_t nr = s->nroots; - for(i=0; i < nr; i++) { + jl_value_t ***rts = (jl_value_t***)(((void**)s)+2); + size_t nr = s->nroots>>1; + if (s->nroots & 1) { + for(size_t i=0; i < nr; i++) { jl_value_t **ptr = (jl_value_t**)((char*)rts[i] + offset); if (*ptr != NULL) gc_push_root(*ptr); } } else { - size_t nr = s->nroots; - for(i=0; i < nr; i++) { + for(size_t i=0; i < nr; i++) { if (rts[i] != NULL) gc_push_root(rts[i]); } diff --git a/src/gf.c b/src/gf.c index 98cbf5f1a6612..987a1b9f41815 100644 --- a/src/gf.c +++ b/src/gf.c @@ -1637,23 +1637,3 @@ jl_value_t *jl_matching_methods(jl_function_t *gf, jl_value_t *type, int lim) jl_methtable_t *mt = jl_gf_mtable(gf); return ml_matches(mt->defs, type, jl_gf_name(gf), lim); } - -DLLEXPORT -int jl_is_builtin(jl_value_t *v) -{ - return ((jl_is_func(v) && (((jl_function_t*)v)->linfo==NULL) && - !jl_is_gf(v)) || - jl_typeis(v,jl_intrinsic_type)); -} - -DLLEXPORT -int jl_is_genericfunc(jl_value_t *v) -{ - return (jl_is_func(v) && jl_is_gf(v)); -} - -DLLEXPORT -jl_sym_t *jl_genericfunc_name(jl_value_t *v) -{ - return jl_gf_name(v); -} diff --git a/src/h2j.cpp b/src/h2j.cpp index 1b950569f071e..158d531f74932 100644 --- a/src/h2j.cpp +++ b/src/h2j.cpp @@ -22,11 +22,14 @@ using namespace clang; class PrintFunctionsConsumer : public ASTConsumer { public: - virtual void HandleTopLevelDecl(DeclGroupRef DG) { + virtual bool HandleTopLevelDecl(DeclGroupRef DG) { for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) { const Decl *D = *i; const FunctionDecl *FD = dyn_cast(D); - if (!FD || !FD->hasPrototype() || !FD->isExternC() || !FD->isGlobal()) return; + //D->dump(); + //cout << '\n'; + //return true; + if (!FD || !FD->hasPrototype() || !FD->isExternC() || !FD->isGlobal() || FD->getBuiltinID() != 0) return true; cout << FD->getResultType().getAsString() << " "; cout << FD->getNameAsString() << "("; bool printComma = false; @@ -40,6 +43,7 @@ class PrintFunctionsConsumer : public ASTConsumer { } cout << ");\n"; } + return true; } }; @@ -49,15 +53,15 @@ int main() ci.createDiagnostics(0,NULL); TargetOptions to; - to.Triple = llvm::sys::getHostTriple(); + to.Triple = llvm::sys::getDefaultTargetTriple(); TargetInfo *pti = TargetInfo::CreateTargetInfo(ci.getDiagnostics(), to); ci.setTarget(pti); ci.getHeaderSearchOpts().AddPath( - StringRef("lib/clang/3.0/include"), frontend::Angled, false, false, false + StringRef("../usr/lib/clang/3.0/include"), frontend::Angled, false, false, false ); ci.getHeaderSearchOpts().AddPath( - StringRef("src/support"), frontend::Quoted, true, false, false + StringRef("support"), frontend::Quoted, true, false, false ); ci.createFileManager(); @@ -67,7 +71,7 @@ int main() ci.setASTConsumer(astConsumer); ci.createASTContext(); - const FileEntry *pFile = ci.getFileManager().getFile("src/julia.h"); + const FileEntry *pFile = ci.getFileManager().getFile("julia.h"); ci.getSourceManager().createMainFileID(pFile); ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(), &ci.getPreprocessor()); clang::ParseAST(ci.getPreprocessor(), astConsumer, ci.getASTContext()); diff --git a/src/interpreter.c b/src/interpreter.c index 55f0a94d0322e..3acdbd63700ec 100644 --- a/src/interpreter.c +++ b/src/interpreter.c @@ -46,11 +46,11 @@ jl_value_t *jl_interpret_toplevel_expr_in(jl_module_t *m, jl_value_t *e, static jl_value_t *do_call(jl_function_t *f, jl_value_t **args, size_t nargs, jl_value_t **locals, size_t nl) { - jl_value_t **argv = alloca((nargs+1) * sizeof(jl_value_t*)); + jl_value_t **argv; + JL_GC_PUSHARGS(argv, nargs+1); size_t i; argv[0] = (jl_value_t*)f; for(i=1; i < nargs+1; i++) argv[i] = NULL; - JL_GC_PUSHARGS(argv, nargs+1); for(i=0; i < nargs; i++) argv[i+1] = eval(args[i], locals, nl); jl_value_t *result = jl_apply(f, &argv[1], nargs); @@ -363,7 +363,8 @@ jl_value_t *jl_interpret_toplevel_thunk_with(jl_lambda_info_t *lam, size_t llength = jl_array_len(l); jl_value_t **names = &((jl_value_t**)l->data)[0]; nl += llength; - jl_value_t **locals = (jl_value_t**)alloca(nl*2*sizeof(void*)); + jl_value_t **locals; + JL_GC_PUSHARGS(locals, nl*2); jl_value_t *r = (jl_value_t*)jl_null; size_t i=0; for(i=0; i < llength; i++) { @@ -374,7 +375,6 @@ jl_value_t *jl_interpret_toplevel_thunk_with(jl_lambda_info_t *lam, locals[i*2] = loc[(i-llength)*2]; locals[i*2+1] = loc[(i-llength)*2+1]; } - JL_GC_PUSHARGS(locals, nl*2); r = eval_body(stmts, locals, nl, 0); JL_GC_POP(); return r; diff --git a/src/jltypes.c b/src/jltypes.c index 8de47d5eda77d..6d141f188ae20 100644 --- a/src/jltypes.c +++ b/src/jltypes.c @@ -200,10 +200,10 @@ DLLEXPORT jl_tuple_t *jl_compute_type_union(jl_tuple_t *types) { size_t n = count_union_components(types); - jl_value_t **temp = alloca(n * sizeof(jl_value_t*)); + jl_value_t **temp; + JL_GC_PUSHARGS(temp, n); size_t idx=0; flatten_type_union(types, temp, &idx); - JL_GC_PUSHARGS(temp, n); assert(idx == n); size_t i, j, ndel=0; for(i=0; i < n; i++) { @@ -254,8 +254,10 @@ jl_value_t *jl_type_union(jl_tuple_t *types) typedef enum {invariant, covariant} variance_t; +#define MAX_CENV_SIZE 128 + typedef struct { - jl_value_t *data[128]; + jl_value_t **data; size_t n; } cenv_t; @@ -279,7 +281,7 @@ static void extend_(jl_value_t *var, jl_value_t *val, cenv_t *soln, int allow) type_eqv_(soln->data[i+1],val)))) return; } - if (soln->n >= sizeof(soln->data)/sizeof(void*)) + if (soln->n >= MAX_CENV_SIZE) jl_error("type too large"); soln->data[soln->n++] = var; soln->data[soln->n++] = val; @@ -1124,16 +1126,12 @@ void print_env(cenv_t *soln) jl_value_t *jl_type_intersection_matching(jl_value_t *a, jl_value_t *b, jl_tuple_t **penv, jl_tuple_t *tvars) { - cenv_t eqc; eqc.n = 0; memset(eqc.data, 0, sizeof(eqc.data)); - cenv_t env; env.n = 0; memset(env.data, 0, sizeof(env.data)); - jl_value_t *ti = NULL; - - JL_GC_PUSH(&ti); - int nrts = sizeof(eqc.data)/sizeof(void*); - JL_GC_PUSHARGS(eqc.data, nrts); - jl_gcframe_t __gc_stkf3_ = { (jl_value_t***)env.data, nrts, - 0, jl_pgcstack }; - jl_pgcstack = &__gc_stkf3_; + jl_value_t **rts; + JL_GC_PUSHARGS(rts, 1 + 2*MAX_CENV_SIZE); + memset(rts, 0, (1+2*MAX_CENV_SIZE)*sizeof(void*)); + cenv_t eqc; eqc.n = 0; eqc.data = &rts[1]; + cenv_t env; env.n = 0; env.data = &rts[1+MAX_CENV_SIZE]; + jl_value_t **pti = &rts[0]; has_ntuple_intersect_tuple = 0; JL_TRY { @@ -1142,15 +1140,15 @@ jl_value_t *jl_type_intersection_matching(jl_value_t *a, jl_value_t *b, // that we allow Range{T} to exist, even though the declaration of // Range specifies Range{T<:Real}. Therefore intersection cannot see // that some parameter values actually don't match. - ti = jl_type_intersect(a, b, &env, &eqc, covariant); + *pti = jl_type_intersect(a, b, &env, &eqc, covariant); } JL_CATCH { - ti = (jl_value_t*)jl_bottom_type; + *pti = (jl_value_t*)jl_bottom_type; } - if (ti == (jl_value_t*)jl_bottom_type || + if (*pti == (jl_value_t*)jl_bottom_type || !(env.n > 0 || eqc.n > 0 || tvars != jl_null)) { - JL_GC_POP(); JL_GC_POP(); JL_GC_POP(); - return ti; + JL_GC_POP(); + return *pti; } int e; @@ -1172,16 +1170,16 @@ jl_value_t *jl_type_intersection_matching(jl_value_t *a, jl_value_t *b, to find all other constraints on N first, then do intersection again with that knowledge. */ - ti = jl_type_intersect(a, b, &env, &eqc, covariant); - if (ti == (jl_value_t*)jl_bottom_type) { - JL_GC_POP(); JL_GC_POP(); JL_GC_POP(); - return ti; + *pti = jl_type_intersect(a, b, &env, &eqc, covariant); + if (*pti == (jl_value_t*)jl_bottom_type) { + JL_GC_POP(); + return *pti; } } } if (!solve_tvar_constraints(&env, &eqc)) { - JL_GC_POP(); JL_GC_POP(); JL_GC_POP(); + JL_GC_POP(); return (jl_value_t*)jl_bottom_type; } //JL_PRINTF(JL_STDOUT, "env: "); print_env(&env); @@ -1219,16 +1217,16 @@ jl_value_t *jl_type_intersection_matching(jl_value_t *a, jl_value_t *b, if (env0 > 0) { JL_TRY { - ti = (jl_value_t*)jl_instantiate_type_with((jl_type_t*)ti, + *pti=(jl_value_t*)jl_instantiate_type_with((jl_type_t*)*pti, &jl_t0(*penv), eqc.n/2); } JL_CATCH { - ti = (jl_value_t*)jl_bottom_type; + *pti = (jl_value_t*)jl_bottom_type; } } - JL_GC_POP(); JL_GC_POP(); JL_GC_POP(); - return ti; + JL_GC_POP(); + return *pti; } // --- type instantiation and cache --- @@ -1370,9 +1368,9 @@ jl_value_t *jl_apply_type_(jl_value_t *tc, jl_value_t **params, size_t n) size_t ntp = jl_tuple_len(tp); if (n > ntp) jl_errorf("too many parameters for type %s", tname); - jl_value_t **env = alloca(2 * ntp * sizeof(jl_value_t*)); - memset(env, 0, 2 * ntp * sizeof(jl_value_t*)); + jl_value_t **env; JL_GC_PUSHARGS(env, 2*ntp); + memset(env, 0, 2 * ntp * sizeof(jl_value_t*)); size_t ne = 0; for(i=0; i < ntp; i++) { jl_tvar_t *tv = (jl_tvar_t*)jl_tupleref(tp,i); @@ -1559,12 +1557,12 @@ static jl_type_t *inst_type_w_(jl_value_t *t, jl_value_t **env, size_t n, jl_type_t *result; size_t ntp = jl_tuple_len(tp); assert(ntp == jl_tuple_len(((jl_tag_type_t*)tc)->parameters)); - jl_value_t **iparams = (jl_value_t**)alloca((ntp+2) * sizeof(void*)); + jl_value_t **iparams; + JL_GC_PUSHARGS(iparams, ntp+2); for(i=0; i < ntp+2; i++) iparams[i] = NULL; jl_value_t **rt1 = &iparams[ntp+0]; // some extra gc roots jl_value_t **rt2 = &iparams[ntp+1]; int cacheable = 1, isabstract = 0; - JL_GC_PUSHARGS(iparams, ntp+2); for(i=0; i < ntp; i++) { jl_value_t *elt = jl_tupleref(tp, i); if (elt == t) { @@ -2103,6 +2101,7 @@ static jl_value_t *type_match_(jl_value_t *child, jl_value_t *parent, jl_tuple_t *t = ((jl_uniontype_t*)child)->types; if (morespecific) { cenv_t tenv; + tenv.data = alloca(MAX_CENV_SIZE*sizeof(void*)); for(i=0; i < jl_tuple_len(t); i++) { int n = env->n; tmp = type_match_(jl_tupleref(t,i), parent, env, 1, invariant); @@ -2255,8 +2254,10 @@ static jl_value_t *type_match_(jl_value_t *child, jl_value_t *parent, */ jl_value_t *jl_type_match_(jl_value_t *a, jl_value_t *b, int morespecific) { - cenv_t env; env.n = 0; memset(env.data, 0, sizeof(env.data)); - JL_GC_PUSHARGS(env.data, sizeof(env.data)/sizeof(void*)); + jl_value_t **rts; + JL_GC_PUSHARGS(rts, MAX_CENV_SIZE); + cenv_t env; env.n = 0; env.data = rts; + memset(env.data, 0, MAX_CENV_SIZE*sizeof(void*)); jl_value_t *m = type_match_(a, b, &env, morespecific, 0); if (m != jl_false) { m = (jl_value_t*)jl_alloc_tuple_uninit(env.n); @@ -2555,12 +2556,11 @@ void jl_init_types(void) jl_any_type, jl_null, jl_tuple(14, jl_symbol("ast"), jl_symbol("sparams"), jl_symbol("tfunc"), jl_symbol("name"), - /* - jl_symbol("roots"), jl_symbol("specTypes"), + jl_symbol("roots"), + /* jl_symbol("specTypes"), jl_symbol("unspecialized"), jl_symbol("specializations")*/ - jl_symbol(""), jl_symbol(""), - jl_symbol(""), jl_symbol(""), + jl_symbol(""), jl_symbol(""), jl_symbol(""), jl_symbol("module"), jl_symbol("def"), jl_symbol("capt"), jl_symbol("file"), jl_symbol("line"), diff --git a/src/julia-parser.scm b/src/julia-parser.scm index 4d218e31b4aa3..af6b846600c9b 100644 --- a/src/julia-parser.scm +++ b/src/julia-parser.scm @@ -774,7 +774,11 @@ (take-token s) (if (eqv? (peek-token s) #\() (loop `(|.| ,ex ,(parse-atom s))) - (loop `(|.| ,ex (quote ,(parse-atom s)))))) + (let ((name (parse-atom s))) + (if (and (pair? name) (eq? (car name) 'macrocall)) + `(macrocall (|.| ,ex (quote ,(cadr name))) + ,@(cddr name)) + (loop `(|.| ,ex (quote ,name))))))) ((|.'| |'|) (take-token s) (loop (list t ex))) ((#\{ ) (take-token s) @@ -974,9 +978,9 @@ ;; add definitions for module-local eval (let ((x (gensym))) `(= (call eval ,x) - (call (|.| Core 'eval) ,name ,x))) + (call (|.| (top Core) 'eval) ,name ,x))) `(= (call eval m x) - (call (|.| Core 'eval) m x)) + (call (|.| (top Core) 'eval) m x)) (cdr body)) body)))) ((export) diff --git a/src/julia-syntax.scm b/src/julia-syntax.scm index fef6900af3063..eccac12750b99 100644 --- a/src/julia-syntax.scm +++ b/src/julia-syntax.scm @@ -793,7 +793,8 @@ ;; (a, b, ...) = (x, y, ...) (tuple-to-assignments lhss x) ;; (a, b, ...) = other - (let* ((xx (if (symbol? x) x (gensy))) + (let* ((xx (if (and (symbol? x) (not (memq x lhss))) + x (gensy))) (ini (if (eq? x xx) '() `((= ,xx ,x)))) (st (gensy))) `(block diff --git a/src/julia.expmap b/src/julia.expmap index fbb6052d4d000..2f1a41ea1e6c6 100644 --- a/src/julia.expmap +++ b/src/julia.expmap @@ -142,7 +142,6 @@ jl_ios_eof; jl_ios_fd; jl_ios_size; - jl_is_builtin; jl_is_const; jl_is_leaf_type; jl_is_rest_arg; diff --git a/src/julia.h b/src/julia.h index 9874aee596575..82b32e8d3eda8 100644 --- a/src/julia.h +++ b/src/julia.h @@ -985,30 +985,29 @@ jl_value_t *jl_apply(jl_function_t *f, jl_value_t **args, uint32_t nargs) #ifdef JL_GC_MARKSWEEP typedef struct _jl_gcframe_t { - jl_value_t ***roots; size_t nroots; - int indirect; struct _jl_gcframe_t *prev; + // actual roots go here } jl_gcframe_t; // NOTE: it is the caller's responsibility to make sure arguments are // rooted. foo(f(), g()) will not work, and foo can't do anything about it, // so the caller must do -// jl_value_t *x, *y; JL_GC_PUSH(&x, &y); +// jl_value_t *x=NULL, *y=NULL; JL_GC_PUSH(&x, &y); // x = f(); y = g(); foo(x, y) extern DLLEXPORT jl_gcframe_t *jl_pgcstack; -#define JL_GC_PUSH(...) \ - void *__gc_rts[] = {__VA_ARGS__}; \ - jl_gcframe_t __gc_stkf_ = { (jl_value_t***)__gc_rts, VA_NARG(__VA_ARGS__), \ - 1, jl_pgcstack }; \ - jl_pgcstack = &__gc_stkf_; +#define JL_GC_PUSH(...) \ + void *__gc_stkf[] = {(void*)((VA_NARG(__VA_ARGS__)<<1)|1), jl_pgcstack, \ + __VA_ARGS__}; \ + jl_pgcstack = (jl_gcframe_t*)__gc_stkf; -#define JL_GC_PUSHARGS(rts,n) \ - jl_gcframe_t __gc_stkf2_ = { (jl_value_t***)rts, (n), \ - 0, jl_pgcstack }; \ - jl_pgcstack = &__gc_stkf2_; +#define JL_GC_PUSHARGS(rts_var,n) \ + rts_var = ((jl_value_t**)alloca(((n)+2)*sizeof(jl_value_t*)))+2; \ + ((void**)rts_var)[-2] = (void*)(((size_t)n)<<1); \ + ((void**)rts_var)[-1] = jl_pgcstack; \ + jl_pgcstack = (jl_gcframe_t*)&(((void**)rts_var)[-2]) #define JL_GC_POP() (jl_pgcstack = jl_pgcstack->prev) diff --git a/src/module.c b/src/module.c index a7a8df064aa9d..90db912256ea0 100644 --- a/src/module.c +++ b/src/module.c @@ -268,13 +268,14 @@ DLLEXPORT int jl_is_const(jl_module_t *m, jl_sym_t *var) void jl_checked_assignment(jl_binding_t *b, jl_value_t *rhs) { if (b->constp && b->value != NULL) { - //jl_errorf("cannot redefine constant %s", b->name->name); - JL_PRINTF(JL_STDERR, "Warning: redefinition of constant %s ignored.\n", - b->name->name); - } - else { - b->value = rhs; + if (!jl_egal(rhs, b->value) && + (jl_typeof(rhs) != jl_typeof(b->value) || + jl_is_type(rhs) || jl_is_function(rhs) || jl_is_module(rhs))) { + jl_errorf("invalid redefinition of constant %s", b->name->name); + } + JL_PRINTF(JL_STDERR,"Warning: redefining constant %s\n",b->name->name); } + b->value = rhs; } void jl_declare_constant(jl_binding_t *b) diff --git a/src/os_detect.h b/src/os_detect.h index f608207db51a3..d1969d3dddc02 100644 --- a/src/os_detect.h +++ b/src/os_detect.h @@ -70,7 +70,7 @@ const OS_NAME = :OS_CURRENT #define OS_NAME_IFELSE(NUM,NAME) JL_IF(JL_BOOL(NUM),elseif,if) (os==:NAME) return #define ATTR(IS_UNIX) JL_TF(JL_BOOL(IS_UNIX)); \n -function _jl_is_unix(os::Symbol) +function is_unix(os::Symbol) JL_OS_MAP2(OS_NAME_IFELSE,ATTR) else error("Unknown Operating System") diff --git a/src/support/Makefile b/src/support/Makefile index 62913e41f3092..a3f867b09e24c 100644 --- a/src/support/Makefile +++ b/src/support/Makefile @@ -31,9 +31,9 @@ default: release HEADERS = $(wildcard *.h) $(JULIAHOME)/deps/libuv/include/uv.h %.o: %.c $(HEADERS) - $(QUIET_CC) $(CC) $(SHIPFLAGS) -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(SHIPFLAGS) -c $< -o $@ %.do: %.c $(HEADERS) - $(QUIET_CC) $(CC) $(DEBUGFLAGS) -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(DEBUGFLAGS) -c $< -o $@ release debug: libsupport.a diff --git a/src/sys.c b/src/sys.c index ad6d2cb0ae114..888f1e679ea91 100644 --- a/src/sys.c +++ b/src/sys.c @@ -317,14 +317,7 @@ jl_value_t *jl_readuntil(ios_t *s, uint8_t delim) ((char*)a->data)[n] = '\0'; } } - JL_GC_PUSH(&a); - jl_struct_type_t* string_type = u8_isvalid(jl_array_data(a), jl_array_len(a)) == 1 ? // ASCII - jl_ascii_string_type : jl_utf8_string_type; - jl_value_t *str = alloc_2w(); - str->type = (jl_type_t*)string_type; - jl_set_nth_field(str, 0, (jl_value_t*)a); - JL_GC_POP(); - return str; + return (jl_value_t*)a; } void jl_free2(void *p, void *hint) diff --git a/src/task.c b/src/task.c index 01e3f797133e9..da310d43f679e 100644 --- a/src/task.c +++ b/src/task.c @@ -540,6 +540,14 @@ static void record_backtrace(void) while (unw_step(&cursor) && n < MAX_BT_SIZE) { unw_get_reg(&cursor, UNW_REG_IP, &ip); bt_data[n++] = ip; + /* + char *func_name; + int line_num; + const char *file_name; + getFunctionInfo(&func_name, &line_num, &file_name, ip); + if (func_name != NULL) + ios_printf(ios_stdout, "in %s at %s:%d\n", func_name, file_name, line_num); + */ } bt_size = n; } diff --git a/src/toplevel.c b/src/toplevel.c index 95e66dfaf46a9..ce67470b5ea61 100644 --- a/src/toplevel.c +++ b/src/toplevel.c @@ -88,7 +88,7 @@ jl_value_t *jl_eval_module_expr(jl_expr_t *ex) if (table[i] != HT_NOTFOUND) { jl_binding_t *b = (jl_binding_t*)table[i]; // remove non-exported macros - if (b->name->name[0]=='@' && !b->exportp) + if (b->name->name[0]=='@' && !b->exportp && b->owner==newm) b->value = NULL; // error for unassigned exports /* diff --git a/test/arrayops.jl b/test/arrayops.jl index 55256265d2c77..6d2da1a4e3180 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -277,3 +277,5 @@ begin @test isequal(c[:,4], [2.0,2.0,2.0,2.0]*1000) end + +@test (1:5)[[true,false,true,false,true]] == [1,3,5] diff --git a/test/bitarray.jl b/test/bitarray.jl index 5d6213b27a03b..b6b5f5792a432 100644 --- a/test/bitarray.jl +++ b/test/bitarray.jl @@ -63,6 +63,7 @@ b2 = randbool(m1, m2) @check_bit_operation copy_to BitMatrix (b1, b2) @check_bit_operation ref BitMatrix (b1, 1:m1, m2:n2) @check_bit_operation ref BitVector (b1, 1:m1, m2) +@check_bit_operation ref BitMatrix (b1, 1:m1, [n2,m2,1]) b2 = randbool(m1, m2) @check_bit_operation assign BitMatrix (b1, b2, 1:m1, n2-m2+1:n2) b2 = randbool(m1) diff --git a/test/combinatorics.jl b/test/combinatorics.jl index 57ad7da8a501d..57b167d27ec1d 100644 --- a/test/combinatorics.jl +++ b/test/combinatorics.jl @@ -18,3 +18,67 @@ @test search_sorted_last([1, 1, 2, 2, 3, 3], 2) == 4 @test search_sorted_last([1, 1, 2, 2, 3, 3], 4) == 6 @test search_sorted_last([1.0, 1, 2, 2, 3, 3], 2.5) == 4 + +rg = 49:57; rgv = [rg] +rg_r = 57:-1:49; rgv_r = [rg_r] +for i = 47:59 + @test search_sorted_first(rg, i) == search_sorted_first(rgv, i) + @test search_sorted_last(rg, i) == search_sorted_last(rgv, i) + @test search_sorted_first_r(rg_r, i) == search_sorted_first_r(rgv_r, i) + @test search_sorted_last_r(rg_r, i) == search_sorted_last_r(rgv_r, i) +end +rg = 1:2:17; rgv = [rg] +rg_r = 17:-2:1; rgv_r = [rg_r] +for i = -1:19 + @test search_sorted_first(rg, i) == search_sorted_first(rgv, i) + @test search_sorted_last(rg, i) == search_sorted_last(rgv, i) + @test search_sorted_first_r(rg_r, i) == search_sorted_first_r(rgv_r, i) + @test search_sorted_last_r(rg_r, i) == search_sorted_last_r(rgv_r, i) +end +rg = -3:0.5:2; rgv = [rg] +rg_r = 2:-0.5:-3; rgv_r = [rg_r] +for i = -5:.5:4 + @test search_sorted_first(rg, i) == search_sorted_first(rgv, i) + @test search_sorted_last(rg, i) == search_sorted_last(rgv, i) + @test search_sorted_first_r(rg_r, i) == search_sorted_first_r(rgv_r, i) + @test search_sorted_last_r(rg_r, i) == search_sorted_last_r(rgv_r, i) +end + +a = randi(10000, 1000) + +# insertion_sort +for _sort in [insertionsort, mergesort, timsort] + _sort_r = symbol("$(_sort)_r") + _sort_by = symbol("$(_sort)_by") + _sort_perm = symbol("$(_sort)_perm") + _sort_perm_r = symbol("$(_sort)_perm_r") + _sort_perm_by = symbol("$(_sort)_perm_by") + + b = _sort(a) + @test issorted(b) + (b, ix) = Base.(_sort_perm)(a) + @test issorted(b) + @test a[ix] == b + + b = Base.(_sort_r)(a) + @test issorted_r(b) + (b, ix) = Base.(_sort_perm_r)(a) + @test issorted_r(b) + @test a[ix] == b + + b = Base.(_sort_by)((x -> -10x), a) + @test issorted_by((x -> -10x), b) + (b, ix) = Base.(_sort_perm_by)((x -> -10x), a) + @test issorted_by((x -> -10x), b) + @test a[ix] == b +end + +b = quicksort(a) +@test issorted(b) +b = Base.quicksort_r(a) +@test issorted_r(b) +b = Base.quicksort_by((x -> -10x), a) +@test issorted_by((x -> -10x), b) + +@test select_r([3,6,30,1,9],2) == 9 +@test select_by((x -> -x),[3,6,30,1,9],2) == 9 diff --git a/test/core.jl b/test/core.jl index 3214f25cd8974..6e2325eeb8dda 100644 --- a/test/core.jl +++ b/test/core.jl @@ -501,3 +501,10 @@ end @test_fails NewEntity(Transform, Transform, Body, Body) @test isa(NewEntity(Transform, Transform), (Transform, Transform)) @test_fails NewEntity(Transform, Transform, Body, Body) + +# issue #1826 +let + a = (1,2) + a,b = a + @test a==1 && b==2 +end diff --git a/test/corelib.jl b/test/corelib.jl index 4635cd4c78202..aaed760f503b7 100644 --- a/test/corelib.jl +++ b/test/corelib.jl @@ -109,6 +109,14 @@ end _d = {"a"=>0} @test isa([k for k in filter(x->length(x)==1, keys(_d))], Vector{Any}) +# issue #1821 +let + d = Dict{UTF8String, Vector{Int}}() + d["a"] = [1, 2] + @test_fails d["b"] = 1 + @test isa(repr(d), String) # check that printable without error +end + # issue #1438 type I1438T id diff --git a/test/file.jl b/test/file.jl index 76bed6609f83f..92553c495e7ac 100644 --- a/test/file.jl +++ b/test/file.jl @@ -15,7 +15,7 @@ end ############################################# dir_name = mktempdir() filename = file_path(dir_name, "afile.txt") -file_create(filename) +touch(filename) ####################################################################### # This section tests some of the features of the stat-based file info # @@ -46,7 +46,7 @@ end # rename file newfilename = file_path(dir_name, "bfile.txt") -path_rename(filename, newfilename) +mv(filename, newfilename) @test ispath(filename) == false @test isfile(newfilename) == true filename = newfilename @@ -70,7 +70,7 @@ filename = newfilename ############ # Clean up # ############ -file_remove(filename) +rm(filename) rmdir(dir_name) @test ispath(filename) == false @test ispath(dir_name) == false diff --git a/test/math.jl b/test/math.jl index 76eebd4a9a252..058c794ab2193 100644 --- a/test/math.jl +++ b/test/math.jl @@ -1,3 +1,15 @@ +# error functions +@assert_approx_eq erf(1) 0.84270079294971486934 +@assert_approx_eq erf(1+2im) -0.53664356577856503399-5.0491437034470346695im +@assert_approx_eq erfc(1) 0.15729920705028513066 +@assert_approx_eq erfc(1+2im) 1.5366435657785650340+5.0491437034470346695im +@assert_approx_eq erfcx(1) 0.42758357615580700442 +@assert_approx_eq erfcx(1+2im) 0.14023958136627794370-0.22221344017989910261im +@assert_approx_eq erfi(1) 1.6504257587975428760 +@assert_approx_eq erfi(1+2im) -0.011259006028815025076+1.0036063427256517509im +@assert_approx_eq dawson(1) 0.53807950691276841914 +@assert_approx_eq dawson(1+2im) -13.388927316482919244-11.828715103889593303im + # airy @assert_approx_eq airy(1.8) 0.0470362168668458052247 @assert_approx_eq airyprime(1.8) -0.0685247801186109345638 diff --git a/test/numbers.jl b/test/numbers.jl index d6775e0fcc6f2..e3ecebad952bc 100644 --- a/test/numbers.jl +++ b/test/numbers.jl @@ -212,6 +212,35 @@ if WORD_SIZE > 32 @test base(12,typemax(Int128)) == "2a695925806818735399a37a20a31b3534a7" end +# floating-point printing +@test repr(1.0) == "1.0" +@test repr(-1.0) == "-1.0" +@test repr(0.0) == "0.0" +@test repr(-0.0) == "-0.0" +@test repr(0.1) == "0.1" +@test repr(0.2) == "0.2" +@test repr(0.3) == "0.3" +@test repr(0.1+0.2) != "0.3" +@test repr(Inf) == "Inf" +@test repr(-Inf) == "-Inf" +@test repr(NaN) == "NaN" +@test repr(-NaN) == "NaN" +@test repr(pi) == "3.141592653589793" + +@test repr(1.0f0) == "1.0f0" +@test repr(-1.0f0) == "-1.0f0" +@test repr(0.0f0) == "0.0f0" +@test repr(-0.0f0) == "-0.0f0" +@test repr(0.1f0) == "0.1f0" +@test repr(0.2f0) == "0.2f0" +@test repr(0.3f0) == "0.3f0" +@test repr(0.1f0+0.2f0) == "0.3f0" +@test repr(Inf32) == "Inf32" +@test repr(-Inf32) == "-Inf32" +@test repr(NaN32) == "NaN32" +@test repr(-NaN32) == "NaN32" +@test repr(float32(pi)) == "3.1415927f0" + # signs @test sign(1) == 1 @test sign(-1) == -1 diff --git a/test/perf/Makefile b/test/perf/Makefile index 7df61a2e663b0..33f8936bc49b0 100644 --- a/test/perf/Makefile +++ b/test/perf/Makefile @@ -12,8 +12,8 @@ perf.h: echo '#include "$(JULIAHOME)/deps/openblas-$(OPENBLAS_VER)/cblas.h"' > $@ echo '#include "$(JULIAHOME)/deps/random/dsfmt-$(DSFMT_VER)/dSFMT.c"' >> $@ -bin/perf%: perf.cpp perf.h - $(CXX) -O$* $< -o $@ $(JULIAHOME)/deps/openblas-$(OPENBLAS_VER)/libopenblas.a -lpthread +bin/perf%: perf.c perf.h + $(CC) -std=c99 -O$* $< -o $@ $(JULIAHOME)/deps/openblas-$(OPENBLAS_VER)/libopenblas.a -lpthread bin/fperf%: perf.f90 $(FC) -static-libgfortran -O$* -fexternal-blas $< -o $@ $(JULIAHOME)/deps/openblas-$(OPENBLAS_VER)/libopenblas.a -lpthread diff --git a/test/perf/perf.cpp b/test/perf/perf.c similarity index 95% rename from test/perf/perf.cpp rename to test/perf/perf.c index 3cf74080cd81b..e06e59a04c155 100644 --- a/test/perf/perf.cpp +++ b/test/perf/perf.c @@ -1,18 +1,9 @@ -#include -#include -#include -#include -#include -#include -#include -#include +#include #define DSFMT_MEXP 19937 #include "perf.h" #include "../../deps/random/randmtzig.c" -using namespace std; - double *myrand(int n) { double *d = (double *)malloc(n*sizeof(double)); dsfmt_gv_fill_array_close_open(d, n); @@ -64,15 +55,15 @@ double *matmul_aat(int n, double *b) { return c; } -int mandel(complex z) { +int mandel(double complex z) { int n = 0; - complex c = complex(real(z), imag(z)); + double complex c = z; for (n=0; n<=79; ++n) { - if (abs(z) > 2.0) { + if (cabs(z) > 2.0) { n -= 1; break; } - z = pow(z,2)+c; + z = cpow(z,2)+c; } return n+1; } @@ -81,7 +72,7 @@ int mandelperf() { int mandel_sum = 0; for (double re=-2.0; re<=0.5; re+=0.1) { for (double im=-1.0; im<=1.0; im+=0.1) { - int m = mandel(complex(re, im)); + int m = mandel(re+im*I); mandel_sum += m; } } @@ -296,7 +287,7 @@ int main() { t = clock_now()-t; if (t < tmin) tmin = t; } - assert(mandel_sum == 14720); + assert(mandel_sum == 14719); print_perf("mandel", tmin); // sort diff --git a/test/perf/perf.jl b/test/perf/perf.jl index 2bde95a092997..0ad73686e1684 100644 --- a/test/perf/perf.jl +++ b/test/perf/perf.jl @@ -59,7 +59,7 @@ function mandel(z) return maxiter end -mandelperf() = [ mandel(complex(r,i)) for r=-2.0:.1:0.5, i=-1.:.1:1. ] +mandelperf() = [ mandel(complex(r,i)) for i=-1.:.1:1., r=-2.0:.1:0.5 ] @test sum(mandelperf()) == 14791 @timeit mandelperf() "mandel" diff --git a/test/perf/perf.m b/test/perf/perf.m index 523ebab915a0e..a68b17e6be38a 100644 --- a/test/perf/perf.m +++ b/test/perf/perf.m @@ -69,28 +69,22 @@ function timeit(name, func, varargin) %% mandelbrot set: complex arithmetic and comprehensions %% -function n = mandel(z) - n = 0; - c = z; - for n=0:79 - if abs(z)>2 - break - end - z = z^2+c; - end +function M = mandel(C) + Z = C; + M = zeros(size(C)); + n = 0; + keep_going = abs(Z) <= 2; + while any(keep_going(:)) && (n < 79) + keep_going(keep_going) = abs(Z(keep_going)) <= 2; + Z(keep_going) = (Z(keep_going).^2) + C(keep_going); + M(keep_going) = M(keep_going) + 1; + n = n + 1; + end end -mandel(complex(-.53,.68)); - function M = mandelperf(ignore) - M = zeros(length(-2.0:.1:0.5), length(-1:.1:1)); - count = 1; - for r = -2:0.1:0.5 - for i = -1:.1:1 - M(count) = mandel(complex(r,i)); - count = count + 1; - end - end + Z = bsxfun(@plus,(-2.0:0.1:0.5)',complex(0,(-1:0.1:1))); + M = mandel(Z); end assert(sum(sum(mandelperf(true))) == 14628) timeit('mandel', @mandelperf, true) diff --git a/test/perf2/perf2.jl b/test/perf2/perf2.jl index a72da2fefc2f0..320db828f5dc4 100644 --- a/test/perf2/perf2.jl +++ b/test/perf2/perf2.jl @@ -18,10 +18,10 @@ srand(1776) # get more consistent times require("$JULIA_HOME/../../examples/list.jl") -function listn1n2(n1::Int64,n2::Int64) - l1 = Nil{Int64}() +function listn1n2(n1::Int,n2::Int) + l1 = Nil{Int}() for i=n2:-1:n1 - l1 = Cons{Int64}(i,l1) + l1 = Cons{Int}(i,l1) end l1 end @@ -109,7 +109,7 @@ end @timeit parse() "splitline" -file_remove("random.csv") +rm("random.csv") load("json") diff --git a/test/remote.jl b/test/remote.jl index 2becd3a933903..2ac0496cf847c 100644 --- a/test/remote.jl +++ b/test/remote.jl @@ -1,4 +1,17 @@ # Check that serializer hasn't gone out-of-frame -@test Base._jl_ser_tag[Symbol] == 2 -@test Base._jl_ser_tag[()] == 49 -@test Base._jl_ser_tag[false] == 125 +@test Base.ser_tag[Symbol] == 2 +@test Base.ser_tag[()] == 49 +@test Base.ser_tag[false] == 125 + +# issue #1770 +let + a = ['T', 'e', 's', 't'] + f = memio() + serialize(f, a) + seek(f, 0) + @test deserialize(f) == a + f = IOString() + serialize(f, a) + seek(f, 0) + @test deserialize(f) == a +end diff --git a/test/runtests.jl b/test/runtests.jl index a0f2e3be7c5a8..0339ace67bcb8 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -4,7 +4,7 @@ using Test function runtests(name) println(" \033[1m*\033[0m \033[31m$(name)\033[0m") #flush(OUTPUT_STREAM) - load("$name") + load(name) end function check_approx_eq(va, vb, Eps, astr, bstr) diff --git a/test/statistics.jl b/test/statistics.jl index dad62bfb09c71..97f65b0884057 100644 --- a/test/statistics.jl +++ b/test/statistics.jl @@ -1,10 +1,9 @@ - @test median([1.]) == 1. @test median([1.,3]) == 2. @test median([1.,3,2]) == 2. -# integer array -@test median([1,3,2]) == 2 +@test median([1,3,2]) == 2.0 +@test median([1,3,2,4]) == 2.5 @test mean([1,2,3]) == 2. @test var([1,2,3]) == 1. @@ -15,3 +14,31 @@ @test quantile([1,2,3,4],0.5) == 2.5 @test quartile([1., 3])[2] == median([1., 3]) @test decile([0.:100.])[1] == 10.0 + +@test abs(autocor([1, 2, 3, 4, 5]) - 1.0) < 10e-8 + +@test iqr([1, 2, 3, 4, 5]) == [2.0, 4.0] + +z = [true, true, false, false, true, false, true, true, true] +values, lengths = rle(z) +@test values == [true, false, true, false, true] +@test lengths == [2, 2, 1, 1, 3] +@test inverse_rle(values, lengths) == z + +z = [true, true, false, false, true, false, true, true, true, false] +values, lengths = rle(z) +@test values == [true, false, true, false, true, false] +@test lengths == [2, 2, 1, 1, 3, 1] +@test inverse_rle(values, lengths) == z + +m = [1 0; 0 1] +d = [0.0 sqrt(2); sqrt(2) 0.0] +@test norm(dist(m) - d) < 10e-8 + +m = [3.0 1.0; 5.0 1.0] +d = [0.0 2.0; 2.0 0.0] +@test norm(dist(m) - d) < 10e-8 + +m = [1 0 0; 0 1 0 ; 1 0 1] +d = [0.0 sqrt(2) 1.0; sqrt(2) 0.0 sqrt(3); 1.0 sqrt(3) 0.0] +@test norm(dist(m) - d) < 10e-8 diff --git a/test/unicode.jl b/test/unicode.jl index 36cd2c799c9fd..f922d8a91ea3a 100644 --- a/test/unicode.jl +++ b/test/unicode.jl @@ -27,6 +27,6 @@ str2 = CharString( # Cleanup unicode data for encoding in ["UTF-32BE", "UTF-32LE", "UTF-16BE", "UTF-16LE", "UTF-8"] - file_remove( file_path(unicodedir,encoding*".unicode")) + rm( file_path(unicodedir,encoding*".unicode")) end rmdir(unicodedir) diff --git a/test/zlib.jl b/test/zlib.jl index 09f7bb3d3ae15..28adae8a7932a 100644 --- a/test/zlib.jl +++ b/test/zlib.jl @@ -27,7 +27,7 @@ r = b[randi((1,256), BUFSIZE)] # zlibCompileFlags function. # Get compile-time option flags -zlib_compile_flags = ccall(dlsym(Zlib._zlib, :zlibCompileFlags), Uint, ()) +zlib_compile_flags = ccall((:zlibCompileFlags, Zlib._zlib), Uint, ()) # Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: # @@ -48,7 +48,10 @@ z_off_t_sz = 2 << ((zlib_compile_flags >> 6) & uint(3)) @test(z_uInt_sz == sizeof(Uint32)) @test(z_uLong_sz == sizeof(Uint)) @test(z_voidpf_sz == sizeof(Ptr)) -@test(z_off_t_sz == sizeof(Zlib.ZFileOffset) || (dlsym(Zlib._zlib, :crc32_combine64) != C_NULL && sizeof(Zlib.ZFileOffset) == 8)) + +let _zlib_h = dlopen("libz") + @test(z_off_t_sz == sizeof(Zlib.ZFileOffset) || (dlsym_e(_zlib_h, :gzopen64) != C_NULL && sizeof(Zlib.ZFileOffset) == 8)) +end ######################## # compress/uncompress tests diff --git a/ui/Makefile b/ui/Makefile index 66fa384122c83..ffcaa82e46f14 100644 --- a/ui/Makefile +++ b/ui/Makefile @@ -5,7 +5,8 @@ override CFLAGS += $(JCFLAGS) override CXXFLAGS += $(JCXXFLAGS) FLAGS = -Wall -Wno-strict-aliasing -fno-omit-frame-pointer \ - -I$(JULIAHOME)/src -I$(JULIAHOME)/src/support -I$(USR)/include $(CFLAGS) + -I$(JULIAHOME)/src -I$(JULIAHOME)/src/support -I$(BUILD)/include $(CFLAGS) + DEBUGFLAGS += $(FLAGS) SHIPFLAGS += $(FLAGS) JLDFLAGS += $(shell $(LLVM_CONFIG) --ldflags) $(OSLIBS) -lpthread $(LDFLAGS) $(RPATH) @@ -16,25 +17,25 @@ release debug: $(MAKE) julia-$@ %.o: %.c repl.h - $(QUIET_CC) $(CC) $(SHIPFLAGS) -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(CFLAGS) $(SHIPFLAGS) -c $< -o $@ %.do: %.c repl.h - $(QUIET_CC) $(CC) $(DEBUGFLAGS) -c $< -o $@ + $(QUIET_CC) $(CC) $(CPPFLAGS) $(CFLAGS) $(DEBUGFLAGS) -c $< -o $@ -julia-release-basic: $(USRBIN)/julia-release-basic -julia-debug-basic: $(USRBIN)/julia-debug-basic -julia-release-readline: $(USRBIN)/julia-release-readline -julia-debug-readline: $(USRBIN)/julia-debug-readline +julia-release-basic: $(BUILD)/bin/julia-release-basic +julia-debug-basic: $(BUILD)/bin/julia-debug-basic +julia-release-readline: $(BUILD)/bin/julia-release-readline +julia-debug-readline: $(BUILD)/bin/julia-debug-readline -$(USRBIN)/julia-release-basic: repl.o repl-basic.o - $(QUIET_LINK) $(CXX) $(LINK_FLAGS) $(SHIPFLAGS) $^ -o $@ -L$(USR)/$(JL_PRIVATE_LIBDIR) -L$(USR)/$(JL_LIBDIR) $(JLDFLAGS) -ljulia-release -$(USRBIN)/julia-debug-basic: repl.do repl-basic.do - $(QUIET_LINK) $(CXX) $(LINK_FLAGS) $(DEBUGFLAGS) $^ -o $@ -L$(USR)/$(JL_PRIVATE_LIBDIR) -L$(USR)/$(JL_LIBDIR) $(JLDFLAGS) -ljulia-debug +$(BUILD)/bin/julia-release-basic: repl.o repl-basic.o + $(QUIET_LINK) $(CXX) $(LINK_FLAGS) $(SHIPFLAGS) $^ -o $@ -L$(BUILD)/$(JL_PRIVATE_LIBDIR) -L$(BUILD)/$(JL_LIBDIR) $(JLDFLAGS) -ljulia-release +$(BUILD)/bin/julia-debug-basic: repl.do repl-basic.do + $(QUIET_LINK) $(CXX) $(LINK_FLAGS) $(DEBUGFLAGS) $^ -o $@ -L$(BUILD)/$(JL_PRIVATE_LIBDIR) -L$(BUILD)/$(JL_LIBDIR) $(JLDFLAGS) -ljulia-debug -$(USRBIN)/julia-release-readline: repl.o repl-readline.o - $(QUIET_LINK) $(CXX) $(LINK_FLAGS) $(SHIPFLAGS) $^ -o $@ $(READLINE) -L$(USR)/$(JL_PRIVATE_LIBDIR) -L$(USR)/$(JL_LIBDIR) $(JLDFLAGS) -ljulia-release -$(USRBIN)/julia-debug-readline: repl.do repl-readline.do - $(QUIET_LINK) $(CXX) $(LINK_FLAGS) $(DEBUGFLAGS) $^ -o $@ $(READLINE) -L$(USR)/$(JL_PRIVATE_LIBDIR) -L$(USR)/$(JL_LIBDIR) $(JLDFLAGS) -ljulia-debug +$(BUILD)/bin/julia-release-readline: repl.o repl-readline.o + $(QUIET_LINK) $(CXX) $(LINK_FLAGS) $(SHIPFLAGS) $^ -o $@ $(READLINE) -L$(BUILD)/$(JL_PRIVATE_LIBDIR) -L$(BUILD)/$(JL_LIBDIR) $(JLDFLAGS) -ljulia-release +$(BUILD)/bin/julia-debug-readline: repl.do repl-readline.do + $(QUIET_LINK) $(CXX) $(LINK_FLAGS) $(DEBUGFLAGS) $^ -o $@ $(READLINE) -L$(BUILD)/$(JL_PRIVATE_LIBDIR) -L$(BUILD)/$(JL_LIBDIR) $(JLDFLAGS) -ljulia-debug clean: | $(CLEAN_TARGETS) rm -f *.o *.do - rm -f $(USRBIN)/julia-*-basic $(USRBIN)/julia-*-readline $(USRBIN)/julia + rm -f $(BUILD)/bin/julia-*-basic $(BUILD)/bin/julia-*-readline $(BUILD)/bin/julia diff --git a/ui/repl-readline.c b/ui/repl-readline.c index 6a46fdac2b025..f6c9d30044a58 100644 --- a/ui/repl-readline.c +++ b/ui/repl-readline.c @@ -473,6 +473,7 @@ static int symtab_get_matches(jl_sym_t *tree, const char *str, char **answer) name = t; } + if (!name) goto symtab_get_matches_exit; plen = strlen(name); while (tree != NULL) { diff --git a/ui/webserver/Makefile b/ui/webserver/Makefile index 7144f2590d860..1e316721fcef0 100644 --- a/ui/webserver/Makefile +++ b/ui/webserver/Makefile @@ -4,7 +4,7 @@ include $(JULIAHOME)/Make.inc override CFLAGS += $(JCFLAGS) override CXXFLAGS += $(JCXXFLAGS) -LIBS = -lpthread $(USR)/$(JL_LIBDIR)/libuv.a +LIBS = -lpthread $(BUILD)/$(JL_LIBDIR)/libuv.a ifeq ($(OS), Linux) LIBS += -lrt endif @@ -14,17 +14,16 @@ LIBS += -lWs2_32 -lIphlpapi -lpsapi endif ifeq ($(OS),Darwin) -LIBS += -framework CoreServices +LIBS += -framework ApplicationServices endif -WEBSERVER_SRCS = webserver.cpp server.cpp jsoncpp.cpp +WEBSERVER_SRCS = webserver.o server.o jsoncpp.o -%.o: %.c - $(QUIET_CC)$(CC) $(CFLAGS) $(SHIPFLAGS) -c $< -o $@ -%.do: %.c - $(QUIET_CC)$(CC) $(CFLAGS) $(DEBUGFLAGS) -c $< -o $@ +%.o: %.cpp *.h + $(QUIET_CC)$(CXX) $(CPPFLAGS) $(CXXFLAGS) $(SHIPFLAGS) -c $< -o $@ +%.do: %.cpp *.h + $(QUIET_CC)$(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DEBUGFLAGS) -c $< -o $@ - ifeq ($(OS),WINNT) LAUNCH_SCRIPT = launch-julia-webserver.bat $(USRBIN)/$(LAUNCH_SCRIPT): ${JULIAHOME}/contrib/windows/*.bat @@ -34,19 +33,22 @@ LAUNCH_SCRIPT = launch-julia-webserver $(USRBIN)/$(LAUNCH_SCRIPT): $(LAUNCH_SCRIPT) cp $< $@ endif - -julia-release julia-debug: %: $(USRBIN)/%-webserver $(USRBIN)/$(LAUNCH_SCRIPT) + +julia-release julia-debug: %: $(BUILD)/bin/%-webserver $(BUILD)/bin/$(LAUNCH_SCRIPT) release debug: $(MAKE) julia-$@ -$(USRBIN)/julia-release-webserver: $(WEBSERVER_SRCS) server.h - $(QUIET_LINK) $(CXX) $(CXXFLAGS) -o $@ $(SHIPFLAGS) $(WEBSERVER_SRCS) $(LIBS) +$(BUILD)/bin/julia-release-webserver: $(WEBSERVER_SRCS) + $(QUIET_LINK) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -o $@ $(SHIPFLAGS) $(LDFLAGS) $(WEBSERVER_SRCS) $(LIBS) + +$(BUILD)/bin/julia-debug-webserver: $(WEBSERVER_SRCS) + $(QUIET_LINK) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -o $@ $(DEBUGFLAGS) $(LDFLAGS) $(WEBSERVER_SRCS) $(LIBS) + +$(BUILD)/bin/$(LAUNCH_SCRIPT): $(LAUNCH_SCRIPT) + cp $< $@ -$(USRBIN)/julia-debug-webserver: $(WEBSERVER_SRCS) server.h - $(QUIET_LINK) $(CXX) $(CXXFLAGS) -o $@ $(DEBUGFLAGS) $(WEBSERVER_SRCS) $(LIBS) - clean: rm -f *.o *.do - rm -f $(USRBIN)/julia-*-webserver - rm -f $(USRBIN)/*.bat + rm -f $(BUILD)/bin/julia-*-webserver + rm -f $(BUILD)/bin/*.bat diff --git a/ui/webserver/server.cpp b/ui/webserver/server.cpp old mode 100755 new mode 100644 diff --git a/ui/webserver/server.h b/ui/webserver/server.h old mode 100755 new mode 100644 diff --git a/ui/webserver/webserver.cpp b/ui/webserver/webserver.cpp old mode 100755 new mode 100644